def step_impl(context, challenge_id): context.json_object = json.loads(context.rv.body) assert_that(context.json_object, has_key("error")) if context.json_object["error"] is False: assert_that(context.json_object, has_key("challenge_id")) assert_that(context.json_object["challenge_id"], equal_to(int(challenge_id)))
def test_mapping_of_piwik_datapoint_keys(self): parser = build_parser() parsed_data = parser.parse(get_piwik_data()) assert_that(parsed_data[0], has_key('browser')) assert_that(parsed_data[0], has_key('sessions')) self.assertFalse('label' in parsed_data[0]) self.assertFalse('nb_visits' in parsed_data[0])
def test_update_instance_flavor_for_terminated_instance(self): some_new_flavor = 'some_new_flavor' data = dict(flavor=some_new_flavor) start = '2016-03-01 00:00:00.000000' end = '2016-03-03 00:00:00.000000' self.controller.should_receive('update_inactive_entity') \ .with_args( instance_id="INSTANCE_ID", start=a_date_matching(start), end=a_date_matching(end), flavor=some_new_flavor, ).and_return(a( instance(). with_id('INSTANCE_ID'). with_start(2016, 03, 01, 00, 0, 00). with_end(2016, 03, 03, 00, 0, 00). with_flavor(some_new_flavor)) ) code, result = self.api_put( '/entity/instance/INSTANCE_ID', headers={'X-Auth-Token': 'some token value'}, query_string={ 'start': start, 'end': end, }, data=data, ) assert_that(code, equal_to(200)) assert_that(result, has_key('entity_id')) assert_that(result, has_key('flavor')) assert_that(result['flavor'], is_(some_new_flavor))
def test_get(self): collector = CollectorFactory() response = self.client.get( '/collector/{}'.format(collector.slug), HTTP_AUTHORIZATION='Bearer development-oauth-access-token', content_type='application/json') assert_that(response.status_code, equal_to(200)) resp_json = json.loads(response.content) assert_that(resp_json['id'], equal_to(str(collector.id))) assert_that(resp_json['slug'], equal_to(collector.slug)) assert_that(resp_json['name'], equal_to(collector.name)) assert_that(resp_json['type']['name'], equal_to( collector.type.name)) assert_that(resp_json['type']['slug'], equal_to( collector.type.slug)) assert_that(resp_json['entry_point'], equal_to( collector.type.entry_point)) assert_that( resp_json['data_source']['name'], equal_to( collector.data_source.name)) assert_that(resp_json['data_set']['data_type'], equal_to( collector.data_set.data_type.name)) assert_that(resp_json['data_set']['data_group'], equal_to( collector.data_set.data_group.name)) assert_that(resp_json['data_set'], has_key('bearer_token')) assert_that(resp_json['query'], equal_to(collector.query)) assert_that(resp_json['options'], equal_to(collector.options)) assert_that(resp_json['provider']['slug'], equal_to( collector.type.provider.slug)) assert_that(resp_json['provider']['name'], equal_to( collector.type.provider.name)) assert_that(resp_json, not(has_key('owners')))
def test_application_info(self): app_info = { 'text_key': u'a value', 'byte_key': b'bytes', 'int_key': 7, 'list_key': [42,] } class IA(Interface): field = Attribute("A field") field.setTaggedValue(jsonschema.TAG_APPLICATION_INFO, app_info) schema = TranslateTestSchema(IA, context=u' TEST').make_schema() assert_that(schema, has_key("field")) field = schema['field'] assert_that(field, has_key("application_info")) # The dict itself was copied assert_that(field['application_info'], is_not(same_instance(app_info))) # as were its contents assert_that(field['application_info'], has_entry('list_key', is_([42]))) assert_that(field['application_info'], has_entry('list_key', is_not(same_instance(app_info['list_key'])))) # Text strings were translated assert_that(field['application_info'], has_entry('text_key', u'a value TEST')) # Byte strings were not (is that even legel in json?) assert_that(field['application_info'], has_entry('byte_key', b'bytes'))
def test_removes_old_ipi_frames(mp3): filename = mp3(TXXX_IPI_Joel_Miller="00000123456789", TXXX_IPI_Rebecca_Ann_Maloy="98765432100000") container.save(filename, Metadata(ipis={"Joel Miller": "00000123456789"})) tags = MP3(filename) assert_that(tags, all_of(has_key("TXXX:IPI:Joel Miller"), not_(has_key("TXXX:IPI:Rebecca Ann Maloy"))), "tags in file")
def step_impl(context): context.json_object = json.loads(context.rv.body) assert_that(context.json_object, has_key("game")) assert_that(context.json_object["game"], has_key(u'original_release_date')) assert_that(context.json_object["game"], has_key(u'description')) assert_that(context.json_object["game"], has_key(u'image')) assert_that(context.json_object["game"], has_key(u'name'))
def assert_response_for_list(self, response, expected): assert_that(response.status_code, equal_to(200)) data = self._serialize_decode(response.data) assert_that(data, has_key('total')) assert_that(data, has_key('items')) list_assertion = contains(*(self._build_assertion(i) for i in data['items'])) assert_that(data['items'], list_assertion)
def test_dict_should_behave_as_dict(self): config = probe(path=_dir("single-file"), patterns=["(*).yaml"]) assert_that(config["stuff"]["key"], is_("stuff-value")) assert_that(dict(config), has_key('stuff')) assert_that(dict(**config), has_key('stuff')) assert_that(dict(config.stuff), has_key('key')) assert_that(dict(**config.stuff), has_key('key'))
def test_removes_contributor_from_chain_of_title(): chain_of_title = make_chain_of_title( authors_composers=[joel_miller(), john_roney(), contributor("Yoko Ono"), contributor("John Lennon")], publishers=[effendi_records(), contributor("Effendi Records")]) chain_of_title.update(lyricists=["Joel Miller"], composers=["John Lennon"], publishers=["Effendi Records"]) assert_that(chain_of_title, not_(any_of(has_key("John Roney"), has_key("Yoko Ono"), has_key("Universals"))), "The chain of title")
def test_removes_deprecated_frames_on_save(mp3): filename = mp3(TXXX_Tagger="TGiT v1.1", TXXX_TAGGING_TIME="2014-03-26 14:18:55 EDT-0400", TXXX_UPC="987654321111") container.save(filename, Metadata()) tags = MP3(filename) assert_that(tags, all_of(not_(has_key("TXXX:Tagger")), not_(has_key("TXXX:TAGGING_TIME")), not_(has_key("TXXX:UPC"))), "tags in file")
def task_information_is_retrieved(context): """TASK status data is retrieved""" assert_that(str(context.response.status_code), is_(equal_to("200")), "HTTP Status code is for TASK INFORMATION request not the expected one.") assert_that(context.body, has_key('taskId'), "The response of TASK INFORMATION request does not contain the expected attribute.") assert_that(context.body, has_key('status'), "The response of TASK INFORMATION request does not contain the expected attribute.")
def test_to_user_data(self): line_sip = LineSIP() line_sip.private_value = 'private_value' provisioning_extension = line_sip.provisioning_extension = '192837' username = line_sip.username = '******' line_sip_dict = line_sip.to_user_data() assert_that(line_sip_dict, has_entries({ 'provisioning_extension': provisioning_extension, 'username': username, })) assert_that(line_sip_dict, all_of(is_not(has_key('private_value')), # not mapped is_not(has_key('secret')))) # not set
def test_swagger(self): response = self.client.get("/api/swagger") assert_that(response.status_code, is_(equal_to(200))) data = loads(response.data) upload = data["paths"]["/file"]["post"] upload_for = data["paths"]["/person/{person_id}/file"]["post"] # both endpoints return form data assert_that( upload["consumes"], contains("multipart/form-data"), ) assert_that( upload_for["consumes"], contains("multipart/form-data"), ) # one endpoint gets an extra query string parameter (and the other doesn't) assert_that( upload["parameters"], has_item( has_entries(name="extra"), ), ) assert_that( upload_for["parameters"], has_item( is_not(has_entries(name="extra")), ), ) # one endpoint gets a custom response type (and the other doesn't) assert_that( upload["responses"], all_of( has_key("204"), is_not(has_key("200")), has_entry("204", is_not(has_key("schema"))), ), ) assert_that( upload_for["responses"], all_of( has_key("200"), is_not(has_key("204")), has_entry("200", has_entry("schema", has_entry("$ref", "#/definitions/FileResponse"))), ), )
def test_create_data_set(self): self.engine.create_data_set('should_have_index', 0) coll = self.engine._collection('should_have_index') indicies = coll.index_information() assert_that(indicies, has_key('_timestamp_-1'))
def test_volume_type_with_authentication(self): self.having_config('api_auth_token', 'some token value') self.controller.should_receive('get_volume_type') \ .with_args('A_VOLUME_TYPE_ID') \ .and_return([a(volume_type().with_volume_type_id('A_VOLUME_TYPE_ID') .with_volume_type_name('some_volume_type_name'))]) \ .once() code, result = self.api_get('/volume_type/A_VOLUME_TYPE_ID', headers={'X-Auth-Token': 'some token value'}) assert_that(code, equal_to(200)) assert_that(result, has_length(1)) assert_that(result[0], has_key('volume_type_id')) assert_that(result[0]['volume_type_id'], equal_to('A_VOLUME_TYPE_ID')) assert_that(result[0], has_key('volume_type_name')) assert_that(result[0]['volume_type_name'], equal_to('some_volume_type_name'))
def test_bulk_with_report(self): results = self.store.bulk( actions=[ ("index", self.kevin), ("delete", self.steph), ], batch_size=2, ) assert_that( self.store.retrieve(self.kevin.id), all_of( has_property("id", self.kevin.id), has_property("first", "Kevin"), has_property("middle", none()), has_property("last", "Durant"), ), ) result = results[0] # Updated items assert_that(result[0], is_(equal_to(1))) # Report on failed to delete items assert_that(result[1], contains( has_key('delete'), )) assert_that(result[1][0]['delete'], has_entry('result', 'not_found'))
def test_remove_module_from_existing_dashboard( self, mock_list_organisations, mock_list_data_sets, mock_list_module_types, client): data = { 'slug': 'my-valid-slug', 'title': 'My valid title', 'modules-0-slug': 'carers-realtime', 'modules-0-data_group': 'carers-allowance', 'modules-0-data_type': 'realtime', 'modules-0-options': '{}', 'modules-0-query_parameters': '{}', 'modules-0-id': 'module-uuid', 'remove_module_0': 'remove', } client.post( '/admin/dashboards/uuid', data=data) with client.session_transaction() as session: assert_that(session['pending_dashboard'], has_key('slug')) assert_that(len(session['pending_dashboard']['modules']), equal_to(0))
def test_swagger(self): response = self.client.get("/api/swagger") assert_that(response.status_code, is_(equal_to(200))) data = loads(response.data) alias = data["paths"]["/person/{person_name}"]["get"] assert_that( alias["responses"], has_key("302"), ) retrieve = data["paths"]["/person/{person_id}"]["get"] assert_that( retrieve["responses"], has_key("200"), )
def EventNotification_FileReadyToParse_SyntaxKeywords_SeedWithCache_test( ycm, *args ): current_buffer = VimBuffer( name = 'current_buffer', filetype = 'some_filetype' ) with patch( 'ycm.client.event_notification.EventNotification.' 'PostDataToHandlerAsync' ) as post_data_to_handler_async: with MockVimBuffers( [ current_buffer ], [ current_buffer ] ): ycm.OnFileReadyToParse() assert_that( # Positional arguments passed to PostDataToHandlerAsync. post_data_to_handler_async.call_args[ 0 ], contains( has_entry( 'syntax_keywords', has_items( 'foo', 'bar' ) ), 'event_notification' ) ) # Do not send again syntax keywords in subsequent requests. ycm.OnFileReadyToParse() assert_that( # Positional arguments passed to PostDataToHandlerAsync. post_data_to_handler_async.call_args[ 0 ], contains( is_not( has_key( 'syntax_keywords' ) ), 'event_notification' ) )
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_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))
def test_parses_non_list_based_data_points(self): options = { 'mappings': { 'nb_visits_converted': 'converted', 'nb_conversions': 'sessions'}, 'idMapping': [ 'dataType', '_timestamp', 'timeSpan'] } parser = Parser(query(), options, 'journey-by-goal') data = get_piwik_data( filename='piwik_goal_completion', period='weekly') parsed_data = parser.parse(data) assert_that(parsed_data[0], has_key('converted')) assert_that(parsed_data[0], has_key('sessions')) assert_that(parsed_data[0]['converted'], equal_to(730)) assert_that(parsed_data[0]['sessions'], equal_to(730))
def test_spotlightify_handles_other_and_transaction_links(self): self.dashboard.add_other_link('other', 'http://www.gov.uk') self.dashboard.add_other_link('other2', 'http://www.gov.uk') self.dashboard.update_transaction_link( 'transaction', 'http://www.gov.uk' ) self.dashboard.validate_and_save() transaction_link = self.dashboard.get_transaction_link() assert_that(transaction_link, instance_of(Link)) assert_that( transaction_link.link_type, equal_to('transaction') ) assert_that( self.dashboard.get_other_links()[0].link_type, equal_to('other') ) assert_that( self.dashboard.spotlightify(), has_entries({ 'title': 'title', 'page-type': 'dashboard', 'relatedPages': has_entries({ 'improve-dashboard-message': True, 'transaction': has_entries({ 'url': 'http://www.gov.uk', 'title': 'transaction', }), 'other': has_items( has_entries({ 'url': 'http://www.gov.uk', 'title': 'other', }), has_entries({ 'url': 'http://www.gov.uk', 'title': 'other2', }), ) }) }) ) assert_that(self.dashboard.spotlightify(), is_not(has_key('id'))) assert_that(self.dashboard.spotlightify(), is_not(has_key('link')))
def test_load_multiple_files(): """ Registry can load multiple files. """ registry = Registry() schema_ids = registry.load( schema_for("data/address.json"), schema_for("data/name.json"), ) assert_that(schema_ids, has_length(2)) assert_that(schema_ids, has_item(ADDRESS_ID)) assert_that(schema_ids, has_item(NAME_ID)) assert_that(registry, has_length(2)) assert_that(registry, has_key(ADDRESS_ID)) assert_that(registry, has_key(NAME_ID))
def step_impl(context, number): try: context.json_object = json.loads(context.rv.body) assert_that(context.json_object, has_key("unseen")) assert_that(context.json_object["unseen"], equal_to(int(number))) except ValueError, e: return False
def step_impl(context, boolean): if boolean == "True": boolean_value = True else: boolean_value = False context.json_object = json.loads(context.rv.body) assert_that(context.json_object, has_key("game")) assert_that(context.json_object["game"], equal_to(boolean_value))
def test_get(self): data_source = DataSourceFactory() response = self.client.get( '/data-source/{}'.format(data_source.name), HTTP_AUTHORIZATION='Bearer development-oauth-access-token', content_type='application/json') assert_that(response.status_code, equal_to(200)) resp_json = json.loads(response.content) assert_that(resp_json['id'], equal_to(str(data_source.id))) assert_that(resp_json['slug'], equal_to(data_source.slug)) assert_that(resp_json['name'], equal_to(data_source.name)) assert_that( resp_json['provider']['name'], equal_to(data_source.provider.name)) assert_that(resp_json, not(has_key('credentials'))) assert_that(resp_json, not(has_key('owners')))
def test_table_parameterized(self, query_result_example, query_results): if 'results' in query_result_example: assert_that(query_results.table, has_length(len( query_result_example['results']['bindings']))) else: assert_that(query_results.table[0], has_key('boolean')) assert_that(query_results.table, has_length(1))
def test_when_deleting_func_key_then_removes_func_key_from_template(self): funckey = Mock(FuncKey) template = FuncKeyTemplate(keys={1: funckey}) self.service.get.return_value = template self.manipulator.remove_funckey(sentinel.template_id, 1) assert_that(template.keys, is_not(has_key(1))) self.service.get.assert_called_once_with(sentinel.template_id) self.service.edit.assert_called_once_with(template)
def test_default_pagination(self): """Results are paginated without specifying params.""" view = View.as_view({"get": "list"}) request = APIRequestFactory().get("/") response = view(request) # check the response is successful self.assertEqual(response.status_code, status.HTTP_200_OK) resp_json = get_json_from_response(response) # check the JSON:API pagination params are present # https://jsonapi.org/format/#fetching-pagination pagination_keys = ["first", "last", "prev", "next"] assert_that( resp_json, has_entry("links", all_of(*[has_key(key) for key in pagination_keys])), )
def test_override_inheritance(self): """ Registering an associated schema with an already-used suffix should raise """ class ParentSchema(Schema): someField = fields.String(attribute="some_field") add_associated_schema("Bar", [], (ParentSchema, ))(PersonSchema) associated_schema = get_associated_schema(PersonSchema, "Bar") assert_that( associated_schema._declared_fields, has_key("someField"), )
def test_that_config_includes_a_backends_list_if_config_contains_backends_definition(self): root = ET.Element('config') backends = ET.SubElement(root, 'backends') name = 'db' plugin = 'mysql' ET.SubElement(backends, 'backend', {'name':name, 'plugin':plugin}) op = BackendParser() _dump_xml_as_file(root, 'backend.xml') op.parse(root) result = op.backends assert_that(result, is_not(None)) assert_that(len(result), is_not(0)) assert_that(result, has_key(name)) assert_that(result[name].plugin, is_(plugin))
def bus_received_msg(): assert_that( msg_accumulator.accumulate(with_headers=True), contains_exactly( has_entries( message=has_entries( data={ 'user_uuid': user['uuid'], 'external_auth_name': 'foo', } ), headers=has_key('tenant_uuid'), ) ), )
def test_validate_total_length(self): body = dict( transport='tcp', sip_username='******', auth_password='******', auth_username='******', remote_host='remote_host_really_really_really_really_really_really_really_long_string', remote_port=6666, callback_extension='callback_extension_really_long_string', ) assert_that( calling(self.schema.load).with_args(body), raises(ValidationError, has_property('messages', has_key('_schema'))), )
def compare_nodes(self, actual_node, node): assert_that(unqualify(node.tag), equal_to(unqualify(actual_node.tag))) assert_that(node, has_length(len(actual_node))) if node.text is not None: if node.text.strip() == "": assert_that(actual_node.text is None or actual_node.text.strip() == "") else: assert_that(node.text.strip(), equal_to(actual_node.text.strip())) for name, value in node.attrib.items(): assert_that(actual_node.attrib, has_key(name)) assert_that(actual_node.attrib[name], equal_to(value)) assert_that(actual_node.nsmap, equal_to(node.nsmap)) self.compare_children(node, actual_node)
def test_event_marshaller(self): event = MockEvent('marshaller', id=1234, value='something') with self.remote_event(event.name): self.local_bus.publish(event) assert_that( self.remote_messages(event.name, 1), has_items( has_entry('data', has_entries(id=1234, value='something')), has_entry('name', 'marshaller'), has_entry('origin_uuid', self.local_bus.service_uuid), has_key('timestamp'), ), )
def test_address_field(self): params = {'emails': [ONE, SIX]} body, error = self.user_schema.load(params) field = list(error['emails'][1].keys())[0] assert_that(field, equal_to('address')) params = {'emails': [ONE, TWO, TWO]} body, error = self.user_schema.load(params) assert_that( error, has_entries( _schema=contains('The same address can only be used once'))) params = {} body, error = self.user_schema.load(params) assert_that(error, has_key('emails'))
def test_signals_main_artist_only_when_album_is_compilation(driver): track = make_track() album = make_album(compilation=False, tracks=[track]) metadata_changed_signal = KeywordsValueMatcherProbe("metadata changed") _ = show_page(album, track, on_track_changed=metadata_changed_signal.received) metadata_changed_signal.expect(is_not(has_key("lead_performer"))) driver.change_track_title("Title") driver.check(metadata_changed_signal) metadata_changed_signal.expect(has_entries(recording_time="2008-09-15")) driver.change_recording_time(2008, 9, 15) driver.check(metadata_changed_signal)
def test_post(self): provider = {"name": "some-provider", "slug": "some-provider"} resp = self.client.post( '/provider', data=json.dumps(provider), HTTP_AUTHORIZATION='Bearer development-oauth-access-token', content_type='application/json') assert_that(resp.status_code, equal_to(200)) resp_json = json.loads(resp.content) assert_that(resp_json, has_key('id')) assert_that(resp_json['name'], equal_to('some-provider')) assert_that(resp_json['slug'], equal_to('some-provider'))
def test_removes_linked_publisher_from_a_contributor_when_removing_a_publisher( ): chain_of_title = make_chain_of_title( authors_composers=[joel_miller(), john_roney()], publishers=[effendi_records()]) chain_of_title.update(lyricists=["Joel Miller"], composers=["John Roney"], publishers=[]) assert_that( chain_of_title.contributors, all_of(has_author_composer("John Roney", has_entry("publisher", "")), has_author_composer("Joel Miller", has_entry("publisher", "")), has_entry("publishers", not_(has_key("Effendi Records")))), "The chain of title")
def test_create(self, group_uuid, tenant_uuid): name = 'foobar' assert_that(group_uuid, equal_to(ANY_UUID)) filter_ = models.Group.uuid == group_uuid group = self.session.query(models.Group).filter(filter_).first() assert_that(group, has_properties(name=name, tenant_uuid=tenant_uuid)) assert_that( calling(self._group_dao.create).with_args(name, tenant_uuid), raises(exceptions.ConflictException).matching( has_properties( 'status_code', 409, 'resource', 'groups', 'details', has_key('name') ) ), )
def test_inherits_external_can_create(self): class IExt(interface.Interface): interface.taggedValue('__external_class_name__', 'Ext') class Base(object): __external_can_create__ = False @interface.implementer(IExt) class E(Base): pass AutoPackage._ap_handle_one_potential_factory_class(E, 'nti.package', E) assert_that(E, has_property('__external_can_create__', False)) assert_that(E.__dict__, does_not(has_key('__external_can_create__')))
def test_import_c_accel(self): import sys old_pp = FUT.PURE_PYTHON assert not hasattr(sys, 'import_c_accel') sys.import_c_accel = self try: FUT.PURE_PYTHON = False d = {'__name__': 'foo', 'import_c_accel': self} FUT.import_c_accel(d, 'sys') assert_that(d, has_key('modules')) assert_that(d, has_entry('__name__', 'sys')) self.assertNotIn('import_c_accel', d) FUT.import_c_accel(d, 'sys') finally: FUT.PURE_PYTHON = old_pp del sys.import_c_accel
def validate_response_setting(context): response = context.response_setting assert_that(response.status_code, equal_to(HTTPStatus.OK)) setting = json.loads(response.data) assert_that(response.status_code, equal_to(HTTPStatus.OK)) assert_that(setting, has_key('uuid')) assert_that(setting, has_key('systemUnit')) assert_that(setting['systemUnit'], equal_to('imperial')) assert_that(setting, has_key('timeFormat')) assert_that(setting, has_key('dateFormat')) assert_that(setting, has_key('optIn')) assert_that(setting['optIn'], equal_to(True)) assert_that(setting, has_key('ttsSettings')) tts = setting['ttsSettings'] assert_that(tts, has_key('module'))
def the_api_information_has_these_attributes(context): """Check that the response of the request has the given values""" for element in context.table.rows: attribute_key = element['attribute_name'] assert_that(context.body, has_key(attribute_key), "Missing attribute in the response") if element['value'] == FEATURES_NOT_EMPTY_VALUE: assert_that(context.body[attribute_key], has_length(greater_than(0)), "Empty attribute value") else: attribute_value = element['value'] assert_that( context.body[attribute_key], is_(equal_to(attribute_value)), "Attribute '{}' does not have the expected value".format( attribute_key))
def test_reset_to_autoprov_device_associated_to_line(provd, device, line): with a.line_device(line, device, check=False): response = confd.devices(device['id']).autoprov.get() response.assert_ok() response = confd.lines(line['id']).get() assert_that(response.item, has_entry('device_id', none())) device_cfg = provd.devices.get(device['id']) assert_that(device_cfg, has_entries(config=starts_with('autoprov'))) assert_that(device_cfg, is_not(has_key('options'))) config_cfg = provd.configs.get(device_cfg['config']) assert_that(config_cfg, not_none()) response = confd.lines(line['id']).get() assert_that(response.item, has_entries(device_id=none()))
def test_given_resources_already_exist_when_importing_then_resources_associated( sip, extension, extension_incall, voicemail, call_permission ): csv = [ { "firstname": "importassociate", "exten": extension['exten'], "context": extension['context'], "line_protocol": "sip", "sip_username": sip['username'], "incall_exten": extension_incall['exten'], "incall_context": extension_incall['context'], "voicemail_number": voicemail['number'], "voicemail_context": voicemail['context'], "call_permissions": call_permission['name'], } ] response = client.post("/users/import", csv) user_id = get_import_field(response, 'user_id') line_id = get_import_field(response, 'line_id') extension_incall_id = get_import_field(response, 'incall_extension_id') response = confd.users(user_id).lines.get() assert_that(response.items, contains(has_entries(line_id=line_id))) response = confd.lines(line_id).extensions.get() assert_that(response.items, has_items(has_entries(extension_id=extension['id']))) response = confd.extensions(extension_incall_id).get() assert_that(response.item['incall'], has_key('id')) response = confd.users(user_id).voicemail.get() assert_that(response.item, has_entries(voicemail_id=voicemail['id'])) response = confd.lines(line_id).endpoints.sip.get() assert_that(response.item, has_entries(endpoint='sip', endpoint_id=sip['id'])) response = confd.users(user_id).callpermissions.get() assert_that( response.items, contains( has_entries(call_permission_id=call_permission['id'], user_id=user_id) ), )
def test_when_user_list_cdr_with_arg_user_uuid_then_user_uuid_is_ignored( self): SOME_TOKEN = 'my-token' self.auth.set_token(MockUserToken(SOME_TOKEN, user_uuid=USER_1_UUID)) self.call_logd.set_token(SOME_TOKEN) result = self.call_logd.cdr.list_from_user(user_uuid=USER_2_UUID) self.call_logd.set_token(VALID_TOKEN) assert_that( result, has_entries(filtered=1, total=1, items=contains( has_entries(start='2017-04-11T00:00:00+00:00'), ))) assert_that(result, has_entries(items=only_contains(not_(has_key('tags')))))
def test_spotlightify_with_no_data_set(self): module = ModuleFactory(slug='a-module', type=self.module_type, dashboard=self.dashboard_a, order=1, options={ 'foo': 'bar', }, query_parameters={'sort_by': 'foo'}) spotlight_module = module.spotlightify() assert_that(spotlight_module['slug'], equal_to('a-module')) assert_that(spotlight_module['foo'], equal_to('bar')) assert_that(spotlight_module['module-type'], equal_to(self.module_type.name)) assert_that(spotlight_module, is_not(has_key('data-source')))
def test_post(self): transform_type = TransformTypeFactory() input_data_type = DataTypeFactory() input_data_group = DataGroupFactory() output_data_type = DataTypeFactory() output_data_group = DataGroupFactory() payload = { "type_id": str(transform_type.id), "input": { "data-type": input_data_type.name, "data-group": input_data_group.name, }, "query-parameters": {}, "options": {}, "output": { "data-type": output_data_type.name, "data-group": output_data_group.name, }, } resp = self.client.post( '/transform', data=json.dumps(payload), HTTP_AUTHORIZATION='Bearer development-oauth-access-token', content_type='application/json') assert_that(resp.status_code, equal_to(200)) resp_json = json.loads(resp.content) assert_that(resp_json, has_key('id')) assert_that(resp_json['type']['id'], equal_to(str(transform_type.id))) assert_that(resp_json['input']['data-type'], equal_to(input_data_type.name)) assert_that(resp_json['input']['data-group'], equal_to(input_data_group.name)) assert_that(resp_json['output']['data-type'], equal_to(output_data_type.name)) assert_that(resp_json['output']['data-group'], equal_to(output_data_group.name)) assert_that( Transform.objects.get(id=resp_json['id']).owners.first().email, equal_to('*****@*****.**'))
def test_shouldInvokeCallbackThatIsRegisteredWithInstanceWhenFlowIsComplete( self): authorized_permission = PermissionObjectFactory() authorized_user = UserObjectFactory( user_permissions=[authorized_permission]) content_type = ContentType.objects.get_for_model(BasicTestModel) state1 = RawState("state1") state2 = RawState("state2") state3 = RawState("state3") authorization_policies = [ AuthorizationPolicyBuilder().with_permission( authorized_permission).build(), ] flow = FlowBuilder("my_field", content_type) \ .with_transition(state1, state2, authorization_policies) \ .with_transition(state2, state3, authorization_policies) \ .build() workflow_object = flow.objects[0] self.hook_post_complete(flow.workflow, workflow_object=workflow_object) assert_that(self.get_output(), none()) assert_that(workflow_object.my_field, equal_to(flow.get_state(state1))) workflow_object.river.my_field.approve(as_user=authorized_user) assert_that(workflow_object.my_field, equal_to(flow.get_state(state2))) assert_that(self.get_output(), none()) workflow_object.river.my_field.approve(as_user=authorized_user) assert_that(workflow_object.my_field, equal_to(flow.get_state(state3))) output = self.get_output() assert_that(output, has_length(1)) assert_that(output[0], has_key("hook")) assert_that(output[0]["hook"], has_entry("type", "on-complete")) assert_that(output[0]["hook"], has_entry("when", AFTER)) assert_that( output[0]["hook"], has_entry( "payload", has_entry(equal_to("workflow_object"), equal_to(workflow_object))))
def test_when_create_http_subscription_then_subscription_no_error(self): webhookd = self.make_webhookd(MASTER_TOKEN) response = webhookd.subscriptions.create(TEST_SUBSCRIPTION) subscription_uuid = response['uuid'] assert_that(response, has_entries(owner_tenant_uuid=MASTER_TENANT)) assert_that(response, has_key('uuid')) response = webhookd.subscriptions.list() assert_that( response, has_entry('items', has_item(has_entry('uuid', subscription_uuid))) ) assert_that( response, has_entry('items', has_item(has_entry('owner_tenant_uuid', MASTER_TENANT))), )
def test_for_author(self): with self.app.test_request_context(): g.user = self.author result = self.call_serialize() assert_that( result, has_entries({ 'status': None, 'contest_id': self.run.contest_id, 'prob_id': 1, 'run_id': self.run.run_id, 'create_time': 'None', 'lang_id': None, 'score': None, 'size': None, })) assert_that(result, has_entries(self.pynformatics_run_serialized)) assert_that(result, is_not(has_key('user')))
def check_bus_event(routing_key, url, body=None): bus_events = BusClient.accumulator(routing_key) url(body) if body else url() assertions = all_of( has_length(1), contains( has_entry( 'headers', has_key('tenant_uuid'), ) ), ) def assert_function(): assert_that(bus_events.accumulate(with_headers=True), assertions) until.assert_(assert_function, tries=5)
def test_updates_cert_arn_for_supplied_distribution_id(): # Given cf_wrapper = CloudfrontWrapper() the_existing_distribution_id = "some-distribution-id" initial_distribution_config_etag = "GetRequestEtag" cf_wrapper.get_distribution_config = Mock( return_value=a_boto3_cloudfront_get_distribution_response( with_acm_certificate_arn="old:certificate:arn", with_etag=initial_distribution_config_etag), side_effect=error_if_distribution_id_not(the_existing_distribution_id), ) cf_wrapper.update_distribution_config = MagicMock() # When new_cert_arn = "new:certificate:arn" CertRotator(cf_wrapper).rotate_cert(the_existing_distribution_id, new_cert_arn) # Then # Updates distribution cf_wrapper.update_distribution_config.assert_called_once update_call_args = cf_wrapper.update_distribution_config.call_args_list[0][ 1] # updates correct distribution id assert_that(update_call_args["distribution_id"], is_(the_existing_distribution_id)) # includes the etag from the latest fetched config assert_that(update_call_args["if_etag_matches"], is_(initial_distribution_config_etag)) # distribution config supplied includes viewer certificate info distribution_config = update_call_args["distribution_configuration"] viewer_certificate = distribution_config["ViewerCertificate"] # ... with new cert assert_that(viewer_certificate["ACMCertificateArn"], is_(new_cert_arn)) # ... but without deprecated 'Certificate' field which is present in the get distribution config response assert_that(viewer_certificate, not_(has_key("Certificate")))
def check_json(json_expected, json_response): if type(json_expected) is list: for i in range(0, len(json_expected)): check_json(json_expected[i], json_response[i]) check_json(json_response[i], json_expected[i]) elif type(json_expected) is dict: for key, value in json_expected.items(): if type(value) is dict: assert_that(json_response, has_key(key)) check_json(value, json_response[key]) check_json(json_response[key], value) elif type(value) is list: for i in range(0, len(value)): check_json(json_expected[key][i], json_response[key][i]) check_json(json_response[key][i], json_expected[key][i]) else: assert_that(json_response, has_entry(key, value)) else: assert_that(json_response, equal_to(json_expected))
def test_expected_exceptions_still_have_cors(self): def raises_app(environ, start_response): raise IOError('bad') catching_app = ErrorMiddleware(raises_app) app = cors_filter_factory(catching_app) testapp = TestApp(app) res = testapp.get('/the_path_doesnt_matter', status=500) assert_that(res.normal_body, is_(b'Failed to handle request bad')) # Errors set the right response headers res = testapp.get('/', extra_environ={ 'HTTP_ORIGIN': 'http://example.org'}, status=500) assert_that(res.headers, has_key('Access-Control-Allow-Origin'))
def test_validate_total_length(self): body = { 'auth_username': '******', 'auth_password': '******', 'remote_host': 'remote_host_really_really_really_really_really_really_really_long_string', 'remote_port': 6666, 'callback_extension': 'callback_extension_really_really_really_really_really_long_string', } assert_that( calling(self.schema.load).with_args(body), raises(ValidationError, has_property('messages', has_key('_schema'))), )
def LanguageServerCompleter_GetCompletions_UnsupportedKinds_test(): completer = MockCompleter() request_data = RequestWrap( BuildRequest() ) completion_response = { 'result': [ { 'label': 'test', 'kind': len( lsp.ITEM_KIND ) + 1 } ] } resolve_responses = [ { 'result': { 'label': 'test' } }, ] with patch.object( completer, 'ServerIsReady', return_value = True ): with patch.object( completer.GetConnection(), 'GetResponse', side_effect = [ completion_response ] + resolve_responses ): assert_that( completer.ComputeCandidatesInner( request_data ), has_items( all_of( has_entry( 'insertion_text', 'test' ), is_not( has_key( 'kind' ) ) ) ) )