Python fixtures.MonkeyPatch() Examples

The following are 30 code examples of fixtures.MonkeyPatch(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module fixtures , or try the search function .
Example #1
Source File: base.py    From DLRN with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        "Run before each test method to initialize test environment."

        super(TestCase, self).setUp()
        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

        self.useFixture(fixtures.NestedTempfile())
        self.useFixture(fixtures.TempHomeDir())

        if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))

        self.log_fixture = self.useFixture(fixtures.FakeLogger()) 
Example #2
Source File: base.py    From oslo.utils with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        """Run before each test method to initialize test environment."""

        super(TestCase, self).setUp()
        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

        self.useFixture(fixtures.NestedTempfile())
        self.useFixture(fixtures.TempHomeDir())

        if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))

        self.log_fixture = self.useFixture(fixtures.FakeLogger()) 
Example #3
Source File: base.py    From oslo.vmware with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        """Run before each test method to initialize test environment."""

        super(TestCase, self).setUp()
        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

        self.useFixture(fixtures.NestedTempfile())
        self.useFixture(fixtures.TempHomeDir())

        if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))

        self.log_fixture = self.useFixture(fixtures.FakeLogger()) 
Example #4
Source File: base.py    From python-designateclient with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        """Run before each test method to initialize test environment."""

        super(TestCase, self).setUp()
        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

        self.useFixture(fixtures.NestedTempfile())
        self.useFixture(fixtures.TempHomeDir())

        if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))

        self.log_fixture = self.useFixture(fixtures.FakeLogger()) 
Example #5
Source File: base.py    From os-client-config with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        super(TestCase, self).setUp()

        self.useFixture(fixtures.NestedTempfile())
        conf = copy.deepcopy(USER_CONF)
        tdir = self.useFixture(fixtures.TempDir())
        conf['cache']['path'] = tdir.path
        self.cloud_yaml = _write_yaml(conf)
        self.secure_yaml = _write_yaml(SECURE_CONF)
        self.vendor_yaml = _write_yaml(VENDOR_CONF)
        self.no_yaml = _write_yaml(NO_CONF)
        self.useFixture(fixtures.MonkeyPatch(
            'os_client_config.__version__', '1.2.3'))
        self.useFixture(fixtures.MonkeyPatch(
            'openstack.version.__version__', '3.4.5'))

        # Isolate the test runs from the environment
        # Do this as two loops because you can't modify the dict in a loop
        # over the dict in 3.4
        keys_to_isolate = []
        for env in os.environ.keys():
            if env.startswith('OS_'):
                keys_to_isolate.append(env)
        for env in keys_to_isolate:
            self.useFixture(fixtures.EnvironmentVariable(env)) 
Example #6
Source File: test_dnsmasq_pxe_filter.py    From ironic-inspector with Apache License 2.0 6 votes vote down vote up
def test_write_would_block_too_many_times(self):
        self.useFixture(fixtures.MonkeyPatch(
            'ironic_inspector.pxe_filter.dnsmasq._EXCLUSIVE_WRITE_ATTEMPTS',
            1))
        err = IOError('Oops!')
        err.errno = errno.EWOULDBLOCK
        self.mock_fcntl.side_effect = [err, None]

        wrote = dnsmasq._exclusive_write_or_pass(self.path, self.buf)
        self.assertFalse(wrote)
        self.mock_open.assert_called_once_with(self.path, 'w', 1)
        self.mock_fcntl.assert_has_calls(
            [self.fcntl_lock_call, self.fcntl_unlock_call])
        self.mock_fd.write.assert_not_called()
        retry_log_call = mock.call('%s locked; will try again (later)',
                                   self.path)
        failed_log_call = mock.call(
            'Failed to write the exclusively-locked path: %(path)s for '
            '%(attempts)s times', {
                'attempts': dnsmasq._EXCLUSIVE_WRITE_ATTEMPTS,
                'path': self.path
            })
        self.mock_log.assert_has_calls([retry_log_call, failed_log_call])
        self.mock_sleep.assert_called_once_with(
            dnsmasq._EXCLUSIVE_WRITE_ATTEMPTS_DELAY) 
