github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/acceptancetests/jujupy/tests/test_utility.py (about)

     1  from datetime import (
     2      datetime,
     3      timedelta,
     4      )
     5  from contextlib import contextmanager
     6  import errno
     7  import os
     8  import socket
     9  
    10  try:
    11      from mock import patch
    12  except ImportError:
    13      from unittest.mock import patch
    14  
    15  from tests import (
    16      TestCase,
    17      )
    18  import jujupy.utility
    19  from jujupy.utility import (
    20      is_ipv6_address,
    21      quote,
    22      scoped_environ,
    23      skip_on_missing_file,
    24      split_address_port,
    25      temp_dir,
    26      until_timeout,
    27      unqualified_model_name,
    28      qualified_model_name,
    29      )
    30  
    31  
    32  class TestUntilTimeout(TestCase):
    33  
    34      def test_no_timeout(self):
    35  
    36          iterator = until_timeout(0)
    37  
    38          def now_iter():
    39              yield iterator.start
    40              yield iterator.start
    41              assert False
    42  
    43          with patch.object(iterator, 'now', lambda: next(now_iter())):
    44              for x in iterator:
    45                  self.assertIs(None, x)
    46                  break
    47  
    48      @contextmanager
    49      def patched_until(self, timeout, deltas):
    50          iterator = until_timeout(timeout)
    51  
    52          def now_iter():
    53              for d in deltas:
    54                  yield iterator.start + d
    55              assert False
    56          now_iter_i = now_iter()
    57          with patch.object(iterator, 'now', lambda: next(now_iter_i)):
    58              yield iterator
    59  
    60      def test_timeout(self):
    61          with self.patched_until(
    62                  5, [timedelta(), timedelta(0, 4), timedelta(0, 5)]) as until:
    63              results = list(until)
    64          self.assertEqual([5, 1], results)
    65  
    66      def test_long_timeout(self):
    67          deltas = [timedelta(), timedelta(4, 0), timedelta(5, 0)]
    68          with self.patched_until(86400 * 5, deltas) as until:
    69              self.assertEqual([86400 * 5, 86400], list(until))
    70  
    71      def test_start(self):
    72          now = datetime.now() + timedelta(days=1)
    73          now_iter = iter([now, now, now + timedelta(10)])
    74          with patch('utility.until_timeout.now',
    75                     side_effect=lambda: next(now_iter)):
    76              self.assertEqual(list(until_timeout(10, now - timedelta(10))), [])
    77  
    78  
    79  class TestIsIPv6Address(TestCase):
    80  
    81      def test_hostname(self):
    82          self.assertIs(False, is_ipv6_address("name.testing"))
    83  
    84      def test_ipv4(self):
    85          self.assertIs(False, is_ipv6_address("127.0.0.2"))
    86  
    87      def test_ipv6(self):
    88          self.assertIs(True, is_ipv6_address("2001:db8::4"))
    89  
    90      def test_ipv6_missing_support(self):
    91          socket_error = jujupy.utility.socket.error
    92          with patch('jujupy.utility.socket', wraps=socket) as wrapped_socket:
    93              # Must not convert socket.error into a Mock, because Mocks don't
    94              # descend from BaseException
    95              wrapped_socket.error = socket_error
    96              del wrapped_socket.inet_pton
    97              result = is_ipv6_address("2001:db8::4")
    98          # Would use expectedFailure here, but instead just assert wrong result.
    99          self.assertIs(False, result)
   100  
   101  
   102  class TestSplitAddressPort(TestCase):
   103  
   104      def test_hostname(self):
   105          self.assertEqual(
   106              ("name.testing", None), split_address_port("name.testing"))
   107  
   108      def test_ipv4(self):
   109          self.assertEqual(
   110              ("127.0.0.2", "17017"), split_address_port("127.0.0.2:17017"))
   111  
   112      def test_ipv6(self):
   113          self.assertEqual(
   114              ("2001:db8::7", "17017"), split_address_port("2001:db8::7:17017"))
   115  
   116  
   117  class TestSkipOnMissingFile(TestCase):
   118  
   119      def test_skip_on_missing_file(self):
   120          """Test if skip_on_missing_file hides the proper exceptions."""
   121          with skip_on_missing_file():
   122              raise OSError(errno.ENOENT, 'should be hidden')
   123          with skip_on_missing_file():
   124              raise IOError(errno.ENOENT, 'should be hidden')
   125  
   126      def test_skip_on_missing_file_except(self):
   127          """Test if skip_on_missing_file ignores other types of exceptions."""
   128          with self.assertRaises(RuntimeError):
   129              with skip_on_missing_file():
   130                  raise RuntimeError(errno.ENOENT, 'pass through')
   131          with self.assertRaises(IOError):
   132              with skip_on_missing_file():
   133                  raise IOError(errno.EEXIST, 'pass through')
   134  
   135  
   136  class TestQuote(TestCase):
   137  
   138      def test_quote(self):
   139          self.assertEqual(quote("arg"), "arg")
   140          self.assertEqual(quote("/a/file name"), "'/a/file name'")
   141          self.assertEqual(quote("bob's"), "'bob'\"'\"'s'")
   142  
   143  
   144  class TestScopedEnviron(TestCase):
   145  
   146      def test_scoped_environ(self):
   147          old_environ = dict(os.environ)
   148          with scoped_environ():
   149              os.environ.clear()
   150              os.environ['foo'] = 'bar'
   151              self.assertNotEqual(old_environ, os.environ)
   152          self.assertEqual(old_environ, os.environ)
   153  
   154      def test_new_environ(self):
   155          new_environ = {'foo': 'bar'}
   156          with scoped_environ(new_environ):
   157              self.assertEqual(os.environ, new_environ)
   158          self.assertNotEqual(os.environ, new_environ)
   159  
   160  
   161  class TestTempDir(TestCase):
   162  
   163      def test_temp_dir(self):
   164          with temp_dir() as d:
   165              self.assertTrue(os.path.isdir(d))
   166          self.assertFalse(os.path.exists(d))
   167  
   168      def test_temp_dir_contents(self):
   169          with temp_dir() as d:
   170              self.assertTrue(os.path.isdir(d))
   171              open(os.path.join(d, "a-file"), "w").close()
   172          self.assertFalse(os.path.exists(d))
   173  
   174      def test_temp_dir_parent(self):
   175          with temp_dir() as p:
   176              with temp_dir(parent=p) as d:
   177                  self.assertTrue(os.path.isdir(d))
   178                  self.assertEqual(p, os.path.dirname(d))
   179              self.assertFalse(os.path.exists(d))
   180          self.assertFalse(os.path.exists(p))
   181  
   182      def test_temp_dir_keep(self):
   183          with temp_dir() as p:
   184              with temp_dir(parent=p, keep=True) as d:
   185                  self.assertTrue(os.path.isdir(d))
   186                  open(os.path.join(d, "a-file"), "w").close()
   187              self.assertTrue(os.path.exists(d))
   188              self.assertTrue(os.path.exists(os.path.join(d, "a-file")))
   189          self.assertFalse(os.path.exists(p))
   190  
   191  
   192  class TestUnqualifiedModelName(TestCase):
   193  
   194      def test_returns_just_model_name_when_passed_qualifed_full_username(self):
   195          self.assertEqual(
   196              unqualified_model_name('admin@local/default'),
   197              'default'
   198          )
   199  
   200      def test_returns_just_model_name_when_passed_just_username(self):
   201          self.assertEqual(
   202              unqualified_model_name('admin/default'),
   203              'default'
   204          )
   205  
   206      def test_returns_just_model_name_when_passed_no_username(self):
   207          self.assertEqual(
   208              unqualified_model_name('default'),
   209              'default'
   210          )
   211  
   212  
   213  class TestQualifiedModelName(TestCase):
   214  
   215      def test_raises_valueerror_when_model_name_blank(self):
   216          with self.assertRaises(ValueError):
   217              qualified_model_name('', 'admin@local')
   218  
   219      def test_raises_valueerror_when_owner_name_blank(self):
   220          with self.assertRaises(ValueError):
   221              qualified_model_name('default', '')
   222  
   223      def test_raises_valueerror_when_owner_and_model_blank(self):
   224          with self.assertRaises(ValueError):
   225              qualified_model_name('', '')
   226  
   227      def test_raises_valueerror_when_owner_name_doesnt_match_model_owner(self):
   228          with self.assertRaises(ValueError):
   229              qualified_model_name('test/default', 'admin')
   230  
   231          with self.assertRaises(ValueError):
   232              qualified_model_name('test@local/default', 'admin@local')
   233  
   234      def test_returns_qualified_model_name_with_plain_model_name(self):
   235          self.assertEqual(
   236              qualified_model_name('default', 'admin@local'),
   237              'admin@local/default'
   238          )
   239  
   240          self.assertEqual(
   241              qualified_model_name('default', 'admin'),
   242              'admin/default'
   243          )
   244  
   245      def test_returns_qualified_model_name_with_model_name_with_owner(self):
   246          self.assertEqual(
   247              qualified_model_name('admin@local/default', 'admin@local'),
   248              'admin@local/default'
   249          )
   250  
   251          self.assertEqual(
   252              qualified_model_name('admin/default', 'admin'),
   253              'admin/default'
   254          )