コード例 #1
0
    def test_comparison(self):
        q2_2013 = Quarter.parse("2013_q2")
        q1_2013 = Quarter.parse("2013_q1")
        q4_2012 = Quarter.parse("2012_q4")

        assert_that(q4_2012, is_(less_than(q1_2013)))
        assert_that(q1_2013, is_(less_than(q2_2013)))
        assert_that(q1_2013, is_(greater_than(q4_2012)))
        assert_that(q2_2013, is_(greater_than(q1_2013)))
        assert_that(q2_2013, is_(equal_to(q2_2013)))
コード例 #2
0
    def test_it_should_get_closest_bikes(self):
        position = (40.4168984, -3.7024244)
        stations = list(self.stations.by_distance(position))

        assert_that(stations, all_of(
            has_length(greater_than(0)),
            only_contains(has_properties(dict(
                distance=greater_than(0)
            )))
        ))
コード例 #3
0
def test_duration(allured_testdir, snipped):
    allured_testdir.testdir.makepyfile("""
        def test_duration_example():
            {snipped}
    """.format(snipped=snipped))

    timestamp = now()
    allured_testdir.run_with_allure()

    assert_that(allured_testdir.allure_report,
                has_test_case("test_duration_example",
                              all_of(
                                  has_entry("start", greater_than(timestamp)),
                                  has_entry("stop", greater_than(timestamp))
                              ))
                )
コード例 #4
0
ファイル: get_completions_test.py プロジェクト: Xiol/ycmd
def GetCompletions_CsCompleter_ImportsOrderedAfter_test():
  app = TestApp( handlers.app )
  app.post_json( '/ignore_extra_conf_file',
                 { 'filepath': PathToTestFile( '.ycm_extra_conf.py' ) } )
  filepath = PathToTestFile( 'testy/ImportTest.cs' )
  contents = open( filepath ).read()
  event_data = BuildRequest( filepath = filepath,
                             filetype = 'cs',
                             contents = contents,
                             event_name = 'FileReadyToParse' )

  app.post_json( '/event_notification', event_data )
  WaitUntilOmniSharpServerReady( app, filepath )

  completion_data = BuildRequest( filepath = filepath,
                                  filetype = 'cs',
                                  contents = contents,
                                  line_num = 9,
                                  column_num = 12,
                                  force_semantic = True,
                                  query = 'Date' )
  response_data = app.post_json( '/completions', completion_data ).json

  min_import_index = min( loc for loc, val
                          in enumerate( response_data[ 'completions' ] )
                          if val[ 'extra_data' ][ 'required_namespace_import' ] )
  max_nonimport_index = max( loc for loc, val
                            in enumerate( response_data[ 'completions' ] )
                            if not val[ 'extra_data' ][ 'required_namespace_import' ] )

  assert_that( min_import_index, greater_than( max_nonimport_index ) ),
  StopOmniSharpServer( app, filepath )
コード例 #5
0
ファイル: get_completions_test.py プロジェクト: SolaWing/ycmd
def GetCompletions_ImportsOrderedAfter_test( app ):
  filepath = PathToTestFile( 'testy', 'ImportTest.cs' )
  with WrapOmniSharpServer( app, filepath ):
    contents = ReadFile( filepath )

    completion_data = BuildRequest( filepath = filepath,
                                    filetype = 'cs',
                                    contents = contents,
                                    line_num = 9,
                                    column_num = 12,
                                    force_semantic = True,
                                    query = 'Date' )
    response_data = app.post_json( '/completions', completion_data ).json

    min_import_index = min(
      loc for loc, val
      in enumerate( response_data[ 'completions' ] )
      if val[ 'extra_data' ][ 'required_namespace_import' ]
    )

    max_nonimport_index = max(
      loc for loc, val
      in enumerate( response_data[ 'completions' ] )
      if not val[ 'extra_data' ][ 'required_namespace_import' ]
    )

    assert_that( min_import_index, greater_than( max_nonimport_index ) ),
