How to use assertQuerysetEqual method in pytest-django

Best Python code snippet using pytest-django_python

test_filtering.py

Source:test_filtering.py Github

copy

Full Screen

...51 model = Book52 fields = ['title']53 qs = Book.objects.all()54 f = F(queryset=qs)55 self.assertQuerysetEqual(f.qs, [b1.pk, b2.pk, b3.pk],56 lambda o: o.pk, ordered=False)57 f = F({'title': 'Snowcrash'}, queryset=qs)58 self.assertQuerysetEqual(f.qs, [b3.pk], lambda o: o.pk)59class IntegerFilterTest(TestCase):60 def test_filtering(self):61 default_values = {62 'in_good_standing': True,63 'friendly': False,64 }65 b1 = BankAccount.objects.create(amount_saved=0, **default_values)66 b2 = BankAccount.objects.create(amount_saved=3, **default_values)67 b3 = BankAccount.objects.create(amount_saved=10, **default_values)68 class F(FilterSet):69 class Meta:70 model = BankAccount71 fields = ['amount_saved']72 qs = BankAccount.objects.all()73 f = F(queryset=qs)74 self.assertQuerysetEqual(f.qs, [b1.pk, b2.pk, b3.pk],75 lambda o: o.pk, ordered=False)76 f = F({'amount_saved': '10'}, queryset=qs)77 self.assertQuerysetEqual(f.qs, [b3.pk], lambda o: o.pk)78 f = F({'amount_saved': '0'}, queryset=qs)79 self.assertQuerysetEqual(f.qs, [b1.pk], lambda o: o.pk)80class BooleanFilterTests(TestCase):81 def test_filtering(self):82 User.objects.create(username='alex', is_active=False)83 User.objects.create(username='jacob', is_active=True)84 User.objects.create(username='aaron', is_active=False)85 class F(FilterSet):86 class Meta:87 model = User88 fields = ['is_active']89 qs = User.objects.all()90 # '2' and '3' are how the field expects the data from the browser91 f = F({'is_active': '2'}, queryset=qs)92 self.assertQuerysetEqual(f.qs, ['jacob'], lambda o: o.username, False)93 f = F({'is_active': '3'}, queryset=qs)94 self.assertQuerysetEqual(f.qs,95 ['alex', 'aaron'],96 lambda o: o.username, False)97 f = F({'is_active': '1'}, queryset=qs)98 self.assertQuerysetEqual(f.qs,99 ['alex', 'aaron', 'jacob'],100 lambda o: o.username, False)101class ChoiceFilterTests(TestCase):102 def test_filtering(self):103 User.objects.create(username='alex', status=1)104 User.objects.create(username='jacob', status=2)105 User.objects.create(username='aaron', status=2)106 User.objects.create(username='carl', status=0)107 class F(FilterSet):108 class Meta:109 model = User110 fields = ['status']111 f = F()112 self.assertQuerysetEqual(f.qs,113 ['aaron', 'alex', 'jacob', 'carl'],114 lambda o: o.username, False)115 f = F({'status': '1'})116 self.assertQuerysetEqual(f.qs, ['alex'], lambda o: o.username, False)117 f = F({'status': '2'})118 self.assertQuerysetEqual(f.qs, ['jacob', 'aaron'],119 lambda o: o.username, False)120 f = F({'status': '0'})121 self.assertQuerysetEqual(f.qs, ['carl'], lambda o: o.username, False)122 def test_filtering_on_explicitly_defined_field(self):123 """124 Test for #30.125 If you explicitly declare ChoiceFilter fields you **MUST** pass `choices`.126 """127 User.objects.create(username='alex', status=1)128 User.objects.create(username='jacob', status=2)129 User.objects.create(username='aaron', status=2)130 User.objects.create(username='carl', status=0)131 class F(FilterSet):132 status = ChoiceFilter(choices=STATUS_CHOICES)133 class Meta:134 model = User135 fields = ['status']136 f = F()137 self.assertQuerysetEqual(f.qs,138 ['aaron', 'alex', 'jacob', 'carl'],139 lambda o: o.username, False)140 f = F({'status': '1'})141 self.assertQuerysetEqual(f.qs, ['alex'], lambda o: o.username, False)142 f = F({'status': '2'})143 self.assertQuerysetEqual(f.qs, ['jacob', 'aaron'],144 lambda o: o.username, False)145 f = F({'status': '0'})146 self.assertQuerysetEqual(f.qs, ['carl'], lambda o: o.username, False)147class MultipleChoiceFilterTests(TestCase):148 def test_filtering(self):149 User.objects.create(username='alex', status=1)150 User.objects.create(username='jacob', status=2)151 User.objects.create(username='aaron', status=2)152 User.objects.create(username='carl', status=0)153 class F(FilterSet):154 status = MultipleChoiceFilter(choices=STATUS_CHOICES)155 class Meta:156 model = User157 fields = ['status']158 qs = User.objects.all().order_by('username')159 f = F(queryset=qs)160 self.assertQuerysetEqual(161 f.qs, ['aaron', 'jacob', 'alex', 'carl'],162 lambda o: o.username, False)163 f = F({'status': ['0']}, queryset=qs)164 self.assertQuerysetEqual(165 f.qs, ['carl'], lambda o: o.username)166 f = F({'status': ['0', '1']}, queryset=qs)167 self.assertQuerysetEqual(168 f.qs, ['alex', 'carl'], lambda o: o.username)169 f = F({'status': ['0', '1', '2']}, queryset=qs)170 self.assertQuerysetEqual(171 f.qs, ['aaron', 'alex', 'carl', 'jacob'], lambda o: o.username)172class DateFilterTests(TestCase):173 def test_filtering(self):174 today = now().date()175 timestamp = now().time().replace(microsecond=0)176 last_week = today - datetime.timedelta(days=7)177 check_date = six.text_type(last_week)178 u = User.objects.create(username='alex')179 Comment.objects.create(author=u, time=timestamp, date=today)180 Comment.objects.create(author=u, time=timestamp, date=last_week)181 Comment.objects.create(author=u, time=timestamp, date=today)182 Comment.objects.create(author=u, time=timestamp, date=last_week)183 class F(FilterSet):184 class Meta:185 model = Comment186 fields = ['date']187 f = F({'date': check_date}, queryset=Comment.objects.all())188 self.assertEqual(len(f.qs), 2)189 self.assertQuerysetEqual(f.qs, [2, 4], lambda o: o.pk, False)190class TimeFilterTests(TestCase):191 def test_filtering(self):192 today = now().date()193 now_time = now().time().replace(microsecond=0)194 ten_min_ago = (now() - datetime.timedelta(minutes=10))195 fixed_time = ten_min_ago.time().replace(microsecond=0)196 check_time = six.text_type(fixed_time)197 u = User.objects.create(username='alex')198 Comment.objects.create(author=u, time=now_time, date=today)199 Comment.objects.create(author=u, time=fixed_time, date=today)200 Comment.objects.create(author=u, time=now_time, date=today)201 Comment.objects.create(author=u, time=fixed_time, date=today)202 class F(FilterSet):203 class Meta:204 model = Comment205 fields = ['time']206 f = F({'time': check_time}, queryset=Comment.objects.all())207 self.assertEqual(len(f.qs), 2)208 self.assertQuerysetEqual(f.qs, [2, 4], lambda o: o.pk, False)209class DateTimeFilterTests(TestCase):210 def test_filtering(self):211 now_dt = now()212 ten_min_ago = now_dt - datetime.timedelta(minutes=10)213 one_day_ago = now_dt - datetime.timedelta(days=1)214 u = User.objects.create(username='alex')215 Article.objects.create(author=u, published=now_dt)216 Article.objects.create(author=u, published=ten_min_ago)217 Article.objects.create(author=u, published=one_day_ago)218 tz = timezone.get_current_timezone()219 # make naive, like a browser would send220 local_ten_min_ago = timezone.make_naive(ten_min_ago, tz)221 check_dt = six.text_type(local_ten_min_ago)222 class F(FilterSet):223 class Meta:224 model = Article225 fields = ['published']226 qs = Article.objects.all()227 f = F({'published': ten_min_ago}, queryset=qs)228 self.assertEqual(len(f.qs), 1)229 self.assertQuerysetEqual(f.qs, [2], lambda o: o.pk)230 # this is how it would come through a browser231 f = F({'published': check_dt}, queryset=qs)232 self.assertEqual(233 len(f.qs),234 1,235 "%s isn't matching %s when cleaned" % (check_dt, ten_min_ago))236 self.assertQuerysetEqual(f.qs, [2], lambda o: o.pk)237class ModelChoiceFilterTests(TestCase):238 def test_filtering(self):239 alex = User.objects.create(username='alex')240 jacob = User.objects.create(username='jacob')241 date = now().date()242 time = now().time()243 Comment.objects.create(author=jacob, time=time, date=date)244 Comment.objects.create(author=alex, time=time, date=date)245 Comment.objects.create(author=jacob, time=time, date=date)246 class F(FilterSet):247 class Meta:248 model = Comment249 fields = ['author']250 qs = Comment.objects.all()251 f = F({'author': jacob.pk}, queryset=qs)252 self.assertQuerysetEqual(f.qs, [1, 3], lambda o: o.pk, False)253class ModelMultipleChoiceFilterTests(TestCase):254 def setUp(self):255 alex = User.objects.create(username='alex')256 User.objects.create(username='jacob')257 aaron = User.objects.create(username='aaron')258 b1 = Book.objects.create(title="Ender's Game", price='1.00',259 average_rating=3.0)260 b2 = Book.objects.create(title="Rainbow Six", price='1.00',261 average_rating=3.0)262 b3 = Book.objects.create(title="Snowcrash", price='1.00',263 average_rating=3.0)264 Book.objects.create(title="Stranger in a Strage Land", price='1.00',265 average_rating=3.0)266 alex.favorite_books = [b1, b2]267 aaron.favorite_books = [b1, b3]268 self.alex = alex269 def test_filtering(self):270 class F(FilterSet):271 class Meta:272 model = User273 fields = ['favorite_books']274 qs = User.objects.all().order_by('username')275 f = F({'favorite_books': ['1']}, queryset=qs)276 self.assertQuerysetEqual(f.qs, ['aaron', 'alex'], lambda o: o.username)277 f = F({'favorite_books': ['1', '3']}, queryset=qs)278 self.assertQuerysetEqual(f.qs, ['aaron', 'alex'], lambda o: o.username)279 f = F({'favorite_books': ['2']}, queryset=qs)280 self.assertQuerysetEqual(f.qs, ['alex'], lambda o: o.username)281 f = F({'favorite_books': ['4']}, queryset=qs)282 self.assertQuerysetEqual(f.qs, [], lambda o: o.username)283 def test_filtering_dictionary(self):284 class F(FilterSet):285 class Meta:286 model = User287 fields = {'favorite_books': ['exact']}288 qs = User.objects.all().order_by('username')289 f = F({'favorite_books': ['1']}, queryset=qs)290 self.assertQuerysetEqual(f.qs, ['aaron', 'alex'], lambda o: o.username)291 f = F({'favorite_books': ['1', '3']}, queryset=qs)292 self.assertQuerysetEqual(f.qs, ['aaron', 'alex'], lambda o: o.username)293 f = F({'favorite_books': ['2']}, queryset=qs)294 self.assertQuerysetEqual(f.qs, ['alex'], lambda o: o.username)295 f = F({'favorite_books': ['4']}, queryset=qs)296 self.assertQuerysetEqual(f.qs, [], lambda o: o.username)297 def test_filtering_on_all_of_subset_of_choices(self):298 class F(FilterSet):299 class Meta:300 model = User301 fields = ['favorite_books']302 def __init__(self, *args, **kwargs):303 super(F, self).__init__(*args, **kwargs)304 # This filter has a limited number of choices.305 self.filters['favorite_books'].extra.update({306 'queryset': Book.objects.filter(id__in=[1, 2])307 })308 self.filters['favorite_books'].required = True309 qs = User.objects.all().order_by('username')310 # Select all the given choices.311 f = F({'favorite_books': ['1', '2']}, queryset=qs)312 # The results should only include matching users - not Jacob.313 self.assertQuerysetEqual(f.qs, ['aaron', 'alex'], lambda o: o.username)314 def test_filtering_on_non_required_fields(self):315 # See issue #132 - filtering with all options on a non-required316 # field should exclude any results where the field is null.317 class F(FilterSet):318 author = ModelMultipleChoiceFilter(queryset=User.objects.all())319 class Meta:320 model = Article321 fields = ['author']322 published = now()323 Article.objects.create(published=published, author=self.alex)324 Article.objects.create(published=published, author=self.alex)325 Article.objects.create(published=published)326 qs = Article.objects.all()327 # Select all authors.328 authors = [329 str(user.id)330 for user in User.objects.all()331 ]332 f = F({'author': authors}, queryset=qs)333 # The results should not include anonymous articles334 self.assertEqual(335 set(f.qs),336 set(Article.objects.exclude(author__isnull=True)),337 )338class NumberFilterTests(TestCase):339 def setUp(self):340 Book.objects.create(title="Ender's Game", price='10.0',341 average_rating=4.7999999999999998)342 Book.objects.create(title="Rainbow Six", price='15.0',343 average_rating=4.5999999999999996)344 Book.objects.create(title="Snowcrash", price='20.0',345 average_rating=4.2999999999999998)346 def test_filtering(self):347 class F(FilterSet):348 class Meta:349 model = Book350 fields = ['price']351 f = F({'price': 10}, queryset=Book.objects.all())352 self.assertQuerysetEqual(f.qs, ['Ender\'s Game'], lambda o: o.title)353 def test_filtering_with_single_lookup_type(self):354 class F(FilterSet):355 price = NumberFilter(lookup_type='lt')356 class Meta:357 model = Book358 fields = ['price']359 f = F({'price': 16}, queryset=Book.objects.all().order_by('title'))360 self.assertQuerysetEqual(361 f.qs, ['Ender\'s Game', 'Rainbow Six'], lambda o: o.title)362 def test_filtering_with_single_lookup_type_dictionary(self):363 class F(FilterSet):364 class Meta:365 model = Book366 fields = {'price': ['lt']}367 f = F({'price__lt': 16}, queryset=Book.objects.all().order_by('title'))368 self.assertQuerysetEqual(369 f.qs, ['Ender\'s Game', 'Rainbow Six'], lambda o: o.title)370 def test_filtering_with_multiple_lookup_types(self):371 class F(FilterSet):372 price = NumberFilter(lookup_type=['lt', 'gt'])373 class Meta:374 model = Book375 fields = ['price']376 qs = Book.objects.all()377 f = F({'price_0': '15', 'price_1': 'lt'}, queryset=qs)378 self.assertQuerysetEqual(f.qs, ['Ender\'s Game'], lambda o: o.title)379 f = F({'price_0': '15', 'price_1': 'lt'})380 self.assertQuerysetEqual(f.qs, ['Ender\'s Game'], lambda o: o.title)381 f = F({'price_0': '', 'price_1': 'lt'})382 self.assertQuerysetEqual(f.qs,383 ['Ender\'s Game', 'Rainbow Six', 'Snowcrash'],384 lambda o: o.title, ordered=False)385 class F(FilterSet):386 price = NumberFilter(lookup_type=['lt', 'gt', 'exact'])387 class Meta:388 model = Book389 fields = ['price']390 f = F({'price_0': '15'})391 self.assertQuerysetEqual(f.qs, ['Rainbow Six'], lambda o: o.title)392class RangeFilterTests(TestCase):393 def setUp(self):394 Book.objects.create(title="Ender's Game", price='10.0',395 average_rating=4.7999999999999998)396 Book.objects.create(title="Rainbow Six", price='15.0',397 average_rating=4.5999999999999996)398 Book.objects.create(title="Snowcrash", price='20.0',399 average_rating=4.2999999999999998)400 def test_filtering(self):401 class F(FilterSet):402 price = RangeFilter()403 class Meta:404 model = Book405 fields = ['price']406 qs = Book.objects.all().order_by('title')407 f = F(queryset=qs)408 self.assertQuerysetEqual(f.qs,409 ['Ender\'s Game', 'Rainbow Six', 'Snowcrash'],410 lambda o: o.title)411 f = F({'price_0': '5', 'price_1': '15'}, queryset=qs)412 self.assertQuerysetEqual(f.qs,413 ['Ender\'s Game', 'Rainbow Six'],414 lambda o: o.title)415 f = F({'price_0': '11'}, queryset=qs)416 self.assertQuerysetEqual(f.qs,417 ['Rainbow Six', 'Snowcrash'],418 lambda o: o.title)419 f = F({'price_1': '19'}, queryset=qs)420 self.assertQuerysetEqual(f.qs,421 ['Ender\'s Game', 'Rainbow Six'],422 lambda o: o.title)423@unittest.skip('date-range is funky')424class DateRangeFilterTests(TestCase):425 def setUp(self):426 today = now().date()427 five_days_ago = today - datetime.timedelta(days=5)428 two_weeks_ago = today - datetime.timedelta(days=14)429 two_months_ago = today - datetime.timedelta(days=62)430 two_years_ago = today - datetime.timedelta(days=800)431 alex = User.objects.create(username='alex')432 time = now().time()433 Comment.objects.create(date=two_weeks_ago, author=alex, time=time)434 Comment.objects.create(date=two_years_ago, author=alex, time=time)435 Comment.objects.create(date=five_days_ago, author=alex, time=time)436 Comment.objects.create(date=today, author=alex, time=time)437 Comment.objects.create(date=two_months_ago, author=alex, time=time)438 def test_filtering_for_year(self):439 class F(FilterSet):440 date = DateRangeFilter()441 class Meta:442 model = Comment443 fields = ['date']444 f = F({'date': '4'}) # this year445 self.assertQuerysetEqual(f.qs, [1, 3, 4, 5], lambda o: o.pk, False)446 def test_filtering_for_month(self):447 class F(FilterSet):448 date = DateRangeFilter()449 class Meta:450 model = Comment451 fields = ['date']452 f = F({'date': '3'}) # this month453 self.assertQuerysetEqual(f.qs, [1, 3, 4], lambda o: o.pk, False)454 @unittest.expectedFailure455 def test_filtering_for_week(self):456 class F(FilterSet):457 date = DateRangeFilter()458 class Meta:459 model = Comment460 fields = ['date']461 f = F({'date': '2'}) # this week462 self.assertQuerysetEqual(f.qs, [3, 4], lambda o: o.pk, False)463 def test_filtering_for_today(self):464 class F(FilterSet):465 date = DateRangeFilter()466 class Meta:467 model = Comment468 fields = ['date']469 f = F({'date': '1'}) # today470 self.assertQuerysetEqual(f.qs, [4], lambda o: o.pk, False)471 # it will be difficult to test for TZ related issues, where "today" means472 # different things to both user and server.473class AllValuesFilterTests(TestCase):474 def test_filtering(self):475 User.objects.create(username='alex')476 User.objects.create(username='jacob')477 User.objects.create(username='aaron')478 class F(FilterSet):479 username = AllValuesFilter()480 class Meta:481 model = User482 fields = ['username']483 self.assertEqual(list(F().qs), list(User.objects.all()))484 self.assertEqual(list(F({'username': 'alex'})),485 [User.objects.get(username='alex')])486 self.assertEqual(list(F({'username': 'jose'})),487 list())488 def test_filtering_without_strict(self):489 User.objects.create(username='alex')490 User.objects.create(username='jacob')491 User.objects.create(username='aaron')492 class F(FilterSet):493 username = AllValuesFilter()494 strict = False495 class Meta:496 model = User497 fields = ['username']498 self.assertEqual(list(F().qs), list(User.objects.all()))499 self.assertEqual(list(F({'username': 'alex'})),500 [User.objects.get(username='alex')])501 self.assertEqual(list(F({'username': 'jose'})),502 list(User.objects.all()))503class MethodFilterTests(TestCase):504 def test_filtering(self):505 User.objects.create(username='alex')506 User.objects.create(username='jacob')507 User.objects.create(username='aaron')508 class F(FilterSet):509 username = MethodFilter(action='filter_username')510 class Meta:511 model = User512 fields = ['username']513 def filter_username(self, queryset, value):514 return queryset.filter(515 username=value516 )517 self.assertEqual(list(F().qs), list(User.objects.all()))518 self.assertEqual(list(F({'username': 'alex'})),519 [User.objects.get(username='alex')])520 self.assertEqual(list(F({'username': 'jose'})),521 list())522 def test_filtering_external(self):523 User.objects.create(username='alex')524 User.objects.create(username='jacob')525 User.objects.create(username='aaron')526 def filter_username(queryset, value):527 return queryset.filter(528 username=value529 )530 class F(FilterSet):531 username = MethodFilter(action=filter_username)532 class Meta:533 model = User534 fields = ['username']535 self.assertEqual(list(F().qs), list(User.objects.all()))536 self.assertEqual(list(F({'username': 'alex'})),537 [User.objects.get(username='alex')])538 self.assertEqual(list(F({'username': 'jose'})),539 list())540class O2ORelationshipTests(TestCase):541 def setUp(self):542 a1 = Account.objects.create(543 name='account1', in_good_standing=False, friendly=False)544 a2 = Account.objects.create(545 name='account2', in_good_standing=True, friendly=True)546 a3 = Account.objects.create(547 name='account3', in_good_standing=True, friendly=False)548 a4 = Account.objects.create(549 name='account4', in_good_standing=False, friendly=True)550 Profile.objects.create(account=a1, likes_coffee=True, likes_tea=False)551 Profile.objects.create(account=a2, likes_coffee=False, likes_tea=True)552 Profile.objects.create(account=a3, likes_coffee=True, likes_tea=True)553 Profile.objects.create(account=a4, likes_coffee=False, likes_tea=False)554 def test_o2o_relation(self):555 class F(FilterSet):556 class Meta:557 model = Profile558 fields = ('account',)559 f = F()560 self.assertEqual(f.qs.count(), 4)561 f = F({'account': 1})562 self.assertEqual(f.qs.count(), 1)563 self.assertQuerysetEqual(f.qs, [1], lambda o: o.pk)564 def test_o2o_relation_dictionary(self):565 class F(FilterSet):566 class Meta:567 model = Profile568 fields = {'account': ['exact'], }569 f = F()570 self.assertEqual(f.qs.count(), 4)571 f = F({'account': 1})572 self.assertEqual(f.qs.count(), 1)573 self.assertQuerysetEqual(f.qs, [1], lambda o: o.pk)574 def test_reverse_o2o_relation(self):575 class F(FilterSet):576 class Meta:577 model = Account578 fields = ('profile',)579 f = F()580 self.assertEqual(f.qs.count(), 4)581 f = F({'profile': 1})582 self.assertEqual(f.qs.count(), 1)583 self.assertQuerysetEqual(f.qs, [1], lambda o: o.pk)584 def test_o2o_relation_attribute(self):585 class F(FilterSet):586 class Meta:587 model = Profile588 fields = ('account__in_good_standing',)589 f = F()590 self.assertEqual(f.qs.count(), 4)591 f = F({'account__in_good_standing': '2'})592 self.assertEqual(f.qs.count(), 2)593 self.assertQuerysetEqual(f.qs, [2, 3], lambda o: o.pk, False)594 def test_o2o_relation_attribute2(self):595 class F(FilterSet):596 class Meta:597 model = Profile598 fields = ('account__in_good_standing', 'account__friendly',)599 f = F()600 self.assertEqual(f.qs.count(), 4)601 f = F({'account__in_good_standing': '2', 'account__friendly': '2'})602 self.assertEqual(f.qs.count(), 1)603 self.assertQuerysetEqual(f.qs, [2], lambda o: o.pk)604 def test_reverse_o2o_relation_attribute(self):605 class F(FilterSet):606 class Meta:607 model = Account608 fields = ('profile__likes_coffee',)609 f = F()610 self.assertEqual(f.qs.count(), 4)611 f = F({'profile__likes_coffee': '2'})612 self.assertEqual(f.qs.count(), 2)613 self.assertQuerysetEqual(f.qs, [1, 3], lambda o: o.pk, False)614 def test_reverse_o2o_relation_attribute2(self):615 class F(FilterSet):616 class Meta:617 model = Account618 fields = ('profile__likes_coffee', 'profile__likes_tea')619 f = F()620 self.assertEqual(f.qs.count(), 4)621 f = F({'profile__likes_coffee': '2', 'profile__likes_tea': '2'})622 self.assertEqual(f.qs.count(), 1)623 self.assertQuerysetEqual(f.qs, [3], lambda o: o.pk)624class FKRelationshipTests(TestCase):625 def test_fk_relation(self):626 company1 = Company.objects.create(name='company1')627 company2 = Company.objects.create(name='company2')628 Location.objects.create(629 company=company1, open_days="some", zip_code="90210")630 Location.objects.create(631 company=company2, open_days="WEEKEND", zip_code="11111")632 Location.objects.create(633 company=company1, open_days="monday", zip_code="12345")634 class F(FilterSet):635 class Meta:636 model = Location637 fields = ('company',)638 f = F()639 self.assertEqual(f.qs.count(), 3)640 f = F({'company': 1})641 self.assertEqual(f.qs.count(), 2)642 self.assertQuerysetEqual(f.qs, [1, 3], lambda o: o.pk, False)643 def test_reverse_fk_relation(self):644 alex = User.objects.create(username='alex')645 jacob = User.objects.create(username='jacob')646 date = now().date()647 time = now().time()648 Comment.objects.create(text='comment 1',649 author=jacob, time=time, date=date)650 Comment.objects.create(text='comment 2',651 author=alex, time=time, date=date)652 Comment.objects.create(text='comment 3',653 author=jacob, time=time, date=date)654 class F(FilterSet):655 class Meta:656 model = User657 fields = ['comments']658 qs = User.objects.all()659 f = F({'comments': [2]}, queryset=qs)660 self.assertQuerysetEqual(f.qs, ['alex'], lambda o: o.username)661 class F(FilterSet):662 comments = AllValuesFilter()663 class Meta:664 model = User665 fields = ['comments']666 f = F({'comments': 2}, queryset=qs)667 self.assertQuerysetEqual(f.qs, ['alex'], lambda o: o.username)668 def test_fk_relation_attribute(self):669 now_dt = now()670 alex = User.objects.create(username='alex')671 jacob = User.objects.create(username='jacob')672 User.objects.create(username='aaron')673 Article.objects.create(author=alex, published=now_dt)674 Article.objects.create(author=jacob, published=now_dt)675 Article.objects.create(author=alex, published=now_dt)676 class F(FilterSet):677 class Meta:678 model = Article679 fields = ['author__username']680 self.assertEqual(list(F.base_filters), ['author__username'])681 self.assertEqual(F({'author__username': 'alex'}).qs.count(), 2)682 self.assertEqual(F({'author__username': 'jacob'}).qs.count(), 1)683 class F(FilterSet):684 author__username = AllValuesFilter()685 class Meta:686 model = Article687 fields = ['author__username']688 self.assertEqual(F({'author__username': 'alex'}).qs.count(), 2)689 def test_reverse_fk_relation_attribute(self):690 alex = User.objects.create(username='alex')691 jacob = User.objects.create(username='jacob')692 date = now().date()693 time = now().time()694 Comment.objects.create(text='comment 1',695 author=jacob, time=time, date=date)696 Comment.objects.create(text='comment 2',697 author=alex, time=time, date=date)698 Comment.objects.create(text='comment 3',699 author=jacob, time=time, date=date)700 class F(FilterSet):701 class Meta:702 model = User703 fields = ['comments__text']704 qs = User.objects.all()705 f = F({'comments__text': 'comment 2'}, queryset=qs)706 self.assertQuerysetEqual(f.qs, ['alex'], lambda o: o.username)707 class F(FilterSet):708 comments__text = AllValuesFilter()709 class Meta:710 model = User711 fields = ['comments__text']712 f = F({'comments__text': 'comment 2'}, queryset=qs)713 self.assertQuerysetEqual(f.qs, ['alex'], lambda o: o.username)714 @unittest.skip('todo - need correct models')715 def test_fk_relation_multiple_attributes(self):716 pass717 @unittest.expectedFailure718 def test_reverse_fk_relation_multiple_attributes(self):719 company = Company.objects.create(name='company')720 Location.objects.create(721 company=company, open_days="some", zip_code="90210")722 Location.objects.create(723 company=company, open_days="WEEKEND", zip_code="11111")724 class F(FilterSet):725 class Meta:726 model = Company727 fields = ('locations__zip_code', 'locations__open_days')728 f = F({'locations__zip_code': '90210',729 'locations__open_days': 'WEEKEND'})730 self.assertEqual(f.qs.count(), 0)731class M2MRelationshipTests(TestCase):732 def setUp(self):733 alex = User.objects.create(username='alex', status=1)734 User.objects.create(username='jacob', status=1)735 aaron = User.objects.create(username='aaron', status=1)736 b1 = Book.objects.create(title="Ender's Game", price='1.00',737 average_rating=3.0)738 b2 = Book.objects.create(title="Rainbow Six", price='2.00',739 average_rating=4.0)740 b3 = Book.objects.create(title="Snowcrash", price='1.00',741 average_rating=4.0)742 Book.objects.create(title="Stranger in a Strage Land", price='2.00',743 average_rating=3.0)744 alex.favorite_books = [b1, b2]745 aaron.favorite_books = [b1, b3]746 def test_m2m_relation(self):747 class F(FilterSet):748 class Meta:749 model = User750 fields = ['favorite_books']751 qs = User.objects.all().order_by('username')752 f = F({'favorite_books': ['1']}, queryset=qs)753 self.assertQuerysetEqual(f.qs, ['aaron', 'alex'], lambda o: o.username)754 f = F({'favorite_books': ['1', '3']}, queryset=qs)755 self.assertQuerysetEqual(f.qs, ['aaron', 'alex'], lambda o: o.username)756 f = F({'favorite_books': ['2']}, queryset=qs)757 self.assertQuerysetEqual(f.qs, ['alex'], lambda o: o.username)758 f = F({'favorite_books': ['4']}, queryset=qs)759 self.assertQuerysetEqual(f.qs, [], lambda o: o.username)760 def test_reverse_m2m_relation(self):761 class F(FilterSet):762 class Meta:763 model = Book764 fields = ['lovers']765 qs = Book.objects.all().order_by('title')766 f = F({'lovers': [1]}, queryset=qs)767 self.assertQuerysetEqual(768 f.qs, ["Ender's Game", "Rainbow Six"], lambda o: o.title)769 class F(FilterSet):770 lovers = AllValuesFilter()771 class Meta:772 model = Book773 fields = ['lovers']774 f = F({'lovers': 1}, queryset=qs)775 self.assertQuerysetEqual(776 f.qs, ["Ender's Game", "Rainbow Six"], lambda o: o.title)777 def test_m2m_relation_attribute(self):778 class F(FilterSet):779 class Meta:780 model = User781 fields = ['favorite_books__title']782 qs = User.objects.all().order_by('username')783 f = F({'favorite_books__title': "Ender's Game"}, queryset=qs)784 self.assertQuerysetEqual(f.qs, ['aaron', 'alex'], lambda o: o.username)785 f = F({'favorite_books__title': 'Rainbow Six'}, queryset=qs)786 self.assertQuerysetEqual(f.qs, ['alex'], lambda o: o.username)787 class F(FilterSet):788 favorite_books__title = MultipleChoiceFilter()789 class Meta:790 model = User791 fields = ['favorite_books__title']792 f = F()793 self.assertEqual(794 len(f.filters['favorite_books__title'].field.choices), 0)795 # f = F({'favorite_books__title': ['1', '3']},796 # queryset=qs)797 # self.assertQuerysetEqual(798 # f.qs, ['aaron', 'alex'], lambda o: o.username)799 class F(FilterSet):800 favorite_books__title = AllValuesFilter()801 class Meta:802 model = User803 fields = ['favorite_books__title']804 f = F({'favorite_books__title': "Snowcrash"}, queryset=qs)805 self.assertQuerysetEqual(f.qs, ['aaron'], lambda o: o.username)806 def test_reverse_m2m_relation_attribute(self):807 class F(FilterSet):808 class Meta:809 model = Book810 fields = ['lovers__username']811 qs = Book.objects.all().order_by('title')812 f = F({'lovers__username': "alex"}, queryset=qs)813 self.assertQuerysetEqual(814 f.qs, ["Ender's Game", "Rainbow Six"], lambda o: o.title)815 f = F({'lovers__username': 'jacob'}, queryset=qs)816 self.assertQuerysetEqual(f.qs, [], lambda o: o.title)817 class F(FilterSet):818 lovers__username = MultipleChoiceFilter()819 class Meta:820 model = Book821 fields = ['lovers__username']822 f = F()823 self.assertEqual(824 len(f.filters['lovers__username'].field.choices), 0)825 # f = F({'lovers__username': ['1', '3']},826 # queryset=qs)827 # self.assertQuerysetEqual(828 # f.qs, ["Ender's Game", "Rainbow Six"], lambda o: o.title)829 class F(FilterSet):830 lovers__username = AllValuesFilter()831 class Meta:832 model = Book833 fields = ['lovers__username']834 f = F({'lovers__username': "alex"}, queryset=qs)835 self.assertQuerysetEqual(836 f.qs, ["Ender's Game", "Rainbow Six"], lambda o: o.title)837 @unittest.expectedFailure838 def test_m2m_relation_multiple_attributes(self):839 class F(FilterSet):840 class Meta:841 model = User842 fields = ['favorite_books__price',843 'favorite_books__average_rating']844 qs = User.objects.all().order_by('username')845 f = F({'favorite_books__price': "1.00",846 'favorite_books__average_rating': 4.0},847 queryset=qs)848 self.assertQuerysetEqual(f.qs, ['aaron'], lambda o: o.username)849 f = F({'favorite_books__price': "3.00",850 'favorite_books__average_rating': 4.0},851 queryset=qs)852 self.assertQuerysetEqual(f.qs, [], lambda o: o.username)853 @unittest.expectedFailure854 def test_reverse_m2m_relation_multiple_attributes(self):855 class F(FilterSet):856 class Meta:857 model = Book858 fields = ['lovers__status', 'lovers__username']859 qs = Book.objects.all().order_by('title')860 f = F({'lovers__status': 1, 'lovers__username': "alex"}, queryset=qs)861 self.assertQuerysetEqual(862 f.qs, ["Ender's Game", "Rainbow Six"], lambda o: o.title)863 f = F({'lovers__status': 1, 'lovers__username': 'jacob'}, queryset=qs)864 self.assertQuerysetEqual(f.qs, [], lambda o: o.title)865 @unittest.skip('todo')866 def test_fk_relation_on_m2m_relation(self):867 pass868 @unittest.skip('todo')869 def test_fk_relation_attribute_on_m2m_relation(self):870 pass871class SymmetricalSelfReferentialRelationshipTests(TestCase):872 def setUp(self):873 n1 = Node.objects.create(name='one')874 n2 = Node.objects.create(name='two')875 n3 = Node.objects.create(name='three')876 n4 = Node.objects.create(name='four')877 n1.adjacents.add(n2)878 n2.adjacents.add(n3)879 n2.adjacents.add(n4)880 n4.adjacents.add(n1)881 def test_relation(self):882 class F(FilterSet):883 class Meta:884 model = Node885 fields = ['adjacents']886 qs = Node.objects.all().order_by('pk')887 f = F({'adjacents': ['1']}, queryset=qs)888 self.assertQuerysetEqual(f.qs, [2, 4], lambda o: o.pk)889class NonSymmetricalSelfReferentialRelationshipTests(TestCase):890 def setUp(self):891 n1 = DirectedNode.objects.create(name='one')892 n2 = DirectedNode.objects.create(name='two')893 n3 = DirectedNode.objects.create(name='three')894 n4 = DirectedNode.objects.create(name='four')895 n1.outbound_nodes.add(n2)896 n2.outbound_nodes.add(n3)897 n2.outbound_nodes.add(n4)898 n4.outbound_nodes.add(n1)899 def test_forward_relation(self):900 class F(FilterSet):901 class Meta:902 model = DirectedNode903 fields = ['outbound_nodes']904 qs = DirectedNode.objects.all().order_by('pk')905 f = F({'outbound_nodes': ['1']}, queryset=qs)906 self.assertQuerysetEqual(f.qs, [4], lambda o: o.pk)907 def test_reverse_relation(self):908 class F(FilterSet):909 class Meta:910 model = DirectedNode911 fields = ['inbound_nodes']912 qs = DirectedNode.objects.all().order_by('pk')913 f = F({'inbound_nodes': ['1']}, queryset=qs)914 self.assertQuerysetEqual(f.qs, [2], lambda o: o.pk)915class MiscFilterSetTests(TestCase):916 def setUp(self):917 User.objects.create(username='alex', status=1)918 User.objects.create(username='jacob', status=2)919 User.objects.create(username='aaron', status=2)920 User.objects.create(username='carl', status=0)921 def test_filtering_with_declared_filters(self):922 class F(FilterSet):923 account = CharFilter(name='username')924 class Meta:925 model = User926 fields = ['account']927 qs = mock.MagicMock()928 f = F({'account': 'jdoe'}, queryset=qs)929 result = f.qs930 self.assertNotEqual(qs, result)931 qs.all.return_value.filter.assert_called_with(username__exact='jdoe')932 def test_filtering_with_multiple_filters(self):933 class F(FilterSet):934 class Meta:935 model = User936 fields = ['status', 'username']937 qs = User.objects.all()938 f = F({'username': 'alex', 'status': '1'}, queryset=qs)939 self.assertQuerysetEqual(f.qs, ['alex'], lambda o: o.username)940 f = F({'username': 'alex', 'status': '2'}, queryset=qs)941 self.assertQuerysetEqual(f.qs, [], lambda o: o.pk)942 def test_filter_with_action(self):943 class F(FilterSet):944 username = CharFilter(action=lambda qs, value: (945 qs.filter(**{'username__startswith': value})))946 class Meta:947 model = User948 fields = ['username']949 f = F({'username': 'a'}, queryset=User.objects.all())950 self.assertQuerysetEqual(951 f.qs, ['alex', 'aaron'], lambda o: o.username, False)952 def test_filter_with_initial(self):953 class F(FilterSet):954 status = ChoiceFilter(choices=STATUS_CHOICES, initial=1)955 class Meta:956 model = User957 fields = ['status']958 qs = User.objects.all()959 f = F(queryset=qs)960 self.assertQuerysetEqual(f.qs, ['alex'], lambda o: o.username)961 f = F({'status': 0}, queryset=qs)962 self.assertQuerysetEqual(f.qs, ['carl'], lambda o: o.username)963 def test_qs_count(self):964 class F(FilterSet):965 class Meta:966 model = User967 fields = ['status']968 qs = User.objects.all()969 f = F(queryset=qs)970 self.assertEqual(len(f.qs), 4)971 self.assertEqual(f.count(), 4)972 f = F({'status': '0'}, queryset=qs)973 self.assertEqual(len(f.qs), 1)974 self.assertEqual(f.count(), 1)975 f = F({'status': '1'}, queryset=qs)976 self.assertEqual(len(f.qs), 1)...

