Ejemplo n.º 1
0
    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')
Ejemplo n.º 2
0
    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!')
Ejemplo n.º 3
0
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)
Ejemplo n.º 4
0
 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())
Ejemplo n.º 5
0
    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!')
Ejemplo n.º 6
0
    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])
Ejemplo n.º 7
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()
Ejemplo n.º 8
0
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))
Ejemplo n.º 9
0
    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)
Ejemplo n.º 10
0
    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()
Ejemplo n.º 11
0
    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()
Ejemplo n.º 12
0
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(),
    ])
Ejemplo n.º 13
0
    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)
Ejemplo n.º 14
0
    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)
Ejemplo n.º 15
0
    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])
Ejemplo n.º 16
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()
Ejemplo n.º 17
0
    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))
Ejemplo n.º 18
0
    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))
Ejemplo n.º 19
0
    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)"
        ))
Ejemplo n.º 20
0
    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'))
Ejemplo n.º 21
0
    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])
Ejemplo n.º 22
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))
Ejemplo n.º 23
0
 def test_invalid_three_args(self):
     with ShouldRaise(TypeError(
             "Exactly two objects needed, you supplied: ['x', 'y', 'z']"
     )):
         compare('x', 'y', 'z')
Ejemplo n.º 24
0
 def test_invalid_zero_args(self):
     with ShouldRaise(TypeError(
             'Exactly two objects needed, you supplied: []'
     )):
         compare()
Ejemplo n.º 25
0
 def test_invalid_two_args_expected(self):
     with ShouldRaise(TypeError(
             "Exactly two objects needed, you supplied: ['z', 'x', 'y']"
     )):
         compare('x', 'y', expected='z')
Ejemplo n.º 26
0
 def test_unless_true_okay(self):
     with ShouldRaise(unless=True):
         pass
Ejemplo n.º 27
0
 def test_unless_false_okay(self):
     with ShouldRaise(unless=False):
         raise AttributeError()
Ejemplo n.º 28
0
 def test_import_errors_2(self):
     with ShouldRaise(ImportError('X')):
         raise ImportError('X')
Ejemplo n.º 29
0
 def test_with_getting_raised_exception(self):
     with ShouldRaise() as s:
         raise ValueError('foo bar')
     self.assertEqual(C(ValueError('foo bar')), s.raised)
Ejemplo n.º 30
0
 def test_neither_supplied(self):
     with ShouldRaise():
         raise ValueError('foo bar')