コード例 #6
0
def GetCompletions_CsCompleter_ImportsOrderedAfter_test():
    app = TestApp(handlers.app)
    app.post_json("/ignore_extra_conf_file", {"filepath": PathToTestFile(".ycm_extra_conf.py")})
    filepath = PathToTestFile("testy/ImportTest.cs")
    contents = open(filepath).read()
    event_data = BuildRequest(filepath=filepath, filetype="cs", contents=contents, event_name="FileReadyToParse")

    app.post_json("/event_notification", event_data)
    WaitUntilOmniSharpServerReady(app, filepath)

    completion_data = BuildRequest(
        filepath=filepath,
        filetype="cs",
        contents=contents,
        line_num=9,
        column_num=12,
        force_semantic=True,
        query="Date",
    )
    response_data = app.post_json("/completions", completion_data).json

    min_import_index = min(
        loc for loc, val in enumerate(response_data["completions"]) if val["extra_data"]["required_namespace_import"]
    )
    max_nonimport_index = max(
        loc
        for loc, val in enumerate(response_data["completions"])
        if not val["extra_data"]["required_namespace_import"]
    )

    assert_that(min_import_index, greater_than(max_nonimport_index)),
    StopOmniSharpServer(app, filepath)
コード例 #7
0
ファイル: test_module.py プロジェクト: NRCan/stagecraft
    def test_add_a_module_to_a_dashboard(self):
        existing_modules_count = len(Module.objects.all())
        resp = self.client.post(
            '/dashboard/{}/module'.format(self.dashboard.slug),
            data=json.dumps({
                'slug': 'a-module',
                'type_id': str(self.module_type.id),
                'title': 'Some module',
                'description': 'Some text about the module',
                'info': ['foo'],
                'options': {
                    'thing': 'a value',
                },
                'objects': "some object",
                'order': 1,
                'modules': [],
            }),
            HTTP_AUTHORIZATION='Bearer development-oauth-access-token',
            content_type='application/json')

        assert_that(resp.status_code, is_(equal_to(200)))
        assert_that(
            len(Module.objects.all()),
            greater_than(existing_modules_count))

        resp_json = json.loads(resp.content)

        assert_that(resp_json, has_key('id'))
        assert_that(resp_json, has_entry('slug', 'a-module'))
        assert_that(resp_json, has_entry('options', {'thing': 'a value'}))

        stored_module = Module.objects.get(id=resp_json['id'])
        assert_that(stored_module, is_not(None))
コード例 #8
0
def step_impl(context):
    try:
        context.json_object = json.loads(context.rv.body)
        assert_that(len(context.json_object["challenges"]), greater_than(0))

    except ValueError, e:
        return False
コード例 #9
0
    def test_connect_row_of_sections(self):
        """
        Test special case where connections have to branch

        Row of Sections is connected, starting from the middle
        RandomConnector can not connect this in one path, but has to branch
        """
        section0 = new_section((0, 0), (10, 10), self.level, self.rng)
        section1 = new_section((11, 0), (20, 10), self.level, self.rng)
        section2 = new_section((21, 0), (30, 10), self.level, self.rng)
        section3 = new_section((31, 0), (40, 10), self.level, self.rng)
        section4 = new_section((41, 0), (50, 10), self.level, self.rng)

        mark_neighbours(section0, section1)
        mark_neighbours(section1, section2)
        mark_neighbours(section2, section3)
        mark_neighbours(section3, section4)

        sections = [section0, section1, section2, section3, section4]

        connected_sections = self.connector.connect_sections(sections, section2)  # noqa

        for section in connected_sections:
            assert_that(list(section_connections(section)),
                        has_length(greater_than(0)))
            assert_that(is_connected(section))
コード例 #10
0
ファイル: test_connector.py プロジェクト: zalphi/kco_python
    def test_apply_post_200(self):
        payload = '{"flobadob": "test"}'
        self.http.add_response(
            payload=payload)
        self.resource.marshal.return_value = {
            'flodbadob': ['bobcat', 'wookie']
        }
        expected_digest = 'stnaeu\eu2341aoaaoae=='
        self.digester.return_value = expected_digest

        res = self.connector.apply(
            'POST',
            self.resource)
        req = res.req

        digester_call = self.digester.call_args[0]
        assert_that(len(digester_call[0]), greater_than(10))  # json payload

        assert_that(
            req.get_header('Authorization'),
            equal_to('Klarna ' + expected_digest))
        assert_that(
            req.get_header('Content-type'),
            equal_to(self.content_type))
        assert_that(
            self.resource.parse,
            called_once_with({'flobadob': 'test'}))
