示例#1
0
文件: test_lola.py 项目: mgood/lola
def test_with_block_closes_runner_after_error():
  with expect.raises(KeyError):
    with lola.Runner() as runner:
      raise KeyError()

  with expect.raises(ValueError):
    runner.close()
示例#2
0
def test_with_block_closes_runner_after_error():
    with expect.raises(KeyError):
        with lola.Runner() as runner:
            raise KeyError()

    with expect.raises(ValueError):
        runner.close()
示例#3
0
def test_dump_xearth_markers():
    markers = {
        500936: Trigpoint(52.066035, -0.281449, 37.000000, 'Broom Farm'),
        501097: Trigpoint(52.010585, -0.173443, 97.000000, 'Bygrave'),
        505392: Trigpoint(51.910886, -0.186462, 136.000000, 'Sish Lane')
    }
    data = dump_xearth_markers(markers)
    expect(data[0]) == '52.066035 -0.281449 "500936" # Broom Farm, alt 37m'
    expect(data[1]) == '52.010585 -0.173443 "501097" # Bygrave, alt 97m'
    expect(data[2]) == '51.910886 -0.186462 "505392" # Sish Lane, alt 136m'

    data = dump_xearth_markers(markers, 'name')
    expect(data[0]) == '52.066035 -0.281449 "Broom Farm" # 500936, alt 37m'
    expect(data[1]) == '52.010585 -0.173443 "Bygrave" # 501097, alt 97m'
    expect(data[2]) == '51.910886 -0.186462 "Sish Lane" # 505392, alt 136m'

    with expect.raises(ValueError, "Unknown name type 'falseKey'"):
        dump_xearth_markers(markers, 'falseKey')

    points = {
        'Broom Farm': Point(52.066035, -0.281449),
        'Bygrave': Point(52.010585, -0.173443),
        'Sish Lane': Point(51.910886, -0.186462)
    }
    data = dump_xearth_markers(points)
    expect(data[0]) == '52.066035 -0.281449 "Broom Farm"'
    expect(data[1]) == '52.010585 -0.173443 "Bygrave"'
    expect(data[2]) == '51.910886 -0.186462 "Sish Lane"'
示例#4
0
        def it_ignores_new_attributes(obj, mapper):
            mapper.create()
            mapper.text = "var4: foo"

            mapper.load()
            with expect.raises(AttributeError):
                print(obj.var4)
示例#5
0
def test_angle_to_distance():
    expect('%.3f' % angle_to_distance(1)) == '111.125'
    expect('%i' % angle_to_distance(360, 'imperial')) == '24863'
    expect('%i' % angle_to_distance(1.0 / 60, 'nautical')) == '1'

    with expect.raises(ValueError, "Unknown units type 'baseless'"):
        '%i' % angle_to_distance(10, 'baseless')
示例#6
0
    def test_issues(self):
        title = 'Test issue for github3.py'
        with expect.raises(github3.GitHubError):
            # Try to create one without authenticating
            self.g.create_issue(self.sigm, self.todo, title)
            # Try to get individual ones
            self.g.issue(self.sigm, self.todo, 2000)
            self.g.list_user_issues()

        i = self.g.issue(self.sigm, self.todo, 1)
        self.assertIsNotNone(i)
        expect(i).isinstance(github3.issues.Issue)
        expect(i.list_comments()) != []
        # Test listing issues
        list_issues = self.g.list_repo_issues
        expect(list_issues(self.kr, 'requests')) != []
        expect(list_issues(self.sigm, self.todo)).isinstance(list)
        for f in ('assigned', 'created', 'mentioned'):
            self.assertIsNotNone(list_issues(self.sigm, self.todo, f))
        for s in ('open', 'closed'):
            self.assertIsNotNone(list_issues(self.sigm, self.todo, state=s))
        self.assertIsNotNone(list_issues(self.sigm, self.todo, state='closed',
            labels='Bug,Enhancement'))
        for s in ('created', 'updated', 'comments'):
            self.assertIsNotNone(list_issues(self.sigm, self.todo, sort=s))
        for d in ('asc', 'desc'):
            self.assertIsNotNone(list_issues(self.sigm, self.todo,
                state='closed', direction=d))
        self.assertIsNotNone(list_issues(self.sigm, self.todo,
            since='2011-01-01T00:00:01Z'))
