def populate_data(self): people = AutoFixture( Person, field_values={ "anonymised": False, "name": generators.FirstNameGenerator() }, ).create(5) for person in people: AutoFixture(HealthRecord, field_values={ "anonymised": False, "person": person }).create(random.randint(1, 3)) AutoFixture( PersonProfile, field_values={ "anonymised": False, "person": person, "age": generators.IntegerGenerator(5, 55), "address": generators.LoremGenerator(max_length=100), }, ).create(random.randint(1, 3)) AutoFixture( MailingListLog, field_values={ "anonymised": False, "email": person.email, "sent_at": generators.DateTimeGenerator(), }, ).create(random.randint(1, 3))
class BrewTest(TestCase): """Test Class for Brew model""" def setUp(self): "Set up test data for Brew Test " self.brew = AutoFixture( Brew, field_values={'name': 'test', 'start_time': START_DATE}).create(1)[0] time_stamp = START_DATE while time_stamp <= END_DATE: AutoFixture(Bubble, field_values={'time_stamp': time_stamp}).create() time_stamp = time_stamp + timedelta(hours=1) def test_str(self): "Test String representation" self.assertEqual('test', self.brew.name) def test_get_max_date(self): "Ensure we get the max date" self.assertEqual(END_DATE, self.brew.get_max_date()) def test_get_min_date(self): "Ensure we get the min date" self.assertEqual(START_DATE, self.brew.get_min_date()) def test_bubbles_in_interval(self): "test bubbles in interval" self.assertEqual(24, self.brew.bubbles_in_interval(START_DATE, END_DATE))
def fake_book(count=10): fixture = AutoFixture(Book) entries = fixture.create(count, commit=False) for entry in entries: entry.currency = choice([entry.USD, entry.CAD, entry.EUR, entry.AED]) entry.save() entry.authors.add(choice(Author.objects.values_list('id', flat=True)))
def test_trigger_create(self): """ Create the star trigger, check if it does it's work """ data = { "code": "star", "condition": "NEW.hit_views >= 1000 ", "name": "Star", "trigger_condition": "update", "trigger_table": "dummy_sketch", "user_field": "user_id" } create_trigger(data) self.assertEqual(Badge.objects.count(), 0) users = User.objects.all()[:10] for user in users: fixture = AutoFixture( Sketch, field_values={"user": user, "hit_views": 0}) sketch = fixture.create(1)[0] sketch.hit_views = 1000 sketch.save() self.assertEqual(Badge.objects.count(), 10)
def setUp(self): self.client = Client() self.url = reverse('tasks') self.user = AutoFixture(User).create(1)[0] fixture = AutoFixture(Task, field_values={'owner': self.user}) self.tasks = fixture.create(10)
def test_update_topic_assign_concurrent_categories_ok(self): AutoFixture(Type, field_values={ 'name': '.:en:concurrent1', 'is_category': True }).create_one() AutoFixture(Type, field_values={ 'name': '.:en:concurrent2', 'is_category': True }).create_one() Type.objects.categories().order_by('id').all() categories_str = ['concurrent'] self.client.put(reverse('topic-detail', args=(self.topic.pk, )), data={ 'title': '.:en:Test title', 'body': '.:en\nTest body', 'type': Topic.IDEA, 'categories_str': categories_str, }) instance = Topic.objects.first() self.assertEqual(instance.categories.count(), 1) self.assertIn('concurrent1', instance.categories.first().name)
def test_bill_video_str(self): self.theme_fixture.create_one() self.bill_fixture.create_one() fixture = AutoFixture(models.BillVideo) video = fixture.create_one() video.url = 'http://test.url/' self.assertEquals(video.__str__(), 'http://test.url/')
def test_bill_reference_str(self): self.theme_fixture.create_one() self.bill_fixture.create_one() fixture = AutoFixture(models.BillReference, field_values={'title': 'test title'}) reference = fixture.create_one() self.assertEquals(reference.__str__(), 'test title')
def test_proposal_type_str(self): proposal_type = AutoFixture(models.ProposalType, field_values={ 'initials': 'PL', 'description': 'PL' }).create_one() self.assertEquals(proposal_type.__str__(), 'PL - PL')
def create_tournament(beginDate=None, endDate=None): beginDate = beginDate or datetime.date(2007, 4, 24) endDate = endDate or datetime.date(2010, 4, 22) fixture_tournament = AutoFixture( Tournament, generate_fk=True, field_values={"begin_date": beginDate, "end_date": endDate} ) return fixture_tournament.create(1)[0]
def create_obj(self): fixture = AutoFixture(ProductImage, field_values={'status': 0}, generate_fk=True) fixture.create(1) self.obj = ProductImage.objects.get(pk=1) return self.obj
def test_no_triggers(self): """ Try to create event that would normaly launch badge earning. Ensure it's not. """ users = User.objects.all()[:10] for user in users: user.date_joined = user.date_joined - datetime.timedelta(days=370) user.save() # no pionner self.assertEqual(Badge.objects.count(), 0) for user in users: fixture = AutoFixture( Sketch, field_values={"user": user}) fixture.create(5) # no collector self.assertEqual(Badge.objects.count(), 0) for user in users: fixture = AutoFixture( Sketch, field_values={"user": user, "hit_views": 0}) sketch = fixture.create(1)[0] sketch.hit_views = 1000 sketch.save() # no star self.assertEqual(Badge.objects.count(), 0)
def generate_sample_from_model(model, num): """ Generate num instances of model """ fixture = AutoFixture(model) entries = fixture.create(num) return entries
def setup_module(): test_user = User.objects.create_user(username='******',password='******',email='*****@*****.**') test_user.save() test_user_2 = User.objects.create_user(username='******',password='******',email='*****@*****.**') test_user_2.save() fixture = AutoFixture(Patrao, field_values={'usuario': test_user_2}) fixture.create(QTD_PATROES)
def create_technican_detail(): for i in range(0, N): lat_long = generate_random_location() res = w3w.reverse(lat=lat_long[0], lng=lat_long[1])['words'] willing_to_travel = random.randint(1, 30) max_num_jobs_allowed = random.randint(1, 6) av_rating = random.uniform(0, 5) ficture3 = AutoFixture(TechnicianDetail, field_values={ 'number_jobs_active': random.randint(0, 5), 'number_of_jobs_completed': random.randint(0, 100), 'rating': [{ 'job_id': 1, 'user_rating': 3 }], 'what3words': res, 'willing_to_travel': willing_to_travel, 'max_num_jobs_allowed': max_num_jobs_allowed, 'average_rating': av_rating }) entries3 = ficture3.create(1)
def setUp(self): self.client = Client() self.user = AutoFixture(User).create(1)[0] self.task = AutoFixture(Task, field_values={ 'owner': self.user }).create(1)[0] self.url = reverse('task-edit', args=[self.task.id])
class TagTests(TestCase): """tests for Tag""" def setUp(self): self.client = Client() self.fixture = AutoFixture(Tag) def tearDown(self): Tag.objects.all().delete() def populate(self, num): self.fixture.create(num) def test_save(self): tag = Tag() tag.name = 'test tag' tag.save() self.assertIsNotNone(tag.pk) self.assertIsNotNone(tag.slug) def test_unique_slug(self): self.populate(10) # TODO: test Tag duplicate names not allowed # raises TransactionError: # django.db.transaction.TransactionManagementError: # An error occurred in the current transaction. # You can't execute queries until the end of the 'atomic' block. # line 22, in tearDown # def test_duplicate_name(self): # self.populate(1) # t_db = Tag.objects.all()[0] # t = Tag(name=t_db.name) # with self.assertRaises(IntegrityError): # t.save() # t.delete() # Tag.objects.all().delete() def test_slug_immutable(self): self.populate(1) t = Tag.objects.all()[0] slug = t.slug t.name = 'mutable field' t.save() self.assertEqual(slug, t.slug) def test_str(self): self.populate(1) t = Tag.objects.all()[0] self.assertEqual(t.name, str(t)) def test_url(self): self.populate(1) t = Tag.objects.all()[0] self.assertEqual( t.get_absolute_url(), reverse( 'sitebase:tags:get', args=[t.slug])) def test_tags_url(self): self.assertIsNotNone(reverse('sitebase:tags:list'))
def incident_detail(business: Business, d: DateDim): v = { 'business': business, 'building': business.building, 'incident_type': 'Structural', 'occurrence': d, 'region': region, 'province': province, 'city': city } checklist = business.building.building_checklist.get( date_checked__year=d.year, business=business) if business.building.avg_fire_rating() < 2: damage_range = [5, 25] casualty_range = [0, .1] intensity_range = [1, 5] severity_range = [1, 6] duration_range = [30, 240] minor_injuries_range = [0, .1] major_injuries_range = [0, .2] elif business.building.avg_fire_rating() < 3: damage_range = [5, 60] casualty_range = [0, .15] intensity_range = [1, 7] severity_range = [1, 6] duration_range = [45, 340] minor_injuries_range = [0, .4] major_injuries_range = [0, .3] elif business.building.avg_fire_rating() < 4: damage_range = [12, 95] casualty_range = [0, .2] intensity_range = [1, 8] severity_range = [1, 8] duration_range = [60, 540] minor_injuries_range = [0, .5] major_injuries_range = [0, .4] else: damage_range = [30, 999] casualty_range = [0, .5] intensity_range = [2, 10] severity_range = [3, 10] duration_range = [60, 1940] minor_injuries_range = [0, .6] major_injuries_range = [0, .5] v['property_damage'] = random.uniform(damage_range[0], damage_range[1]) v['casualties'] = random.uniform(casualty_range[0], casualty_range[1]) v['major_injuries'] = random.uniform(major_injuries_range[0], major_injuries_range[1]) v['minor_injuries'] = random.uniform(minor_injuries_range[0], minor_injuries_range[1]) v['intensity'] = random.uniform(intensity_range[0], intensity_range[1]) v['severity'] = random.uniform(severity_range[0], severity_range[1]) v['duration'] = random.uniform(duration_range[0], duration_range[1]) fixture = AutoFixture(Incident, field_values=v) fixture.create(1) print(f"{fixture} created")
def preload_businesses(data): for key, item in data.items(): __building = item['building'] __business = item['business'] __address = item['address'] __latitude = item['latitude'] __longitude = item['longitude'] try: building = Building.objects.get(name=__building) except Building.DoesNotExist: building = create_building(item) building = Building.objects.get(name=__building) try: business = Business.objects.get(name=__business) except Business.DoesNotExist: fixture = AutoFixture(Business, field_values={ 'name': __business, 'address': __address, 'region': region, 'province': province, 'city': city, 'building': building }) business = fixture.create(1) print(f"{business} created in {building}")
def test_ibanuser_list_displays_users_ibanuser_only(self): other_user = AutoFixture(User).create(1)[0] AutoFixture(IbanInfo, field_values={'owner': other_user}).create(1) self.client.force_login(self.user) response = self.client.get(self.url) self.assertEqual(len(self.ibanusers), len(response.context['ibanusers']))
class AdminTestCase(TestCase): def setUp(self): self.factory = RequestFactory() self.theme_fixture = AutoFixture(models.BillTheme) self.bill_fixture = AutoFixture(models.Bill) self.segment_fixture = AutoFixture(models.BillSegment) self.admin_fixture = AutoFixture(get_user_model(), field_values={ 'is_superuser': True, 'is_member': True, 'is_staff': True }) def instance_admin_classes(self, url): self.theme_fixture.create_one() user_admin = self.admin_fixture.create_one() request = self.factory.get(url) request.user = user_admin bill_inline = admin.BillSegmentInline(models.Bill, django_admin.site) formset = bill_inline.get_formset(request) pagination_formset = formset() self.assertEqual(pagination_formset.per_page, 20) def test_bill_segment_inline(self): self.instance_admin_classes("/admin/core/bill/add/") def test_pagination_formset_value_error(self): self.instance_admin_classes("/admin/core/bill/add/?p=a") def test_pagination_formset_empty_page(self): self.instance_admin_classes("/admin/core/bill/add/?p=-2") def test_pagination_formset_change_list_show_all(self): self.instance_admin_classes("/admin/core/bill/add/?all")
def test_view_can_access_scripts_without_flag(self): script = AutoFixture(Script).create_one() script.has_access = False script.save() self.valid_headers['HTTP_X_RANDOM_ID'] = codecs.encode(script.hash, 'rot_13') response = self._action('scripts:view', {'slug': script.hash}, 'post', **self.valid_headers) self.assertEquals(200, response.status_code)
class AuthorTests(TestCase): """tests for Author""" def setUp(self): self.client = Client() self.fixture = AutoFixture(Author) def tearDown(self): Author.objects.all().delete() def populate(self, num): self.fixture.create(num) def test_save(self): author = Author() author.name = 'test Author' author.email = '*****@*****.**' author.short_bio = 'just an awesome author' author.save() self.assertIsNotNone(author.pk) self.assertIsNotNone(author.slug) def test_unique_slug(self): self.populate(10) def test_slug_immutable(self): self.populate(1) a = Author.objects.all()[0] slug = a.slug a.name = 'mutable field' a.save() self.assertEqual(slug, a.slug) def test_duplicate_names(self): self.populate(1) a_db = Author.objects.all()[0] a = Author( name=a_db.name, email='*****@*****.**', short_bio='just another author') try: a.save() except Exception as e: self.fail('Failed: {}'.format(e)) def test_str(self): self.populate(1) a = Author.objects.all()[0] self.assertEqual(a.name, str(a)) def test_url(self): self.populate(1) a = Author.objects.all()[0] self.assertEqual( a.get_absolute_url(), reverse( 'sitebase:authors:get', args=[a.slug])) def test_authors_url(self): self.assertIsNotNone(reverse('sitebase:authors:list'))
def setUp(self): self.client = Client() self.user = AutoFixture(User).create(1)[0] self.ibanuser = AutoFixture(IbanInfo, field_values={ 'owner': self.user }).create(1)[0] self.url = reverse('deleteuser', args=[self.ibanuser.id])
def create_cup(beginDate=None, endDate=None): beginDate = beginDate or datetime.date(2007, 4, 25) endDate = endDate or datetime.date(2008, 1, 1) fixture_cup = AutoFixture( Cup, generate_fk=True, field_values={'begin_date': beginDate, 'end_date': endDate}) return fixture_cup.create(1)[0]
def setUp(self): super(TransformTests, self).setUp() self.model = AutoFixture(SimpleModel).create_one() self.fk_model = AutoFixture(FkSimpleModel, field_values={ 'fk': self.model }).create_one()
def setUp(self): ''' initialisation for tests ''' location_fixture = AutoFixture(Location) location_fixture.create(1) self.test_user_util = TestUserUtility() self.user = self.test_user_util.user
def create_tournament(beginDate=None, endDate=None): beginDate = beginDate or datetime.date(2007, 4, 24) endDate = endDate or datetime.date(2010, 4, 22) fixture_tournament = AutoFixture( Tournament, generate_fk=True, field_values={'begin_date': beginDate, 'end_date': endDate}) return fixture_tournament.create(1)[0]
def test_chunk_set_status(exporter): chunk = AutoFixture(ExporterChunk, field_values={ 'exporter': exporter }).create_one() chunk.set_status(ExporterChunk.STATUS_CHOICES.success) assert chunk.status == ExporterChunk.STATUS_CHOICES.success
class TagTests(TestCase): """tests for Tag""" def setUp(self): self.client = Client() self.fixture = AutoFixture(Tag) def tearDown(self): Tag.objects.all().delete() def populate(self, num): self.fixture.create(num) def test_save(self): tag = Tag() tag.name = 'test tag' tag.save() self.assertIsNotNone(tag.pk) self.assertIsNotNone(tag.slug) def test_unique_slug(self): self.populate(10) # TODO: test Tag duplicate names not allowed # raises TransactionError: # django.db.transaction.TransactionManagementError: # An error occurred in the current transaction. # You can't execute queries until the end of the 'atomic' block. # line 22, in tearDown # def test_duplicate_name(self): # self.populate(1) # t_db = Tag.objects.all()[0] # t = Tag(name=t_db.name) # with self.assertRaises(IntegrityError): # t.save() # t.delete() # Tag.objects.all().delete() def test_slug_immutable(self): self.populate(1) t = Tag.objects.all()[0] slug = t.slug t.name = 'mutable field' t.save() self.assertEqual(slug, t.slug) def test_str(self): self.populate(1) t = Tag.objects.all()[0] self.assertEqual(t.name, str(t)) def test_url(self): self.populate(1) t = Tag.objects.all()[0] self.assertEqual(t.get_absolute_url(), reverse('sitebase:tags:get', args=[t.slug])) def test_tags_url(self): self.assertIsNotNone(reverse('sitebase:tags:list'))
def create_brand(self): fixture = AutoFixture(Brand, field_values={ 'slug': 'obj-slug', 'status': 0 }) fixture.create(1) self.obj = Brand.objects.get(slug='obj-slug') return self.obj
def test_can_manage_superuser(self): """ The user, which is superuser, can manage the cooperative. """ user = User(is_superuser=True) fixture = AutoFixture(HousingCooperative) cooperative = fixture.create(1)[0] self.assertTrue(user.can_manage(cooperative))
def _create_versions(self): version_fixture = AutoFixture( Version, field_values={ "yw_graph_output": DUMMY_GRAPH_STRING, "yw_model_checksum": str(uuid.uuid4()), }, ) _ = version_fixture.create(self.num_entries)
def create_biogas_plant_contact(): fixture5 = AutoFixture(BiogasPlantContact, field_values={ 'first_name': fake.first_name(), 'surname': fake.last_name(), 'mobile': random_phone_number(), 'email': fake.email(), }) entries5 = fixture5.create(10)
def test_bill_author_str_with_register_id(self): author = AutoFixture(models.BillAuthor, field_values={ 'name': 'author name', 'region': 'UF', 'party': 'TT', 'register_id': 123 }).create_one() self.assertEquals(author.__str__(), 'author name - TT(UF)')
def test_bill_author_str(self): author = AutoFixture(models.BillAuthor, field_values={ 'name': 'author name', 'region': None, 'party': None, 'register_id': None }).create_one() self.assertEquals(author.__str__(), 'author name')
def test_task_list_displays_users_tasks_only(self): other_user = AutoFixture(User).create(1)[0] AutoFixture(Task, field_values={'owner': other_user}).create(1) self.client.force_login(self.user) response = self.client.get(self.url) self.assertEqual(len(self.tasks), len(response.context['tasks']))
def testLocationGetChildren(self): fixtureParent=AutoFixture(StockLocation) locationParent=fixtureParent.create(1)[0] fixture=AutoFixture(StockLocation, field_values={"ParentLocation":locationParent}, generate_fk=True) locations=fixture.create(5) self.assertEqual(5,len( locationParent.GetChildren()))
def test_GenerateStockDetail(self): ft_stockbill=AutoFixture(StockBill,generate_fk=True) stockbills=ft_stockbill.create(2) ft_cbd=AutoFixture(CheckBillDetail,generate_fk=True, field_values={'quantity':1,'realquantity':4}) detail=ft_cbd.create(1)[0] #import pdb;pdb.set_trace() detail.GenerateStockDetail(stockbills[0],stockbills[1]) self.assertEqual(1,stockbills[1].billdetailbase_set.count()) self.assertEqual(3,stockbills[1].billdetailbase_set.all()[0].quantity)
def setUpTestData(cls): cls.req_courses = AutoFixture(Course, generate_fk=True, field_values=dict(course_number='101', credit_hours=4)).create(10) cls.other_courses = AutoFixture(Course, generate_fk=True, field_values=dict(course_number='102')).create(5) req_queryset = Course.objects.filter(course_number__exact='101') cls.req = create_requirement('test', None, 10, req_queryset) cls.user = AutoFixture(User, generate_fk=True).create_one() cls.schedule = AutoFixture(Schedule, generate_m2m=False, field_values=dict(user=cls.user.profile)).create_one()
def get_autofixture(app_label, model_name, f_key=False, n_instances=1): app_label = get_module_name(app_label) try: model_class = get_app_model(app_label, model_name) #ContentType.objects.get(model=model_name).model_class() fixtures = AutoFixture(model_class, generate_fk=f_key) entries = fixtures.create(n_instances) except Exception as e: print e return 'Error!' return 'Created(s)!'
class BlogSeriesTests(TestCase): """tests for BlogSeries""" def setUp(self): self.client = Client() self.fixture = AutoFixture(BlogSeries) def tearDown(self): BlogSeries.objects.all().delete() def populate(self, num): self.fixture.create(num) def test_save(self): series = BlogSeries() series.title = 'test BlogSeries' series.short_description = 'just some blog series' series.save() self.assertIsNotNone(series.pk) self.assertIsNotNone(series.slug) def test_unique_slug(self): self.populate(10) def test_slug_immutable(self): self.populate(1) series = BlogSeries.objects.all()[0] slug = series.slug series.title = 'mutable field' series.save() self.assertEqual(slug, series.slug) def test_duplicate_names(self): self.populate(1) series = BlogSeries.objects.all()[0] series.title='mutable field' try: series.save() except Exception as e: self.fail('Failed: {}'.format(e)) def test_str(self): self.populate(1) series = BlogSeries.objects.all()[0] self.assertEqual(series.title, str(series)) def test_url(self): self.populate(1) series = BlogSeries.objects.all()[0] self.assertEqual( series.get_absolute_url(), reverse( 'blog:series', args=[series.slug])) def test_seriess_url(self): self.assertIsNotNone(reverse('blog:series-list'))
def test_GenerateChangeDetail(self): af_checkbill=AutoFixture(CheckBill,generate_fk=True) bill=af_checkbill.create(1)[0] af_checkbilldetail=AutoFixture(CheckBillDetail, generate_fk=True,field_values={'stockbill':bill,'quantity':1,'realquantity':4}) billdetails=af_checkbilldetail.create(4) self.assertEqual(4,len(billdetails)) change_list=bill.GenerateChangeDetail() self.assertEqual(4,len(change_list)) for change in change_list: self.assertEqual(change.quantity,3)
def handle(self, *args, **options): toto = User.objects.get(pk=1) android = Category.objects.get(pk=7) subject = Subject.objects.create(category=android, author=toto, name="Ths is a subject", nb_see=0, nb_message=0) subject.save() #subject = Subject.objects.filter(category=android, author=toto) fixture = AutoFixture(NormalMessage, field_values={'author': toto, 'subject': subject}) entries = fixture.create(100) message = "Thread created please go here for test localhost:8000/subject/" + str(subject.pk) + "/1" print(message)
def setUp(self): super(LocationTestCase, self).setUp() self.user = User(username="******", password="******", email="*****@*****.**") self.user.save() fixture = AutoFixture(Location) locations = fixture.create(10) try: self.api_key = ApiKey.objects.get(user=self.user) except ApiKey.DoesNotExist: self.api_key = ApiKey.objects.create(user=self.user) self.auth_string = "&username={0}&api_key={1}".format(self.user.username, self.api_key.key)
def create_category_caracteristic(self, slug="slug", category=None, ftype='boolean', choices=choices, name='carac_name'): if category is None: category = self.create_category() fixture = AutoFixture(CategoryCaracteristic, field_values={ 'slug':slug, 'category':category, 'choices':choices, 'name':name, 'type':ftype, } ) return fixture.create(1)[0]
def setUp(self): super(MonitorUpdateTestCase, self).setUp() self.user = User(username='******', password='******', email='*****@*****.**') self.user.save() fixture = AutoFixture(MonitorUpdate) fixture.create(10) try: self.api_key = ApiKey.objects.get(user=self.user) except ApiKey.DoesNotExist: self.api_key = ApiKey.objects.create(user=self.user) self.auth_string = '&username={0}&api_key={1}'.format( self.user.username, self.api_key.key)
def test_unique_slug(self): fixture = AutoFixture(Author) fixture.create(1) author_orig = Author.objects.all()[0] unique_slug = get_unique_slug( Author, author_orig, 'name', name=author_orig.name) author_new = Author(name=author_orig.name) author_new.save() self.assertNotEqual(author_new.slug, author_orig.slug) self.assertEqual(author_new.slug, unique_slug) self.assertNotEqual( author_new.slug, get_unique_slug( Author, author_orig, 'name', name=author_orig.name))
def test_url(self): self.populate(1) b = BlogPost.objects.filter(series=None)[0] self.assertEqual( b.get_absolute_url(), reverse( 'blog:post', args=[b.slug])) series_fixture = AutoFixture(BlogSeries) series_fixture.create(1) b.series = BlogSeries.objects.all()[0] b.save() b = BlogPost.objects.filter(series__isnull=False)[0] self.assertEqual( b.get_absolute_url(), reverse( 'blog:post', args=[b.series.slug, b.slug]))
def test_athletes_races_are_sorted(self): race_fixture = AutoFixture(Race) races = race_fixture.create(10) user = User.objects.create() for race in races: CalendarItem.objects.create(race=race, user=user, priority='A') AutoFixture(CalendarItem, {user:user}) response = self.client.get('/athlete/{id}/calendar/'.format(id=user.id)) races = response.context_data['races'] races_sorted = sorted(races, key=lambda x: x.date) self.assertListEqual(races, races_sorted)
def post_save_student(sender, instance, created, **kwargs): if created: print("post_save_student") from autofixture import generators pl = AutoFixture(Placement, overwrite_defaults=True, field_values={ 'report': generators.StaticGenerator('ullmanfa/placement/report/Arbeitszeugnis_Audi.pdf'), 'presentation': generators.StaticGenerator( 'ullmanfa/placement/presentation/Arbeitszeugnis_Audi.pdf'), 'certificate': generators.StaticGenerator( 'ullmanfa/placement/certificate/Arbeitszeugnis_Audi.pdf'), 'student': instance}) pl.create(1)
def testSaveBill(self): fixtureProduct=AutoFixture(Product,field_values={'Price':1}) theproduct=fixtureProduct.create(1)[0] theproduct.Price=1 fixtureLocation=AutoFixture(StockLocation,generate_fk=True, field_values={'LocationCode':'1.1'}) location=fixtureLocation.create(1)[0] fixtureBill=AutoFixture(StockBill,generate_fk=True,field_values={'BillState':'applied'}) bill=fixtureBill.create(1)[0] fixtureBillDetail=AutoFixture(StockBillDetail,generate_fk=True ,field_values={'stockbill':bill,'product':theproduct,'quantity':1 ,'location':location}) detail=fixtureBillDetail.create(5) bill.save() print (bill.BillType) self.assertEqual(len(ProductStock.objects.all()),1) self.assertEqual(ProductStock.objects.all()[0].quantity,5) print ([ProductStock.objects.all()]) self.assertEqual(bill.TotalAmount,5) bill.BillType='out' bill.save() print (bill.BillType) print ([ProductStock.objects.all()]) self.assertEqual(len(ProductStock.objects.all()),1) self.assertEqual(ProductStock.objects.all()[0].quantity,0) self.assertEqual(bill.TotalAmount,5)
def create_match(home_goal, away_goal, home_goal_first=None, away_goal_first=None): home_goal_first = home_goal_first or 0 away_goal_first = away_goal_first or 0 fixture_match = AutoFixture( Match, generate_fk=True, field_values={ "home_goal": home_goal, "away_goal": away_goal, "home_goal_first": home_goal_first, "away_goal_first": home_goal_first, }, ) return fixture_match.create(1)[0]
def setUp(self): super(TimeInfoTestCase, self).setUp() self.user = User(username='******', password='******', email='*****@*****.**') self.user.save() fixture = AutoFixture(TimeInfo) fixture.create(10) now = timezone.now() self.from_datetime = now.isoformat() self.to_datetime = now.isoformat() try: self.api_key = ApiKey.objects.get(user=self.user) except ApiKey.DoesNotExist: self.api_key = ApiKey.objects.create(user=self.user) self.auth_string = '&username={0}&api_key={1}'.format( self.user.username, self.api_key.key)
def setUp(self): super(ActorRelationshipTestCase, self).setUp() self.user = User(username='******', password='******', email='*****@*****.**') self.user.save() self.actor = Actor(fullname_ar='Test name ar', nickname_en='nick name', nickname_ar='nick name') self.actor.save() fixture = AutoFixture(ActorRelationship, generate_m2m={1, 4}) actorRelationshipps = fixture.create(10) try: self.api_key = ApiKey.objects.get(user=self.user) except ApiKey.DoesNotExist: self.api_key = ApiKey.objects.create(user=self.user) self.auth_string = '&username={0}&api_key={1}'.format( self.user.username, self.api_key.key)
def test_assigned_user_perm_enforced(self): self.test_user_util.add_user_to_group('data-analyst') fixture = AutoFixture(User) fixture.create(1) precreated_incident = Incident.objects.all()[0] precreated_incident.assigned_user = User.objects.get(id=2) precreated_incident.save() url = '/api/v1/incident/{0}/?format=json{1}'.format( precreated_incident.id, self.auth_string) put_data = create_put_data(4) response = self.api_client.put(url, data=put_data) assigned_user_id = retrieve_user_id(response) self.assertEqual(assigned_user_id, 2) self.test_user_util.add_user_to_group('chief-data-analyst') response = self.api_client.put(url, data=put_data) assigned_user_id = retrieve_user_id(response) self.assertEqual(assigned_user_id, 1)
def setUp(self): "Set up test data for Brew Test " self.brew = AutoFixture( Brew, field_values={'name': 'test', 'start_time': START_DATE}).create(1)[0] time_stamp = START_DATE while time_stamp <= END_DATE: AutoFixture(Bubble, field_values={'time_stamp': time_stamp}).create() time_stamp = time_stamp + timedelta(hours=1)
def setUp(self): super(SourceTestCase, self).setUp() self.sourceType = SourceType( source_type="test type", description="test description" ) self.sourceType.save() self.user = User(username='******', password='******', email='*****@*****.**') self.user.save() fixture = AutoFixture(Source) sources = fixture.create(10) try: self.api_key = ApiKey.objects.get(user=self.user) except ApiKey.DoesNotExist: self.api_key = ApiKey.objects.create(user=self.user) self.auth_string = '&username={0}&api_key={1}'.format( self.user.username, self.api_key.key)