コード例 #11
0
  def ImportsOrderedAfter_test( self ):
    filepath = self._PathToTestFile( 'testy', 'ImportTest.cs' )
    contents = open( filepath ).read()
    event_data = self._BuildRequest( filepath = filepath,
                                     filetype = 'cs',
                                     contents = contents,
                                     event_name = 'FileReadyToParse' )

    self._app.post_json( '/event_notification', event_data )
    self._WaitUntilOmniSharpServerReady( filepath )

    completion_data = self._BuildRequest( filepath = filepath,
                                          filetype = 'cs',
                                          contents = contents,
                                          line_num = 9,
                                          column_num = 12,
                                          force_semantic = True,
                                          query = 'Date' )
    response_data = self._app.post_json( '/completions', completion_data ).json

    min_import_index = min(
      loc for loc, val
      in enumerate( response_data[ 'completions' ] )
      if val[ 'extra_data' ][ 'required_namespace_import' ]
    )

    max_nonimport_index = max(
      loc for loc, val
      in enumerate( response_data[ 'completions' ] )
      if not val[ 'extra_data' ][ 'required_namespace_import' ]
    )

    assert_that( min_import_index, greater_than( max_nonimport_index ) ),
    self._StopOmniSharpServer( filepath )
コード例 #12
0
ファイル: test_spells.py プロジェクト: tuturto/pyherc
    def test_triggering_effect(self):
        """
        Casting a spell should trigger the effect
        """
        self.spell.cast(self.effects)

        assert_that(self.character.hit_points, is_(greater_than(10)))
コード例 #13
0
def step_impl(context, dup_feed_id, dup_file):
    """
    :type context behave.runner.Context
    """
    dup = Key(s3_connect.b)
    dup.key = dup_file
    dup_contents = dup.get_contents_as_string()
    dup_contents = dup_contents.splitlines()

    dup_list_id = list()
    dup_counts = dict()

    for line in dup_contents:
        r = line.split("!@!")
        dup_list_id.append(r[4])

    for item in dup_list_id:
        dup_counts[item] = dup_counts.get(item, 0) + 1

    context.dup_feed_id = list()
    cnt = 0

    for k,v in dup_counts.items():
        if v > 1:
            context.dup_feed_id.append(k)
            cnt = cnt + 1

    context.dup_feed_id.sort()
    # print("=== Feed file duplicates: ", context.dup_feed_id, "\n")

    assert_that(cnt, greater_than(0))
コード例 #14
0
ファイル: test_action_state.py プロジェクト: Dunes/janitor
    def test_is_not_greater_than(self):

        for attr in ("time", "state", "action"):
            with self.subTest(attr=attr):
                args = {"time": 0, "state": 0, "action": 0}
                first = ActionState(**args)

                assert_that(first, is_not(greater_than(first)))
コード例 #15
0
def check_field_value(driver, veld, waarde):
	if len(driver.find_elements_by_css_selector(veld))>0:
		if driver.find_element_by_css_selector(veld).get_attribute('value') is not None :
			assert_that(driver.find_element_by_css_selector(veld).get_attribute('value').strip() , equal_to(waarde.strip()), "Assert gefaald voor element: " + veld + " en waarde: " + waarde)
		else:
			print('dan maar text : ' + veld)
			assert_that((driver.find_element_by_css_selector(veld).text).strip() , equal_to(waarde.strip()), "Assert gefaald voor element: " + veld + " en waarde: " + waarde)
	assert_that(len(driver.find_elements_by_css_selector(veld)), greater_than(0), "Het element " + veld + " is niet gevonden")
コード例 #16
0
    def test_drinking_healing_potion(self):
        """
        Test that character drinking a healing potion gets healed
        """
        drink(self.character,
              self.potion)

        assert_that(self.character.hit_points, is_(greater_than(1)))
        assert_that(self.potion.maximum_charges_left, is_(equal_to(0)))
