我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用testtools.TestCase()。
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()) environ_enabled = (lambda var_name: strutils.bool_from_string(os.environ.get(var_name))) if environ_enabled('OS_STDOUT_CAPTURE'): stdout = self.useFixture(fixtures.StringStream('stdout')).stream self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout)) if environ_enabled('OS_STDERR_CAPTURE'): stderr = self.useFixture(fixtures.StringStream('stderr')).stream self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr)) self.start = timeutils.utcnow()
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())
def setUp(self): super(TestCase, self).setUp() if self.api_class is None: app = falcon.API() else: app = self.api_class() # NOTE(kgriffs): Don't use super() to avoid triggering # unittest.TestCase.__init__() TestClient.__init__(self, app) # Reset to simulate "restarting" the WSGI container falcon.request._maybe_wrap_wsgi_stream = True # NOTE(warsaw): Pythons earlier than 2.7 do not have a # self.assertIn() method, so use this compatibility function # instead.
def __call__(self, func_or_cls): condition = self.condition reason = self.reason if inspect.isfunction(func_or_cls): @six.wraps(func_or_cls) def wrapped(*args, **kwargs): if condition: raise testtools.TestCase.skipException(reason) return func_or_cls(*args, **kwargs) return wrapped elif inspect.isclass(func_or_cls): orig_func = getattr(func_or_cls, 'setUp') @six.wraps(orig_func) def new_func(self, *args, **kwargs): if condition: raise testtools.TestCase.skipException(reason) orig_func(self, *args, **kwargs) func_or_cls.setUp = new_func return func_or_cls else: raise TypeError('skipUnless can be used only with functions or ' 'classes')
def test_catches_generator_tests(self): class BrokenTests(TestCase): run_tests_with = self.executor def test(self): yield None test = BrokenTests("test") result = test.run() self.assertThat(result.errors, HasLength(1)) self.assertThat(result.errors[0], MatchesListwise(( Is(test), DocTestMatches( """\ ...InvalidTest: Test returned a generator. Should it be decorated with inlineCallbacks? """ ), )))
def patch( self, obj, attribute=None, value=mock.sentinel.unset) -> MagicMock: """Patch `obj.attribute` with `value`. If `value` is unspecified, a new `MagicMock` will be created and patched-in instead. Its ``__name__`` attribute will be set to `attribute` or the ``__name__`` of the replaced object if `attribute` is not given. This is a thin customisation of `testtools.TestCase.patch`, so refer to that in case of doubt. :return: The patched-in object. """ # If 'attribute' is None, assume 'obj' is a 'fully-qualified' object, # and assume that its __module__ is what we want to patch. For more # complex use cases, the two-parameter 'patch' will still need to # be used. if attribute is None: attribute = obj.__name__ obj = import_module(obj.__module__) if value is mock.sentinel.unset: value = MagicMock(__name__=attribute) super(MAASTestCase, self).patch(obj, attribute, value) return value
def skip_because(*args, **kwargs): """A decorator useful to skip tests hitting known bugs @param bug: bug number causing the test to skip @param condition: optional condition to be True for the skip to have place @param interface: skip the test if it is the same as self._interface """ def decorator(f): @functools.wraps(f) def wrapper(self, *func_args, **func_kwargs): skip = False if "condition" in kwargs: if kwargs["condition"] is True: skip = True elif "interface" in kwargs: if kwargs["interface"] == self._interface: skip = True else: skip = True if "bug" in kwargs and skip is True: msg = "Skipped until Bug: %s is resolved." % kwargs["bug"] raise testtools.TestCase.skipException(msg) return f(self, *func_args, **func_kwargs) return wrapper return decorator
def requires_ext(*args, **kwargs): """A decorator to skip tests if an extension is not enabled @param extension @param service """ def decorator(func): @functools.wraps(func) def wrapper(*func_args, **func_kwargs): if not is_extension_enabled(kwargs['extension'], kwargs['service']): msg = "Skipped because %s extension: %s is not enabled" % ( kwargs['service'], kwargs['extension']) raise testtools.TestCase.skipException(msg) return func(*func_args, **func_kwargs) return wrapper return decorator
def setUp(self): super(TestCase, self).setUp() stdout = self.useFixture(fixtures.StringStream('stdout')).stream self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout)) stderr = self.useFixture(fixtures.StringStream('stderr')).stream self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
def setUp(self): """Base setup provides container data back individual tests.""" super(TestCase, self).setUp() self.container_setup_error = _container.error self.session = requests.Session() if not self.container_setup_error: data = _container.container_data self.service_ip = data['NetworkSettings']['IPAddress'] self.url = 'http://{}:7780'.format(self.service_ip) self.session.headers[HEADER_PROJECT] = FAKE_DATA_GEN_PROJECT_ID self.session.headers[HEADER_USERNAME] = FAKE_DATA_GEN_USERNAME self.session.headers[HEADER_TOKEN] = FAKE_DATA_GEN_TOKEN self.root_headers = copy.deepcopy(self.session.headers) self.root_headers.update(get_root_headers()) setup_database(self.service_ip)
def tearDown(self): super(TestCase, self).tearDown()
def setUp(self): super(TestCase, self).setUp() self.addCleanup(mock.patch.stopall) self.context = make_context(auth_token='fake-token', user='fake-user', tenant='fake-tenant', is_admin=True, is_admin_project=True)
def setUp(self): super(TestCase, self).setUp() self.inject(steps.login, self)
def test_get_token_invalid_credentials(self): self.requests_mock.register_uri('GET', self.LOGIN_URL, status_code=401, text='body') with super(testtools.TestCase, self).assertRaises(ECSClientException) as error: self.client.get_token() exception = error.exception self.assertIsNone(self.client._token_request.token) self.assertEqual(exception.message, 'Invalid username or password') self.assertEqual(exception.http_response_content, 'body') self.assertEqual(exception.http_status, 401) self.assertEqual(self.requests_mock.last_request.method, 'GET') self.assertEqual(self.requests_mock.last_request.url, self.LOGIN_URL) self.assertEqual(self.requests_mock.last_request.headers['authorization'], _basic_auth_str('someone', 'password'))
def test_get_new_token_should_throw_ecsclientexception_500(self): self.requests_mock.register_uri('GET', 'https://127.0.0.1:4443/login', status_code=http_client.INTERNAL_SERVER_ERROR) with super(testtools.TestCase, self).assertRaises(ECSClientException) as error: self.token_request.get_new_token() exception = error.exception self.assertEqual(exception.http_status, http_client.INTERNAL_SERVER_ERROR)
def test_get_new_token_should_throw_ecsclientexception_401(self): self.requests_mock.register_uri('GET', 'https://127.0.0.1:4443/login', status_code=http_client.UNAUTHORIZED) with super(testtools.TestCase, self).assertRaises(ECSClientException) as error: self.token_request.get_new_token() exception = error.exception self.assertEqual(exception.http_status, http_client.UNAUTHORIZED)
def test_get_new_token_cache_invalid_token_path(self, mock_isdir): self.requests_mock.register_uri('GET', 'https://127.0.0.1:4443/login', headers={'X-SDS-AUTH-TOKEN': 'NEW-TOKEN-123'}) mock_isdir.side_effect = lambda dir_: dir_ != '/foo/bar' self.token_request.cache_token = True self.token_request.token_path = '/foo/bar/token.txt' with super(testtools.TestCase, self).assertRaises(ECSClientException) as error: self.token_request.get_new_token() exception = error.exception self.assertEqual(exception.message, "Token directory not found")
def test_token_validation_500(self, mock_get_existing_token): self.requests_mock.register_uri('GET', 'https://127.0.0.1:4443/user/whoami', status_code=http_client.INTERNAL_SERVER_ERROR) mock_get_existing_token.return_value = 'EXISTING-TOKEN-123' with super(testtools.TestCase, self).assertRaises(ECSClientException) as error: self.token_request.get_token() exception = error.exception self.assertEqual(exception.message, "Token validation error (Code: 500)") self.assertEqual(exception.http_status, http_client.INTERNAL_SERVER_ERROR)
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))
def setUp(self): """Run before each test method to initialize test environment.""" super(TestCase, self).setUp() self.useFixture(Timeout( os.environ.get('OS_TEST_TIMEOUT', 0))) self.useFixture(OutputStreamCapture())
def setUp(self): super(TestCase, self).setUp() if os.environ.get('OS_STDOUT_CAPTURE') in self.true: stdout = self.useFixture(fixtures.StringStream('stdout')).stream self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout)) if os.environ.get('OS_STDERR_CAPTURE') in self.true: stderr = self.useFixture(fixtures.StringStream('stderr')).stream self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr)) if (os.environ.get('OS_LOG_CAPTURE') != 'False' and os.environ.get('OS_LOG_CAPTURE') != '0'): self.useFixture(fixtures.LoggerFixture(nuke_handlers=False, level=None))
def setUp(self): super(TestCase, self).setUp() self.app = main.app.test_client()
def patchobject(self, obj, attr, **kwargs): mockfixture = self.useFixture(fixtures.MockPatchObject(obj, attr, **kwargs)) return mockfixture.mock # NOTE(pshchelo): this overrides the testtools.TestCase.patch method # that does simple monkey-patching in favor of mock's patching
def setUp(self): super(TestCase, self).setUp() 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))
def setUp(self): super(TestCase, self).setUp() self.addCleanup(mock.patch.stopall) app.app.config["TESTING"] = True self.app = app.app.test_client()
def setUp(self): super(TestCase, self).setUp()
def setUp(self): super(TestCase, self).setUp() self.addCleanup(mock.patch.stopall) plugins.load()
def setUp(self): """Run before each test method to initialize test environment.""" super(TestCase, self).setUp() # Timeout test_timeout = int(os.environ.get('OS_TEST_TIMEOUT', 0)) try: test_timeout = int(test_timeout * self.TIMEOUT_SCALING_FACTOR) except ValueError: # If timeout value is invalid do not set a timeout. test_timeout = 0 if test_timeout > 0: # gentle timeout = raise TimeoutException self.useFixture(fixtures.Timeout(test_timeout, gentle=True)) # Nest all temporary files and directories inside another directory self.useFixture(fixtures.NestedTempfile()) # Create a temporary directory and set it as $HOME self.useFixture(fixtures.TempHomeDir()) # Capture STDOUT if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES: stdout = self.useFixture(fixtures.StringStream('stdout')).stream self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout)) # Capture STDERR if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES: stderr = self.useFixture(fixtures.StringStream('stderr')).stream self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
def setUp(self): super(TestCase, self).setUp() self.addCleanup(mock.patch.stopall)
def setUp(self): """Run before each test method to initialize test environment.""" super(TestCase, self).setUp() self.useFixture(conf_fixture.ConfFixture(CONF)) mox_fixture = self.useFixture(moxstubout.MoxStubout()) self.mox = mox_fixture.mox self.stubs = mox_fixture.stubs self.policy = self.useFixture(policy_fixture.PolicyFixture()) if self.USES_DB: self.useFixture(masakari_fixtures.Database()) else: self.useFixture(masakari_fixtures.DatabasePoisonFixture())
def setup_example(self): try: # TesttoolsTestCase starts without this attribute set at all. Get # us back to that state. It won't be set at all on the first # setup_example call, nor if the previous run didn't have a failed # expectation. del self.force_failure except AttributeError: pass
def setUp(self): super(TestCase, self).setUp() 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)) mox_fixture = self.useFixture(moxstubout.MoxStubout()) self.mox = mox_fixture.mox self.stubs = mox_fixture.stubs
def is_extension_enabled(extension_name, service): """A function that will check the list of enabled extensions from config """ config_dict = { 'compute': CONF.compute_feature_enabled.api_extensions, 'compute_v3': CONF.compute_feature_enabled.api_v3_extensions, 'volume': CONF.volume_feature_enabled.api_extensions, 'network': CONF.network_feature_enabled.api_extensions, 'object': CONF.object_storage_feature_enabled.discoverable_apis, } if config_dict[service][0] == 'all': return True if extension_name in config_dict[service]: return True return False # there is a mis-match between nose and testtools for older pythons. # testtools will set skipException to be either # unittest.case.SkipTest, unittest2.case.SkipTest or an internal skip # exception, depending on what it can find. Python <2.7 doesn't have # unittest.case.SkipTest; so if unittest2 is not installed it falls # back to the internal class. # # The current nose skip plugin will decide to raise either # unittest.case.SkipTest or its own internal exception; it does not # look for unittest2 or the internal unittest exception. Thus we must # monkey-patch testtools.TestCase.skipException to be the exception # the nose skip plugin expects. # # However, with the switch to testr nose may not be available, so we # require you to opt-in to this fix with an environment variable. # # This is temporary until upstream nose starts looking for unittest2 # as testtools does; we can then remove this and ensure unittest2 is # available for older pythons; then nose and testtools will agree # unittest2.case.SkipTest is the one-true skip test exception. # # https://review.openstack.org/#/c/33056 # https://github.com/nose-devs/nose/pull/699
def setUp(self): super(TestCase, self).setUp() stdout = self.useFixture(fixtures.StringStream('stdout')).stream self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout)) stderr = self.useFixture(fixtures.StringStream('stderr')).stream self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr)) self.useFixture(fixtures.LoggerFixture(nuke_handlers=False, level=None))
def _reset_everything(self): rpc.TRANSPORT = self.trans rpc.NOTIFICATION_TRANSPORT = self.noti_trans rpc.NOTIFIER = self.noti rpc.ALLOWED_EXMODS = self.all_mods rpc.EXTRA_EXMODS = self.ext_mods # We can't import nova.test.TestCase because that sets up an RPCFixture # that pretty much nullifies all of this testing
def setUp(self): """Run before each test method to initialize test environment.""" super(TestCase, self).setUp() self.useFixture(obj_fixtures.Timeout( os.environ.get('OS_TEST_TIMEOUT', 0), self.TIMEOUT_SCALING_FACTOR)) self.useFixture(fixtures.NestedTempfile()) self.useFixture(fixtures.TempHomeDir()) self.useFixture(obj_fixtures.TranslationFixture()) self.useFixture(logging_error.get_logging_handle_error_fixture()) self.useFixture(obj_fixtures.OutputStreamCapture()) self.useFixture(obj_fixtures.StandardLogging()) # NOTE(sdague): because of the way we were using the lock # wrapper we eneded up with a lot of tests that started # relying on global external locking being set up for them. We # consider all of these to be *bugs*. Tests should not require # global external locking, or if they do, they should # explicitly set it up themselves. # # The following REQUIRES_LOCKING class parameter is provided # as a bridge to get us there. No new tests should be added # that require it, and existing classes and tests should be # fixed to not need it. if self.REQUIRES_LOCKING: lock_path = self.useFixture(fixtures.TempDir()).path self.fixture = self.useFixture( config_fixture.Config(lockutils.CONF)) self.fixture.config(lock_path=lock_path, group='oslo_concurrency') # NOTE(blk-u): WarningsFixture must be after the Database fixture # because sqlalchemy-migrate messes with the warnings filters. self.useFixture(obj_fixtures.WarningsFixture()) mox_fixture = self.useFixture(moxstubout.MoxStubout()) self.mox = mox_fixture.mox self.stubs = mox_fixture.stubs self.addCleanup(self._clear_attrs) self.useFixture(fixtures.EnvironmentVariable('http_proxy'))