示例#7
0
def test_start_time_validity(string, expected):
    p = StartTimeParamType()
    if expected is True:
        expect(p.convert(string, None, None) == string)
    else:
        with expect.raises(expected):
            p.convert(string, None, None)
示例#8
0
 def test_signature_doesnt_verify(self):
     sp = Pysamlsp({
         'certificate':
         os.path.dirname(os.path.abspath(__file__)) + '/support/saml.crt'
     })
     with expect.raises():
         sp.verify_signature(TEST_NONSENSE_RESPONSE)
示例#9
0
 def should_enforce_time_moves_only_forward(self):
     async def first(clock, balances):
         yield 100, 'A', 'B', 'Meh'
         await clock.until(date(2010, 1,1))
     sim = Simulation(first, start_date=date(2019, 6, 1), end_date=date(2030, 6, 1))
     with expect.raises(InvalidWaitTime):
         sim.run()
def test_unsupported_comparision():
    from sys import version_info
    repr_name = 'class' if version_info[0] >= 3 else 'type'

    with expect.raises(NotImplementedError, 'Unable to compare Version and '
                       "<%s 'float'>" % repr_name):
        float(3.2) == Version('0.2.0')
示例#11
0
 def should_enforce_cash_only_flows_between_with_registered_accounts(self):
     @assert_accounts('registered_acct')
     async def badly_written_generator(clock, balances):
         yield 100, 'registered_acct', 'forgotten_acct', 'should die because forgotten not registered'
     sim = Simulation(badly_written_generator, start_date=date(2019, 6, 1), end_date=date(2030, 6, 1))
     with expect.raises(InvalidAccount):
         sim.run()
示例#12
0
def test_fail_start_when_task_typo():
    events = Events.read('tests/data/test_not_running')
    with expect.raises(
            TaskNotExistError,
            "Task non_existant does not exist!  Use `--new' to "
            "create it"):
        events.start(task='non_existant')
示例#13
0
def test_exit_with_failure(stdout):
    @exit('custom message')
    def f(x, y):
        raise ValueError('boom')
    with expect.raises(ValueError):
        f(4, 3)
    expect(stdout.getvalue()) == 'custom message\n'
示例#14
0
 def test_user_is_invalid(self):
     sp = Pysamlsp({
         'certificate':
         os.path.dirname(os.path.abspath(__file__)) + '/support/saml.crt'
     })
     with expect.raises(SAMLNameIDError):
         sp.user_is_valid(TEST_NONSENSE_RESPONSE)
示例#15
0
    def test_gists(self):
        gists = self.g.list_gists()
        expect(gists) != []

        for g in gists:
            expect(g).isinstance(Gist)
            expect(g.files) >= 0
            expect(g.list_files()).isinstance(list)
            expect(g.forks) >= 0
            self.assertAreNotNone(g, 'created_at', 'description',
                    'git_pull_url', 'git_push_url', 'html_url', 'id')
            expect(g.is_public()).isinstance(bool)
            expect(g.is_starred()).isinstance(bool)
            expect(g.to_json()).isinstance(dict)
            comments = g.list_comments()
            if comments:
                for c in comments:
                    expect(c).isinstance(GistComment)

            expect(g.refresh()).isinstance(bool)
            expect(g.user).isinstance(User)

            with expect.raises(github3.GitHubError):
                g.create_comment('Foo')
                g.delete()
                g.edit()
                g.fork()
                g.star()
                g.unstar()
示例#16
0
def test_task_name_validity(string, expected):
    p = TaskNameParamType()
    if expected is True:
        expect(p.convert(string, None, None) == string)
    else:
        with expect.raises(expected):
            p.convert(string, None, None)