コード例 #17
0
    def test_it_should_search_stations_by_name(self):
        query = 'callEaVapiés'
        stations = list(self.stations.by_search(query))

        assert_that(stations, only_contains(any_of(
            has_property('nombre', contains_string('Lavapies')),
            has_property('address', contains_string('Lavapies')),
        )))
        assert_that(stations, has_length(greater_than(0)))
コード例 #18
0
ファイル: test_heart_beat.py プロジェクト: crook/storops
 def test_update_by_ip_latency(self):
     hb = NodeHeartBeat(interval=0.01)
     hb.add('spa', '1.1.1.1', False)
     node = hb.nodes[0]
     assert_that(node.available, equal_to(False))
     time.sleep(0.06)
     assert_that(node.available, equal_to(True))
     assert_that(hb.command_count, greater_than(1))
     hb.stop()
コード例 #19
0
    def test_adding_items(self):
        """
        Test basic case of adding items on the level
        """
        assert_that(list(get_items(self.level)), has_length(greater_than(3)))
        assert_that(list(get_items(self.level)), has_length(less_than(6)))

        assert_that(self.level, does_have_item('dagger',
                                               greater_than_or_equal_to(3)))
        assert_that(self.level, does_have_item('red potion', 1))
コード例 #20
0
ファイル: test_time.py プロジェクト: NextThought/nti.testing
    def test_increases_relative_to_real(self):
        import time
        before_all = time.time()

        @time_monotonically_increases
        def f():
            return self._check_time()

        after_first = f()
        assert_that(after_first, is_(greater_than(before_all)))
コード例 #21
0
ファイル: test_action_state.py プロジェクト: Dunes/janitor
    def test_is_greater_than(self):

        for attr in ("time", "state"):
            with self.subTest(attr=attr):
                args = {"time": 0, "state": 0, "action": 0}
                first = ActionState(**args)
                args[attr] = -1
                second = ActionState(**args)

                assert_that(first, greater_than(second))
コード例 #22
0
    def test_it_should_calculate_0_as_distance_to_same_point(self):
        """Check it actually computes distances"""
        position = AVAILABLE_STATION['latitud'], AVAILABLE_STATION['longitud']
        result = self.filter(distance(position),
                             (AVAILABLE_STATION, NO_BIKES_STATION))

        assert_that(result, contains(
            has_property('distance', 0.0),
            has_property('distance', all_of(greater_than(1401), less_than(1402)))
        ))
コード例 #23
0
ファイル: test_smoke.py プロジェクト: manojpkr/allure-python
def test_suite_times(report_for):
    start = time.time()

    report = report_for("""
    def test():
        assert True
    """)

    stop = time.time()

    assert_that(report.get('start'), has_float(all_of(
        greater_than(start * 1000),
        less_than(float(report.get('stop')))
    )))

    assert_that(report.get('stop'), has_float(all_of(
        greater_than(float(report.get('start'))),
        less_than(stop * 1000),
    )))
コード例 #24
0
    def test_get_cram_metadata(self):
        meta_list = arrayexpress.get_cram_metadata('oryza_sativa')
        assert_that(len(meta_list), greater_than(100))

        first = meta_list[0]
        assert_that(first.study_id, starts_with('DRP'))
        assert_that(first.sample_ids[0], starts_with('SAMD'))
        assert_that(first.biorep_id, starts_with('DRR'))
        assert_that(first.run_ids[0], starts_with('DRR'))
        assert_that(first.ftp_location, starts_with('ftp://ftp.ebi.ac.uk/pub/databases/arrayexpress/data/atlas/rnaseq'))
