# Copyright 2016 Rackspace
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os.path
import random
import string

import testtools

import syntribos.utils.file_utils as utils


class ConfigUnittest(testtools.TestCase):

    ept = utils.ExistingPathType()
    edt = utils.ExistingDirType()
    eft = utils.ExistingFileType()
    tt = utils.ContentType('r', 0)

    def test_invalid_path_raises_ioerror(self):
        """Test that a random, invalid path raises IOError for each type."""
        filename = "/"
        for i in range(0, 32):
            filename += random.choice(string.ascii_letters)
        if not os.path.exists(filename):
            self.assertRaises(IOError, self.ept, filename)
            self.assertRaises(IOError, self.edt, filename)
            self.assertRaises(IOError, self.eft, filename)
            self.assertRaises(IOError, self.tt, filename)

    def test_etc_handling(self):
        """Test that the /etc/ dir, if found, is treated right by each type."""
        filename = "/etc/"
        if os.path.exists(filename):
            self.assertEqual(filename, self.ept(filename))
            self.assertEqual(filename, self.edt(filename))
            self.assertRaises(IOError, self.eft, filename)

    def test_etc_passwd_handling(self):
        """Test that /etc/passwd, if found, is treated right by each type."""
        filename = "/etc/passwd"
        if os.path.exists(filename):
            self.assertEqual(filename, self.ept(filename))
            self.assertRaises(IOError, self.edt, filename)
            self.assertEqual(filename, self.eft(filename))
