def test_an_invalid_prompt_number(self): """Provide an invalid number of prompts""" data = factory.build( dict, FACTORY_CLASS=EntityFormsetFactory, n_prompts=0 ) form = EntityFormset(data, entities=[{'entity_name': 'sys.places'}]) self.assertFalse( form.is_valid(), 'Invalid entity name, should be greater than 0, should fail' ) data = factory.build( dict, FACTORY_CLASS=EntityFormsetFactory, n_prompts=19 ) form = EntityFormset(data, entities=[{'entity_name': 'sys.places'}]) self.assertFalse( form.is_valid(), 'Invalid entity name, should be lower than 16, should fail' )
def test_get_categories_data(self, mock_get): """Response contains a categories dictionary of bots lists""" response = { 'categories': { 'Social': [ factory.build(dict, FACTORY_CLASS=BotDetailsFactory), factory.build(dict, FACTORY_CLASS=BotDetailsFactory), ], }, 'status': { 'code': 200, 'info': 'OK' } } # Configure the mock to return a response with an OK status code, and # mocked data. mock_get.return_value = response # Call the service, which will send a request to the server. categories = get_categories(self.token) # If the request is sent successfully, then I expect a response to be # returned. self.assertDictEqual(categories, response)
def test_intent_name_slug(self): """Intent name should be a slug""" data = factory.build( dict, FACTORY_CLASS=IntentFactory, intent_name='Not a slug' ) form = IntentForm(data) self.assertFalse( form.is_valid(), 'Intent name should be a slug' ) data = factory.build( dict, FACTORY_CLASS=IntentFactory, intent_name='!#@$%^&' ) form = IntentForm(data) self.assertFalse( form.is_valid(), 'Intent name should be a slug' )
def test_concepts_should_have_unique_fully_specified_name_per_locale(self): name_fully_specified1 = LocalizedTextFactory.build( name='FullySpecifiedName1') source = OrganizationSourceFactory( custom_validation_schema=CUSTOM_VALIDATION_SCHEMA_OPENMRS, version=HEAD) concept1_data = { **factory.build(dict, FACTORY_CLASS=ConceptFactory), 'mnemonic': 'c1', 'parent': source, 'names': [name_fully_specified1] } concept2_data = { **factory.build(dict, FACTORY_CLASS=ConceptFactory), 'mnemonic': 'c2', 'parent': source, 'names': [name_fully_specified1] } concept1 = Concept.persist_new(concept1_data) concept2 = Concept.persist_new(concept2_data) self.assertEqual(concept1.errors, {}) self.assertEqual( concept2.errors, dict(names=[ OPENMRS_FULLY_SPECIFIED_NAME_UNIQUE_PER_SOURCE_LOCALE + ': FullySpecifiedName1 (locale: en, preferred: no)' ]))
def setUp(self): self.credentials = {'username': '******', 'password': '******'} first_name = 'Test' last_name = 'User' self.user = User.objects.create_user( username=self.credentials['username'], password=self.credentials['password'], email='*****@*****.**', first_name=first_name, last_name=last_name, is_staff=True, is_superuser=True) self.contract_one_data = factory.build(dict, FACTORY_CLASS=ContractFactory) self.contract_one_data['property'].landlord.save() self.contract_one_data['property'].save() self.contract_one_data['tenant'].save() self.contract_two_data = factory.build(dict, FACTORY_CLASS=ContractFactory) self.contract_two_data['property'].landlord.save() self.contract_two_data['property'].save() self.contract_two_data['tenant'].save() self.client.login(username=self.credentials['username'], password=self.credentials['password'])
def test_get_bots_data(self, mock_get): """Response contains a list of bots details""" response = { 'items': [ factory.build(dict, FACTORY_CLASS=BotDetailsFactory), factory.build(dict, FACTORY_CLASS=BotDetailsFactory), ], 'page_start': 0, 'total_page': 7, 'total_results': 7, 'status': { 'code': 200, 'info': 'OK' } } # Configure the mock to return a response with an OK status code, and # mocked data. mock_get.return_value = response # Call the service, which will send a request to the server. bots_list = get_bots(self.token, 'other') # If the request is sent successfully, then I expect a response to be # returned. self.assertDictEqual(bots_list, response)
def setUp(self): """Provide a user token""" self.token = 'token' self.created = { **factory.build(dict, FACTORY_CLASS=AiFactory), **factory.build(dict, FACTORY_CLASS=SuccessFactory) }
def setUp(self): self.user = UserFactory() self.client.force_authenticate(user=self.user) self.message_data = factory.build(dict, FACTORY_CLASS=ContactMessageFactory) self.contact = factory.build(dict, FACTORY_CLASS=ContactFactory) self.message_data["contact"] = self.contact self.url_list = reverse("contactmessage-list")
def setUp(self): self.prop_values_one = factory.build(dict, FACTORY_CLASS=PropertyFactory) self.prop_values_one['landlord'].save() self.prop_values_two = factory.build(dict, FACTORY_CLASS=PropertyFactory) self.prop_values_two['landlord'].save()
def make_factory(factory_class, parent_field=None, parent=None): """ """ c = getattr(factories, factory_class) if parent_field is not None: return factory.build(c, **{parent_field: parent}) else: return factory.build(c)
def test_update_customer(update_fields, db_session, customer_factory): initial_data = factory.build(dict, FACTORY_CLASS=CustomerFactoryBase) customer = customer_factory(**initial_data) db_session.commit() updated_data = project(factory.build(dict, FACTORY_CLASS=CustomerFactoryBase), update_fields) ser = CustomerSchema(partial=True) validated_data = ser.load(updated_data) updated_customer = update_customer(customer_id=customer.id, validated_data=validated_data) filter_data = {**initial_data, **updated_data} qry = [getattr(Customer, field_name).like(field_value) for field_name, field_value in filter_data.items()] assert db_session.query(Customer).filter(*qry).first() == updated_customer
def setUp(self): """Create a user to test response as registered user""" self.user = UserFactory() self.ai = factory.build(dict, FACTORY_CLASS=AiFactory) self.ai_details = factory.build(dict, FACTORY_CLASS=AIDetails) Profile.objects.create(user=self.user) self.client.force_login(self.user) session = self.client.session session['token'] = 'token' session.save()
def setUp(self): self.list_url = vn.HUMAN_VIEW_LIST self.detail_url = vn.HUMAN_VIEW_DETAIL # home FK is created before creating the Human object self.home = HomeFactory.create() self.data = factory.build( dict, FACTORY_CLASS=HumanFactory, home=self.home) # Serve as the modifying data scheme self.new_data = factory.build( dict, FACTORY_CLASS=HumanFactory, home=HomeFactory.create()) # Parsing the human object into acceptable dict object self.parse_obj(self.data, self.new_data)
def test_add_meta_fields(self): media = MediaFactory() url = reverse( "api:meta-fields-create-update-multiple", kwargs={"uuid": media.uuid}, ) meta_field_1 = factory.build(dict, FACTORY_CLASS=MetaFieldsFactory) meta_field_2 = factory.build(dict, FACTORY_CLASS=MetaFieldsFactory) meta_field_1.pop("media") meta_field_2.pop("media") data = {"meta_fields": [meta_field_1, meta_field_2]} response = self.client.post(url, data=data, format="json") self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_create_an_instrument(self): """ Ensure we can create an Instrument object """ data = factory.build( dict, FACTORY_CLASS=InstrumentFactory) typology = HornbostelSachs.objects.first() # Write the HornbostelSachs object in the item data object. data['typology'] = typology.id url = reverse('instrument-list') response = self.client.post(url, data, format='json') # Check only expected attributes returned self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertIsInstance(response.data, dict) self.assertEqual( sorted(response.data.keys()), INSTRUMENT_FIELDS) url = reverse( 'instrument-detail', kwargs={'pk': response.data['id']} ) response_get = self.client.get(url) self.assertEqual(response_get.status_code, status.HTTP_200_OK) self.assertIsInstance(response_get.data, dict)
def test_modify_cat_obj(self): cat_obj = self.create_cat_obj() serializer = self.serializer_class( instance=cat_obj, context=self.context ) modified_data = factory.build( dict, FACTORY_CLASS=CatFactory, breed=self.breed, owner=self.owner ) self.parse_cat_dict(modified_data) # Check that the new data is not the same as the old data self.assertNotEqual( serializer.data, self.obtain_expected_result(modified_data, cat_obj) ) # Update the cat object serializer = self.serializer_class( instance=cat_obj, data=modified_data, context=self.context ) self.assertTrue(serializer.is_valid(), serializer.errors) serializer.save() # To check if the objects is modified self.assertDictEqual( serializer.data, self.obtain_expected_result(modified_data, cat_obj) )
def setUp(self): self.user = UserFactory() self.person = PersonFactory() self.client.force_authenticate(user=self.user) self.url = reverse("ownerships-list") self.ownership_data = factory.build(dict, FACTORY_CLASS=OwnershipFactory) self.ownership_data["owner"] = self.person.pk
def test_program_uuid(self): """ Verify a ValidationError is raised if the program's authoring organizations have no certificate images. """ sc = SiteConfigurationFactory() data = factory.build(dict, FACTORY_CLASS=ProgramCertificateFactory) data['site'] = sc.site.id form = ProgramCertificateAdminForm(data) with mock.patch.object( SiteConfiguration, 'get_program', return_value=self.BAD_MOCK_API_PROGRAM) as mock_method: self.assertFalse(form.is_valid()) mock_method.assert_called_with(data['program_uuid'], ignore_cache=True) self.assertEqual( form.errors['program_uuid'][0], 'All authoring organizations of the program MUST have a certificate image defined!' ) form = ProgramCertificateAdminForm(data) with mock.patch.object( SiteConfiguration, 'get_program', return_value=self.GOOD_MOCK_API_PROGRAM) as mock_method: self.assertFalse(form.is_valid()) mock_method.assert_called_with(data['program_uuid'], ignore_cache=True) self.assertNotIn('program_uuid', form.errors)
def test_create_an_authority(self): """ Ensure we can create an Authority object """ data = factory.build(dict, FACTORY_CLASS=AuthorityFactory) loc = Location.objects.first() # Write the Location object in the authority data object. data['birth_location'] = loc.id data['death_location'] = loc.id url = reverse('authority-list') response = self.client.post(url, data, format='json') # Check only expected attributes returned self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertIsInstance(response.data, dict) self.assertEqual(sorted(response.data.keys()), AUTHORITY_FIELDS) url = reverse('authority-detail', kwargs={'pk': response.data['id']}) response_get = self.client.get(url) self.assertEqual(response_get.status_code, status.HTTP_200_OK) self.assertIsInstance(response_get.data, dict)
def test_create(db_query, client, proposition_factory, logged_in_user_with_departments): user = logged_in_user_with_departments data = factory.build(dict, FACTORY_CLASS=proposition_factory) data['tags'] = 'Tag1,' + "".join( random.choices(string.ascii_lowercase, k=10)).capitalize() data['status'] = data['status'].name data['area_id'] = user.departments[0].areas[0].id data['related_proposition_id'] = 3 data['relation_type'] = 'modifies' data['external_discussion_url'] = 'http://example.com' with assert_difference(db_query(Proposition).count, 1, 'proposition'): with assert_difference(db_query(Tag).count, 1, 'tag'): client.post('/p', data, status=302) proposition = db_query(Proposition).order_by( Proposition.id.desc()).limit(1).first() other_proposition = db_query(Proposition).get(3) assert proposition.modifies == other_proposition data['relation_type'] = 'replaces' client.post('/p', data, status=302) proposition = db_query(Proposition).order_by( Proposition.id.desc()).limit(1).first() assert proposition.replaces == other_proposition
def test_newline_non_extra_kwargs(self): a = factory.build(dict, FACTORY_CLASS=FacMedicament, ordonnance=FacOrdonnance()) a["rin"] = "rien" with pytest.raises(AssertionError): Medicament.objects.new_ligne(**a)
def prepare_registration_data(password2=None, **kwargs): if password2 is None: password2 = factory.LazyAttribute(lambda user: user.password) return factory.build(dict, FACTORY_CLASS=UserFactory, password2=password2, **kwargs)
def test_update_mutation_correct(self): """ Add an object. Call an update with 2 (or more) fields updated. Fetch the object back and confirm that the update was successful. """ make = MakeFactory.create() make_id = to_global_id(MakeNode._meta.name, make.pk) make_dict = factory.build(dict, FACTORY_CLASS=MakeFactory) response = self.query(""" mutation($input: UpdateMakeInput!){ updateMake(input: $input) { make{ name } } } """, input_data={ 'id': make_id, 'data': { 'name': make_dict['name'], } }) self.assertResponseNoErrors(response) parsed_response = json.loads(response.content) updated_make_data = parsed_response['data']['updateMake']['make'] self.assertEquals(updated_make_data['name'], make_dict['name'])
def test_form_is_not_valid_when_try_to_pass_string_diffrent_than_url_adress( self): url_data = factory.build(dict, FACTORY_CLASS=UrlFactory) url_data["url"] = "test" form = UrlForm(url_data) self.assertFalse(form.is_valid())
def test_does_not_create_without_title(db_query, client, proposition_factory, logged_in_user): data = factory.build(dict, FACTORY_CLASS=proposition_factory) del data['title'] with assert_no_difference(db_query(Proposition).count): client.post('/p', data, status=200)
def test_create_an_document_collection(self): """ Ensure we can create an DocumentCollection object """ data = factory.build( dict, FACTORY_CLASS=DocumentCollectionFactory) # Convert the related entity in dictionnaryself. # Then they will be easily converted in JSON format. data['document'] = Document.objects.first().id data['collection'] = Collection.objects.first().id response = self.client.post(self.url, data, format='json') # Check only expected attributes returned self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertIsInstance(response.data, dict) self.assertEqual( sorted(response.data.keys()), DOCUMENTCOLLECTION_FIELDS) self.assertEqual(response.data["id"], 2) response_get = self.client.get(self.url + "/2") self.assertEqual(response_get.status_code, status.HTTP_200_OK) self.assertIsInstance(response_get.data, dict)
def form_data(num_appl_forms=0, num_review_forms=0, delete=0, stages=1, same_forms=False, form_stage_info=[1]): form_data = formset_base('forms', num_appl_forms, delete, same=same_forms, factory=ApplicationFormFactory, form_stage_info=form_stage_info) review_form_data = formset_base('review_forms', num_review_forms, False, same=same_forms, factory=ReviewFormFactory) form_data.update(review_form_data) fund_data = factory.build(dict, FACTORY_CLASS=FundTypeFactory) fund_data['workflow_name'] = workflow_for_stages(stages) form_data.update(fund_data) form_data.update(approval_form='') return form_data
def test_create_an_item_domain_song(self): """ Ensure we can create an ItemDomainSong object """ data = factory.build( dict, FACTORY_CLASS=ItemDomainSongFactory) # Convert the related entity in dictionnary. # Then they will be easily converted in JSON format. data['item'] = 1 data['domain_song'] = 2 url = reverse('itemdomainsong-list', kwargs={ 'item_pk': data['item']}) response = self.client.post(url, data, format='json') # Check only expected attributes returned self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertIsInstance(response.data, dict) self.assertEqual( sorted(response.data.keys()), ITEMDOMAINSONG_FIELDS) url = reverse( 'itemdomainsong-detail', kwargs={'item_pk': response.data['item']['id'], 'pk': response.data['id']} ) response_get = self.client.get(url) self.assertEqual(response_get.status_code, status.HTTP_200_OK) self.assertIsInstance(response_get.data, dict)
def test_create_an_mission(self): """ Ensure we can create an Mission object """ data = factory.build( dict, FACTORY_CLASS=MissionFactory) fonds = Fond.objects.first() data['fonds'] = fonds.id url = reverse('mission-list') response = self.client.post(url, data, format='json') # Check only expected attributes returned self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertIsInstance(response.data, dict) self.assertEqual( sorted(response.data.keys()), MISSION_FIELDS) url = reverse( 'mission-detail', kwargs={'pk': response.data['id']} ) response_get = self.client.get(url) self.assertEqual(response_get.status_code, status.HTTP_200_OK) self.assertIsInstance(response_get.data, dict)
def test_create_a_fond(self): """ Ensure we can create an Fond object """ data = factory.build(dict, FACTORY_CLASS=FondFactory) institution = Institution.objects.first() acquisition_mode = AcquisitionMode.objects.first() # Write the Location object in the authority data object. data['institution'] = institution.id data['acquisition_mode'] = acquisition_mode.id url = reverse('fond-list') response = self.client.post(url, data, format='json') # Check only expected attributes returned self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertIsInstance(response.data, dict) self.assertEqual(sorted(response.data.keys()), FOND_FIELDS) url = reverse('fond-detail', kwargs={'pk': response.data['id']}) response_get = self.client.get(url) self.assertEqual(response_get.status_code, status.HTTP_200_OK) self.assertIsInstance(response_get.data, dict)
def _fake_bulk_model_data(n_models): max_attempts = 1000 attempt = 0 data = [] while len(data) < n_models: attempt += 1 data_record = factory.build( dict, FACTORY_CLASS=factories.ExampleBulkModelFactory) if next( (x for x in data if x["something_unique"] == data_record["something_unique"]), None, ): continue data.append(data_record) if attempt >= max_attempts: msg = f"Exceeded {attempt} attempts to generate a unique FakeBulkModel" raise ValidationError(msg) return data
def build_dict(cls, **kwargs): ret = factory.build(dict, FACTORY_CLASS=cls) try: # creator is an user instance, that isn't serializable. Ignore it del ret['creator'] except KeyError: pass return ret
def test_form_entity(admin_client): """Simple test on Entity form""" entity_datas = factory.build(dict, FACTORY_CLASS=factories.EntityFormFactory) form = EntityForm(data=entity_datas) assert form.is_valid() == True form.save() assert Entity.objects.count() == 1
def test_form_note(admin_client): """Simple test on Note form""" factory_entity = factories.EntityModelFactory() note_datas = factory.build(dict, FACTORY_CLASS=factories.NoteFormFactory) # Save related object since we used build() author = note_datas.pop('author') entity = note_datas.pop('entity') author.save() entity.save() form = NoteForm(author=author, entity=entity, data=note_datas) # Submitted field values are valid assert form.is_valid() == True # Save note object note_instance = form.save() # Ensure foreignkey has been saved assert note_instance.author == author assert note_instance.entity == entity
def test_complex(self): obj = factory.build(TestObject, two=2, three=factory.LazyAttribute(lambda o: o.two + 1)) self.assertEqual(obj.one, None) self.assertEqual(obj.two, 2) self.assertEqual(obj.three, 3) self.assertEqual(obj.four, None)
def test_build(self): obj = factory.build(TestObject, two=2) self.assertEqual(obj.one, None) self.assertEqual(obj.two, 2) self.assertEqual(obj.three, None) self.assertEqual(obj.four, None)
def evaluate_declaration(declaration, force_sequence=None): kwargs = {'attr': declaration} if force_sequence is not None: kwargs['__sequence'] = force_sequence return factory.build(dict, **kwargs)['attr']
def get_create_data(self): return factory.build(dict, FACTORY_CLASS=self.factory_class)