def test_raises(self): def test_z(): return 'replacement z' compare(sample1.z(), 'original z') @replace('testfixtures.tests.sample1.z', test_z) def test_something(): compare(sample1.z(), 'replacement z') raise Exception() compare(sample1.z(), 'original z') with ShouldRaise(): test_something() compare(sample1.z(), 'original z')
def test_assert_keyerror_raised(self): expected = "KeyError('foo',) raised, AttributeError('foo',) expected" class Dodgy(dict): def __getattr__(self, name): # NB: we forgot to turn our KeyError into an attribute error return self[name] try: with ShouldRaise(AttributeError('foo')): Dodgy().foo except AssertionError as e: self.assertEqual( C(AssertionError(expected)), e ) else: self.fail('No exception raised!')
def test_resolve_unresolvable(): dist = JohnnyDist('distX') data = dist.serialise(recurse=False, fields=['project_name', 'summary', 'requires']) assert data == [{ 'project_name': 'distX', 'summary': 'Dist with unresolvable dependencies', 'requires': ['distC (<=0.1)', 'distC (>0.2)'], # this installation requirement can not be resolved }] gen = flatten_deps(dist) assert next(gen) is dist with ShouldRaise( DistributionNotFound( 'No matching distribution found for distc<=0.1,>0.2')): next(gen)
def test_how_to_create(self): register_session('sqlite://', transactional=False) # at this stage we have no tables session = get_session() session.add(self.Model(name='foo')) # so we get an error with ShouldRaise(OperationalError): session.commit() # ...which we then need to abort: session.rollback() # if we know we have no tables, we can do: self.Base.metadata.create_all(session.bind) # now we can commit: session.add(self.Model(name='foo')) session.commit() # ...and get stuff back: self.assertEqual(1,session.query(self.Model).count())
def test_identical_reprs(self): class AnnoyingException(Exception): def __init__(self, **kw): self.other = kw.get('other') try: with ShouldRaise(AnnoyingException(other='bar')): raise AnnoyingException(other='baz') except AssertionError as e: print repr(e) self.assertEqual( C( AssertionError( "AnnoyingException() raised, AnnoyingException() expected, attributes differ:\n other:'bar' != 'baz'" )), e) else: self.fail('No exception raised!')
def test_correct_url(self): good_checks = [ ["https://deluded-musings.fanficauthors.net/A_Matter_of_Perspective/Mirror_Mirror/", "https://deluded-musings.fanficauthors.net/A_Matter_of_Perspective/index"], ["https://deluded-musings.fanficauthors.net/A_Matter_of_Perspective/index", "https://deluded-musings.fanficauthors.net/A_Matter_of_Perspective/index"], ["https://jeconais.fanficauthors.net/No_Good_Deed/No_Good_Deed/", "https://jeconais.fanficauthors.net/No_Good_Deed/index"], ] bad_checks = [ ["https://jeconais.fanficauthors.net/", "Unknown URL format"], ] for check in good_checks: fixed_url = self.fanfiction.correct_url(check[0]) self.assertEqual(fixed_url, check[1], 'Correct URL for ' + check[0]) for check in bad_checks: with ShouldRaise(URLError(check[1])): print("Checking " + check[0]) self.fanfiction.correct_url(check[0])
def test_gotcha_import(self): @replace('datetime.date', test_date()) def test_something(): from datetime import date compare(date.today(), d(2001, 1, 1)) compare(sample1.str_today_1(), '2001-01-02') with ShouldRaise(AssertionError) as s: test_something() j, dt1, j, dt2, j = s.raised.args[0].split("'") dt1 = strptime(dt1, '%Y-%m-%d') compare(dt2, '2001-01-02') @replace('testfixtures.tests.sample1.date', test_date()) def test_something(): compare(sample1.str_today_1(), '2001-01-01') test_something()
def it_can_find_the_user(tmpdir): testfile = tmpdir.join('testfile').ensure() assert_does_not_find(str(testfile)) with testfile.open(): with ShouldRaise(AssertionError): assert_does_not_find(str(testfile)) from os import getpid assert_command( ('pgctl-fuser', str(testfile)), '%i\n' % getpid(), '', 0, close_fds=True, ) assert_does_not_find(str(testfile))
def test_patterns_exclude_all(self): """Test patterns exclude all.""" msg = ( "Empty list of files for Lambda payload. Check your " "include/exclude options for errors." ) with self.temp_directory_with_files() as temp_dir, ShouldRaise( RuntimeError(msg) ): results = self.run_hook( functions={ "MyFunction": {"path": temp_dir.path + "/f1", "exclude": ["**"]} } ) self.assertIsNone(results)
def test_order_matters_no_type_flush(self): self.session.add(Simple(key='a', value=2)) self.session.add(Simple(key='b', value=1)) imported = [ dict(key='b', value=2), dict(key='d', value=1), ] class TestDiff(SQLAlchemyDiff): model = Simple extract_imported = MultiKeyDictExtractor('key') flush_per_type = False diff = TestDiff(self.session, imported) diff.apply() with ShouldRaise(IntegrityError): self.session.flush()
def test_duplicate_imported_key_not_dealt_with(self): DiffTuple, mock = self.make_differ() def handle_imported_problem(self, key, dups): return DiffTuple.handle_imported_problem = handle_imported_problem diff = DiffTuple([], [('a', 1, 2), ('a', 3, 4)]) with ShouldRaise( AssertionError( "'a' occurs 2 times in imported: " "('a', 2) from ('a', 1, 2), " "('a', 4) from ('a', 3, 4)" )): diff.compute()
def test_exception_during_action(dir): m = Mock() dir.write( 'pyproject.toml', toml.dumps({ 'tool': { 'carthorse': { 'version-from': { 'name': 'dummy' }, 'when': [], 'actions': [ { 'name': 'dummy1' }, { 'name': 'dummy2' }, ] } } })) with Replacer() as r: r.replace( 'carthorse.plugins.Plugins.load', lambda *args: { 'version_from': { 'dummy': m.version_from }, 'actions': { 'dummy1': m.action1, 'dummy2': m.action2 }, }) m.version_from.return_value = '1.2.3' m.action1.side_effect = Exception('Boom!') r.replace('sys.argv', ['x']) with ShouldRaise(Exception('Boom!')): main() compare(m.mock_calls, expected=[ call.version_from(), call.action1(), ])
def test_duplicate_name(self): self._write_jpi('test1', """ Junk: 1.0 Extension-Name: test1 Implementation-Title: test1 Implementation-Version: 2 Plugin-Version: 2 """) self._write_jpi('test2', """ Junk: 1.0 Extension-Name: test1 Implementation-Title: test1 Implementation-Version: 1 Plugin-Version: 1 """) with ShouldRaise(AssertionError( "'test1' and 'test2' both said they were 'test1'" )): check(self.c.dir.path, self.jenkins.path)
def test_django_orm_is_horrible_part_3(self): class OrmObj(object): def __init__(self, a): self.a = a def __eq__(self, other): return True def __repr__(self): return 'OrmObj: ' + str(self.a) if PY3: with ShouldRaise(TypeError("unhashable type: 'OrmObj'")): compare(expected=OrmObj(1), actual=OrmObj(1), ignore_eq=True) else: self.checkRaises( message=("OrmObj: 1 (expected) != OrmObj: 1 (actual)"), expected=OrmObj(1), actual=OrmObj(1), ignore_eq=True)
def test_correct_url(self): good_checks = [ ["https://www.animationsource.org/balto/en/view_fanfic/An-Unexpected-Future-Aleu-Part-IV/53773.html", "https://www.animationsource.org/balto/en/view_fanfic/An-Unexpected-Future-Aleu-Part-IV/53773.html"], ["https://www.animationsource.org/balto/en/view_fanfic/Balto-s-Inside-Story-The-Family-Expands/263740.html", "https://www.animationsource.org/balto/en/view_fanfic/Balto-s-Inside-Story-The-Family-Expands/263740.html"], ["https://www.animationsource.org/balto/en/view_fanfic/Jenna-s-Journey/55497.html&deb=0&nsite=1", "https://www.animationsource.org/balto/en/view_fanfic/Jenna-s-Journey/55497.html"], ] bad_checks = [ ["https://www.animationsource.org/balto/en/view_fanfic/Jenna-s-Journey/", "Unknown URL format"], ["https://www.animationsource.org/balto/en/view_fanfic/Jenna-s-Journey", "Unknown URL format"], ["https://www.animationsource.org/balto/en/view_fanfic/Jenna-s-Journey/55497.html/t", "Unknown URL format"], ] for check in good_checks: fixed_url = self.fanfiction.correct_url(check[0]) self.assertEqual(fixed_url, check[1], 'Correct URL for ' + check[0]) for check in bad_checks: with ShouldRaise(URLError(check[1])): print("Checking " + check[0]) self.fanfiction.correct_url(check[0])
def test_exists_upstream(self, git, capfd): with Replace('os.environ.TAG', 'v1.2.3', strict=False): git.make_repo_with_content('remote') rev = git.rev_parse('HEAD', 'remote') git('clone remote local', git.dir.path) git('tag v1.2.3', 'remote') git.check_tags(repo='remote', expected={b'v1.2.3': rev}) os.chdir(git.dir.getpath('local')) git.dir.write('local/a', 'changed') git('config user.email "*****@*****.**"') git('config user.name "Test User"') git("commit -am changed") with ShouldRaise(CalledProcessError) as s: create_tag() assert 'git push origin tag v1.2.3' in str(s.raised) git.check_tags(repo='remote', expected={b'v1.2.3': rev}) capfd.readouterr()
def test_missing_from_context_no_chain(self): class T(object): pass @requires(T) def job(arg): pass # pragma: nocover runner = Runner(job) with ShouldRaise(ContextError) as s: runner() text = '\n'.join(( 'While calling: '+repr(job)+' requires(T) returns_result_type()', 'with <Context: {}>:', '', 'No '+repr(T)+' in context', )) compare(text, repr(s.raised)) compare(text, str(s.raised))
def test_missing_from_context_with_chain(self): class T(object): pass def job1(): pass def job2(): pass @requires(T) def job3(arg): pass # pragma: nocover def job4(): pass def job5(): pass runner = Runner() runner.add(job1, label='1') runner.add(job2) runner.add(job3) runner.add(job4, label='4') runner.add(job5, requires('foo', bar='baz'), returns('bob')) with ShouldRaise(ContextError) as s: runner() text = '\n'.join(( '', '', 'Already called:', repr(job1)+' requires() returns_result_type() <-- 1', repr(job2)+' requires() returns_result_type()', '', 'While calling: '+repr(job3)+' requires(T) returns_result_type()', 'with <Context: {}>:', '', 'No '+repr(T)+' in context', '', 'Still to call:', repr(job4)+' requires() returns_result_type() <-- 4', repr(job5)+" requires('foo', bar='baz') returns('bob')", )) compare(text, repr(s.raised)) compare(text, str(s.raised))
def test_recursive_check(self): with LogCapture(recursive_check=True) as log: getLogger().info('oh hai') with ShouldRaise(AssertionError) as s: log.check(('root', 'INFO', 'oh noez')) compare(str(s.raised), expected=( "sequence not as expected:\n\n" "same:\n()\n\n" "expected:\n(('root', 'INFO', 'oh noez'),)\n\n" "actual:\n(('root', 'INFO', 'oh hai'),)\n\n" "While comparing [0]: sequence not as expected:\n\n" "same:\n('root', 'INFO')\n\n" "expected:\n" "('oh noez',)\n\n" "actual:\n" "('oh hai',)\n\n" "While comparing [0][2]: 'oh noez' (expected) != 'oh hai' (actual)" ))
def test_does_not_match(self): with ShouldRaise( AssertionError('''\ Sequence not as expected: same: ((u'R0C0', u'R0C1'), (u'R1C0', u'R1C1'), (u'A merged cell', ''), ('', ''), ('', '')) first: ((u'More merged cells', 'XX'),) second: ((u'More merged cells', ''),)''')): CheckerView(path.join(test_files, 'testall.xls'))['Sheet1'].compare( (u'R0C0', u'R0C1'), (u'R1C0', u'R1C1'), (u'A merged cell', ''), ('', ''), ('', ''), (u'More merged cells', 'XX'))
def test_correct_url(self): good_checks = [ [ "http://www.hpfanficarchive.com/stories/viewstory.php?sid=270&chapter=81", "http://www.hpfanficarchive.com/stories/viewstory.php?sid=270" ], [ "http://www.hpfanficarchive.com/stories/viewstory.php?sid=270", "http://www.hpfanficarchive.com/stories/viewstory.php?sid=270" ], [ "http://www.hpfanficarchive.com/stories/viewstory.php?sid=270&textsize=0&chapter=81", "http://www.hpfanficarchive.com/stories/viewstory.php?sid=270" ], ] bad_checks = [ [ "http://www.hpfanficarchive.com/stories/viewstory.php?sid=270/test", "Unknown URL format" ], ["http://www.hpfanficarchive.com/stories", "Unknown URL format"], [ "http://www.hpfanficarchive.com/stories/viewstory.php", "Unknown URL format" ], ["http://www.hpfanficarchive.com/", "Unknown URL format"], ] for check in good_checks: fixed_url = self.fanfiction.correct_url(check[0]) self.assertEqual(fixed_url, check[1], 'Correct URL for ' + check[0]) for check in bad_checks: with ShouldRaise(URLError(check[1])): print("Checking " + check[0]) self.fanfiction.correct_url(check[0])
def test_already_in_context(self): class T(object): pass t1 = T() @returns(T, T) def job(): return t1, T() runner = Runner(job) with ShouldRaise(ContextError) as s: runner() text = '\n'.join(( 'While calling: '+repr(job)+' requires() returns(T, T)', 'with <Context: {\n' ' '+repr(T)+': '+repr(t1)+'\n' '}>:', '', 'Context already contains '+repr(T), )) compare(text, repr(s.raised)) compare(text, str(s.raised))
def test_invalid_three_args(self): with ShouldRaise(TypeError( "Exactly two objects needed, you supplied: ['x', 'y', 'z']" )): compare('x', 'y', 'z')
def test_invalid_zero_args(self): with ShouldRaise(TypeError( 'Exactly two objects needed, you supplied: []' )): compare()
def test_invalid_two_args_expected(self): with ShouldRaise(TypeError( "Exactly two objects needed, you supplied: ['z', 'x', 'y']" )): compare('x', 'y', expected='z')
def test_unless_true_okay(self): with ShouldRaise(unless=True): pass
def test_unless_false_okay(self): with ShouldRaise(unless=False): raise AttributeError()
def test_import_errors_2(self): with ShouldRaise(ImportError('X')): raise ImportError('X')
def test_with_getting_raised_exception(self): with ShouldRaise() as s: raise ValueError('foo bar') self.assertEqual(C(ValueError('foo bar')), s.raised)
def test_neither_supplied(self): with ShouldRaise(): raise ValueError('foo bar')