def test_import_errors_1(self): if PY3: message = "No module named 'textfixtures'" else: message = 'No module named textfixtures.foo.bar' exception = ModuleNotFoundError if PY_36_PLUS else ImportError with ShouldRaise(exception(message)): import textfixtures.foo.bar
def test_example_bad_returncode(self): # set up Popen.set_command('svn ls -R foo', stdout=b'o', stderr=b'e', returncode=1) # testing of error with ShouldRaise(RuntimeError('something bad happened')): my_func()
def test_load_single(self): self.server.add(url='/TEST', params='method=GET&id=xx', response='{"data": {"ID": "yyy", "fieldOne": 1}}') obj = self.session.load(self.api.TestObject, 'xx') self.assertTrue(isinstance(obj, self.api.TestObject)) compare(obj.id, 'yyy') compare(obj.field_one, 1) with ShouldRaise(FieldNotLoaded('fieldTwo')): obj.field_two
def test_warn_not_expected(self): with ShouldRaise( AssertionError("sequence not as expected:\n\n" "same:\n[]\n\n" "expected:\n[]\n\n" "actual:\n[UserWarning('foo',)]")): with warnings.catch_warnings(record=True) as backstop: with ShouldNotWarn(): warnings.warn('foo') compare(len(backstop), expected=0)
def test_not_there(self): o = object() @replace('testfixtures.tests.sample1.bad',o) def test_something(r): pass # pragma: no cover with ShouldRaise(AttributeError("Original 'bad' not found")): test_something()
def test_supply_comparer(self): def compare_dict(x, y, context): self.assertEqual(x, {1:1}) self.assertEqual(y, {2:2}) self.assertEqual(context.get_option('foo'), 'bar') return 'not equal' with ShouldRaise(AssertionError('not equal')): compare({1:1}, {2:2}, foo='bar', comparers={dict: compare_dict})
def test_with_no_exception_when_expected(self): try: with ShouldRaise(ValueError('foo')): pass except AssertionError as e: self.assertEqual( e, C(AssertionError("None raised, ValueError('foo',) expected"))) else: self.fail('No exception raised!')
def test_minimal_bad(self): with ShouldRaise( AssertionError("sequence not as expected:\n\n" "same:\n[]\n\n" "expected:\n" "[<C(failed):" + warn_module + ".DeprecationWarning>wrong type</C>]\n\n" "actual:\n[UserWarning('foo',)]")): with ShouldWarn(DeprecationWarning): warnings.warn('foo')
def test_arguments(self): # the first parameter to declarative_base :-) engine = object() if PY2: text = 'declarative_base() takes exactly 0 arguments (1 given)' else: text = 'declarative_base() takes 0 positional arguments but 1 was given' with ShouldRaise(TypeError(text)): declarative_base(engine)
def test_api_error(self): self.server.add( url='/user', params='action=getApiKey&method=PUT&username=u&password=p', response='{"error": "your foo went bar"}') with ShouldRaise(WorkfrontAPIError(u'your foo went bar', 200)): with OutputCapture() as output: main() output.compare("")
def test_checker_re(self): self.assertIsNotNone(namespace.valid_checker_id("validname")) self.assertIsNotNone(namespace.valid_checker_id("valid_name_1")) with ShouldRaise( NameError("Id 'Invalidname' is not allowed for " "checker")): namespace.valid_checker_id("Invalidname") with ShouldRaise( NameError("Id '_invalidname' is not allowed for " "checker")): namespace.valid_checker_id("_invalidname") with ShouldRaise( NameError("Id 'invalidname_' is not allowed for " "checker")): namespace.valid_checker_id("invalidname_") with ShouldRaise( NameError("Id '3invalidname' is not allowed for " "checker")): namespace.valid_checker_id("3invalidname")
def test_not_as_expected(self): if PY2: message = ('ValidationError([u"d\'oh"]) (expected) != ' 'ValidationError([u\'nuts\']) (raised)') else: message = ('ValidationError(["d\'oh"]) (expected) != ' 'ValidationError([\'nuts\']) (raised)') with ShouldAssert(message): with ShouldRaise(ValidationError("d'oh")): raise ValidationError("nuts")
def test_add_datetime_supplied(self,t): from datetime import datetime t.add(d(2002,1,1,1)) t.add(datetime(2002,1,1,2)) compare(datetime.now(),d(2002,1,1,1,0,0)) compare(datetime.now(),d(2002,1,1,2,0,0)) with ShouldRaise(ValueError( 'Cannot add datetime with tzinfo set' )): t.add(d(2001, 1, 1, tzinfo=TestTZInfo()))
def test_multiple_discriminator(self): with ShouldRaise( TypeError( "Multiple discriminators are not supported, found: ['d1', 'd2']" )): class Normal(Record): d1 = Discriminator('N') d2 = Discriminator('M')
def test_bad_args(self): mltprsm = MultiprocessingManager() mltprsm.append(exeption_raising_func, {'x': 0}) exp = IOError( "The function 'exeption_raising_func' of " "'slidelint.tests.modules.linter.test_modules' module raised an " "Exception:\nexeption_raising_func() got an unexpected keyword" " argument 'x'", ) with ShouldRaise(exp): [i for i in mltprsm]
def test_invalid_poll(self): Popen = MockPopen() Popen.set_command('bar') process = Popen('bar') if PY2: text = 'poll() takes exactly 1 argument (2 given)' else: text = 'poll() takes 1 positional argument but 2 were given' with ShouldRaise(TypeError(text)): process.poll('moo')
def test_no_warn_not_expected(self): with ShouldRaise( AssertionError("sequence not as expected:\n\n" "same:\n[]\n\n" "expected:\n[\n <C:" + warn_module + ".UserWarning>\n" " args:('foo',)\n </C>]" "\n\nactual:\n[]")): with ShouldWarn(UserWarning('foo')): pass
def test_request_with_dodgy_absolute_url(self): session = Session('test') with ShouldRaise( TypeError( 'url not for this session: ' 'https://bad.example.com/attask/api/unsupported/some/url') ): session.request( 'GET', 'https://bad.example.com/attask/api/unsupported/some/url')
def test_with_no_exception_when_neither_expected(self): try: with ShouldRaise(): pass except AssertionError as e: self.assertEqual( e, C(AssertionError("No exception raised!")) ) else: self.fail('No exception raised!')
def test_push_empty(self): config = Config({'x': 1, 'y': 2}) compare(config.x, expected=1) compare(config.y, expected=2) config.push(Config({'x': 3}), empty=True) compare(config.x, expected=3) with ShouldRaise(AttributeError('y')): config.y config.pop() compare(config.x, expected=1) compare(config.y, expected=2)
def test_resumable_file_update_raise_etag(self, mock_resp, sess): mock_resp.status_code = 412 mock_resp.content = "Precondition error" sess.return_value = mock_resp fd, temp_path = tempfile.mkstemp() with os.fdopen(fd, 'w') as f: f.write("File content is here") with ShouldRaise(GoogleApiError(code=412, message='Precondition error')): self.ar.resumable_file_update('id_b', temp_path, etag="hi")
def test_http_error(self): # somewhat hypothetical, error is usually in the return json session = Session('test') self.server.add( url='/login', params='method=GET', response=MockHTTPError('{"data": "foo"}', 500), ) with ShouldRaise(WorkfrontAPIError('Unknown error, check log', 500)): session.get('/login') self.server.assert_called(times=1)
def test_exeption(self): mltprsm = MultiprocessingManager() mltprsm.append(exeption_raising_func, {'arg': 0}) exp = IOError(StringComparison( "The function 'exeption_raising_func' of " "'slidelint.tests.modules.linter.test_modules' module" " raised an Exception:\n" "integer division or modulo by zero\n" ".*")) with ShouldRaise(exp): [i for i in mltprsm]
def test_write_unicode_bad(self): if PY_35_PLUS: expected = TypeError("a bytes-like object is required, not 'str'") elif PY3: expected = TypeError("'str' does not support the buffer interface") else: expected = UnicodeDecodeError('ascii', '\xa3', 0, 1, 'ordinal not in range(128)') with TempDirectory() as d: with ShouldRaise(expected): d.write('test.file', Unicode('\xa3'))
def test_not_in_git_repo(self, dir, capfd): with Replace('os.environ.TAG', 'v1.2.3', strict=False): with ShouldRaise(CalledProcessError): version_not_tagged() out, err = capfd.readouterr() compare(out, expected='$ git remote -v\n') compare( err.lower(), expected= 'fatal: not a git repository (or any of the parent directories): .git\n' )
def test_default_expection_handling(self): # raises class MyHandler(Handler): @handles(self.parser.ARecord) def handle_ARecord(self, source, line_no, rec): pass handler = MyHandler() with ShouldRaise(fixed.UnknownRecordType('C', 'YY')): handler.handle(['CYY'])
def test_patterns_invalid(self): msg = ("Invalid file patterns in key 'include': must be a string or " 'list of strings') with ShouldRaise(ValueError(msg)): self.run_hook(functions={ 'MyFunction': { 'path': 'test', 'include': {'invalid': 'invalid'} } })
def test_duplicate_label_runner_next_add(self): m = Mock() runner = Runner() runner.add(m.job1, label='label') with ShouldRaise(ValueError( "'label' already points to "+repr(m.job1)+" requires() " "returns_result_type() <-- label" )): runner.add(m.job2, label='label') verify(runner, (m.job1, {'label'}), )
def test_inconsisent_discriminator_length(self): with ShouldRaise( TypeError( "Inconsistent discriminators: [<Discriminator 'A' (0-1)>, " "<Discriminator 'BB' (0-2)>]")): class TheParser(Parser): class ARecord(Record): prefix = Discriminator('A') class BRecord(Record): prefix = Discriminator('BB')
def test_exception(self): with ShouldRaise(Exception('foo')): with DatabaseHandler(self.db_path) as handler: handler.conn.execute('insert into notes values (?, ?)', ('test.txt', 'a note')) raise Exception('foo') # check the row not inserted and the transaction was rolled back curs = handler.conn.cursor() curs.execute('select * from notes') self.assertEqual(curs.fetchall(), []) # check the error was logged self.log.check(('root', 'ERROR', 'Something went wrong'))