コード例 #25
0
ファイル: test_bridge.py プロジェクト: midonet/midonet
def test_dhcp():
    """
    Title: DHCP feature in MidoNet Bridge

    Scenario 1:
    Given: a bridge that has DHCP configurations
    When: a VM connected to the bridge sends DHCP requests,
    Then: the VM should get DHCP response accoridingly.
    """
    iface = BM.get_iface_for_port('bridge-000-001', 2)
    iface_new = BM.get_iface_for_port('bridge-000-001', 3)
    shared_lease = '/override/shared-%s.lease' % iface.get_ifname()
    try:

        # Check that interface has 1500 byte MTU before DHCP
        assert iface.get_mtu(update=True) == 1500

        # Check that namespace doesn't have routes before DHCP
        assert iface.get_num_routes(update=True) == 0

        # Run dhclient in the namespace for a while with a specific lease file
        # FIXME: wait 15 seconds? better to wait for an ack from the command?
        result = iface.execute(
            'dhclient -lf %s %s' % (shared_lease, iface.get_ifname()),
            timeout=15, sync=True)
        LOG.debug('dhclient got response: %s' % result)

        # Assert that the interface gets ip address
        assert_that(iface.get_cidr(update=True), equal_to('172.16.1.101/24'),
                    "Wrong CIDR")

        # TODO(tomoe): assert for default gw and static routes with opt 121
        assert_that(iface.get_num_routes(update=True), greater_than(0),
                    "No routes found")

        # MTU should be 1450 (interface mtu minus 50B, max of gre/vxlan overhead)
        assert_that(iface.get_mtu(update=True), equal_to(1450),
                    "Wrong MTU")

        # MI-536 regression test
        # Check that the 2nd vm using an incorrect lease file, receives a nack
        # without waiting for the request to timeout which is 60s.
        iface_new.update_interface_name(iface.get_ifname())
        result = iface_new.execute(
            'dhclient -lf %s %s' % (shared_lease, iface_new.get_ifname()),
            timeout=15, sync=True)
        LOG.debug('dhclient got response: %s' % result)

        # After 15s, check if the interface is correctly configured
        assert iface_new.get_cidr(update=True) == '172.16.1.100/24'
        assert iface_new.get_num_routes(update=True) > 0
        assert iface_new.get_mtu(update=True) == 1450
    finally:
        # Cleanup lease file
        iface.execute('rm -rf /override/shared-%s.lease' % iface.get_ifname())
コード例 #26
0
    def test__hamcrest_not__called_with_matcher(self):
        spy = doublex.Spy()
        spy.unexpected(2)

        self.assert_with_message(
            spy.unexpected,
            is_not(doublex.called().with_args(greater_than(1))),
            '''
Expected: not these calls:
          Spy.unexpected(a value greater than <1>)
     but: was ''')
    def test_write_memory_with_commit_delay(self, t):
        t.child.timeout = 10
        enable(t)
        start_time = time()
        t.write("write memory")
        t.readln("Building configuration...")
        t.readln("OK")
        t.read("my_switch#")
        end_time = time()

        assert_that((end_time - start_time), greater_than(COMMIT_DELAY))
コード例 #28
0
    def test_called_with_matcher(self):
        spy = doublex.Spy()

        self.assert_with_message(
            spy.unexpected,
            doublex.called().with_args(greater_than(1)),
            '''
Expected: these calls:
          Spy.unexpected(a value greater than <1>)
     but: calls that actually ocurred were:
          No one''')
コード例 #29
0
    def test_account_creation__3_accounts(self):
        with Stub(PasswordService) as password_service:
            password_service.generate().returns('some')

        store = Spy(AccountStore)
        service = AccountService(store, password_service)

        service.create_group('team', ['John', 'Peter', 'Alice'])

        assert_that(store.save, called().times(3))
        assert_that(store.save, called().times(greater_than(2)))
コード例 #30
0
 def test_handle_message_succeeded(self):
     result = self.dispatcher.handle_message(
         message=self.message,
         bound_handlers=self.daemon.bound_handlers,
     )
     assert_that(
         result,
         has_properties(
             elapsed_time=greater_than(0.0),
             result=MessageHandlingResultType.SUCCEEDED,
         ),
     )
コード例 #31
0
ファイル: test_strategies.py プロジェクト: moshez/moderation
def between(lower_bound, upper_bound):
    return all_of(
        greater_than(lower_bound),
        less_than(upper_bound),
    )
コード例 #32
0
 def test_delta(self):
     stock = self.get_stock()
     assert_that(len(stock['volume_delta']), greater_than(1))
     assert_that(stock.loc[20141219]['volume_delta'], equal_to(-63383600))