示例#17
0
    def test_blob(self):
        r = self.todor
        blob = r.blob("f737918b90118a6aea991f89f444b150a2360393")
        expect(blob).isinstance(Blob)
        self.assertAreNotNone(blob, "content", "decoded", "encoding", "sha", "size")

        with expect.raises(github3.GitHubError):
            r.create_blob("Foo bar bogus", "utf-8")
示例#18
0
    def test___init__(self):
        test = Point(math.pi / 4, math.pi / 2, angle='radians')
        expect(test.latitude) == 45
        expect(test.longitude) == 90

        test = Point((50, 20, 10), (-1, -3, -12))
        expect('%.3f' % test.latitude) == '50.336'
        expect('%.3f' % test.longitude) == '-1.053'

        with expect.raises(ValueError, 'Unknown angle type None'):
            Point(52.015, -0.221, angle=None)
        with expect.raises(ValueError, 'Invalid latitude value -92'):
            Point(-92, -0.221)
        with expect.raises(ValueError, 'Invalid longitude value 185'):
            Point(52.015, 185)
        with expect.raises(ValueError, 'Unknown units type None'):
            Point(52.015, -0.221, units=None)
示例#19
0
def test_call_with_closed_runner_throws_error():
    runner = lola.Runner()
    runner.close()

    with expect.raises(ValueError):
        runner.call(['test_scripts/success.py'],
                    stdout=DEVNULL,
                    stderr=DEVNULL)
    def it_allows_only_attributes_listed_in__slots__to_be_assigned(self):

        class Eggs(object):
            __slots__ = ["spam"]

        eggs = Eggs()
        eggs.spam = True
        with expect.raises(AttributeError):
            eggs.bacon = True
示例#21
0
 def test_requires_auth(self):
     with expect.raises(github3.GitHubError):
         for g in self.gists:
             g.create_comment('Foo')
             g.delete()
             g.edit()
             g.fork()
             g.star()
             g.unstar()
示例#22
0
 def should_enforce_only_registered_accounts_are_accessed(self):
     @assert_accounts('registered_acct1', 'registered_acct2')
     async def badly_written_generator(clock, balances):
         balances['registered_acct1']
         balances['forgotten_acct']
         yield 100, 'registered_acct1', 'registered_acct2', 'Should not get this far'
     sim = Simulation(badly_written_generator, start_date=date(2019, 6, 1), end_date=date(2030, 6, 1))
     with expect.raises(InvalidAccount):
         sim.run()
示例#23
0
 def should_be_able_to_manually_set_ids_only_while_clock_not_started(self):
     Synapse.clock.reset()
     neuron = Neuron(id=3)
     expect(neuron.id) == 3
     expect(Synapse(neuron, 10, id=7).id) == 7
     Synapse.clock.start()
     expect(Neuron().id) == 8
     with expect.raises(AssertionError):
         Neuron(id=3)
示例#24
0
    def test_refs(self):
        r = self.todor
        ref = r.ref("heads/development")
        expect(ref).isinstance(Reference)
        self.assertAreNotNone(ref, "object", "ref")

        with expect.raises(github3.GitHubError):
            ref.delete()
            ref.update("31e862095dffa60744f1ce16a431ea040381f053")
示例#25
0
 def should_enforce_generators_await_clock(self):
     # doesn't work because call to async wait method without await means it won't be run
     # is there a way to see which futures are doing nothing and assert failure?
     async def badly_written_generator(clock, balances):
         yield 100, 'A', 'B', 'ok'
         clock.tick(years=1)
         yield 100, 'A', 'B', 'ok'
     sim = Simulation(badly_written_generator, start_date=date(2019, 6, 1), end_date=date(2030, 6, 1))
     with expect.raises(FailedToAwaitClock):
         sim.run()