Full Screen

Full Screen

tests.py

Source:tests.py Github

copy

Full Screen

...37 def _sort_by_pk(self, list_or_qs):38 annotated = [(item.pk, item) for item in list_or_qs]39 annotated.sort()40 return map(lambda item_tuple: item_tuple[1], annotated)41 def assertQuerysetEqual(self, a, b):42 return self.assertEqual(self._sort_by_pk(a), self._sort_by_pk(b))43class RelationshipsTestCase(BaseRelationshipsTestCase):44 def setUp(self):45 BaseRelationshipsTestCase.setUp(self)46 self.second_site = Site.objects.create(name='ex2.com', domain='ex2.com')47 def test_manager(self):48 rel = self.walrus.relationships.all()49 self.assertQuerysetEqual(rel, [])50 rel = self.john.relationships.all()51 self.assertQuerysetEqual(rel, [self.paul, self.yoko])52 rel = self.paul.relationships.all()53 self.assertQuerysetEqual(rel, [self.john])54 rel = self.yoko.relationships.all()55 self.assertQuerysetEqual(rel, [self.john])56 def test_related_name(self):57 rel = self.walrus.related_to.all()58 self.assertQuerysetEqual(rel, [])59 rel = self.john.related_to.all()60 self.assertQuerysetEqual(rel, [self.paul, self.yoko])61 rel = self.paul.related_to.all()62 self.assertQuerysetEqual(rel, [self.john])63 rel = self.yoko.related_to.all()64 self.assertQuerysetEqual(rel, [self.john])65 def test_inherited_manager_methods(self):66 # does filter work?67 rel = self.john.relationships.filter(username='Paul')68 self.assertQuerysetEqual(rel, [self.paul])69 # does filter work?70 rel = self.walrus.relationships.filter(username='Paul')71 self.assertQuerysetEqual(rel, [])72 # does exclude work?73 rel = self.john.relationships.exclude(username='Paul')74 self.assertQuerysetEqual(rel, [self.yoko])75 # does clear work?76 self.john.relationships.clear()77 rel = self.john.relationships.all()78 self.assertQuerysetEqual(rel, [])79 # make sure yoko's relationship to john is still there80 rel = self.yoko.relationships.all()81 self.assertQuerysetEqual(rel, [self.john])82 def test_add_method(self):83 self.john.relationships.add(self.walrus)84 rel = self.john.relationships.all()85 self.assertQuerysetEqual(rel, [self.walrus, self.paul, self.yoko])86 # check that it wasn't added symmetrically87 rel = self.john.related_to.all()88 self.assertQuerysetEqual(rel, [self.paul, self.yoko])89 # check that it doesn't show up in walrus' relationships90 rel = self.walrus.relationships.all()91 self.assertQuerysetEqual(rel, [])92 # but it *does* show up in walrus' reverse relationships93 rel = self.walrus.related_to.all()94 self.assertQuerysetEqual(rel, [self.john])95 # test that dupes aren't added96 self.john.relationships.add(self.walrus)97 rel = self.john.relationships.all()98 self.assertQuerysetEqual(rel, [self.walrus, self.paul, self.yoko])99 def test_add_symmetrical(self):100 _, _ = self.john.relationships.add(self.walrus, symmetrical=True)101 # should show up in john's relationships102 rel = self.john.relationships.all()103 self.assertQuerysetEqual(rel, [self.walrus, self.paul, self.yoko])104 # should also show up that walrus has a relationship to john105 rel = self.john.related_to.all()106 self.assertQuerysetEqual(rel, [self.walrus, self.paul, self.yoko])107 # and same for walrus...108 rel = self.walrus.relationships.all()109 self.assertQuerysetEqual(rel, [self.john])110 rel = self.walrus.related_to.all()111 self.assertQuerysetEqual(rel, [self.john])112 def test_remove_method(self):113 self.john.relationships.remove(self.yoko)114 # no longer shows up in the relationships115 rel = self.john.relationships.all()116 self.assertQuerysetEqual(rel, [self.paul])117 # the reverse relationship is still intact118 rel = self.john.related_to.all()119 self.assertQuerysetEqual(rel, [self.paul, self.yoko])120 rel = self.yoko.relationships.all()121 self.assertQuerysetEqual(rel, [self.john])122 rel = self.yoko.related_to.all()123 self.assertQuerysetEqual(rel, [])124 # no error125 self.john.relationships.remove(self.yoko)126 def test_remove_symmetrical(self):127 self.john.relationships.remove(self.yoko, symmetrical=True)128 rel = self.john.relationships.all()129 self.assertQuerysetEqual(rel, [self.paul])130 rel = self.john.related_to.all()131 self.assertQuerysetEqual(rel, [self.paul])132 rel = self.yoko.relationships.all()133 self.assertQuerysetEqual(rel, [])134 rel = self.yoko.related_to.all()135 self.assertQuerysetEqual(rel, [])136 def test_custom_methods(self):137 rel = self.john.relationships.following()138 self.assertQuerysetEqual(rel, [self.paul, self.yoko])139 rel = self.john.relationships.followers()140 self.assertQuerysetEqual(rel, [self.yoko])141 rel = self.john.relationships.blocking()142 self.assertQuerysetEqual(rel, [])143 rel = self.john.relationships.blockers()144 self.assertQuerysetEqual(rel, [self.paul])145 rel = self.john.relationships.friends()146 self.assertQuerysetEqual(rel, [self.yoko])147 ###148 rel = self.paul.relationships.following()149 self.assertQuerysetEqual(rel, [])150 rel = self.paul.relationships.followers()151 self.assertQuerysetEqual(rel, [self.john])152 rel = self.paul.relationships.blocking()153 self.assertQuerysetEqual(rel, [self.john])154 rel = self.paul.relationships.blockers()155 self.assertQuerysetEqual(rel, [])156 rel = self.paul.relationships.friends()157 self.assertQuerysetEqual(rel, [])158 def test_exists(self):159 self.assertTrue(self.john.relationships.exists(self.yoko))160 self.assertTrue(self.john.relationships.exists(self.paul))161 self.assertFalse(self.john.relationships.exists(self.walrus))162 self.assertTrue(self.paul.relationships.exists(self.john))163 self.assertFalse(self.paul.relationships.exists(self.yoko))164 self.assertFalse(self.paul.relationships.exists(self.walrus))165 def test_exists_with_status(self):166 self.assertTrue(self.john.relationships.exists(self.yoko, self.following))167 self.assertTrue(self.john.relationships.exists(self.paul, self.following))168 self.assertFalse(self.john.relationships.exists(self.walrus, self.following))169 self.assertFalse(self.john.relationships.exists(self.yoko, self.blocking))170 self.assertFalse(self.john.relationships.exists(self.paul, self.blocking))171 self.assertFalse(self.john.relationships.exists(self.walrus, self.blocking))172 self.assertFalse(self.paul.relationships.exists(self.john, self.following))173 self.assertFalse(self.paul.relationships.exists(self.yoko, self.following))174 self.assertFalse(self.paul.relationships.exists(self.walrus, self.following))175 self.assertTrue(self.paul.relationships.exists(self.john, self.blocking))176 self.assertFalse(self.paul.relationships.exists(self.yoko, self.blocking))177 self.assertFalse(self.paul.relationships.exists(self.walrus, self.blocking))178 def test_oneway_methods(self):179 self.assertQuerysetEqual(self.john.relationships.only_from(self.following), [self.paul])180 self.assertQuerysetEqual(self.john.relationships.only_to(self.following), [])181 self.assertQuerysetEqual(self.john.relationships.only_from(self.blocking), [])182 self.assertQuerysetEqual(self.john.relationships.only_to(self.blocking), [self.paul])183 def test_site_behavior(self):184 # relationships are site-dependent185 # walrus is now following John on the current site186 self.walrus.relationships.add(self.john)187 # walrus is now following Paul on another site188 status = RelationshipStatus.objects.following()189 r, _ = Relationship.objects.get_or_create(190 from_user=self.walrus,191 to_user=self.paul,192 site=self.second_site,193 status=status,194 )195 # the 'following' method is siteified196 self.assertQuerysetEqual(self.walrus.relationships.following(), [self.john])197 # ... the .all() method is not198 self.assertQuerysetEqual(self.walrus.relationships.all(), [self.john, self.paul])199 # remove only works on the current site, so paul will *NOT* be removed200 self.walrus.relationships.remove(self.paul)201 self.assertQuerysetEqual(self.walrus.relationships.all(), [self.john, self.paul])202class RelationshipsListenersTestCase(BaseRelationshipsTestCase):203 def setUp(self):204 BaseRelationshipsTestCase.setUp(self)205 attach_relationship_listener()206 def tearDown(self):207 detach_relationship_listener()208 BaseRelationshipsTestCase.tearDown(self)209 def test_following_and_blocking(self):210 # check initial state, john is following paul & yoko211 self.assertQuerysetEqual(self.john.relationships.following(), [self.paul, self.yoko])212 # when john blocks paul, his 'following' relationship will be deleted213 self.john.relationships.add(self.paul, self.blocking)214 self.assertQuerysetEqual(self.john.relationships.blocking(), [self.paul])215 self.assertQuerysetEqual(self.john.relationships.following(), [self.yoko])216 # check initial state for paul217 self.assertQuerysetEqual(self.paul.relationships.blocking(), [self.john])218 # when paul follows john his 'blocking' relationship will be deleted219 self.paul.relationships.add(self.john, self.following)220 self.assertQuerysetEqual(self.paul.relationships.following(), [self.john])221 self.assertQuerysetEqual(self.paul.relationships.blocking(), [])222 def test_listener_disconnecting(self):223 # this test simply ensures the default behavior224 detach_relationship_listener()225 # have john start blocking paul226 self.john.relationships.add(self.paul, self.blocking)227 # the blocking relationship is created and the original following228 # relationship is left intact229 self.assertQuerysetEqual(self.john.relationships.blocking(), [self.paul])230 self.assertQuerysetEqual(self.john.relationships.following(), [self.paul, self.yoko])231 # have paul start following john232 self.paul.relationships.add(self.john, self.following)233 # the following relationship is created and the original blocking234 # relationship is left intact235 self.assertQuerysetEqual(self.paul.relationships.following(), [self.john])236 self.assertQuerysetEqual(self.paul.relationships.blocking(), [self.john])237class RelationshipsViewsTestCase(BaseRelationshipsTestCase):238 def test_list_views(self):239 url = reverse('relationship_list', args=['John'])240 resp = self.client.get(url)241 self.assertEquals(resp.status_code, 200)242 self.assertQuerysetEqual(resp.context['relationship_list'], self.john.relationships.following())243 url = reverse('relationship_list', args=['John', 'followers'])244 resp = self.client.get(url)245 self.assertEquals(resp.status_code, 200)246 self.assertQuerysetEqual(resp.context['relationship_list'], self.john.relationships.followers())247 url = reverse('relationship_list', args=['John', 'following'])248 resp = self.client.get(url)249 self.assertEquals(resp.status_code, 200)250 self.assertQuerysetEqual(resp.context['relationship_list'], self.john.relationships.following())251 url = reverse('relationship_list', args=['John', 'friends'])252 resp = self.client.get(url)253 self.assertEquals(resp.status_code, 200)254 self.assertQuerysetEqual(resp.context['relationship_list'], self.john.relationships.friends())255 url = reverse('relationship_list', args=['John', 'blocking'])256 resp = self.client.get(url)257 self.assertEqual(resp.status_code, 302)258 self.client.login(username='John', password='John')259 url = reverse('relationship_list', args=['John', 'blocking'])260 resp = self.client.get(url)261 self.assertQuerysetEqual(resp.context['relationship_list'], self.john.relationships.blocking())262 # this is private, only Paul can see who he's blocking263 url = reverse('relationship_list', args=['Paul', 'blocking'])264 resp = self.client.get(url)265 self.assertEqual(resp.status_code, 404)266 # non existant relationship status slug267 url = reverse('relationship_list', args=['John', 'walrus-friends'])268 resp = self.client.get(url)269 self.assertEqual(resp.status_code, 404)270 def test_add_remove_login_required(self):271 # login required272 url = reverse('relationship_add', args=['The_Walrus', 'following'])273 resp = self.client.get(url)274 self.assertEqual(resp.status_code, 302)275 url = reverse('relationship_remove', args=['The_Walrus', 'following'])276 resp = self.client.get(url)277 self.assertEqual(resp.status_code, 302)278 def test_add_remove_requires_post(self):279 self.client.login(username='John', password='John')280 url = reverse('relationship_add', args=['The_Walrus', 'following'])281 resp = self.client.get(url)282 self.assertEqual(resp.status_code, 200)283 # a relationship has not been created yet284 self.assertFalse(self.john.relationships.exists(self.walrus, self.following))285 url = reverse('relationship_remove', args=['Yoko', 'following'])286 resp = self.client.get(url)287 self.assertEqual(resp.status_code, 200)288 # the relationship has not been removed289 self.assertTrue(self.john.relationships.exists(self.yoko, self.following))290 def test_adding(self):291 self.client.login(username='John', password='John')292 url = reverse('relationship_add', args=['The_Walrus', 'following'])293 resp = self.client.post(url)294 self.assertEqual(resp.status_code, 200)295 # the relationship has been created296 self.assertTrue(self.john.relationships.exists(self.walrus, self.following))297 # the relationship is not symmetrical, though298 self.assertFalse(self.walrus.relationships.exists(self.john, self.following))299 # a nonexistant user causes a 404300 url = reverse('relationship_add', args=['Nobody', 'following'])301 resp = self.client.post(url)302 self.assertEqual(resp.status_code, 404)303 def test_adding_symm(self):304 self.client.login(username='John', password='John')305 url = reverse('relationship_add', args=['The_Walrus', 'friends'])306 resp = self.client.post(url)307 self.assertEqual(resp.status_code, 200)308 # the relationship has been created309 self.assertTrue(self.john.relationships.exists(self.walrus, self.following))310 # the relationship is symmetrical311 self.assertTrue(self.walrus.relationships.exists(self.john, self.following))312 def test_removing(self):313 self.client.login(username='John', password='John')314 url = reverse('relationship_remove', args=['Yoko', 'following'])315 resp = self.client.post(url)316 self.assertEqual(resp.status_code, 200)317 self.assertFalse(self.john.relationships.exists(self.yoko, self.following))318 # the symmetrical relationship was not removed319 self.assertTrue(self.yoko.relationships.exists(self.john, self.following))320 # non existant user causes a 404321 url = reverse('relationship_remove', args=['Nobody', 'following'])322 resp = self.client.post(url)323 self.assertEqual(resp.status_code, 404)324 def test_removing_symm(self):325 self.client.login(username='John', password='John')326 url = reverse('relationship_remove', args=['Yoko', 'friends'])327 resp = self.client.post(url)328 self.assertEqual(resp.status_code, 200)329 self.assertFalse(self.john.relationships.exists(self.yoko, self.following))330 # the symmetrical relationship was not removed331 self.assertFalse(self.yoko.relationships.exists(self.john, self.following))332class RelationshipsTagsTestCase(BaseRelationshipsTestCase):333 def test_add_url_filter(self):334 t = Template('{% load relationship_tags %}{{ user|add_relationship_url:"following" }}')335 c = Context({'user': self.paul})336 rendered = t.render(c)337 url = reverse('relationship_add', args=['Paul', 'following'])338 self.assertEqual(rendered, url)339 # check that a symmetrical slug can be used340 t = Template('{% load relationship_tags %}{{ user|add_relationship_url:"friends" }}')341 c = Context({'user': self.paul})342 rendered = t.render(c)343 url = reverse('relationship_add', args=['Paul', 'friends'])344 self.assertEqual(rendered, url)345 t = Template('{% load relationship_tags %}{{ user|add_relationship_url:blocking }}')346 c = Context({'user': self.paul, 'blocking': self.blocking})347 rendered = t.render(c)348 url = reverse('relationship_add', args=['Paul', 'blocking'])349 self.assertEqual(rendered, url)350 def test_remove_url_filter(self):351 t = Template('{% load relationship_tags %}{{ user|remove_relationship_url:"following" }}')352 c = Context({'user': self.paul})353 rendered = t.render(c)354 url = reverse('relationship_remove', args=['Paul', 'following'])355 self.assertEqual(rendered, url)356 # check that a symmetrical slug can be used357 t = Template('{% load relationship_tags %}{{ user|remove_relationship_url:"friends" }}')358 c = Context({'user': self.paul})359 rendered = t.render(c)360 url = reverse('relationship_remove', args=['Paul', 'friends'])361 self.assertEqual(rendered, url)362 t = Template('{% load relationship_tags %}{{ user|remove_relationship_url:blocking }}')363 c = Context({'user': self.paul, 'blocking': self.blocking})364 rendered = t.render(c)365 url = reverse('relationship_remove', args=['Paul', 'blocking'])366 self.assertEqual(rendered, url)367 def test_if_relationship_tag(self):368 t = Template('{% load relationship_tags %}{% if_relationship john paul "following" %}y{% else %}n{% endif_relationship %}')369 c = Context({'john': self.john, 'paul': self.paul})370 rendered = t.render(c)371 self.assertEqual(rendered, 'y')372 t = Template('{% load relationship_tags %}{% if_relationship paul john "following" %}y{% else %}n{% endif_relationship %}')373 c = Context({'john': self.john, 'paul': self.paul})374 rendered = t.render(c)375 self.assertEqual(rendered, 'n')376 t = Template('{% load relationship_tags %}{% if_relationship paul john "followers" %}y{% else %}n{% endif_relationship %}')377 c = Context({'john': self.john, 'paul': self.paul})378 rendered = t.render(c)379 self.assertEqual(rendered, 'y')380 t = Template('{% load relationship_tags %}{% if_relationship paul john "friends" %}y{% else %}n{% endif_relationship %}')381 c = Context({'john': self.john, 'paul': self.paul})382 rendered = t.render(c)383 self.assertEqual(rendered, 'n')384 t = Template('{% load relationship_tags %}{% if_relationship john yoko "friends" %}y{% else %}n{% endif_relationship %}')385 c = Context({'john': self.john, 'yoko': self.yoko})386 rendered = t.render(c)387 self.assertEqual(rendered, 'y')388 def test_status_filters(self):389 # create some groups to filter390 from django.contrib.auth.models import Group391 beatles = Group.objects.create(name='beatles')392 john_yoko = Group.objects.create(name='john_yoko')393 characters = Group.objects.create(name='characters')394 self.walrus.groups.add(characters)395 self.john.groups.add(beatles)396 self.john.groups.add(john_yoko)397 self.paul.groups.add(beatles)398 self.yoko.groups.add(john_yoko)399 self.yoko.groups.add(characters)400 group_qs = Group.objects.all().order_by('name')401 # john is friends w/ yoko so show yoko's groups402 t = Template('{% load relationship_tags %}{% for group in qs|friend_content:user %}{{ group.name }}|{% endfor %}')403 c = Context({'user': self.john, 'qs': group_qs})404 rendered = t.render(c)405 self.assertEqual(rendered, 'characters|john_yoko|')406 # paul is friends w/ nobody, so no groups407 c = Context({'user': self.paul, 'qs': group_qs})408 rendered = t.render(c)409 self.assertEqual(rendered, '')410 # john is following paul & yoko411 t = Template('{% load relationship_tags %}{% for group in qs|following_content:user %}{{ group.name }}|{% endfor %}')412 c = Context({'user': self.john, 'qs': group_qs})413 rendered = t.render(c)414 self.assertEqual(rendered, 'beatles|characters|john_yoko|')415 # yoko is followed by john416 t = Template('{% load relationship_tags %}{% for group in qs|followers_content:user %}{{ group.name }}|{% endfor %}')417 c = Context({'user': self.yoko, 'qs': group_qs})418 rendered = t.render(c)419 self.assertEqual(rendered, 'beatles|john_yoko|')420 # paul is blocking john, so every group but ones with him421 t = Template('{% load relationship_tags %}{% for group in qs|unblocked_content:user %}{{ group.name }}|{% endfor %}')422 c = Context({'user': self.paul, 'qs': group_qs})423 rendered = t.render(c)424 self.assertEqual(rendered, 'characters|')425 # oh no, john is blocking yoko426 self.john.relationships.add(self.yoko, RelationshipStatus.objects.blocking())427 c = Context({'user': self.john, 'qs': group_qs})428 rendered = t.render(c)429 self.assertEqual(rendered, 'beatles|')430 # make sure it works with a model string431 t = Template('{% load relationship_tags %}{% for group in "auth.group"|unblocked_content:user %}{{ group.name }}|{% endfor %}')432 c = Context({'user': self.john})433 rendered = t.render(c)434 self.assertEqual(rendered, 'beatles|')435class RelationshipStatusAdminFormTestCase(BaseRelationshipsTestCase):436 def test_no_dupes(self):437 payload = {438 'name': 'Testing',439 'verb': 'testing',440 'from_slug': 'testing',441 'to_slug': 'testers',442 'symmetrical_slug': 'tests'443 }444 form = RelationshipStatusAdminForm(payload)445 self.assertTrue(form.is_valid())446 test_status = form.save()447 # saving again should work448 form = RelationshipStatusAdminForm(payload, instance=test_status)449 self.assertTrue(form.is_valid())450 payload['from_slug'] = 'testers'451 payload['to_slug'] = 'testing'452 # saving will work since it will not test against the current instance453 form = RelationshipStatusAdminForm(payload, instance=test_status)454 self.assertTrue(form.is_valid())455 # setting the from_slug to the to_slug will raise an error456 payload['from_slug'] = 'testers'457 payload['to_slug'] = 'testers'458 form = RelationshipStatusAdminForm(payload, instance=test_status)459 self.assertFalse(form.is_valid())460 # setting the from_slug to the symmetrical_slug will raise an error461 payload['from_slug'] = 'tests'462 form = RelationshipStatusAdminForm(payload, instance=test_status)463 self.assertFalse(form.is_valid())464 # setting to a pre-existing from_slug will fail465 payload['from_slug'] = 'following'466 form = RelationshipStatusAdminForm(payload)467 self.assertFalse(form.is_valid())468 self.assertTrue('from_slug' in form.errors)469 # setting the from_slug to a pre-existing to_slug will also fail470 payload['from_slug'] = 'followers'471 form = RelationshipStatusAdminForm(payload)472 self.assertFalse(form.is_valid())473 self.assertTrue('from_slug' in form.errors)474 # setting the from_slug to a pre-existing symetrical_slug will also fail475 payload['from_slug'] = 'friends'476 form = RelationshipStatusAdminForm(payload)477 self.assertFalse(form.is_valid())478 self.assertTrue('from_slug' in form.errors)479class RelationshipUtilsTestCase(BaseRelationshipsTestCase):480 def test_extract_user_field(self):481 # just test a known pass and known fail482 from django.contrib.comments.models import Comment483 from django.contrib.sites.models import Site484 self.assertEqual(extract_user_field(Comment), 'user')485 self.assertEqual(extract_user_field(Site), None)486 def test_positive_filter(self):487 following = RelationshipStatus.objects.following()488 # create some groups to filter489 from django.contrib.auth.models import Group490 beatles = Group.objects.create(name='beatles')491 john_yoko = Group.objects.create(name='john_yoko')492 characters = Group.objects.create(name='characters')493 self.walrus.groups.add(characters)494 self.john.groups.add(beatles)495 self.john.groups.add(john_yoko)496 self.paul.groups.add(beatles)497 self.yoko.groups.add(john_yoko)498 self.yoko.groups.add(characters)499 group_qs = Group.objects.all().order_by('name')500 # groups people paul follows are in (nobody)501 paul_following_groups = positive_filter(502 group_qs,503 self.paul.relationships.following(),504 'user')505 self.assertQuerysetEqual(paul_following_groups, [])506 # when paul follows john he will see john's groups507 self.paul.relationships.add(self.john, following)508 paul_following_groups = positive_filter(509 group_qs,510 self.paul.relationships.following(),511 'user')512 self.assertQuerysetEqual(paul_following_groups, [beatles, john_yoko])513 # now john's + walrus's514 self.paul.relationships.add(self.walrus, following)515 paul_following_groups = positive_filter(516 group_qs,517 self.paul.relationships.following(),518 'user')519 self.assertQuerysetEqual(paul_following_groups, [beatles, characters, john_yoko])520 # everybody's - distinct groups, no dupes521 self.paul.relationships.add(self.yoko, following)522 paul_following_groups = positive_filter(523 group_qs,524 self.paul.relationships.following(),525 'user')526 self.assertQuerysetEqual(paul_following_groups, [beatles, characters, john_yoko])527 # just groups walrus & yoko are in528 self.paul.relationships.remove(self.john, following)529 paul_following_groups = positive_filter(530 group_qs,531 self.paul.relationships.following(),532 'user')533 self.assertQuerysetEqual(paul_following_groups, [characters, john_yoko])534 # just walrus' groups535 self.paul.relationships.remove(self.yoko)536 paul_following_groups = positive_filter(537 group_qs,538 self.paul.relationships.following(),539 'user')540 self.assertQuerysetEqual(paul_following_groups, [characters])541 self.paul.relationships.remove(self.walrus)542 def test_negative_filter(self):543 blocking = RelationshipStatus.objects.blocking()544 # create some groups to filter545 from django.contrib.auth.models import Group546 beatles = Group.objects.create(name='beatles')547 john_yoko = Group.objects.create(name='john_yoko')548 characters = Group.objects.create(name='characters')549 self.walrus.groups.add(characters)550 self.john.groups.add(beatles)551 self.john.groups.add(john_yoko)552 self.paul.groups.add(beatles)553 self.yoko.groups.add(john_yoko)554 self.yoko.groups.add(characters)555 group_qs = Group.objects.all().order_by('name')556 # groups people paul blocks are *not* in (yoko & walrus)557 # since john is in the john_yoko group, just characters will show up558 paul_blocking_groups = negative_filter(559 group_qs,560 self.paul.relationships.blocking(),561 'user')562 self.assertQuerysetEqual(paul_blocking_groups, [characters])563 # block yoko and no groups564 self.paul.relationships.add(self.yoko, blocking)565 paul_blocking_groups = negative_filter(566 group_qs,567 self.paul.relationships.blocking(),568 'user')569 self.assertQuerysetEqual(paul_blocking_groups, [])570 # block walrus - everyone is blocked, no groups571 self.paul.relationships.add(self.walrus, blocking)572 paul_blocking_groups = negative_filter(573 group_qs,574 self.paul.relationships.blocking(),575 'user')576 self.assertQuerysetEqual(paul_blocking_groups, [])577 # unblock john and we'll get beatles578 self.paul.relationships.remove(self.john, blocking)579 paul_blocking_groups = negative_filter(580 group_qs,581 self.paul.relationships.blocking(),582 'user')583 self.assertQuerysetEqual(paul_blocking_groups, [beatles])584 # unblock yoko585 self.paul.relationships.remove(self.yoko, blocking)586 paul_blocking_groups = negative_filter(587 group_qs,588 self.paul.relationships.blocking(),589 'user')590 self.assertQuerysetEqual(paul_blocking_groups, [beatles, john_yoko])591 # unblock walrus and we have them all592 self.paul.relationships.remove(self.walrus, blocking)593 paul_blocking_groups = negative_filter(594 group_qs,595 self.paul.relationships.blocking(),596 'user')597 self.assertQuerysetEqual(paul_blocking_groups, [beatles, characters, john_yoko])598 def test_relationship_exists(self):599 self.assertTrue(relationship_exists(self.john, self.yoko, 'following'))600 self.assertTrue(relationship_exists(self.john, self.yoko, 'followers'))601 self.assertTrue(relationship_exists(self.john, self.yoko, 'friends'))602 self.assertTrue(relationship_exists(self.yoko, self.john, 'following'))603 self.assertTrue(relationship_exists(self.yoko, self.john, 'followers'))604 self.assertTrue(relationship_exists(self.yoko, self.john, 'friends'))605 self.assertTrue(relationship_exists(self.john, self.paul, 'following'))606 self.assertFalse(relationship_exists(self.john, self.paul, 'followers'))607 self.assertFalse(relationship_exists(self.john, self.paul, 'friends'))608 self.assertFalse(relationship_exists(self.paul, self.john, 'following'))609 self.assertTrue(relationship_exists(self.paul, self.john, 'followers'))610 self.assertFalse(relationship_exists(self.paul, self.john, 'friends'))611 self.assertTrue(relationship_exists(self.paul, self.john, 'blocking'))...