Example #7
Source File: base.py    From bashate with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        """Run before each test method to initialize test environment."""

        super(TestCase, self).setUp()
        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

        self.useFixture(fixtures.NestedTempfile())
        self.useFixture(fixtures.TempHomeDir())

        if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))

        self.log_fixture = self.useFixture(fixtures.FakeLogger()) 
Example #8
Source File: base.py    From senlin with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        super(SenlinTestCase, self).setUp()
        self.setup_logging()
        service.ENABLE_SLEEP = False
        self.useFixture(fixtures.MonkeyPatch(
            'senlin.common.exception._FATAL_EXCEPTION_FORMAT_ERRORS',
            True))

        def enable_sleep():
            service.ENABLE_SLEEP = True

        self.addCleanup(enable_sleep)
        self.addCleanup(cfg.CONF.reset)

        messaging.setup("fake://", optional=True)
        self.addCleanup(messaging.cleanup)

        utils.setup_dummy_db()
        self.addCleanup(utils.reset_dummy_db) 
Example #9
Source File: test_wsgi.py    From senlin with Apache License 2.0 6 votes vote down vote up
def test_correct_configure_socket(self):
        mock_socket = mock.Mock()
        self.useFixture(fixtures.MonkeyPatch(
            'senlin.api.common.wsgi.ssl.wrap_socket',
            mock_socket))
        self.useFixture(fixtures.MonkeyPatch(
            'senlin.api.common.wsgi.eventlet.listen',
            lambda *x, **y: mock_socket))
        server = wsgi.Server(name='senlin-api', conf=cfg.CONF.senlin_api)
        server.default_port = 1234
        server.configure_socket()
        self.assertIn(mock.call.setsockopt(socket.SOL_SOCKET,
                                           socket.SO_REUSEADDR, 1),
                      mock_socket.mock_calls)
        self.assertIn(mock.call.setsockopt(socket.SOL_SOCKET,
                                           socket.SO_KEEPALIVE, 1),
                      mock_socket.mock_calls)
        if hasattr(socket, 'TCP_KEEPIDLE'):
            self.assertIn(mock.call().setsockopt(
                socket.IPPROTO_TCP,
                socket.TCP_KEEPIDLE,
                wsgi.cfg.CONF.senlin_api.tcp_keepidle), mock_socket.mock_calls) 
Example #10
Source File: test_wsgi.py    From senlin with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        super(GetSocketTestCase, self).setUp()
        self.useFixture(fixtures.MonkeyPatch(
            "senlin.api.common.wsgi.get_bind_addr",
            lambda x, y: ('192.168.0.13', 1234)))
        addr_info_list = [(2, 1, 6, '', ('192.168.0.13', 80)),
                          (2, 2, 17, '', ('192.168.0.13', 80)),
                          (2, 3, 0, '', ('192.168.0.13', 80))]
        self.useFixture(fixtures.MonkeyPatch(
            "senlin.api.common.wsgi.socket.getaddrinfo",
            lambda *x: addr_info_list))
        self.useFixture(fixtures.MonkeyPatch(
            "senlin.api.common.wsgi.time.time",
            mock.Mock(side_effect=[0, 1, 5, 10, 20, 35])))
        wsgi.cfg.CONF.senlin_api.cert_file = '/etc/ssl/cert'
        wsgi.cfg.CONF.senlin_api.key_file = '/etc/ssl/key'
        wsgi.cfg.CONF.senlin_api.ca_file = '/etc/ssl/ca_cert'
        wsgi.cfg.CONF.senlin_api.tcp_keepidle = 600 
Example #11
Source File: base.py    From oslo.db with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        """Run before each test method to initialize test environment."""

        super(TestCase, self).setUp()
        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

        self.useFixture(fixtures.NestedTempfile())
        self.useFixture(fixtures.TempHomeDir())

        if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))

        self.log_fixture = self.useFixture(fixtures.FakeLogger()) 
