class GenericModelTest(TestCase): def setUp(self): self.client = Client() authenticate(self.client) @given(from_model(model, **kwargs)) def test_generic(self, instance): self.assertIsNotNone(instance.pk) resp = self.client.get(reverse_model(model, "browse"), follow=True) self.assertEqual(resp.status_code, 200) resp = self.client.get(reverse_model(model, "read", kwargs={"pk": instance.pk}), follow=True) self.assertEqual(resp.status_code, 200) resp = self.client.get(reverse_model(model, "edit", kwargs={"pk": instance.pk}), follow=True) resp = self.client.get(reverse_model(model, "delete", kwargs={"pk": instance.pk}), follow=True) self.assertEqual(resp.status_code, 200) def test_add(self): resp = self.client.get(reverse_model(model, "add"), follow=True) self.assertEqual(resp.status_code, 200) # TODO: implement add form, use hypothesis @given(from_model(model, **kwargs)) @settings(deadline=None) def test_forms(self, instance): self.assertIsNotNone(instance.pk)
def person_with_role(draw, **kwargs): defaults = { "contact_phone": french_phone_number, "image": None, "role__is_active": True, "role__is_staff": False, "role__is_superuser": False, "role__type": Role.PERSON_ROLE, } kwargs = {**defaults, **kwargs} email = to_strategy(kwargs.pop("email", st.emails())) role_kwargs = { k[len("role__"):]: to_strategy(kwargs.pop(k)) for k in list(kwargs) if k.startswith("role__") } person_kwargs = {k: to_strategy(v) for k, v in kwargs.items()} r = draw(from_model(Role, **role_kwargs)) p = draw(from_model(Person, role=st.just(r), **person_kwargs)) e = draw(email) p.add_email(e, primary=True) return p
class TestPoll(TestCase): # Initial setup def setUp(self): self.client = APIClient() self.factory = APIRequestFactory() self.view = apiviews.PollViewSet.as_view({"get": "list"}) self.uri = "/polls/" # Testing create polls @settings(deadline=2000, max_examples=10) @given(from_model(User)) def test_create(self, user): user = self.set_password_to_user(user) self.client.login(username=user.username, password="******") body = {"question": st.text(), "created_by": user.id} time.sleep(1) response = self.client.post(self.uri, body) self.assertEqual( response.status_code, 201, "Expected Response Code 201, received {0} instead.".format( response.status_code), ) # Testing list polls - Method I @settings(deadline=2000, max_examples=10) @given(from_model(User)) def test_list(self, user): request = self.factory.get(self.uri) request.user = user response = self.view(request) self.assertEqual( response.status_code, 200, "Expected Response Code 200, received {0} instead.".format( response.status_code), ) # Testing list polls - Method II @settings(deadline=2000, max_examples=10) @given(from_model(User)) def test_list2(self, user): user = self.set_password_to_user(user) self.client.login(username=user.username, password="******") response = self.client.get(self.uri) self.assertEqual( response.status_code, 200, "Expected Response Code 200, received {0} instead.".format( response.status_code), ) # Just a method to set password def set_password_to_user(self, user): user.set_password("hello") user.save() return user
def test_from_model_argspec(self): if sys.version_info[:2] <= (3, 7): self.assertRaises(TypeError, from_model().example) self.assertRaises(TypeError, from_model(Car, None).example) self.assertRaises(TypeError, from_model(model=Customer).example) else: self.assertRaises(TypeError, from_model) self.assertRaises(TypeError, from_model, Car, None) self.assertRaises(TypeError, from_model, model=Customer)
class PurrTest(TestCase): @given(from_model(Purr, user=from_model(get_user_model()))) def test_create_purr(self, purr): self.assertTrue(len(purr.content) < 140) self.assertIsNone(purr.in_reply_to) @given(from_model(Purr, user=from_model(get_user_model()), in_reply_to=from_model(Purr, user=from_model(get_user_model())))) def test_create_reply_purr(self, purr): self.assertTrue(len(purr.content) < 140) self.assertIsNotNone(purr.in_reply_to) original = purr.in_reply_to self.assertTrue(purr in original.replies())
def test_foreign_key_primary(self, buf): # Regression test for #1307 company_strategy = from_model(Company, name=just("test")) strategy = from_model(CompanyExtension, company=company_strategy, self_modifying=just(2)) try: ConjectureData.for_buffer(buf).draw(strategy) except HypothesisException: reject() # Draw again with the same buffer. This will cause a duplicate # primary key. ConjectureData.for_buffer(buf).draw(strategy) assert CompanyExtension.objects.all().count() == 1
def test_foreign_key_primary(self, buf): # Regression test for #1307 company_strategy = from_model(Company, name=just("test")) strategy = from_model( CompanyExtension, company=company_strategy, self_modifying=just(2) ) try: ConjectureData.for_buffer(buf).draw(strategy) except HypothesisException: reject() # Draw again with the same buffer. This will cause a duplicate # primary key. ConjectureData.for_buffer(buf).draw(strategy) assert CompanyExtension.objects.all().count() == 1
class TestView(TestCase): @given( from_model(Trip, user=from_model(User), category=from_model(Category, user=from_model(User)))) def test_trips_cant_have_negative_duration(self, example_trip: Trip): self.assertGreaterEqual(example_trip.duration.total_seconds(), 0) @given( from_model(Trip, user=from_model(User), category=from_model(Category, user=from_model(User)))) def test_duration_without_ended_at(self, example_trip: Trip): example_trip.ended_at = None example_trip.duration def test_vues_index(self): c = Client() ma_page = reverse('front-index') r = c.get(ma_page) self.assertEquals(r.status_code, 200) def test_vues_login(self): c = Client() ma_page = reverse('login') r = c.get(ma_page) self.assertEquals(r.status_code, 200)
class PermissionsTestCase(TestCase): @given(person_with_role(), compte()) def test_pas_de_permissions_par_defaut(self, person, compte): for perm, _ in Compte._meta.permissions: self.assertFalse( person.role.has_perm(f"gestion.{perm}", obj=compte)) @given( person_with_role(), compte(), from_model(Group), st.lists(st.sampled_from([p for p, _ in Compte._meta.permissions]), unique=True), ) def test_peut_avoir_permission(self, person, compte, group, perms): group.user_set.add(person.role) Autorisation.objects.create(compte=compte, group=group, autorisations=perms) for perm in perms: self.assertTrue( person.role.has_perm(f"gestion.{perm}", obj=compte), f"{person} n'a pas {perm} sur {compte}", ) for perm in set( p for p, _ in Compte._meta.permissions).difference(perms): self.assertFalse( person.role.has_perm(f"gestion.{perm}", obj=compte))
def test_echo_json_status_result(self, rf): # pylint: disable=invalid-name """ Testing echo api response status result is function correctly with json data """ #data = {'null':json.dumps(json_data)} #dt = from_model(DeviceType).example() #set manual foreign key dt.id #dr = from_model(DeviceRecords, devices_type=just(dt.id)).example() #strategy = register_field_strategy(DeviceType, DeviceType(id=1, name="voltage", unit="V")) #dr = from_model(DeviceRecords, devices_type=from_model(DeviceType)).example() device_type = from_model(DeviceType, id=just(1)) device_records = from_model(DeviceRecords, devices_type=device_type).example() request = rf.get('data/'+str(datetime.timestamp(device_records.record_time))+'/', None, content_type='application/json') response = echo_filter(request, int(datetime.timestamp(device_records.record_time))) assert response.status_code == 200 response.render()
class TestEvent(django.TestCase): """This is a property-based test that ensures model correctness.""" @given(django.from_model(Event, data=strategies.just({'foo': 'bar'}))) def test_model_properties(self, instance): """Tests that instance can be saved and has correct representation.""" instance.save() assert instance.id assert str(instance)
class TestPosOnlyArg(TestCase): @given(from_model(Car)) def test_user_issue_2369_regression(self, val): pass def test_from_model_argspec(self): self.assertRaises(TypeError, from_model().example) self.assertRaises(TypeError, from_model(Car, None).example) self.assertRaises(TypeError, from_model(model=Customer).example)
class TestBlogPost(django.TestCase): """This is a property-based test that ensures model correctness.""" @given(django.from_model(BlogPost)) def test_model_properties(self, instance): """Tests that instance can be saved and has correct representation.""" instance.save() assert instance.id > 0 assert len(str(instance)) <= 20
class TestModelAdmin(django.TestCase): @hypothesis.given(django.from_model(models.Model),) def test_admin(self, model): site = AdminSite() model_admin = admin.ModelAdmin(models.Model, site) self.assertEqual( model_admin.something(model), model.something(), "Should do something.", )
class StarWarsCollectionPost(django.TestCase): """This is a property-based test that ensures model correctness.""" @given(django.from_model(StarWarsCollection)) def test_model_properties(self, instance): """Tests that instance can be saved and has correct representation.""" instance.save() assert instance.id > 0 assert len(str(instance)) <= 20 assert instance.filename == f'{instance.id}.csv'
class TestUser(django.TestCase): """This is a property-based test that ensures model correctness.""" @given(django.from_model(User)) def test_model_properties(self, instance): """Tests that instance can be saved and has correct representation.""" instance.username = TEST_USERNAME instance.password = TEST_USER_PASSWORD instance.save() assert instance.id > 0 assert len(str(instance)) <= 20
class TestTeacher(django.TestCase): """This is a property-based test that ensures model correctness.""" @given(django.from_model(Teacher)) def test_model_properties(self, instance): """Tests that instance can be saved and has correct representation.""" instance.first_name = TEST_TITLE instance.last_name = TEST_TITLE instance.middle_name = TEST_TITLE instance.save() assert instance.id > 0 assert len(str(instance)) <= 20
class TestVideo(django.TestCase): """This is a property-based test that ensures model correctness.""" @settings(deadline=1000) @given(django.from_model(Video, width=just(None), height=just(None), duration=just(None), preview=just(''))) def test_model_properties(self, instance: Video) -> None: """Tests that instance can be saved and has correct representation.""" instance.save() assert instance.id > 0 assert instance.__str__() == str(instance) assert instance.process_video_async() is None
def submit_details_request(db): submission = from_model(Submission, urls=just(['http://twitter.com/'])).example() yield { "identify": "female", "age": 40, "job": 'public speaker', "perpetrator": PerpetratorType.single_stranger.value, 'interaction': InteractionType.post_rarely_for_friends.value, 'reaction_type': ReactionType.i_took_a_break_from_platform.value, 'experienced': ['sad'], 'feeling': 'hurt', 'submission': submission.id }
class FrontTests(TestCase): @given( from_model(Trip, user=from_model(User), category=from_model(Category, user=from_model(User)))) def test_can_create_a_trip_without_end(self, example_trip: Trip): example_trip.ended_at = None example_trip.save() @given( from_model(Trip, user=from_model(User), category=from_model(Category, user=from_model(User)))) def test_trips_can_be_saved(self, example_trip: Trip): example_trip.save()
class TestRestrictedFields(TestCase): @given(from_model(RestrictedFields)) def test_constructs_valid_instance(self, instance): self.assertTrue(isinstance(instance, RestrictedFields)) instance.full_clean() self.assertLessEqual(len(instance.text_field_4), 4) self.assertLessEqual(len(instance.char_field_4), 4) self.assertIn(instance.choice_field_text, ("foo", "bar")) self.assertIn(instance.choice_field_int, (1, 2)) self.assertIn(instance.null_choice_field_int, (1, 2, None)) self.assertEqual(instance.choice_field_grouped, instance.choice_field_grouped.lower()) self.assertEqual(instance.even_number_field % 2, 0) self.assertTrue(instance.non_blank_text_field)
class TestAdminView(django.TestCase): def test_anonymous(self): req = test.RequestFactory().get("/") req.user = auth_models.AnonymousUser() resp = views.AdminView.as_view()(req) self.assertIn("login", resp.url, "Should be redirected.") @hypothesis.given(django.from_model(auth_models.User)) def test_superuser(self, user): user.is_superuser = True req = test.RequestFactory().get("/") req.user = user resp = views.AdminView.as_view()(req) self.assertEqual(resp.status_code, 200, "Authenticated user can access")
class RuleTestCase(TestCase): @given(person_with_role(), from_model(Compte), printable_text()) def test_aucune_autorisation_par_defaut(self, person, compte, perm): perm_checker = permission_sur_compte(perm) self.assertFalse(perm_checker(person.role)) self.assertFalse(perm_checker(person.role, obj=compte)) @given(person_with_role(), from_model(Group), from_model(Compte), printable_text()) def test_possible_ajouter_permission(self, person, group, compte, perm): group.user_set.add(person.role) Autorisation.objects.create(compte=compte, group=group, autorisations=[perm]) perm_checker = permission_sur_compte(perm) self.assertFalse(perm_checker(person.role)) self.assertTrue(perm_checker(person.role, obj=compte)) @given( person_with_role(), from_model(Group), from_model(Compte), st.lists(printable_text()), printable_text(), ) def test_autorisation_limitee_aux_roles_listes(self, person, group, compte, perms, other_perm): assume(other_perm not in perms) group.user_set.add(person.role) Autorisation.objects.create(compte=compte, group=group, autorisations=perms) perm_checker = permission_sur_compte(other_perm) self.assertFalse(perm_checker(person.role, obj=compte))
class TestTasks(django.TestCase): """This async tasks logic.""" @settings(deadline=1000) @given( django.from_model(Video, width=just(None), height=just(None), duration=just(None), preview=just(''))) def test_video_converted(self, video_instance: Video) -> None: """Tests that video was converted in all formats.""" convert_all_videos('video_archive', 'Video', video_instance.pk) assert video_instance.format_set.complete().all().count() == 2 @given( django.from_model(Video, width=just(None), height=just(None), duration=just(None), preview=just(''))) def test_preview_creation(self, video_instance: Video) -> None: """Tests that preview is created.""" create_preview(video_instance.pk) assert video_instance.preview is not ''
def new_user(self, password: AnyStr = None, username: AnyStr = None) -> (ReaderUser, AnyStr): reader_user_params = { 'is_active': just(True), 'username': just(username) if username else self.username_strategy } user = from_model(ReaderUser, **reader_user_params).example() user_passwd = password or ''.join( random.choices(string.ascii_uppercase + string.digits + string.ascii_lowercase, k=8)) user.set_password(user_passwd) user.save() return user, user_passwd
class UsersManagersTests(TestCase): @given(from_model(get_user_model())) def test_create_user(self, user): # User = get_user_model() # user = User.objects.create_user(email='*****@*****.**', display_name='user', password='******') # self.assertEqual(user.email, '*****@*****.**') self.assertTrue(user.is_active) self.assertFalse(user.is_staff) self.assertFalse(user.is_superuser) try: # username is None for the AbstractUser option # username does not exist for the AbstractBaseUser option self.assertIsNone(user.username) except AttributeError: pass with self.assertRaises(TypeError): get_user_model().objects.create_user() with self.assertRaises(TypeError): get_user_model().objects.create_user(email='') with self.assertRaises(ValueError): get_user_model().objects.create_user(email='', password="******")
def generate_measurements(self, day): """Generate measurements using Hypothesis""" return lists(from_model(Measurement, # deferred so that select happens only after # they are guaranteed to exist (created in # setUp) metric=deferred( lambda: just(Metric.objects.first())), channel=deferred( lambda: just(Channel.objects.first())), user=deferred( lambda: just(get_user_model().objects\ .first()) ), value=integers( min_value=-(10**16) + 1, max_value=(10**16) - 1), # constrain end times to be in range starttime=datetimes( min_value=day + relativedelta(seconds=1), max_value=day + relativedelta(hours=23), timezones=just(pytz.UTC))))
class TestValidatorInference(TestCase): @given(from_model(User)) def test_user_issue_1112_regression(self, user): assert user.username
def test_mandatory_computed_fields_may_not_be_provided(self): mc = from_model(MandatoryComputed, company=from_model(Company)) self.assertRaises(RuntimeError, mc.example)
def test_can_get_examples(self): for _ in range(200): from_model(Company).example()
def test_can_get_examples(self): for _ in range(200): from_model(Company).example()
def test_mandatory_computed_fields_may_not_be_provided(self): mc = from_model(MandatoryComputed, company=from_model(Company)) self.assertRaises(RuntimeError, mc.example)
def test_mandatory_computed_fields_are_mandatory(self): with self.assertRaises(InvalidArgument): from_model(MandatoryComputed).example()
def test_mandatory_fields_are_mandatory(self): self.assertRaises(InvalidArgument, from_model(Store).example)
class TestGetsBasicModels(TestCase): @given(from_model(Company)) def test_is_company(self, company): self.assertIsInstance(company, Company) self.assertIsNotNone(company.pk) @given(from_model(Store, company=from_model(Company))) def test_can_get_a_store(self, store): assert store.company.pk @given(lists(from_model(Company))) def test_can_get_multiple_models_with_unique_field(self, companies): assume(len(companies) > 1) for c in companies: self.assertIsNotNone(c.pk) self.assertEqual(len({c.pk for c in companies}), len({c.name for c in companies})) @settings(suppress_health_check=[HealthCheck.too_slow]) @given(from_model(Customer)) def test_is_customer(self, customer): self.assertIsInstance(customer, Customer) self.assertIsNotNone(customer.pk) self.assertIsNotNone(customer.email) @settings(suppress_health_check=[HealthCheck.too_slow]) @given(from_model(Customer)) def test_tz_presence(self, customer): if django_settings.USE_TZ: self.assertIsNotNone(customer.birthday.tzinfo) else: self.assertIsNone(customer.birthday.tzinfo) @given(from_model(CouldBeCharming)) def test_is_not_charming(self, not_charming): self.assertIsInstance(not_charming, CouldBeCharming) self.assertIsNotNone(not_charming.pk) self.assertIsNone(not_charming.charm) @given(from_model(SelfLoop)) def test_sl(self, sl): self.assertIsNone(sl.me) @given(lists(from_model(ManyNumerics))) def test_no_overflow_in_integer(self, manyints): pass @given(from_model(Customish)) def test_custom_field(self, x): assert x.customish == "a" def test_mandatory_fields_are_mandatory(self): self.assertRaises(InvalidArgument, from_model(Store).example) def test_mandatory_computed_fields_are_mandatory(self): with self.assertRaises(InvalidArgument): from_model(MandatoryComputed).example() def test_mandatory_computed_fields_may_not_be_provided(self): mc = from_model(MandatoryComputed, company=from_model(Company)) self.assertRaises(RuntimeError, mc.example) @given(from_model(CustomishDefault, customish=infer)) def test_customish_default_overridden_by_infer(self, x): assert x.customish == "a" @given(from_model(CustomishDefault, customish=infer)) def test_customish_infer_uses_registered_instead_of_default(self, x): assert x.customish == "a" @given(from_model(OddFields)) def test_odd_fields(self, x): assert isinstance(x.uuid, UUID) assert isinstance(x.slug, str) assert " " not in x.slug assert isinstance(x.ipv4, str) assert len(x.ipv4.split(".")) == 4 assert all(int(i) in range(256) for i in x.ipv4.split(".")) assert isinstance(x.ipv6, str) assert set(x.ipv6).issubset(set("0123456789abcdefABCDEF:.")) @given(from_model(ManyTimes)) def test_time_fields(self, x): assert isinstance(x.time, dt.time) assert isinstance(x.date, dt.date) assert isinstance(x.duration, dt.timedelta) @given(from_model(Company)) def test_no_null_in_charfield(self, x): # regression test for #1045. Company just has a convenient CharField. assert "\x00" not in x.name @given(binary(min_size=10)) def test_foreign_key_primary(self, buf): # Regression test for #1307 company_strategy = from_model(Company, name=just("test")) strategy = from_model(CompanyExtension, company=company_strategy, self_modifying=just(2)) try: ConjectureData.for_buffer(buf).draw(strategy) except HypothesisException: reject() # Draw again with the same buffer. This will cause a duplicate # primary key. ConjectureData.for_buffer(buf).draw(strategy) assert CompanyExtension.objects.all().count() == 1