コード例 #33
0
ファイル: cachez_test.py プロジェクト: jealous/cachez
 def test_get_file_age(self):
     f = os.path.abspath(__file__)
     delta = Persisted.get_file_age(f)
     assert_that(delta, greater_than(0))
コード例 #34
0
def then_see_pptx_file_in_working_dir(context):
    assert_that(os.path.isfile(saved_pptx_path))
    minimum = 30000
    actual = os.path.getsize(saved_pptx_path)
    assert_that(actual, is_(greater_than(minimum)))
コード例 #35
0
 def test_get_persist_rsc_list(self):
     persist_rsc_list_2 = t_cli().get_persist_rsc_list()
     assert_that(len(persist_rsc_list_2), greater_than(3))
     assert_that(t_cli().curr_counter.get_rsc_list_collection(),
                 has_items(*persist_rsc_list_2))
コード例 #36
0
 def _is_rc_file_downloaded():
     waiter.expect_that(os.path.isfile(self._rc_path), equal_to(True))
     return waiter.expect_that(
         os.stat(self._rc_path).st_size, greater_than(0))
コード例 #37
0
 def test_wait(self):
     demo = RetryDemo()
     assert_that(demo.wait, raises(RetryTimeoutError))
     assert_that(demo.call_count, greater_than(2))
     assert_that(demo.call_count, less_than(6))
コード例 #38
0
 def testRunRightAverageAsync(self):
     m = self._build_instance()
     m.run(1, async=True)
     assert_that(m.execution_time, has_entries({'a': greater_than(0)}))
コード例 #39
0
ファイル: matchmock.py プロジェクト: alde/matchmock
def called():
    '''Match mock that was called one or more times'''

    return Called(anything(), count=greater_than(0))
コード例 #40
0
def test_zookeeper_status(znodes_list):
    expected_znodes_list = set(settings.ZOOKEEPER_NODES)
    znodes_list = set(znodes_list)
    min_intersection = len(znodes_list) // 2
    assert_that(znodes_list & expected_znodes_list,
                has_length(greater_than(min_intersection)))
コード例 #41
0
ファイル: test_heart_beat.py プロジェクト: optionalg/storops
 def test_interval_no_loop(self):
     hb = self.get_test_hb()
     assert_that(hb.command_count, equal_to(0))
     hb.interval = 1
     time.sleep(0.2)
     assert_that(hb.command_count, greater_than(0))
コード例 #42
0
    def check_images_pagination(self, image_names):
        """Step to check images pagination."""
        assert_that(image_names, has_length(greater_than(2)))

        ordered_names = []
        count = len(image_names)
        page_images = self._page_images()

        # image names can be unordered so we should try to retrieve
        # any image from image_names list
        def _get_current_image_name():
            rows = page_images.table_images.rows
            assert_that(rows, has_length(1))

            image_name = rows[0].cell('name').value
            assert_that(image_name, is_in(image_names))

            return image_name

        image_name = _get_current_image_name()
        ordered_names.append(image_name)

        assert_that(page_images.table_images.link_next.is_present,
                    equal_to(True))
        assert_that(page_images.table_images.link_prev.is_present,
                    equal_to(False))

        # check all elements except for the first and the last
        for _ in range(1, count - 1):
            page_images.table_images.link_next.click()
            image_name = _get_current_image_name()
            ordered_names.append(image_name)

            assert_that(page_images.table_images.link_next.is_present,
                        equal_to(True))
            assert_that(page_images.table_images.link_prev.is_present,
                        equal_to(True))

        page_images.table_images.link_next.click()
        volume_name = _get_current_image_name()
        ordered_names.append(volume_name)

        assert_that(page_images.table_images.link_next.is_present,
                    equal_to(False))
        assert_that(page_images.table_images.link_prev.is_present,
                    equal_to(True))

        page_images.table_images.link_prev.click()
        page_images.table_images.row(name=image_names[1]).wait_for_presence()

        assert_that(page_images.table_images.link_next.is_present,
                    equal_to(True))
        assert_that(page_images.table_images.link_prev.is_present,
                    equal_to(True))

        # check that all created image names have been checked
        assert_that(ordered_names, contains_inanyorder(*image_names))

        for i in range(count - 2, 0, -1):
            page_images.table_images.link_prev.click()
            page_images.table_images.row(
                name=ordered_names[i]).wait_for_presence()

            assert_that(page_images.table_images.link_next.is_present,
                        equal_to(True))
            assert_that(page_images.table_images.link_prev.is_present,
                        equal_to(True))

        page_images.table_images.link_prev.click()
        page_images.table_images.row(name=ordered_names[0]).wait_for_presence()

        assert_that(page_images.table_images.link_next.is_present,
                    equal_to(True))
        assert_that(page_images.table_images.link_prev.is_present,
                    equal_to(False))