Example #12
Source File: base.py    From sgx-kms with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        self.LOG.info('Starting: %s', self._testMethodName)
        super(TestCase, self).setUp()

        self.client = client.BarbicanClient()

        stdout_capture = os.environ.get('OS_STDOUT_CAPTURE')
        stderr_capture = os.environ.get('OS_STDERR_CAPTURE')
        log_capture = os.environ.get('OS_LOG_CAPTURE')

        if ((stdout_capture and stdout_capture.lower() == 'true') or
                stdout_capture == '1'):
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if ((stderr_capture and stderr_capture.lower() == 'true') or
                stderr_capture == '1'):
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
        if ((log_capture and log_capture.lower() == 'true') or
                log_capture == '1'):
            self.useFixture(fixtures.LoggerFixture(nuke_handlers=False,
                                                   format=self.log_format,
                                                   level=logging.DEBUG)) 
Example #13
Source File: base.py    From barbican with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        self.LOG.info('Starting: %s', self._testMethodName)
        super(TestCase, self).setUp()

        self.client = client.BarbicanClient()

        stdout_capture = os.environ.get('OS_STDOUT_CAPTURE')
        stderr_capture = os.environ.get('OS_STDERR_CAPTURE')
        log_capture = os.environ.get('OS_LOG_CAPTURE')

        if ((stdout_capture and stdout_capture.lower() == 'true') or
                stdout_capture == '1'):
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if ((stderr_capture and stderr_capture.lower() == 'true') or
                stderr_capture == '1'):
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
        if ((log_capture and log_capture.lower() == 'true') or
                log_capture == '1'):
            self.useFixture(fixtures.LoggerFixture(nuke_handlers=False,
                                                   format=self.log_format,
                                                   level=logging.DEBUG)) 
Example #14
Source File: base.py    From python-tripleoclient with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        """Run before each test method to initialize test environment."""

        super(TestCase, self).setUp()
        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

        self.useFixture(fixtures.NestedTempfile())
        self.temp_homedir = self.useFixture(fixtures.TempHomeDir()).path

        if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))

        self.log_fixture = self.useFixture(fixtures.FakeLogger()) 
Example #15
Source File: base.py    From tosca-parser with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        """Run before each test method to initialize test environment."""

        super(TestCase, self).setUp()
        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

        self.useFixture(fixtures.NestedTempfile())
        self.useFixture(fixtures.TempHomeDir())

        if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))

        self.log_fixture = self.useFixture(fixtures.FakeLogger()) 
Example #16
Source File: base.py    From heat-translator with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        """Run before each test method to initialize test environment."""

        super(TestCase, self).setUp()
        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

        self.useFixture(fixtures.NestedTempfile())
        self.useFixture(fixtures.TempHomeDir())

        if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))

        self.log_fixture = self.useFixture(fixtures.FakeLogger()) 
Example #17
Source File: output.py    From oslotest with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(CaptureOutput, self).setUp()
        if self.do_stdout:
            self._stdout_fixture = fixtures.StringStream('stdout')
            self.stdout = self.useFixture(self._stdout_fixture).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', self.stdout))
        if self.do_stderr:
            self._stderr_fixture = fixtures.StringStream('stderr')
            self.stderr = self.useFixture(self._stderr_fixture).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', self.stderr)) 
Example #18
Source File: base.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def _capture_stdout(self):
        self.useFixture(fixtures.MonkeyPatch('sys.stdout', moves.StringIO()))
        return sys.stdout 
Example #19
Source File: test_processutils.py    From oslo.concurrency with Apache License 2.0 5 votes vote down vote up
def test_discard_warnings(self):
        self.useFixture(fixtures.MonkeyPatch(
            'oslo_concurrency.processutils.execute', fake_execute))
        o, e = processutils.trycmd('this is a command'.split(' '),
                                   discard_warnings=True)
        self.assertIsNotNone(o)
        self.assertEqual('', e) 