示例#26
0
    def test___repr__(self):
        expect(repr(Baken(14.460, 20.680, None, None, None, 0.000, None, None,
                          None, None, None))) == \
            'Baken(14.46, 20.68, None, None, None, 0.0, None, None, None, None, None)'
        expect(repr(Baken(None, None, '2 x Turnstile', None, 50.000, 460.000,
                          'IO93BF', 'A1A', None, 25, None))) == \
            ("Baken(%s, -1.875, '2 x Turnstile', None, 50.0, "
             "460.0, 'IO93BF', 'A1A', None, 25, None)" % 53.229166666666686)

        with expect.raises(LookupError,
                           ('Unable to instantiate baken object, no latitude '
                            'or locator string')):
            Baken(None, None)
示例#27
0
    def test_watching(self):
        expect(self.g.list_watching(self.sigm)) != []
        with expect.raises(github3.GitHubError):
            self.g.watch(self.sigm, self.todo)
            self.g.unwatch(self.sigm, self.todo)
            self.g.list_watching()
            self.g.is_watching(self.sigm, self.todo)

        if self.auth:
            expect(self._g.watch(self.sigm, self.todo)).isinstance(bool)
            expect(self._g.unwatch(self.sigm, self.todo)).isinstance(bool)
            expect(self._g.list_watching()) != []
            expect(self._g.is_watching(self.sigm, self.todo)) != []
示例#28
0
    def test_import_locations(self):
        locations = Locations(open('tests/data/geonames'))
        expect(str(locations[0])) == \
            'Afon Wyre (River Wayrai, River Wyrai, Wyre - N52.317°; W004.167°)'
        expect(str(locations[1])) == \
            'Wyre (Viera - N59.117°; W002.967°)'
        expect(str(locations[2])) == \
            'Wraysbury (Wyrardisbury - N51.450°; W000.550°)'

        with expect.raises(FileFormatError,
                           "Incorrect data format, if you're using a file "
                           'downloaded from geonames.org please report this '
                           'to James Rowe <*****@*****.**>'):
            Locations(open('tests/data/broken_geonames'))
示例#29
0
    def test_import_timezones_file(self):
        locations = Locations(None, open('tests/data/geonames_timezones'))
        timezones = locations.timezones
        expect(timezones['Asia/Dubai']) == [240, 240]
        expect(timezones['Asia/Kabul']) == [270, 270]
        expect(timezones['Europe/Andorra']) == [60, 120]

        header_skip_check = Locations(None,
                                      open('tests/data/geonames_timezones_header'))
        expect(header_skip_check) == Locations()

        with expect.raises(FileFormatError,
                           "Incorrect data format, if you're using a file "
                           'downloaded from geonames.org please report this '
                           'to James Rowe <*****@*****.**>'):
            Locations(None, open('tests/data/geonames_timezones_broken'))
示例#30
0
    def test_following(self):
        expect(self.g.list_followers('kennethreitz')) != []
        expect(self.g.list_following('kennethreitz')) != []
        with expect.raises(github3.GitHubError):
            self.g.is_following(self.sigm)
            self.g.follow(self.sigm)
            self.g.unfollow(self.sigm)
            self.g.list_followers()
            self.g.list_following()

        if self.auth:
            expect(self._g.is_following(self.sigm)).isinstance(bool)
            expect(self._g.follow(self.sigm)).isinstance(bool)
            expect(self._g.unfollow(self.sigm)).isinstance(bool)
            expect(self._g.list_followers()) != []
            expect(self._g.list_following()) != []
        def it_raises_exception_when_they_decrease(project2):
            project2.update(dict(unit=5))

            with expect.raises(ValueError):
                project2.update(dict(unit=4))

            expect(project2.metrics) == dict(
                current=dict(
                    unit=4.0,
                    integration=3.4,
                    overall=5.6,
                ),
                minimum=dict(
                    unit=5.0,
                    integration=3.4,
                    overall=5.6,
                ),
            )