コード例 #43
0
ファイル: matchers.py プロジェクト: vreuter/python-doublex
from .internal import (
    Method, InvocationContext, ANY_ARG, MockBase, SpyBase,
    PropertyGet, PropertySet, WrongApiUsage, Invocation)

__all__ = ['called',
           'never',
           'verify', 'any_order_verify',
           'property_got', 'property_set',
           'assert_that', 'wait_that',
           'is_', 'instance_of']


# just hamcrest aliases
at_least = hamcrest.greater_than_or_equal_to
at_most = hamcrest.less_than_or_equal_to
any_time = hamcrest.greater_than(0)


class MatcherRequiredError(Exception):
    pass


def assert_that(actual, matcher=None, reason=''):
    if matcher and not isinstance(matcher, Matcher):
        raise MatcherRequiredError("%s should be a hamcrest Matcher" % str(matcher))
    return hamcrest.assert_that(actual, matcher, reason)


def wait_that(actual, matcher, reason='', delta=1, timeout=5):
    '''
    Poll the given matcher each 'delta' seconds until 'matcher'
コード例 #44
0
ファイル: instances.py プロジェクト: zemuvier/stepler
 def check_instances_sum(self, instance_names, min_instances_sum=2):
     """Step to check quantity of instances."""
     assert_that(instance_names,
                 has_length(greater_than(min_instances_sum)))
コード例 #45
0
ファイル: test_int_date.py プロジェクト: sudodevnull/int_date
 def test_today(self):
     today = int_date.today()
     assert_that(today, greater_than(20150504))
コード例 #46
0
ファイル: api_access.py プロジェクト: zemuvier/stepler
 def _is_ec2_file_downloaded():
     return waiter.expect_that(
         os.stat(self._ec2_path).st_size, greater_than(0))
コード例 #47
0
ファイル: tests.py プロジェクト: Viktoria94/test
def test_1(new_environment):
    driver = new_environment

    with allure.step("1. Перейти на сайт:" + URL):
        driver.get(URL)

    with allure.step("2. Нажать на вкладку 'Транспорт'."):
        driver.find_element(*MainPageLocators.TRUCKS).click()

    with allure.step("3. Убедиться что произошел переход на страницу:" +
                     URL_TRUCKS):
        assert_that(driver.current_url, equal_to(URL_TRUCKS),
                    'Неверный адрес страницы!')

    with allure.step("4. В форме поиска в поле 'Откуда' написать 'Беларусь'."):
        time.sleep(1)
        driver.find_element(
            *TrucksPageLocators.INPUT_FROM).send_keys('Беларусь')

    with allure.step("5. Выбрать из выпадающего списка пункт 'Беларусь'"):
        time.sleep(1)
        driver.find_element(*TrucksPageLocators.DROPDOWN_MENU_FROM).click()

    with allure.step("6. В форме поиска в поле 'Куда' написать 'Россия'."):
        driver.find_element(*TrucksPageLocators.INPUT_TO).send_keys('Россия')

    with allure.step("7. Выбрать из выпадающего списка пункт 'Россия'."):
        time.sleep(1)
        driver.find_element(*TrucksPageLocators.DROPDOWN_MENU_TO).click()

    with allure.step("8. Нажать на кнопку 'Найти транспорт'."):
        time.sleep(1)
        button_search = driver.find_element(
            *TrucksPageLocators.BUTTON_SEARCH_TRUCKS)
        driver.execute_script("window.scrollTo(0,300);")
        ActionChains(driver).move_to_element(button_search).perform()
        button_search.click()

    with allure.step(
            "9. Убедиться что появились результаты поисковой выдачи."):
        time.sleep(2)
        search_results = driver.find_elements(
            *TrucksPageLocators.SEARCH_RESULTS)
        assert_that(search_results.__len__(), greater_than(0),
                    "Нет результатов поиска!")

    with allure.step(
            "10. Нажать на последней карточке поисковой выдачи (в конце страницы) по кнопке 'ПОКАЗАТЬ КОНТАКТЫ'."
    ):
        button_open_contacts = driver.find_element(
            *TrucksPageLocators.SHOW_CONTACTS)
        driver.execute_script("window.scrollTo(0,2500);")
        ActionChains(driver).move_to_element(
            button_open_contacts).click().perform()

    with allure.step(
            "11. Убедиться что появился попап регистрации пользователя."):
        time.sleep(1)
        pop_up_fast_reg = driver.find_element(
            *TrucksPageLocators.POP_UP_FAST_REG)
        driver.switch_to.frame(pop_up_fast_reg)
        pop_up_title = driver.find_element(
            *TrucksPageLocators.POPUP_FAST_REG_TITLE)
        assert_that(pop_up_title.is_displayed(), equal_to(True),
                    "Попап регистрации не появился!")
コード例 #48
0
    def test_that_find_users_returns_list_of_users(self):
        users = self.dut.get_marketplace_users()

        assert_that(len(users), is_(greater_than(0)))
コード例 #49
0
ファイル: matchmock.py プロジェクト: alde/matchmock
def called_with(*args, **kwargs):
    '''Match mock has at least one call with the specified arguments'''

    return Called(Call(match_args(args), match_kwargs(kwargs)),
                  count=greater_than(0))
コード例 #50
0
def test_feature_list():
    feature = vnx.get_pool_feature()
    assert_that(feature.existed, equal_to(True))
    assert_that(len(feature.available_disks), greater_than(0))
コード例 #51
0
 def testOK(self):
     solution, recur, exec_time = self._service.solve(999, [10] * 6)
     assert_that(len(solution), greater_than(0))
コード例 #52
0
    def test_returns_a_dictionary_of_various_hardware_and_software_versions(
            self):
        versions = self.client.get_versions()

        assert_that(isinstance(versions, dict))
        assert_that(len(versions), greater_than(0))
コード例 #53
0
def step_impl(context, minimum_file_size):
    minimum_file_size = int(minimum_file_size)
    file_size = os.path.getsize(context.output_file_path)
    assert_that(file_size, greater_than(minimum_file_size))
コード例 #54
0
def then_i_get_a_list_of_available_ticket_types(context):
    assert_that(context.ticket_types, has_length(greater_than(0)))
コード例 #55
0
def step_impl(context):
    with open(context.test_file_out, "rb") as data_file:
        context.encrypted_file_contents = data_file.read()
    assert_that(len(context.encrypted_file_contents), greater_than(10))
    assert_that(context.encrypted_file_contents,
                not_(contains(context.test_data)))
コード例 #56
0
def then_each_ticket_type_has_at_least_one_price_band(context):
    for ticket_type in context.ticket_types:
        assert_that(ticket_type.price_bands, has_length(greater_than(0)))
コード例 #57
0
 def test_width_and_holiness(self, my_grail):
     assert_that(
         my_grail,
         grail()
             .is_holy()
             .with_width(greater_than(4)))
コード例 #58
0
def then_each_price_band_has_a_price(context):
    for ticket_type in context.ticket_types:
        for price_band in ticket_type.price_bands:
            assert_that(price_band.seatprice, greater_than(0))
コード例 #59
0
ファイル: step_tutorial08.py プロジェクト: imbrra/logowanie
def step_impl(context):
    assert_that(context.duck_count, greater_than(0))
    assert_that(context.red_button_pressed, greater_than(0))
コード例 #60
0
def step_impl(context, kind: str):
    """Check if we have at least one result."""
    assert_that(len(context.result[f"{kind}_environments"]), greater_than(0))