Example #20
Source File: test_processutils.py    From oslo.concurrency with Apache License 2.0 5 votes vote down vote up
def test_keep_warnings_from_raise(self):
        self.useFixture(fixtures.MonkeyPatch(
            'oslo_concurrency.processutils.execute', fake_execute_raises))
        o, e = processutils.trycmd('this is a command'.split(' '),
                                   discard_warnings=True)
        self.assertIsNotNone(o)
        self.assertNotEqual('', e) 
Example #21
Source File: test_processutils.py    From oslo.concurrency with Apache License 2.0 5 votes vote down vote up
def test_keep_warnings(self):
        self.useFixture(fixtures.MonkeyPatch(
            'oslo_concurrency.processutils.execute', fake_execute))
        o, e = processutils.trycmd('this is a command'.split(' '))
        self.assertNotEqual('', o)
        self.assertNotEqual('', e) 
Example #22
Source File: test_nm_repository.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def setUpClass(cls):
        engine = create_engine('sqlite://')

        qry = open('monasca_api/tests/sqlite_alarm.sql', 'r').read()
        sconn = engine.raw_connection()
        c = sconn.cursor()
        c.executescript(qry)
        sconn.commit()
        c.close()
        cls.engine = engine

        def _fake_engine_from_config(*args, **kw):
            return cls.engine
        cls.fixture = fixtures.MonkeyPatch(
            'sqlalchemy.create_engine', _fake_engine_from_config)
        cls.fixture.setUp()

        metadata = MetaData()
        cls.nm = models.create_nm_model(metadata)
        cls._delete_nm_query = delete(cls.nm)
        cls._insert_nm_query = (insert(cls.nm)
                                .values(
                                    id=bindparam('id'),
                                    tenant_id=bindparam('tenant_id'),
                                    name=bindparam('name'),
                                    type=bindparam('type'),
                                    address=bindparam('address'),
                                    period=bindparam('period'),
                                    created_at=bindparam('created_at'),
                                    updated_at=bindparam('updated_at'))) 
Example #23
Source File: base.py    From shade with Apache License 2.0 5 votes vote down vote up
def setUp(self, cloud_config_fixture='clouds.yaml'):

        super(TestCase, self).setUp(cloud_config_fixture=cloud_config_fixture)
        self.session_fixture = self.useFixture(fixtures.MonkeyPatch(
            'os_client_config.cloud_config.CloudConfig.get_session',
            mock.Mock())) 
Example #24
Source File: test_barbican_manage.py    From barbican with Apache License 2.0 5 votes vote down vote up
def _main_test_helper(self, argv, func_name=None, *exp_args, **exp_kwargs):
        self.useFixture(fixtures.MonkeyPatch('sys.argv', argv))
        manager.main()
        func_name.assert_called_once_with(*exp_args, **exp_kwargs) 
Example #25
Source File: fixture.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def _setUp(self):
        # don't actually start RPC listeners when testing
        mock.patch.object(rpc.Connection, 'consume_in_threads',
                          return_value=[]).start()
        self.useFixture(fixtures.MonkeyPatch(
            'oslo_messaging.Notifier', fake_notifier.FakeNotifier))

        self.messaging_conf = conffixture.ConfFixture(CONF)
        self.messaging_conf.transport_url = 'fake:/'
        # NOTE(russellb) We want all calls to return immediately.
        self.messaging_conf.response_timeout = 0
        self.useFixture(self.messaging_conf)

        self.addCleanup(rpc.cleanup)
        rpc.init(CONF) 
Example #26
Source File: test_barbican_manage.py    From barbican with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(TestBarbicanManageBase, self).setUp()

        def clear_conf():
            manager.CONF.reset()
            manager.CONF.unregister_opt(manager.category_opt)
        clear_conf()
        self.addCleanup(clear_conf)

        self.useFixture(fixtures.MonkeyPatch(
            'oslo_log.log.setup', lambda barbican_test, version='test': None))
        manager.CONF.set_override('sql_connection', 'mockdburl') 