示例#32
0
    def test_login(self):
        # Test "regular" auth
        self.g.login(*self.fake_auth)
        h = github3.login(*self.fake_auth)
        for i in [self.g, h]:
            expect(self.fake_auth) == i._session.auth
        # Test "oauth" auth
        self.g.login(token=self.fake_oauth)
        h = github3.login('', '', token=self.fake_oauth)
        for i in [self.g, h]:
            expect(i._session.headers['Authorization']) == 'token ' +\
                self.fake_oauth

        with expect.raises(github3.GitHubError):
            self.g.user()

        if self.auth:
            self.assertIsNotNone(self._g.user())
示例#33
0
    def test_distance(self):
        home = Point(52.015, -0.221)
        dest = Point(52.6333, -2.5)
        expect('%i kM' % home.distance(dest)) == '169 kM'
        expect('%i kM' % home.distance(dest, method='sloc')) == '169 kM'

        with expect.raises(ValueError, "Unknown method type 'Invalid'"):
            home.distance(dest, method='Invalid')

        start = Point(36.1200, -86.6700)
        dest = Point(33.9400, -118.4000)
        expect('%i kM' % start.distance(dest)) == '2884 kM'
        start.units = 'imperial'
        expect('%i mi' % start.distance(dest)) == '1792 mi'
        start.units = 'nautical'
        expect('%i nmi' % start.distance(dest)) == '1557 nmi'
        start.units = 'metric'
        expect('%i kM' % start.distance(dest, method='sloc')) == '2884 kM'
示例#34
0
    def test_files(self):
        ninjax = self.g.gist(3156487)  # An gist I used for someone in
        ##python on freenode. I promise not to update it further
        expect(ninjax.files) == 2
        coms = ninjax.list_comments()
        if coms:
            for c in coms:
                expect(c).isinstance(GistComment)
                self.assertAreNotNone(c, 'body', 'body_html', 'body_text',
                        'created_at', 'id', 'user')
                with expect.raises(github3.GitHubError):
                    c.delete()
                    c.edit('foo')

        files = ninjax.list_files()
        expect(files) != []
        for f in files:
            expect(f).isinstance(GistFile)
            self.assertAreNotNone(f, 'content', 'name', 'lang', 'raw_url',
                    'size')
示例#35
0
def test_from_iso6709_location_page():
    # The following tests are from the Latitude, Longitude and Altitude format
    # for geospatial information page
    # (http://www.w3.org/2005/Incubator/geo/Wiki/LatitudeLongitudeAltitude)

    #  Mount Everest
    expect(from_iso6709('+27.5916+086.5640+8850/')) == \
        (27.5916, 86.564, 8850.0)
    #  South Pole
    expect(from_iso6709('-90+000+2800/')) == (-90.0, 0.0, 2800.0)
    #  New York City
    expect(from_iso6709('+40.75-074.00/')) == (40.75, -74.0, None)
    #  Mount Fuji
    expect(from_iso6709('+352139+1384339+3776/')) == \
        (35.36083333333333, 138.7275, 3776.0)
    #  Tokyo Tower
    expect(from_iso6709('+35.658632+139.745411/')) == \
        (35.658632, 139.745411, None)

    with expect.raises(ValueError, "Incorrect format for longitude '+1'"):
        from_iso6709('+35.658632+1/')
示例#36
0
    def test_gists(self):
        # My gcd example
        gist_id = 2648112
        if not self.g.gist(gist_id):
            self.fail('Check gcd gist')

        with expect.raises(github3.GitHubError):
            self.g.gist(-1)

        for i in None, self.sigm:
            expect(self.g.list_gists(i)) != []

        if self.auth:
            desc = 'Testing gist creation'
            files = {'test.txt': {'content': 'Test contents'}}
            gist = self._g.create_gist(desc, files, False)
            self.assertIsNotNone(gist)
            expect(gist.description) == desc
            expect(gist.is_public()) == False
            for g in gist.files:
                expect(g.content) == files[g.name]['content']
            expect(gist.delete()) == True
