def test_data_coverage_when_quarter_not_requested(self): services = [ Service(details({ "2012-Q4 Vol.": "2,000", '2012-Q4 Digital vol.': '10', u'2012-Q4 CPT (\xa3)': "2.00", "2013-Q1 Vol.": "***", u'2013-Q1 CPT (\xa3)': "***", '2013-Q1 Digital vol.': '***', u'High-volume?': 'yes' })), Service(details({ "2012-Q4 Vol.": "1,000", u'2012-Q4 CPT (\xa3)': "3.00", '2012-Q4 Digital vol.': '10', u'High-volume?': 'yes' })), ] dept = Department("Agency for Beautiful Code", services) coverage = dept.data_coverage assert_that(float(coverage.percentage), close_to(0.1333333, 0.001)) assert_that(coverage.requested, is_(45)) assert_that(coverage.provided, is_(6))
def test_should_report_id_in_xml_tag_if_one_is_provided(self): suite = XunitSuite("my_name") result = suite.to_xml(id=2) assert_that(result.attrib['id'], is_("2")) result = suite.to_xml(id=8) assert_that(result.attrib['id'], is_("8"))
def task_finishes_with_status(context, status): """Wait for task finished: status != syncing""" i = 0 task_status = None while i < MAX_WAIT_TASK_FINISHED: body, response = \ context.glancesync_api_client.get_task_api_client(context.region_name).get_task_details(context.task_id) assert_that(str(response.status_code), is_(equal_to("200")), "HTTP Status code is for TASK request not the expected one.") assert_that(body, has_key('status'), "The response of TASK request does not contain the expected attribute.") task_status = body['status'] if task_status != "syncing": break __logger__.info("#%s Waiting for TASK final status. Status: %s", i, status) time.sleep(WAIT_SECONDS) i += 1 assert_that(task_status, is_(equal_to(status)), "The task has not been successfully executed.")
def test_produce_custom_topic(): """ Producer delegates to SNS client. """ def loader(metadata): return dict( sns_topic_arns=dict( default=None, mappings={ DerivedSchema.MEDIA_TYPE: "special-topic", }, ) ) graph = create_object_graph("example", testing=True, loader=loader) graph.use("opaque") # set up response graph.sns_producer.sns_client.publish.return_value = dict(MessageId=MESSAGE_ID) message_id = graph.sns_producer.produce(DerivedSchema.MEDIA_TYPE, data="data") assert_that(graph.sns_producer.sns_client.publish.call_count, is_(equal_to(1))) assert_that(graph.sns_producer.sns_client.publish.call_args[1]["TopicArn"], is_(equal_to("special-topic"))) assert_that(loads(graph.sns_producer.sns_client.publish.call_args[1]["Message"]), is_(equal_to({ "data": "data", "mediaType": DerivedSchema.MEDIA_TYPE, "opaqueData": {}, }))) assert_that(message_id, is_(equal_to(MESSAGE_ID)))
def test_download_datapackage(self, helpers, config, test_datapackages_path, api_client, dataset_key): datapackage_zip = path.join(test_datapackages_path, 'the-simpsons-by-the-data.zip') with responses.RequestsMock() as rsps, open(datapackage_zip, 'rb') as file: @helpers.validate_request_headers() def datapackage_endpoint(_): return 200, {}, file.read() rsps.add_callback( rsps.GET, 'https://download.data.world/datapackage/agentid/datasetid', datapackage_endpoint) datapackage = api_client.download_datapackage(dataset_key, config.cache_dir) assert_that(datapackage, equal_to( path.join(config.cache_dir, 'datapackage.json'))) assert_that(path.isfile(datapackage), described_as('%0 is a file', is_(True), datapackage)) data_subdirectory = path.join(config.cache_dir, 'data') assert_that(path.isdir(data_subdirectory), described_as('%0 is a directory', is_(True), data_subdirectory)) assert_that(os.listdir(config.tmp_dir), described_as('%0 is empty', empty(), config.tmp_dir))
def test_get(self): node = NodeFactory() status_code, json_response = self.get({'id': node.id}) assert_that(status_code, is_(200)) assert_that(json_response['name'], is_(node.name))
def test_list_returns_all_if_omniscient_nd_collector_view_but_no_ownership( self): view = TestResourceViewCollector() request = HttpRequest() request.method = 'GET' request.META['HTTP_AUTHORIZATION'] = \ 'Bearer correct-token' settings.USE_DEVELOPMENT_USERS = False signon = govuk_signon_mock( permissions=['omniscient', 'collector-view']) with HTTMock(signon): response = view.get(request) try: json_response = json.loads(response.content) except ValueError: json_response = None assert_that(response.status_code, is_(200)) assert_that(len(json_response), is_(2)) assert_that(json_response, contains_inanyorder( has_entry("name", starts_with( self.__class__.collector_type1.name)), has_entry("name", starts_with( self.__class__.collector_type2.name))))
def test_health_check_custom_check_failed(): """ Should return 503 on health check failure. """ loader = load_from_dict( health_convention=dict( include_build_info="false", ), ) graph = create_object_graph(name="example", testing=True, loader=loader) graph.use("health_convention") client = graph.flask.test_client() def fail(graph): raise Exception("failure!") graph.health_convention.checks["foo"] = fail response = client.get("/api/health") assert_that(response.status_code, is_(equal_to(503))) data = loads(response.get_data().decode("utf-8")) assert_that(data, is_(equal_to({ "name": "example", "ok": False, "checks": { "foo": { "message": "failure!", "ok": False, }, }, })))
def test_batch_last_updated(self): records = { # timestamps in ascending order 'some_data': [ {'_timestamp': d_tz(2018, 1, 1)}, {'_timestamp': d_tz(2019, 1, 1)}, {'_timestamp': d_tz(2020, 1, 1)}, ], # timestamps in descending order 'some_other_data': [ {'_timestamp': d_tz(2017, 1, 1)}, {'_timestamp': d_tz(2016, 1, 1)}, {'_timestamp': d_tz(2015, 1, 1)}, ] } for key, items in records.iteritems(): self.engine.create_data_set(key, 0) for item in items: self.engine.save_record(key, item) some_data_set = DataSet(self.engine, {'name': 'some_data'}) some_other_data_set = DataSet(self.engine, {'name': 'some_other_data'}) yet_another_data_set = DataSet(self.engine, {'name': 'yet_another_data'}) self.engine.batch_last_updated([some_data_set, some_other_data_set, yet_another_data_set]) some_data_set_last_updated = some_data_set.get_last_updated() some_other_data_set_last_updated = some_other_data_set.get_last_updated() yet_another_data_set_last_updated = yet_another_data_set.get_last_updated() assert_that(some_data_set_last_updated, is_(d_tz(2020, 1, 1, 0, 0, 0))) assert_that(some_other_data_set_last_updated, is_(d_tz(2017, 1, 1, 0, 0, 0))) assert_that(yet_another_data_set_last_updated, is_(none()))
def test_grid_query(self): grid = Grid(11.0, 12.0, 51.0, 52.0, 0.1, 0.2, self.srid) query = self.query_builder.grid_query("<table_name>", grid, count_threshold=0, time_interval=TimeInterval(self.start_time, self.end_time)) assert_that(str(query), is_( "SELECT TRUNC((ST_X(ST_Transform(geog::geometry, %(srid)s)) - %(xmin)s) / %(xdiv)s)::integer AS rx, " "TRUNC((ST_Y(ST_Transform(geog::geometry, %(srid)s)) - %(ymin)s) / %(ydiv)s)::integer AS ry, " "count(*) AS strike_count, max(\"timestamp\") as \"timestamp\" FROM <table_name> " "WHERE ST_GeomFromWKB(%(envelope)s, %(envelope_srid)s) && geog AND " "\"timestamp\" >= %(start_time)s AND \"timestamp\" < %(end_time)s GROUP BY rx, ry")) parameters = query.get_parameters() assert_that(parameters.keys(), contains_inanyorder('xmin', 'ymin', 'xdiv', 'ydiv', 'envelope', 'envelope_srid', 'srid', 'start_time', 'end_time')) assert_that(parameters.keys(), not contains_inanyorder('count_threshold')) assert_that(parameters['xmin'], is_(11.0)) assert_that(parameters['ymin'], is_(51.0)) assert_that(parameters['xdiv'], is_(0.1)) assert_that(parameters['ydiv'], is_(0.2)) assert_that(parameters['envelope'], is_(not_none())) assert_that(parameters['envelope_srid'], is_(self.srid)) assert_that(parameters['start_time'], is_(self.start_time)) assert_that(parameters['end_time'], is_(self.end_time)) assert_that(parameters['srid'], is_(self.srid))
def test_health_check_custom_check(): """ Should return Custom health check results. """ loader = load_from_dict( health_convention=dict( include_build_info="false", ), ) graph = create_object_graph(name="example", testing=True, loader=loader) graph.use("health_convention") client = graph.flask.test_client() graph.health_convention.checks["foo"] = lambda graph: "hi" response = client.get("/api/health") assert_that(response.status_code, is_(equal_to(200))) data = loads(response.get_data().decode("utf-8")) assert_that(data, is_(equal_to({ "name": "example", "ok": True, "checks": { "foo": { "message": "hi", "ok": True, }, }, })))
def test_float_number(): query = { "id": "12345", "metrics": ["rate"], "dimensions": [], } expected_response_0 = { "start_date": date(2013, 4, 1), "end_date": date(2013, 4, 7), "metrics": {"rate": "23.4"}, } client = mock.Mock() client.query.get.side_effect = [ [expected_response_0], ] items = query_for_range(client, query, date(2013, 4, 1), date(2013, 4, 7)) assert_that(len(items), is_(1)) (response_0,) = items assert_that(response_0, is_(expected_response_0)) (doc_0,) = build_document_set(items, "", None, None) assert_that(doc_0['rate'], is_(23.4))
def test_bent_vertical(self): """ Test that horizontal corridor with bend can be made """ edge_connection = Connection(connection=None, location=(9, 0), direction="down", section=self.section) room_connection = Connection(connection=None, location=(2, 9), direction="up", section=self.section) add_section_connection(self.section, edge_connection) add_room_connection(self.section, (2, 9), "up") generator = CorridorGenerator(start_point=edge_connection, end_point=room_connection, wall_tile=None, floor_tile=self.floor_rock) generator.generate() assert_that(wall_tile(self.level, (9, 0)), is_(equal_to(None))) assert_that(wall_tile(self.level, (2, 9)), is_(equal_to(None))) assert_that(self.level, is_fully_accessible())
def test_error_wrap(): """ Wrapped errors work properly. """ graph = create_object_graph(name="example", testing=True) def fail(): raise Exception("fail") @graph.app.route("/wrap") @graph.audit def wrap(): try: fail() except Exception as error: raise Exception(error) client = graph.app.test_client() response = client.get("/wrap") assert_that(response.status_code, is_(equal_to(500))) data = response.json assert_that(data, is_(equal_to({ "code": 500, "message": "fail", "retryable": False, "context": {"errors": []} })))
def test_werkzeug_http_error(): """ Explicit HTTP errors are reported as expected. """ graph = create_object_graph(name="example", testing=True) @graph.app.route("/not_found") @graph.audit def not_found(): raise NotFound client = graph.app.test_client() response = client.get("/not_found") assert_that(response.status_code, is_(equal_to(404))) data = response.json assert_that(data, is_(equal_to({ "code": 404, "context": { "errors": [], }, "message": "The requested URL was not found on the server. " "If you entered the URL manually please check your spelling and try again.", "retryable": False, })))
def test_compare_configuration(self): result = self.nc.compare_configuration() output = result.xpath("configuration-information/configuration-output")[0] assert_that(output.text.strip(), is_("")) self.edit({ "vlans": [ {"vlan": [ {"name": "VLAN2995"}, {"vlan-id": "2995"}]}, ]}) result = self.nc.compare_configuration() output = result.xpath("configuration-information/configuration-output")[0] assert_that(output.text.strip(), is_not("")) self.nc.commit() result = self.nc.compare_configuration() output = result.xpath("configuration-information/configuration-output")[0] assert_that(output.text.strip(), is_(""))
def test_custom_error_retryable(): """ Custom errors status codes are handled as expected. """ graph = create_object_graph(name="example", testing=True) @graph.app.route("/conflict") @graph.audit def conflict(): raise MyConflictError("Conflict") client = graph.app.test_client() response = client.get("/conflict") assert_that(response.status_code, is_(equal_to(409))) data = response.json assert_that(data, is_(equal_to({ "code": 409, "message": "Conflict", "retryable": True, "context": { "errors": [{ "message": "Banana!", }] }, })))
def test_get_component_hierarchy(self, fake_find): # This is a lousy test, just testing what we already see done, not # correct behaviour pers_comps = BaseComponents(BASE, 'persistent', (BASE,)) class MockSite(object): __parent__ = None __name__ = None def __init__(self): self.__parent__ = {} site_comps_1 = BaseComponents(pers_comps, '1', (pers_comps,)) site_comps_2 = BaseComponents(site_comps_1, '2', (site_comps_1,)) site = MockSite() site.__parent__[site_comps_1.__name__] = site_comps_1 site.__parent__[site_comps_2.__name__] = site_comps_2 fake_find.is_callable().returns(site_comps_2) x = list(get_component_hierarchy(site)) assert_that(x, is_([site_comps_2, site_comps_1])) x = list(get_component_hierarchy_names(site)) assert_that(x, is_(['2', '1'])) x = list(get_component_hierarchy_names(site, reverse=True)) assert_that(x, is_(['1', '2']))
def _store_base_subs_in_zodb(self, storage): db = DB(storage) conn = db.open() base_comps = BLSM(None) base_comps.btree_threshold = 0 base_comps.__name__ = u'base' # replace with "broken" base_comps.adapters = _LocalAdapterRegistry() base_comps.utilities = _LocalAdapterRegistry() sub_comps = BLSM(None) sub_comps.__name__ = u'sub' sub_comps.__bases__ = (base_comps,) assert_that(sub_comps.adapters.__bases__, is_((base_comps.adapters,))) assert_that(sub_comps.utilities.__bases__, is_((base_comps.utilities,))) assert_that(sub_comps.utilities.__bases__[0], is_(_LocalAdapterRegistry)) conn.root()['base'] = base_comps conn.root()['sub'] = sub_comps transaction.commit() conn.close() db.close()
def test_portal_has_icons(self): """ Test that portal created by adder has two icons set One to display and another to be used by opposite end """ level = (LevelBuilder() .with_size((20, 20)) .with_floor_tile(self.floor_rock) .with_wall_tile(self.wall_empty) .build()) level_generator = mock() for loc_y in range(8, 12): for loc_x in range(8, 12): add_location_tag(level, (loc_x, loc_y), 'room') portal_adder = PortalAdder((1, 2), 'room', level_generator, False, self.rng) portal_adder.add_portal(level) portals = [] for loc_y in range(8, 12): for loc_x in range(8, 12): temp = get_portal(level, (loc_x, loc_y)) if temp: portals.append(temp) portal = portals[0] assert_that(portal.icon, is_(equal_to(1))) assert_that(portal.other_end_icon, is_(equal_to(2)))
def test_configure_engine(): """ Engine factory should work with zero configuration. """ graph = create_object_graph(name="example", testing=True) engine = graph.postgres assert_that(engine, is_(instance_of(Engine))) # engine has expected configuration assert_that( str(engine.url), starts_with("postgresql://example:@"), ) assert_that( str(engine.url), ends_with(":5432/example_test_db"), ) # engine supports connections with engine.connect() as connection: row = connection.execute("SELECT 1;").fetchone() assert_that(row[0], is_(equal_to(1)))
def _key_is_stored_in_the_server_helper(context, keyfile_name, keyfile_content): """ Step HELPER. Check if the given keyfile is stored in the server. Performe assertions. :param context: Context :param keyfile_name (string): File name with the key to be uploaded. e.i. 'Spain2.sshkey' :param keyfile_conent (string): The file with the content (key value) to be checked. e.i 'Spain2b.sshkey' :return: None """ aiakos_keyfile_path = configuration_manager.config[PROPERTIES_CONFIG_AIAKOS][PROPERTIES_CONFIG_AIAKOS_KEYFILES_PATH] # Assert: Remote file exists if aiakos_keyfile_path == "": result = True else: result = context.remote_executor.file_exist(aiakos_keyfile_path, keyfile_name) assert_that( result, is_(True), "Remote file '{}/{}' does not exist in remote host".format(aiakos_keyfile_path, keyfile_name) ) # Assert: Content of the remote file is the expected one ssh_key_filepath = os.path.join(RESOURCES_PATH, keyfile_content) with open(ssh_key_filepath, "r") as file_content: if aiakos_keyfile_path == "": result = True else: result = context.remote_executor.content_in_file(aiakos_keyfile_path, keyfile_name, file_content.read()) assert_that( result, is_(True), "Remote file '{}/{}' does not contains the expected key".format(aiakos_keyfile_path, keyfile_name), )
def test_fix_timezone(self): assert_that(self.base.fix_timezone(None), is_(none())) time = datetime.datetime(2013, 1, 1, 12, 0, 0, tzinfo=pytz.timezone("CET")) utc_time = datetime.datetime(2013, 1, 1, 11, 0, 0, tzinfo=pytz.timezone("UTC")) assert_that(self.base.fix_timezone(time), is_(utc_time))
def test_discovery(): graph = create_object_graph(name="example", testing=True) graph.use("discovery_convention") ns = Namespace("foo") @graph.route(ns.collection_path, Operation.Search, ns) def search_foo(): pass client = graph.flask.test_client() response = client.get("/api") assert_that(response.status_code, is_(equal_to(200))) data = loads(response.get_data().decode("utf-8")) assert_that(data, is_(equal_to({ "_links": { "search": [{ "href": "http://localhost/api/foo?offset=0&limit=20", "type": "foo", }], "self": { "href": "http://localhost/api?offset=0&limit=20", }, } })))
def step_then_auto_shape_appears_in_slide(context): prs = Presentation(saved_pptx_path) sp = prs.slides[0].shapes[0] sp_text = sp.textframe.paragraphs[0].runs[0].text assert_that(sp.shape_type, is_(equal_to(MSO.AUTO_SHAPE))) assert_that(sp.auto_shape_type, is_(equal_to(MAST.ROUNDED_RECTANGLE))) assert_that(sp_text, is_(equal_to(test_text)))
def test_get_raw_data_since(self): last_data = datetime.datetime.utcnow() - datetime.timedelta(hours=1) self.data_url.build_path.side_effect = ['full_url1', 'full_url2'] self.url_path_generator.get_paths.return_value = ['url_path1', 'url_path2'] self.data_provider.read_lines.side_effect = [["line11", "line12"], ["line21", "line22"]] raw11 = Mock(name='raw11') raw12 = Mock(name='raw12') raw21 = Mock(name='raw21') raw22 = Mock(name='raw22') self.builder.from_string.return_value = self.builder self.builder.build.side_effect = [raw11, raw12, raw21, raw22] region_id = 5 station_id = 123 raw_signals = list(self.provider.get_raw_data_since(last_data, region_id, station_id)) expected_args = [call(last_data)] assert_that(self.url_path_generator.get_paths.call_args_list, is_(equal_to(expected_args))) expected_args = [ call('{}/url_path1'.format(station_id), region=region_id, host_name='signals'), call('{}/url_path2'.format(station_id), region=region_id, host_name='signals')] assert_that(self.data_url.build_path.call_args_list, is_(equal_to(expected_args))) expected_args = [call('full_url1'), call('full_url2')] assert_that(self.data_provider.read_lines.call_args_list, is_(equal_to(expected_args))) assert_that(raw_signals, contains(raw11, raw12, raw21, raw22))
def test_object(): """ Can create a class for an object schema. """ registry = Registry() registry.load(schema_for("data/name.json")) Name = registry.create_class(NAME_ID) name = Name( first="George", ) assert_that(calling(name.validate), raises(ValidationError)) name.last = "Washington" name.validate() assert_that( name, has_properties( first=equal_to("George"), last=equal_to("Washington"), ) ) assert_that(name, is_(equal_to(NAME))) assert_that(name, is_(equal_to(Name(**NAME)))) assert_that(Name.loads(name.dumps()), is_(equal_to(name))) del name.first assert_that(calling(name.validate), raises(ValidationError))
def test_from_name(): """ Operations can be looked up by name. """ assert_that(Operation.from_name("search"), is_(equal_to(Operation.Search))) assert_that(Operation.from_name("Create"), is_(equal_to(Operation.Create)))
def test_GIVEN_categories_have_land_cover_regions_WHEN_get_categories_THEN_category_has_regions_loaded(self): model_run = self.model_run_service.get_model_being_created_with_non_default_parameter_values(self.user) with session_scope() as session: cat1 = LandCoverRegionCategory() cat1.name = "Countries" cat1.driving_dataset_id = model_run.driving_dataset_id region1 = LandCoverRegion() region1.mask_file = "filepath" region1.name = "Wales" region1.category = cat1 cat2 = LandCoverRegionCategory() cat2.name = "Rivers" cat2.driving_dataset_id = model_run.driving_dataset_id region2 = LandCoverRegion() region2.mask_file = "filepath2" region2.name = "Thames" region2.category = cat2 session.add_all([region1, region2]) categories = self.land_cover_service.get_land_cover_categories(model_run.driving_dataset_id) assert_that(len(categories[0].regions), is_(1)) assert_that(categories[0].regions[0].name, is_("Wales"))
def test_GIVEN_attributes_WHEN_calculate_gridded_THEN_attributes_set_on_output(self): self._make_two_gridded() expr = 'var1 + var2' attributes = {'att1': 'val1', 'att2': 'val2'} res = self.calc.evaluate(self.data, expr, attributes=attributes) assert_that(res.attributes['att1'], is_('val1')) assert_that(res.attributes['att2'], is_('val2'))
def test_is_trap_by_rule3(self): assert_that(is_trap(TRAP + SAFE + SAFE), is_(True))
def test_row_craft6(self): assert_that(craft_row(".^^^^.^^.^"), is_("^^..^.^^.."))
def test_row_craft5(self): assert_that(craft_row("..^^...^^^"), is_(".^^^^.^^.^"))
def test_get_3_tiles_limits(self): assert_that(tiles(".^.", -1, 1), is_("..^")) assert_that(tiles(".^.", 1, 3), is_("^.."))
def test_get_3_tiles_middle(self): assert_that(tiles(".^.", 0, 2), is_(".^.")) assert_that(tiles("^.^.^", 1, 3), is_(".^."))
def test_is_safe(self): assert_that(is_trap(SAFE + SAFE + SAFE), is_(False)) assert_that(is_trap(TRAP + TRAP + TRAP), is_(False)) assert_that(is_trap(TRAP + SAFE + TRAP), is_(False))
def test_is_trap_by_rule4(self): assert_that(is_trap(SAFE + SAFE + TRAP), is_(True))
def test_dont(self): self.registry["a"] = 0 move = JumpOnPositive()(self.registry, Var(self.registry, "a"), Scalar(3)) assert_that(move, is_(None))
def test(self): self.registry["a"] = 5 MultiplyValue()(self.registry, Var(self.registry, "a"), Scalar(5)) assert_that(self.registry["a"], is_(25))
def test_official(self): assert_that(compute(".^^.^.^^^^", rows=10), is_(38))
def test(self): AddValue()(self.registry, Var(self.registry, "a"), Scalar(1)) AddValue()(self.registry, Var(self.registry, "a"), Scalar(1)) assert_that(self.registry["a"], is_(2))
def test(self): self.registry["a"] = 5 ModValue()(self.registry, Var(self.registry, "a"), Scalar(3)) assert_that(self.registry["a"], is_(2))
def test(self): queue = deque() Send(queue)(self.registry, Scalar(1)) assert_that(queue.popleft(), is_(1))
def test(self): SubValue()(self.registry, Var(self.registry, "a"), Scalar(1)) SubValue()(self.registry, Var(self.registry, "a"), Scalar(1)) assert_that(self.registry["a"], is_(-2))
def test_optional(self): validate = is_dict_with(mybool=optional(is_type(bool))) assert_that(validate("{}"), is_({}))
def test(self): queue = deque((13, )) Receive(queue)(self.registry, Var(self.registry, "a")) assert_that(self.registry["a"], is_(13))
def test_empty(self): validate = is_dict_with() assert_that(validate("{}"), is_({}))
def test_do_negative(self): self.registry["a"] = -5 move = JumpOnNonZero()(self.registry, Var(self.registry, "a"), Scalar(3)) assert_that(move, is_(3))
def test_links_empty(): links = Links() assert_that(links.to_dict(), is_(equal_to({})))
def test_one_boolean(self): validate = is_dict_with(mybool=is_type(bool)) data = {"mybool": True} assert_that(validate(json.dumps(data)), is_(data))
def test_is_not_empty_when_holding_tags(): metadata = Metadata() metadata["artist"] = "John Doe" metadata.addImage("img/jpeg", "...") assert_that(metadata.empty(), is_(False), "emptiness")
def test_link_to_dict(): link = Link(href="href", ) assert_that(link.to_dict(), is_(equal_to({ "href": "href", })))
def test_is_initially_empty(): metadata = Metadata() assert_that(metadata, empty(), "tags") assert_that(list(metadata.images), empty(), "images") assert_that(metadata.empty(), is_(True), "emptiness")
def test_is_empty_when_cleared(): metadata = Metadata() metadata["artist"] = "John Doe" metadata.addImage("img/jpeg", "...") metadata.clear() assert_that(metadata.empty(), is_(True), "emptiness")
def _assert_equal(normalized_uri, expected): assert_that(normalized_uri, is_(equal_to(expected)))
def test_is_not_empty_when_containing_images(): metadata = Metadata() metadata.addImage("img/jpeg", "...") assert_that(metadata.empty(), is_(False), "emptiness")
def test_swagger_path(self): with self.graph.app.test_request_context(): path = build_path(Operation.CreateCollection, self.ns) assert_that(path, is_(equal_to("/api/foo")))
def test_uri_load(): schema = URISchema(strict=True) result = schema.load(dict( foo="http://example.com", )) assert_that(result.data["foo"], is_(equal_to("http://example.com")))
def test_create_collection_url(self): with self.graph.app.test_request_context(): url = self.ns.url_for(Operation.CreateCollection) assert_that(url, is_(equal_to("http://localhost/api/foo")))
def test_returns_an_interface(self): interface = self.client.get_interface(self.test_ports[0].name) assert_that(interface.name, is_(self.test_ports[0].name))