Example #27
Source File: test_shell.py    From python-magnumclient with Apache License 2.0 5 votes vote down vote up
def make_env(self, exclude=None, fake_env=FAKE_ENV):
        if 'OS_AUTH_URL' in fake_env:
            fake_env.update({'OS_AUTH_URL': self.AUTH_URL})
        env = dict((k, v) for k, v in fake_env.items() if k != exclude)
        self.useFixture(fixtures.MonkeyPatch('os.environ', env)) 
Example #28
Source File: osc_utils.py    From python-magnumclient with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        testtools.TestCase.setUp(self)

        if (os.environ.get("OS_STDOUT_CAPTURE") == "True" or
                os.environ.get("OS_STDOUT_CAPTURE") == "1"):
            stdout = self.useFixture(fixtures.StringStream("stdout")).stream
            self.useFixture(fixtures.MonkeyPatch("sys.stdout", stdout))

        if (os.environ.get("OS_STDERR_CAPTURE") == "True" or
                os.environ.get("OS_STDERR_CAPTURE") == "1"):
            stderr = self.useFixture(fixtures.StringStream("stderr")).stream
            self.useFixture(fixtures.MonkeyPatch("sys.stderr", stderr)) 
Example #29
Source File: fixture.py    From oslo.i18n with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(PrefixLazyTranslation, self).setUp()
        self.useFixture(ToggleLazy(True))
        self.useFixture(fixtures.MonkeyPatch(
            'oslo_i18n._gettextutils.get_available_languages',
            lambda *x, **y: self.languages))
        self.useFixture(fixtures.MonkeyPatch(
            'oslo_i18n.get_available_languages',
            lambda *x, **y: self.languages))
        self.useFixture(fixtures.MonkeyPatch('gettext.translation',
                                             _prefix_translations))
        self.useFixture(fixtures.MonkeyPatch('locale.getdefaultlocale',
                                             lambda *x, **y: self.locale)) 
Example #30
Source File: test_api_validation.py    From karbor with Apache License 2.0 5 votes vote down vote up
def test_build_regex_range(self):

        def _get_all_chars():
            for i in range(0x7F):
                yield six.unichr(i)

        self.useFixture(fixtures.MonkeyPatch(
            'karbor.api.validation.parameter_types._get_all_chars',
            _get_all_chars))

        r = parameter_types._build_regex_range(ws=False)
        self.assertEqual(re.escape('!') + '-' + re.escape('~'), r)

        # if we allow whitespace the range starts earlier
        r = parameter_types._build_regex_range(ws=True)
        self.assertEqual(re.escape(' ') + '-' + re.escape('~'), r)

        # excluding a character will give us 2 ranges
        r = parameter_types._build_regex_range(ws=True, exclude=['A'])
        self.assertEqual(re.escape(' ') + '-' + re.escape('@') +
                         'B' + '-' + re.escape('~'), r)

        # inverting which gives us all the initial unprintable characters.
        r = parameter_types._build_regex_range(ws=False, invert=True)
        self.assertEqual(re.escape('\x00') + '-' + re.escape(' '), r)

        # excluding characters that create a singleton. Naively this would be:
        # ' -@B-BD-~' which seems to work, but ' -@BD-~' is more natural.
        r = parameter_types._build_regex_range(ws=True, exclude=['A', 'C'])
        self.assertEqual(re.escape(' ') + '-' + re.escape('@') +
                         'B' + 'D' + '-' + re.escape('~'), r)

        # ws=True means the positive regex has printable whitespaces,
        # so the inverse will not. The inverse will include things we
        # exclude.
        r = parameter_types._build_regex_range(
            ws=True, exclude=['A', 'B', 'C', 'Z'], invert=True)
        self.assertEqual(re.escape('\x00') + '-' + re.escape('\x1f') +
                         'A-CZ', r)