示例#37
0
 def test_starting_zibrato_with_an_invalid__socket(self):
     with expect.raises(zmq.ZMQError):
         z1 = Zibrato(host='nowhere')
         del z1
示例#38
0
        def it_raises_an_exception_after_delete(mapper):
            mapper.delete()

            with expect.raises(exceptions.DeletedFileError):
                mapper.load()
示例#39
0
 def when_missing(config):
     with expect.raises(RuntimeError):
         find_config()
示例#40
0
    def it_requires_files_to_not_yet_exist(model_class, instance):
        instance.__mapper__.create()

        with expect.raises(exceptions.DuplicateMappingError):
            utilities.create(model_class, 'foo', 'bar')
示例#41
0
 def it_raises_an_exception_when_platform_is_unknown():
     with expect.raises(RuntimeError):
         system.launch(None)
示例#42
0
def test__isbn_cleanse_invalid(isbn, message):
    with expect.raises(IsbnError, message):
        _isbn_cleanse(isbn)
示例#43
0
 def when_unknown_color():
     with expect.raises(AssertionError):
         common.style("_foo_", 'bar', _color_support=True)
示例#44
0
 def it_requries_color_with_messages():
     with expect.raises(AssertionError):
         common.show("Hello, world!", 'foobar')
示例#45
0
 def should_check_only_valid_cashflows_yielded(self):
     async def badly_written_generator(clock, balances):
         yield 100, 'A', 'B'  # forgot desc
     sim = Simulation(badly_written_generator, start_date=date(2019, 6, 1), end_date=date(2030, 6, 1))
     with expect.raises(InvalidCashFlowYielded):
         sim.run()
示例#46
0
 def it_cannot_be_used_directly():
     with expect.raises(NotImplementedError):
         SortedList.to_value(None)
     with expect.raises(NotImplementedError):
         SortedList.to_data(None)
示例#47
0
 def it_requires_a_mapped_instance():
     with expect.raises(TypeError):
         utilities.load(Mock)
示例#48
0
 def it_is_not_yet_implemented():
     with expect.raises(NotImplementedError):
         utilities.match(Mock)
示例#49
0
 def it_requires_a_mapped_class_or_instance():
     with expect.raises(TypeError):
         utilities.find(Mock)
示例#50
0
 def it_raises_an_exception_when_unable_to_convert():
     with expect.raises(ValueError):
         Integer.to_value("abc")
示例#51
0
 def it_cannot_be_used_directly():
     with expect.raises(NotImplementedError):
         AttributeDictionary.to_value(None)
     with expect.raises(NotImplementedError):
         AttributeDictionary.to_data(None)
示例#52
0
 def test_custom_init_is_invoked(sample):
     sample.__mapper__.text = "var5:\n  checked: 42"
     with expect.raises(RuntimeError):
         print(sample.var5)
示例#53
0
    def it_exits_when_no_config_found(tmpdir):
        tmpdir.chdir()

        with expect.raises(SystemExit):
            cli.main(['edit'])
示例#54
0
def test__isbn_cleanse_invalid_length(checksum, message):
    with expect.raises(IsbnError, message):
        _isbn_cleanse('0-123', checksum=checksum)
 def it_rejects_zero_arguments():
     with expect.raises(ValueError):
         decorators.attr()
示例#56
0
def test_convert_invalid():
    with expect.raises(IsbnError,
                       'Only ISBN-13s with 978 Bookland code can be converted '
                       'to ISBN-10.'):
        convert('0000000000000')
 def it_rejects_more_than_one_argument():
     with expect.raises(ValueError):
         decorators.attr(foo=1, bar=2)
示例#58
0
 def it_cannot_be_subclassed_without_a_type():
     with expect.raises(NotImplementedError):
         UnknownSortedList.to_value(None)
     with expect.raises(NotImplementedError):
         UnknownSortedList.to_data(None)
示例#59
0
    def it_expects_the_file_to_not_be_deleted(instance):
        instance.__mapper__.delete()

        with expect.raises(exceptions.DeletedFileError):
            utilities.save(instance)