def test_endpoint(self): # This line is duplicated on purpose. Currency will have always 1+N number of queries # because of the exchange rate factory.build_batch(PublicsCurrencyFactory, 4) # Create one of each model to check if all serializers are working fine PublicsAirlineCompanyFactory() country = PublicsCountryFactory(currency=None) PublicsDSARegionFactory(country=country) PublicsBusinessAreaFactory() PublicsWBSFactory(business_area=None) PublicsGrantFactory() PublicsFundFactory() PublicsTravelExpenseTypeFactory() with self.assertNumQueries(10): response = self.forced_auth_req('get', reverse('public:static'), user=self.unicef_staff) response_json = json.loads(response.rendered_content) self.assertKeysIn([ 'currencies', 'travel_types', 'countries', 'airlines', 'travel_modes', 'expense_types', 'business_areas' ], response_json, exact=True)
def records(class_type="model", size=1, max_patient_count=30): doctor_class = dict record_class = dict if class_type == "model": doctor_class = models.Doctor record_class = models.Record doctors = factory.build_batch(doctor_class, size=size, FACTORY_CLASS=factories.DoctorFactory) records = [] for doctor in doctors: patient_count = randint(0, max_patient_count) doctor_values = doctor if type(doctor) != dict: doctor_values = doctor.__dict__ records.extend( factory.build_batch( record_class, size=patient_count, FACTORY_CLASS=factories.RecordFactory, **doctor_values, )) if size > 1: return records else: return records[0]
def test_endpoint(self): # This line is duplicated on purpose. Currency will have always 1+N number of queries # because of the exchange rate factory.build_batch(PublicsCurrencyFactory, 4) # Create one of each model to check if all serializers are working fine PublicsAirlineCompanyFactory() country = PublicsCountryFactory(currency=None) PublicsDSARegionFactory(country=country) PublicsBusinessAreaFactory() PublicsTravelExpenseTypeFactory() with self.assertNumQueries(11): response = self.forced_auth_req('get', reverse('publics:static'), user=self.unicef_staff) response_json = json.loads(response.rendered_content) self.assertKeysIn(['currencies', 'travel_types', 'countries', 'airlines', 'travel_modes', 'expense_types', 'business_areas'], response_json, exact=True)
def test_airlines_view(self): factory.build_batch(PublicsAirlineCompanyFactory, 3) with self.assertNumQueries(1): response = self.forced_auth_req('get', reverse('publics:airlines'), user=self.unicef_staff) response_json = json.loads(response.rendered_content) self.assertEqual(len(response_json), 3) expected_keys = ['id', 'name', 'code'] self.assertKeysIn(expected_keys, response_json[0], exact=True)
def test_business_areas_view(self): factory.build_batch(PublicsBusinessAreaFactory, 3) with self.assertNumQueries(1): response = self.forced_auth_req('get', reverse('publics:business_areas'), user=self.unicef_staff) response_json = json.loads(response.rendered_content) self.assertEqual(len(response_json), 3) expected_keys = ['region', 'code', 'id', 'name', 'default_currency'] self.assertKeysIn(expected_keys, response_json[0], exact=True)
def test_expense_types_view(self): factory.build_batch(PublicsTravelExpenseTypeFactory, 3) with self.assertNumQueries(1): response = self.forced_auth_req('get', reverse('publics:expense_types'), user=self.unicef_staff) response_json = json.loads(response.rendered_content) self.assertEqual(len(response_json), 3) expected_keys = ['vendor_number', 'unique', 'id', 'name'] self.assertKeysIn(expected_keys, response_json[0], exact=True)
def test_airlines_view(self): factory.build_batch(PublicsAirlineCompanyFactory, 3) with self.assertNumQueries(1): response = self.forced_auth_req('get', reverse('public:airlines'), user=self.unicef_staff) response_json = json.loads(response.rendered_content) self.assertEqual(len(response_json), 3) expected_keys = ['id', 'name', 'code'] self.assertKeysIn(expected_keys, response_json[0], exact=True)
def test_business_areas_view(self): factory.build_batch(PublicsBusinessAreaFactory, 3) with self.assertNumQueries(1): response = self.forced_auth_req('get', reverse('public:business_areas'), user=self.unicef_staff) response_json = json.loads(response.rendered_content) self.assertEqual(len(response_json), 3) expected_keys = ['region', 'code', 'id', 'name', 'default_currency'] self.assertKeysIn(expected_keys, response_json[0], exact=True)
def test_expense_types_view(self): factory.build_batch(PublicsTravelExpenseTypeFactory, 3) with self.assertNumQueries(1): response = self.forced_auth_req('get', reverse('public:expense_types'), user=self.unicef_staff) response_json = json.loads(response.rendered_content) self.assertEqual(len(response_json), 3) expected_keys = ['vendor_number', 'unique', 'id', 'name'] self.assertKeysIn(expected_keys, response_json[0], exact=True)
def test_currencies_view(self): self.assertEqual(Currency.objects.count(), 1) factory.build_batch(PublicsCurrencyFactory, 3) with self.assertNumQueries(5): response = self.forced_auth_req('get', reverse('publics:currencies'), user=self.unicef_staff) response_json = json.loads(response.rendered_content) self.assertEqual(len(response_json), 4) expected_keys = ['iso_4217', 'code', 'exchange_to_dollar', 'id', 'name'] self.assertKeysIn(expected_keys, response_json[0], exact=True)
class SchoolFactory(factory.Factory): class Meta: model = School schoolName = factory.sequence( lambda n: 'school%04d' % n) #factory.sequence home = factory.List(factory.build_batch(HomeFactory, 4))
def test_currencies_view(self): factory.build_batch(PublicsCurrencyFactory, 3) with self.assertNumQueries(4): response = self.forced_auth_req('get', reverse('public:currencies'), user=self.unicef_staff) response_json = json.loads(response.rendered_content) self.assertEqual(len(response_json), 3) expected_keys = [ 'iso_4217', 'code', 'exchange_to_dollar', 'id', 'name' ] self.assertKeysIn(expected_keys, response_json[0], exact=True)
def test_counting_applications_for_app_info_without_interviews(self): course1, course2 = factory.build_batch(size=2, klass=CourseFactory) cd1 = CourseDescriptionFactory(course=course1) cd2 = CourseDescriptionFactory(course=course2) app_info1 = ApplicationInfoFactory(course=cd1) app_info2 = ApplicationInfoFactory(course=cd2) self.assertEquals( 0, Application.objects.without_interviews_for(app_info1).count()) self.assertEquals( 0, Application.objects.without_interviews_for(app_info2).count()) ApplicationFactory(application_info=app_info1) ApplicationFactory(application_info=app_info1) ApplicationFactory(application_info=app_info1) ApplicationFactory(application_info=app_info1) ApplicationFactory(application_info=app_info2) ApplicationFactory(application_info=app_info2) self.assertEquals( 4, Application.objects.without_interviews_for(app_info1).count()) self.assertEquals( 2, Application.objects.without_interviews_for(app_info2).count()) self.assertEquals(6, Application.objects.without_interviews().count())
def test_not_generate_interviews_when_have_not_enough_free_slots_for_app_info( self): course1, course2 = factory.build_batch(size=2, klass=CourseFactory) cd1 = CourseDescriptionFactory(course=course1) cd2 = CourseDescriptionFactory(course=course2) app_info1 = ApplicationInfoFactory(course=cd1) app_info2 = ApplicationInfoFactory(course=cd2) ApplicationFactory(application_info=app_info1) ApplicationFactory(application_info=app_info1) ApplicationFactory(application_info=app_info1) ApplicationFactory(application_info=app_info2) ApplicationFactory(application_info=app_info2) interviewer1, interviewer2 = factory.build_batch( size=2, klass=InterviewerFactory) interviewer1.courses_to_interview.add(app_info1) interviewer2.courses_to_interview.add(app_info2) InterviewerFreeTime.objects.create(interviewer=interviewer1, date=datetime.now().date(), start_time='11:00', end_time='12:00') InterviewerFreeTime.objects.create(interviewer=interviewer2, date=datetime.now().date(), start_time='12:00', end_time='15:00') self.assertEquals( 3, Application.objects.without_interviews_for(app_info1).count()) self.assertEquals( 2, Application.objects.without_interviews_for(app_info2).count()) call_command('generate_interview_slots') self.assertEquals( 3, Application.objects.without_interviews_for(app_info1).count()) self.assertEquals(2, Interview.objects.free_slots_for(app_info1).count()) self.assertEquals( 0, Application.objects.without_interviews_for(app_info2).count()) self.assertEquals(4, Interview.objects.free_slots_for(app_info2).count())
def books(self, created, extracted, **kwargs): if created: books = factory.build_batch(BookFactory, size=random.randint(1, 10)) for book in books: self.books.add(book) if extracted: for book in extracted: self.books.add(book)
def test_build_batch(self): objs = factory.build_batch(TestObject, 4, two=2, three=factory.LazyAttribute(lambda o: o.two + 1)) self.assertEqual(4, len(objs)) self.assertEqual(4, len(set(objs))) for obj in objs: self.assertEqual(obj.one, None) self.assertEqual(obj.two, 2) self.assertEqual(obj.three, 3) self.assertEqual(obj.four, None)
def test_list_pagination(self): build_batch(PostFactory, 21, rubric=self.category) response = client.get('/' + self.parent.slug + '/') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'posts/list.html') self.assertTemplateUsed(response, 'helpers/pagination.html') self.assertTrue(response.context['page_obj'].has_next()) self.assertFalse(response.context['page_obj'].has_previous()) self.assertEqual(response.context['page_obj'].next_page_number(), 2) self.assertEqual(response.context['page_obj'].number, 1) self.assertEqual(response.context['paginator'].num_pages, 2) self.assertIn(b'pagination', response.content) response = client.get('/' + self.parent.slug + '/?page=2') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'posts/list.html') self.assertTemplateUsed(response, 'helpers/pagination.html') self.assertFalse(response.context['page_obj'].has_next()) self.assertTrue(response.context['page_obj'].has_previous()) self.assertEqual(response.context['page_obj'].previous_page_number(), 1) self.assertEqual(response.context['page_obj'].number, 2) self.assertIn(b'pagination', response.content)
def test_create_related_with_expanded_serializer(self): todos_dict = factory.build_batch(dict, FACTORY_CLASS=TodoFactory, size=3) for todo in todos_dict: todo.pop('assignee') person = factory.build(dict, FACTORY_CLASS=PersonWithForeignFactory, todos=todos_dict) serializer = PersonExpandForeignSerializer(data=person) assert serializer.is_valid() created_person = serializer.save() for todo in todos_dict: assert created_person.todos.filter(id=todo['id']).exists()
def test_build_batch(self): objs = factory.build_batch( TestObject, 4, two=2, three=factory.LazyAttribute(lambda o: o.two + 1)) self.assertEqual(4, len(objs)) self.assertEqual(4, len(set(objs))) for obj in objs: self.assertEqual(obj.one, None) self.assertEqual(obj.two, 2) self.assertEqual(obj.three, 3) self.assertEqual(obj.four, None)
def test_create_related_with_expanded_serializer(self): comments_dict = factory.build_batch(dict, FACTORY_CLASS=CommentFactory, size=3) for comment in comments_dict: comment.pop('todo') assignee_for_todos = PersonFactory.create() todo = factory.build(dict, FACTORY_CLASS=TodoWithForeignFactory, comments=comments_dict, assignee=assignee_for_todos.pk) serializer = TodoExpandForeignSerializer(data=todo) assert serializer.is_valid() created_todo = serializer.save() for comment in comments_dict: assert created_todo.comments.filter(id=comment['id']).exists()
def test_save_replaces_schedule(self): """Check that existing schedule items are removed when posting a new schedule""" plan = factories.CustomPaymentPlanFactory() url = reverse('invoice:save-payment-schedule', kwargs={'plan_id': plan.id}) old_payment = factories.ScheduledPaymentFactory(payment_plan=plan) # A simple way of producing dicts from a factory_boy class. See: # https://factoryboy.readthedocs.io/en/stable/recipes.html#converting-a-factory-s-output-to-a-dict data = factory.build_batch( dict, FACTORY_CLASS=factories.ScheduledPaymentFactory, size=2) response = self.client.post(url, data=data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(plan.scheduled_payments.count(), 2) with self.assertRaises(models.ScheduledPayment.DoesNotExist): old_payment.refresh_from_db()
def test_not_generate_interview_for_past_days(self): app_info = ApplicationInfoFactory() interviewer1, interviewer2 = factory.build_batch( size=2, klass=InterviewerFactory) interviewer1.courses_to_interview.add(app_info) interviewer2.courses_to_interview.add(app_info) InterviewerFreeTime.objects.create(interviewer=interviewer1, date=datetime.now().date() - timedelta(days=1), start_time='11:00', end_time='14:00') InterviewerFreeTime.objects.create(interviewer=interviewer2, date=datetime.now().date(), start_time='11:00', end_time='14:00') call_command('generate_interview_slots') self.assertEquals(6, Interview.objects.get_free_slots().count())
def test_generate_interviews_for_more_interviewers(self): app_info = ApplicationInfoFactory() application1 = ApplicationFactory(application_info=app_info) application2 = ApplicationFactory(application_info=app_info) application3 = ApplicationFactory(application_info=app_info) interviewer1, interviewer2 = factory.build_batch( size=2, klass=InterviewerFactory) interviewer1.courses_to_interview.add(app_info) interviewer2.courses_to_interview.add(app_info) InterviewerFreeTime.objects.create(interviewer=interviewer1, date=datetime.now().date(), start_time='11:00', end_time='14:00') InterviewerFreeTime.objects.create(interviewer=interviewer2, date=datetime.now().date(), start_time='12:00', end_time='15:00') self.assertEquals( 3, Application.objects.without_interviews_for(app_info).count()) call_command('generate_interview_slots') self.assertEquals(9, Interview.objects.free_slots_for(app_info).count()) interviewer_for_app1 = Interview.objects.get( application=application1).interviewer interviewer_for_app2 = Interview.objects.get( application=application2).interviewer interviewer_for_app3 = Interview.objects.get( application=application3).interviewer self.assertNotEqual(interviewer_for_app1, interviewer_for_app2) self.assertEqual(interviewer_for_app1, interviewer_for_app3) self.assertEquals( 0, Application.objects.without_interviews_for(app_info).count())
def mock(self, model, factory, count, chunksize=10, bulk=True, **kwargs): """ The mock function has two modes of operation, bulk or not. Djangos bulk_create method is fast but does not call the .save() method, and does not trigger signals. Use bulk if possible, it is much faster. """ logger.info( "Creating %s instances of model %s using factory %s and kwargs %s" % (count, model, factory, kwargs)) if bulk: for i in range(0, count, chunksize): chunk_items = factory.build_batch( count - i if count - i < chunksize else chunksize, **kwargs) model.objects.bulk_create(chunk_items) if i: logger.debug("Mocked %s objects in %s" % (i, model)) else: for i in range(0, count): item = factory.build(**kwargs) item.save()
class UserFactory(factory.Factory): class Meta: model = User name = factory.Faker("name", locale="zh_CN") #factory.Faker num = factory.Faker("num") #age = factory.fuzzy.FuzzyInteger(42)#factory.fuzzy.FuzzyInteger age = factory.Faker("random_int", min=18, max=30, step=1) city = factory.Faker("address", locale="zh_CN") phone = factory.fuzzy.FuzzyText("138", 7, "1", "1234567890") #factory.fuzzy.FuzzyText school = factory.SubFactory(SchoolFactory) #factory.SubFactory #info=factory.List([SchoolFactory]) info = factory.List(factory.build_batch(SchoolFactory, 4)) #dictmap=factory.Dict([("one",SchoolFactory),("two",SchoolFactory)]) dictmap = factory.Dict({"one": SchoolFactory, "two": SchoolFactory}) #dictmap = factory.Dict(dict(one=1, two=2)) class Params: shipped = factory.Trait(name=None)
class UserFactory(factory.alchemy.SQLAlchemyModelFactory): class Meta: model = User sqlalchemy_session = DBSession # the SQLAlchemy session object sqlalchemy_session_persistence = "commit" #"commit"--perform a session commit() #'flush'-- perform a session flush() id = factory.Sequence(lambda n: n) #id = 9 name = factory.Sequence(lambda n: u'User %d' % n) #清除表内容 DBSession.query(User).delete() #DBSession.query(User).filter(User.id==0).delete() DBSession.commit() # users=DBSession.query(User).all() # for usr in users: # print(usr.__dict__) #创建一条记录 UserFactory() # UserFactory() #创建100条记录 factory.build_batch(UserFactory, 100) #DBSession.commit() users = DBSession.query(User).all() for usr in users: print(usr.__dict__) print(len(users)) DBSession.remove()
def test_counting_interview_slots_for_app_info_without_applications(self): course1, course2 = factory.build_batch(size=2, klass=CourseFactory) cd1 = CourseDescriptionFactory(course=course1) cd2 = CourseDescriptionFactory(course=course2) app_info1 = ApplicationInfoFactory(course=cd1) app_info2 = ApplicationInfoFactory(course=cd2) interviewer1 = InterviewerFactory() interviewer1.courses_to_interview.add(app_info1) interviewer2 = InterviewerFactory() interviewer2.courses_to_interview.add(app_info2) free_time1 = InterviewerFreeTime.objects.create( interviewer=interviewer1, date=datetime.now().date(), start_time='11:00', end_time='14:00') free_time2 = InterviewerFreeTime.objects.create( interviewer=interviewer1, date=datetime.now().date(), start_time='10:00', end_time='14:00') Interview.objects.create(interviewer=interviewer2, date=datetime.now().date(), start_time='12:00', end_time='12:30', interviewer_time_slot=free_time2) Interview.objects.create(interviewer=interviewer2, date=datetime.now().date(), start_time='12:00', end_time='12:30', interviewer_time_slot=free_time2) interview = Interview.objects.create(interviewer=interviewer1, date=datetime.now().date(), start_time='11:00', end_time='11:30', interviewer_time_slot=free_time1) Interview.objects.create(interviewer=interviewer1, date=datetime.now().date(), start_time='12:00', end_time='12:30', interviewer_time_slot=free_time1) self.assertEquals(2, Interview.objects.free_slots_for(app_info1).count()) self.assertEquals(2, Interview.objects.free_slots_for(app_info2).count()) self.assertEquals(4, Interview.objects.get_free_slots().count()) application = ApplicationFactory(application_info=app_info1) interview.application = application interview.save() self.assertEquals(1, Interview.objects.free_slots_for(app_info1).count()) self.assertEquals(2, Interview.objects.free_slots_for(app_info2).count()) self.assertEquals(3, Interview.objects.get_free_slots().count())
# -*- coding: utf-8 -*- # @Time : 2019/8/12 0012 23:40 # @Author : Vincent # @Email : [email protected] # @File : use.py # @Software: PyCharm from django.forms.models import model_to_dict import factory from fbtest.userfc import UserFactory from fbtest.school import School seq = [] uf = UserFactory() print(uf.__dict__) seq.append(uf.__dict__) seq.append(UserFactory().__dict__) print(seq) list = [] fss = factory.build_batch(UserFactory, 4) for fs in fss: list.append(fs.__dict__) print(list) uff = UserFactory(shipped=True) print(uff.__dict__) # uffs=UserFactory(city="1245") # print(model_to_dict(UserFactory(city="1245")))
def test_num_queries_bo(self): factory.build_batch(LicenceWithUserAndBaseObjectsFactory, 100) licence_relation = LicenceRelationsReport() with self.assertNumQueries(3): list(licence_relation.prepare(BackOfficeAsset))
def json_batch(cls, num, **kwargs): return factory.build_batch(dict, num, FACTORY_CLASS=cls, **kwargs)
client.credentials(HTTP_AUTHORIZATION=f"Bearer {jwt}") return client @pytest.fixture def register_form() -> Dict[str, str]: user = f.UserFactory.build() return { "password": data.DEFAULT_PASSWORD, "email": user.email, "firstName": user.first_name, "lastName": user.last_name, "zipcode": user.profile.zipcode, } @pytest.fixture(params={**data.UpdateProfileForm.__members__}) def update_profile_params(request): return data.UpdateProfileForm[request.param].value @pytest.fixture(params=factory.build_batch(dict, 5, FACTORY_CLASS=f.ProfileFactory)) def random_profile_dict(request): profile = request.param if "user" in profile: del profile["user"] return request.param
def build_social_persons(count): return factory.build_batch(dict, FACTORY_CLASS=SocialPersonFactory, size=count)
def existing_instructors(self, group_info): group_info.instructors = factory.build_batch( dict, 3, FACTORY_CLASS=factories.HUser) return group_info.instructors
def test_generate_interviews_for_different_courses_with_different_interviewers( self): course1, course2 = factory.build_batch(size=2, klass=CourseFactory) cd1 = CourseDescriptionFactory(course=course1) cd2 = CourseDescriptionFactory(course=course2) app_info1 = ApplicationInfoFactory(course=cd1) app_info2 = ApplicationInfoFactory(course=cd2) application1 = ApplicationFactory(application_info=app_info1) application2 = ApplicationFactory(application_info=app_info2) application3 = ApplicationFactory(application_info=app_info1) application4 = ApplicationFactory(application_info=app_info2) application5 = ApplicationFactory(application_info=app_info1) interviewer1, interviewer2, interviewer3 = factory.build_batch( size=3, klass=InterviewerFactory) interviewer1.courses_to_interview.add(app_info1) interviewer2.courses_to_interview.add(app_info2) interviewer3.courses_to_interview.add(app_info1) InterviewerFreeTime.objects.create(interviewer=interviewer1, date=datetime.now().date(), start_time='11:00', end_time='14:00') InterviewerFreeTime.objects.create(interviewer=interviewer2, date=datetime.now().date(), start_time='12:00', end_time='15:00') InterviewerFreeTime.objects.create(interviewer=interviewer3, date=datetime.now().date(), start_time='13:00', end_time='15:00') self.assertEquals( 3, Application.objects.without_interviews_for(app_info1).count()) self.assertEquals( 2, Application.objects.without_interviews_for(app_info2).count()) self.assertEquals(5, Application.objects.without_interviews().count()) call_command('generate_interview_slots') self.assertEquals(7, Interview.objects.free_slots_for(app_info1).count()) self.assertEquals(4, Interview.objects.free_slots_for(app_info2).count()) self.assertEquals(11, Interview.objects.get_free_slots().count()) interviewer_for_app1 = Interview.objects.get( application=application1).interviewer interviewer_for_app2 = Interview.objects.get( application=application2).interviewer interviewer_for_app3 = Interview.objects.get( application=application3).interviewer interviewer_for_app4 = Interview.objects.get( application=application4).interviewer interviewer_for_app5 = Interview.objects.get( application=application5).interviewer self.assertEqual(interviewer1, interviewer_for_app1) self.assertEqual(interviewer1, interviewer_for_app5) self.assertEqual(interviewer2, interviewer_for_app2) self.assertEqual(interviewer2, interviewer_for_app4) self.assertEqual(interviewer3, interviewer_for_app3) self.assertTrue(application1 in interviewer1.interviews.all()) self.assertTrue(application5 in interviewer1.interviews.all()) self.assertTrue(application2 in interviewer2.interviews.all()) self.assertTrue(application4 in interviewer2.interviews.all()) self.assertTrue(application3 in interviewer3.interviews.all())
def handle(self, *args, **options): factory.build_batch(ActivityPeriodFactory, size = options['num']) self.stdout.write(self.style.SUCCESS('Successfully generated fields'))