Full Screen

Full Screen

test_basemodelwithsoftdelete.py

Source:test_basemodelwithsoftdelete.py Github

copy

Full Screen

...22 cls.member.members.add(*cls.people)23 def test_softdelete_for_many_to_many(self):24 deleted_member = self.member.delete()25 self.assertEqual(deleted_member, (3, {'core.Member': 1, 'core.Member_members': 2}))26 self.assertQuerysetEqual(Member.objects.all(), [])27 self.assertQuerysetEqual(Member.objects.actives(), [])28 self.assertQuerysetEqual(Member.objects.deleted(), ['<Member: Membership>'])29 self.assertQuerysetEqual(self.member.members.all(), [])30 def test_basemodelwithsoftdelete_fields(self):31 """Test fields"""32 self.assertEqual(self.category.pk, self.category.id)33 self.assertEqual(self.category.status, Post.STATUS_ONLINE)34 for post in self.posts:35 self.assertEqual(post.status, Post.STATUS_ONLINE)36 def test_basemodelwithsoftdelete_queryset(self):37 """Test queryset"""38 self.assertQuerysetEqual(39 self.category.posts.all().order_by('id'), ['<Post: Python post 1>', '<Post: Python post 2>']40 )41 self.assertQuerysetEqual(Category.objects.actives(), ['<Category: Python>'])42 self.assertQuerysetEqual(Category.objects.offlines(), [])43 self.assertQuerysetEqual(Category.objects.deleted(), [])44 self.assertQuerysetEqual(Category.objects.drafts(), [])45 def test_soft_deletetion(self):46 """Test soft deletion"""47 deleted_category = self.category.delete()48 self.assertEqual(deleted_category, (3, {'core.Category': 1, 'core.Post': 2}))49 self.assertQuerysetEqual(Category.objects.deleted(), ['<Category: Python>'])50 self.assertQuerysetEqual(51 Post.objects.deleted().order_by('id'), ['<Post: Python post 1>', '<Post: Python post 2>']52 )53 def test_softdelete_undelete(self):54 """Test undelete feature"""55 deleted_category = self.category.delete()56 self.assertEqual(deleted_category, (3, {'core.Category': 1, 'core.Post': 2}))57 undeleted_items = self.category.undelete()58 self.assertEqual(undeleted_items, (3, {'core.Category': 1, 'core.Post': 2}))59 self.assertQuerysetEqual(Post.objects.deleted(), [])60 def test_softdelete_all(self):61 deleted_posts = Post.objects.delete()...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pytest-django automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful