-
Notifications
You must be signed in to change notification settings - Fork 5
/
tests_views.py
868 lines (705 loc) · 29.6 KB
/
tests_views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
"""
View tests.
Note: there should be tests, subclassed from TestCase.
They all should be using Django's TestClient.
"""
import json
from functools import partial
from itertools import chain
from operator import attrgetter
from urllib.parse import urlparse, quote
from xml.etree import ElementTree as ET
from bs4 import BeautifulSoup
from django.conf import settings
from django.db.models import Q
from django.http import HttpResponse
from django.test import override_settings, TestCase, tag
from django.urls import reverse, reverse_lazy
from django.utils.translation import ugettext as _
from catalog.helpers import reverse_catalog_url
from pages.models import CustomPage
from pages.urls import reverse_custom_page
from shopelectro import models
from shopelectro import views
from shopelectro.views.service import generate_md5_for_ya_kassa, YANDEX_REQUEST_PARAM
CANONICAL_HTML_TAG = '<link rel="canonical" href="{base_url}{path}">'
def get_page_number(response):
return response.context['paginated']['page'].number
def json_to_dict(response: HttpResponse) -> dict:
return json.loads(response.content)
class BaseCatalogTestCase(TestCase):
fixtures = ['dump.json']
def setUp(self):
self.category = models.Category.objects.root_nodes().select_related('page').first()
self.tags = models.Tag.objects.order_by_alphanumeric().all()
def get_category_url(
self,
category: models.Category = None,
tags: models.TagQuerySet = None,
sorting: int = None,
query_string: dict = None,
route='category',
route_kwargs: dict = None,
):
query_string = query_string or {}
route_kwargs = route_kwargs or {}
category = category or self.category
route_kwargs = {
'slug': category.page.slug,
**route_kwargs
}
return reverse_catalog_url(
route, route_kwargs, tags, sorting, query_string,
)
def get_category_page(self, *args, **kwargs):
"""See `self.get_category_url()` interface."""
return self.client.get(self.get_category_url(*args, **kwargs))
@tag('fast', 'catalog')
class CatalogTags(BaseCatalogTestCase):
def test_category_page_contains_all_tags(self):
"""Category contains all Product's tags."""
response = self.get_category_page()
tags = set(chain.from_iterable(map(
lambda x: x.tags.all(), (
models.Product.objects
.prefetch_related('tags')
.filter_descendants(self.category)
)
)))
tag_names = list(map(attrgetter('name'), tags))
for tag_name in tag_names:
self.assertContains(response, tag_name)
def test_contains_product_with_certain_tags(self):
"""Category page contains Product's related by certain tags."""
tags = self.tags
response = self.get_category_page(tags=tags)
products_count = len(list(filter(
lambda x: x.category.is_descendant_of(self.category),
models.Product.objects.filter(Q(tags=tags[0]) | Q(tags=tags[1]))
)))
self.assertEqual(
products_count,
response.context['paginated']['total_products']
)
self.assertContains(response, products_count)
def test_tag_titles_content_disjunction(self):
"""
Test CategoryTagsPage with canonical tags.
CategoryTagsPage with tags "Напряжение 6В" и "Напряжение 24В"
should contain tag_titles var content: "6В или 24В".
"""
tag_group = models.TagGroup.objects.first()
tags = tag_group.tags.order_by_alphanumeric().all()
response = self.get_category_page(tags=tags)
self.assertEqual(response.status_code, 200)
delimiter = settings.TAGS_TITLE_DELIMITER
tag_titles = delimiter.join(t.name for t in tags)
self.assertContains(response, tag_titles)
def test_tag_titles_content_conjunction(self):
"""
Test CategoryTagsPage with canonical tags.
CategoryTagsPage with tags "Напряжение 6В" и "Cила тока 1А" should
contain tag_titles var content: "6В и 1А".
"""
tag_groups = models.TagGroup.objects.order_by('position', 'name').all()
tag_ids = [g.tags.first().id for g in tag_groups]
tags = models.Tag.objects.filter(id__in=tag_ids)
response = self.get_category_page(tags=tags)
self.assertEqual(response.status_code, 200)
delimiter = settings.TAG_GROUPS_TITLE_DELIMITER
tag_titles = delimiter.join(t.name for t in tags)
self.assertContains(response, tag_titles)
def test_tags_var_in_db_template(self):
"""
Test CategoryTagsPage with canonical tags.
"tags" db template at CategoryTagsPage
should render tag names. For example "1 м, 20 кг".
"""
tags = models.Tag.objects.order_by_alphanumeric().all()
response = self.get_category_page(tags=tags)
self.assertEqual(response.status_code, 200)
tag_names = ', '.join([t.name for t in tags])
self.assertContains(response, tag_names)
def test_product_tag_linking(self):
"""Product should contain links on CategoryTagPage for it's every tag."""
product = models.Product.objects.first()
self.assertGreater(product.tags.count(), 0)
property_links = [
reverse('category', kwargs={
'slug': product.category.page.slug,
'tags': tag_.slug,
}) for tag_ in product.tags.all()
]
response = self.client.get(product.url)
for link in property_links:
self.assertContains(response, link)
def test_non_existing_tags_404(self):
"""Product should contain links on CategoryTagPage for it's every tag."""
product = models.Product.objects.first()
self.assertGreater(product.tags.count(), 0)
bad_tag_url = reverse('category', kwargs={
'slug': product.category.page.slug,
'tags': 'non-existent-tag',
})
response = self.client.get(bad_tag_url)
self.assertEqual(response.status_code, 404)
def test_category_tag_relation(self):
"""Category page should contain only tags, related to the current category."""
category = models.Category.objects.get(
name='Category #0 of #Category #0 of #Category #0'
)
# category is not related to this tag at DB ...
tag = models.Tag.objects.exclude_by_products(category.products.all()).first()
# ... so category page should not contain this tag
response = self.client.get(category.url)
self.assertNotContains(response, tag.name)
@tag('fast', 'catalog')
class CatalogPagination(BaseCatalogTestCase):
def test_pagination_numbering(self):
page_number = 1
response = self.get_category_page(query_string={'page': page_number})
self.assertEqual(get_page_number(response), page_number)
def test_pagination_products_count(self): # Ignore PyDocStyleBear
"""
@todo #302:30m Implement test case for pagination logic.
Products number changes in depend on page number.
If step=24 and page number=2, then products quantity is 48.
If step=24 and page number=2 and total products quantity is 40, then products quantity is 40. # Ignore PycodestyleBear (E501)
"""
def test_pagination_step(self):
"""Category page contains `pagination_step` count of products in list."""
pagination_step = 25
response = self.get_category_page(query_string={'step': pagination_step})
self.assertEqual(len(response.context['paginated']['page'].object_list), pagination_step)
def test_pagination_404(self):
"""Category page returns 404 for a nonexistent page number."""
self.assertEqual(
self.get_category_page(query_string={'page': 1000}).status_code,
404,
)
def assert_pagination_link(self, link, page_number):
"""Page numbers from link href and from link anchor should be equal."""
self.assertEqual(
get_page_number(self.client.get(link['href'])),
page_number,
)
def get_category_soup(self, page_number: int) -> BeautifulSoup:
category_page = self.get_category_page(query_string={'page': page_number})
return BeautifulSoup(
category_page.content.decode('utf-8'),
'html.parser'
)
def test_category_200(self):
category_page = self.get_category_page()
assert category_page.status_code == 200
def test_numbered_pagination_links(self):
"""Forward to numbered pagination pages."""
page_number = 3
_, *numbered, _ = self.get_category_soup(page_number).find(
class_='js-catalog-pagination').find_all('a')
for slice, link in zip([-2, -1, 1, 2], numbered):
self.assert_pagination_link(link, page_number + slice)
def test_arrow_pagination_links(self):
"""Each button forward to a previous and a next pagination pages."""
page_number = 3
prev, *_, next_ = self.get_category_soup(page_number).find(
class_='js-catalog-pagination').find_all('a')
self.assert_pagination_link(next_, page_number + 1)
self.assert_pagination_link(prev, page_number - 1)
def test_pagination_canonical(self):
"""Canonical links forward to a previous and a next pagination pages."""
page_number = 3
soup = self.get_category_soup(page_number)
self.assert_pagination_link(
soup.find('link', attrs={'rel': 'next'}),
page_number + 1
)
self.assert_pagination_link(
soup.find('link', attrs={'rel': 'prev'}),
page_number - 1
)
@tag('fast')
class LoadMore(BaseCatalogTestCase):
fixtures = ['dump.json']
DEFAULT_LIMIT = 48
PRODUCT_ID_WITH_IMAGE = 114
def load_more(
self,
category: models.Category=None,
tags: models.TagQuerySet=None,
offset: int=0,
# uncomment after implementation urls for load_more with pagination
# limit: int=0,
sorting: int=0,
query_string: dict=None,
) -> HttpResponse:
category = category or self.category
route_kwargs = {
'offset': offset,
# uncomment after implementation urls for load_more with pagination
# 'limit': limit,
}
return self.get_category_page(
category=category,
tags=tags,
sorting=sorting,
query_string=query_string,
route='load_more',
route_kwargs=route_kwargs
)
def get_load_more_soup(self, *args, **kwargs) -> BeautifulSoup:
"""Use interface of `self.load_more` method."""
load_more_response = self.load_more(*args, **kwargs)
return BeautifulSoup(
load_more_response.content.decode('utf-8'),
'html.parser'
)
def test_pagination_numbering_first_page(self):
self.assertEqual(get_page_number(self.load_more()), 1)
def test_pagination_numbering_last_page(self):
offset = models.Product.objects.filter_descendants(self.category).count() - 1
self.assertEqual(
get_page_number(self.load_more(offset=offset)),
offset // self.DEFAULT_LIMIT + 1,
)
def test_pagination_numbering_rest_page(self):
offset = self.DEFAULT_LIMIT + 1
self.assertEqual(
get_page_number(self.load_more(offset=offset)),
2,
)
def test_image_previews(self):
"""Load_more button should load product with image previews."""
load_more_soup = self.get_load_more_soup(offset=self.DEFAULT_LIMIT)
img_path = (
load_more_soup
.find('a', href=f'/catalog/products/{self.PRODUCT_ID_WITH_IMAGE}/')
.find('img')['src']
)
self.assertNotIn('logo', img_path)
@tag('fast')
class SitemapXML(TestCase):
"""
Test Sitemap XML.
Getting sitemap.xml and parsing it as string.
"""
fixtures = ['dump.json']
def setUp(self):
"""Set up testing url."""
# Namespace for using ET.find()
self.NAMESPACE = '{http://www.sitemaps.org/schemas/sitemap/0.9}'
content = self.client.get('/sitemap.xml').content.decode('utf-8')
self.root = ET.fromstring(content)
def test_url_tags(self):
"""We should see <url> tags on Sitemap page."""
url_tags = self.root.findall('{}url'.format(self.NAMESPACE))
self.assertGreater(len(url_tags), 0)
def test_models_urls(self):
"""Sitemap page should to print correct urls for models."""
path = '{0}url[2]/{0}loc'.format(self.NAMESPACE)
model_url_text = urlparse(self.root.find(path).text).path
response = self.client.get(model_url_text)
self.assertEqual(response.status_code, 200)
@tag('fast')
class RobotsPage(TestCase):
fixtures = ['dump.json']
def setUp(self):
self.response = self.client.get('/robots.txt')
def test_robots_success(self):
self.assertEqual(self.response.status_code, 200)
@tag('fast')
class SitemapPage(TestCase):
fixtures = ['dump.json']
def setUp(self):
self.response = self.client.get('/sitemap/')
def test_pagination_on_page(self):
paginator_pages = list(self.response.context['paginator_pages'])
paginator_links = self.response.context['paginator_links']
self.assertTrue(len(paginator_pages) == 50)
self.assertFalse(len(paginator_links) == 0)
def test_sitemap_self_link_on_page(self):
sitemap_url_slug = reverse_custom_page('sitemap')
self.assertIn(sitemap_url_slug, self.response.content.decode('utf-8'))
@tag('fast')
class YandexKassa(TestCase):
"""
Test yandex check order and yandex aviso.
Yandex docs https://goo.gl/bOf3kw
"""
fixtures = ['dump.json']
def create_aviso_request_data(self):
data_for_md5 = {param: str(number) for number, param in enumerate(YANDEX_REQUEST_PARAM)}
data_for_md5.update({'shopPassword': settings.YANDEX_SHOP_PASS})
md5 = generate_md5_for_ya_kassa(data_for_md5)
request_data = {
'md5': md5,
'orderSumAmount': '12312',
'shopSumAmount': '123123',
**data_for_md5,
}
return request_data
def setUp(self):
self.yandex_aviso_request_data = {
'path': reverse('yandex_aviso'),
'data': self.create_aviso_request_data()
}
self.yandex_check_request_data = {
'path': reverse('yandex_check'),
'data': {'invoiceId': 123}
}
self.yandex_aviso_request = partial(self.client.post, **self.yandex_aviso_request_data)
self.yandex_check_request = partial(self.client.post, **self.yandex_check_request_data)
def test_yandex_check_body(self):
"""Response should contain attr code="0" - it's mean, that all right."""
response = self.yandex_check_request()
self.assertContains(response, 'code="0"')
self.assertContains(response, 'invoiceId="123"')
def test_yandex_aviso_body(self):
"""
Test response code.
Response should contain attr code="0" - it's mean, that all right,
if code="1" - it's mean, yandex's request body contain incorrect data.
"""
response = self.yandex_aviso_request()
self.assertContains(response, 'code="0"')
self.yandex_aviso_request_data['data']['md5'] = 'incorrect data'
response = self.yandex_aviso_request()
self.assertContains(response, 'code="1"')
@tag('fast', 'catalog')
class Category(BaseCatalogTestCase):
fixtures = ['dump.json']
def test_page_db_template_with_special_chars(self):
"""
DB template works with many cyrillic chars in string.
This led to the segmentation fault issue. See #651 for details.
"""
db_template = self.category.page.template
db_template.seo_text = (
'{% if page.name '
'== "Аккумуляторы промышленные 3.7 В, Li-Pol призматические" %}'
'some text{% else %}alt text{% endif %}'
)
db_template.save()
rendered_text = db_template.render_field(
field='seo_text',
context={'page': self.category.page}
)
self.assertEqual('alt text', rendered_text)
response = self.get_category_page()
self.assertEqual(200, response.status_code)
def test_canonical_meta_tag(self):
"""Category page should contain canonical meta tag."""
path = self.get_category_url()
response = self.client.get(path)
self.assertEqual(response.status_code, 200)
self.assertContains(
response,
CANONICAL_HTML_TAG.format(
base_url=settings.BASE_URL,
path=path
),
)
def test_tags_pagination_has_canonical_links(self):
"""
Paginated tags page should contain canonical link.
Link on it's not paginated version.
"""
tags = models.Tag.objects.filter_by_products(
products=(
models.Product.objects.all()
.filter_descendants(self.category)
)
)
not_paginated_url = self.get_category_url(
tags=tags
)
paginated_url = self.get_category_url(
tags=tags,
query_string={'page': 2}
)
response = self.client.get(paginated_url)
self.assertContains(
response, CANONICAL_HTML_TAG.format(
base_url=settings.BASE_URL,
path=not_paginated_url
)
)
def test_category_matrix_page(self):
"""Matrix page should contain all second level categories."""
page = CustomPage.objects.get(slug='catalog')
response = self.client.get(page.url)
soup = BeautifulSoup(
response.content.decode('utf-8'),
'html.parser'
)
self.assertEqual(200, response.status_code)
categories_db = models.Category.objects.active()
categories_app = soup.find_all(tag='a', class_='catalog-list-item')
for from_db, from_app in zip(categories_db, categories_app):
self.assertEqual(from_db.name, from_app.a.text)
@tag('fast', 'catalog')
class CategoriesMatrix(BaseCatalogTestCase):
fixtures = ['dump.json']
URL = reverse_lazy('custom_page', kwargs={'page': 'catalog'})
def get_page(self):
return self.client.get(self.URL)
def get_soup(self) -> BeautifulSoup:
return BeautifulSoup(
self.get_page().content.decode('utf-8'),
'html.parser'
)
def test_roots_sorting(self):
soup = self.get_soup()
from_page = soup.find_all('h2')
from_db = (
models.Category.objects.bind_fields().active()
.filter(level=0)
.order_by('page__position', 'name')
).values_list('name', flat=True)
self.assertEqual([c.text for c in from_page], list(from_db))
def test_second_level_sorting(self):
soup = self.get_soup()
from_page = soup.select('.second-level-category > a')
from_db = (
models.Category.objects.bind_fields().active()
.filter(level=1)
.order_by(
'parent__page__position', 'parent__name',
'page__position', 'name'
)
).values_list('name', flat=True)
self.assertEqual([c.text for c in from_page], list(from_db))
@tag('fast')
class IndexPage(TestCase):
fixtures = ['dump.json']
MAIN_PAGE_TILE = {
'some_section': [
{'name': 'Has url', 'url': '/section/first/'},
{'name': 'Has url and slug', 'slug': 'slug', 'url': '/section/second/'},
{'name': 'Has slug, but not url', 'slug': 'third'},
]
}
@property
def page(self):
return CustomPage.objects.get(slug='')
@override_settings(MAIN_PAGE_TILE=MAIN_PAGE_TILE)
def test_category_tile_links(self):
tile = views.IndexPage.get_categories_tile()
first_url, second_url, third_url = [link['url'] for link in tile['some_section']]
self.assertEqual('/section/first/', first_url)
self.assertEqual('/section/second/', second_url)
self.assertEqual('/catalog/categories/third/', third_url)
def test_index_page_url(self):
self.assertTrue(self.page.url)
def test_product_tile(self):
product = (
models.Product.objects.active()
.filter(id__in=settings.TOP_PRODUCTS)
.first()
)
response = self.client.get(self.page.url)
self.assertIn(product, response.context['tile_products'])
self.assertIn(product.id, response.context['product_images'])
@tag('fast')
class ProductPage(TestCase):
fixtures = ['dump.json']
def setUp(self):
self.product = models.Product.objects.first()
def get_product_page(self, product: models.Product=None):
product = product or self.product
return self.client.get(product.url)
def get_product_soup(self, product: models.Product=None) -> BeautifulSoup:
product_page = self.get_product_page(product)
return BeautifulSoup(
product_page.content.decode('utf-8'),
'html.parser'
)
def test_orphan_product(self):
self.product.category = None
self.product.save()
response = self.client.get(self.product.url)
self.assertEqual(response.status_code, 404)
def test_related_products(self):
"""404 page of sometimes removed product should contain product's siblings."""
response = self.get_product_page()
# 404 page should show 10 siblings. We'll check the last one
sibling_product = self.product.category.products.all()[9]
self.assertTrue(
sibling_product.name in str(response.content)
)
def test_related_products_on_404(self):
"""404 page of some time ago removed product should contain product's siblings."""
self.product.page.is_active = False
self.product.save() # saves product.page too
response = self.get_product_page()
# 404 page should show 10 siblings. We'll check the last one
sibling_product = self.product.category.products.all()[9]
self.assertEqual(response.status_code, 404)
self.assertTrue(
sibling_product.name in str(response.content)
)
def test_related_product_images(self):
"""Check previews for product's siblings on product page."""
product_soup = self.get_product_soup(product=models.Product.objects.get(id=19))
img_path = (
product_soup
.find_all(class_='stuff-top-item')[-1]
.find('img')['src']
)
# app shows logo image if preview can't generated
self.assertNotIn('logo', img_path)
def test_page_obj(self):
"""Page object in context should be relevant to product object."""
product = self.product
response = self.get_product_page(product=product)
self.assertEqual(response.context['page'], product.page)
def test_page_contains_h1(self):
"""Page object in context should be relevant to product object."""
product = self.product
response = self.get_product_page(product=product)
self.assertContains(response, product.page.display.h1)
@tag('fast')
class ProductPageSchema(TestCase):
fixtures = ['dump.json']
schema_url = 'https://schema.org'
def test_available(self):
"""Page of an product with stock > 0 has $schema_url/InStock link."""
self.assertContains(
self.client.get(
models.Product.objects.filter(in_stock__gt=0).first().url
),
f'{self.schema_url}/InStock',
)
def test_not_available(self):
"""Page of an product with stock = 0 has $schema_url/PreOrder link."""
self.assertContains(
self.client.get(
models.Product.objects.filter(in_stock=0).first().url
),
f'{self.schema_url}/PreOrder',
)
@tag('fast')
class ProductsWithoutContent(TestCase):
def test_products_without_images(self):
response = self.client.get(reverse('products_without_images'))
self.assertEqual(response.status_code, 200)
def test_products_without_text(self):
response = self.client.get(reverse('products_without_text'))
self.assertEqual(response.status_code, 200)
@tag('fast')
class TestSearch(TestCase):
"""Test all search methods: search page and autocompletes."""
fixtures = ['dump.json']
TERM = 'Prod'
SIGNLE_RESULT_TERM = '#0'
QUOTED_SIGNLE_RESULT_TERM = quote(SIGNLE_RESULT_TERM)
WRONG_TERM = 'Bugaga' # it's short for trigram search testing
def test_search_has_results(self):
"""Search page should contain at least one result for right term."""
term = self.TERM
response = self.client.get(
f'/search/?term={term}',
follow=True
)
self.assertEqual(response.status_code, 200)
self.assertContains(response, _('Product'))
# search page should contain not only results.
# But markup, menu links and so on.
self.assertContains(response, '<title>')
self.assertContains(response, '<div class="search-result-item">')
def test_search_no_results(self):
"""Search page should contain no results for wrong term."""
term = self.WRONG_TERM
response = self.client.get(
f'/search/?term={term}',
follow=True
)
self.assertEqual(response.status_code, 200)
self.assertNotContains(response, '<div class="search-result-item">')
def test_autocomplete_has_results(self):
"""Autocomplete should contain at least one result for right term."""
term = self.TERM
response = self.client.get(
reverse('autocomplete') + f'?term={term}'
)
self.assertEqual(response.status_code, 200)
self.assertTrue(json_to_dict(response))
self.assertContains(response, term)
def test_autocomplete_no_results(self):
"""Autocomplete should contain no results for wrong term."""
term = self.WRONG_TERM
response = self.client.get(
reverse('autocomplete') + f'?term={term}'
)
self.assertEqual(response.status_code, 200)
self.assertFalse(json_to_dict(response))
self.assertNotContains(response, term)
def test_admin_autocomplete_has_results(self):
"""Admin autocomplete should contain at least one result for right term."""
term = self.TERM
page_type = 'product'
querystring = f'?term={term}&pageType={page_type}'
response = self.client.get(reverse('admin_autocomplete') + querystring)
self.assertEqual(response.status_code, 200)
self.assertTrue(json_to_dict(response))
self.assertContains(response, term)
def test_admin_autocomplete_no_results(self):
"""Admin autocomplete should contain no results for wrong term."""
term = self.WRONG_TERM
page_type = 'product'
querystring = f'?term={term}&pageType={page_type}'
response = self.client.get(reverse('admin_autocomplete') + querystring)
self.assertEqual(response.status_code, 200)
self.assertFalse(json_to_dict(response))
self.assertNotContains(response, term)
def test_search_has_no_model_pages(self):
"""Search page does not contain page with type=MODEL_TYPE and duplicated content."""
response = self.client.get(
f'/search/?term={self.QUOTED_SIGNLE_RESULT_TERM}',
follow=True,
)
result_links = BeautifulSoup(
response.content.decode('utf-8'), 'html.parser'
).find_all(class_='search-result-link')
self.assertTrue(len(result_links) == 1)
def test_autocomplete_has_no_model_pages(self):
"""Autocomplete does not contain page with type=MODEL_TYPE and duplicated content."""
response = self.client.get(
f'{reverse("autocomplete")}?term={self.QUOTED_SIGNLE_RESULT_TERM}'
)
self.assertFalse(
list(filter(
lambda r: r['type'] not in ['category', 'see_all'],
json_to_dict(response),
))
)
def test_admin_autocomplete_has_no_model_pages(self):
"""Admin autocomplete does not contain page with type=MODEL_TYPE and duplicated content."""
response = self.client.get(
f'{reverse("admin_autocomplete")}'
f'?term={self.QUOTED_SIGNLE_RESULT_TERM}&pageType=category'
)
self.assertTrue(len(json_to_dict(response)) == 1)
@tag('fast')
class Order(TestCase):
fixtures = ['dump.json']
def test_disabled_cache(self):
"""Cache-Control is disabled for the order page."""
url = reverse_custom_page('order')
self.assertEqual(
self.client.get(url)['Cache-Control'],
'max-age=0, no-cache, no-store, must-revalidate',
)
@tag('fast')
class Cart(TestCase):
fixtures = ['dump.json']
def test_get_cart(self):
response = self.client.get(reverse('cart_get'))
self.assertEqual(response.status_code, 200)
self.assertTrue(json_to_dict(response))
def test_disabled_cache(self):
"""Cache-Control is disabled for the cart-get."""
self.assertEqual(
self.client.get(reverse('cart_get'))['Cache-Control'],
'max-age=0, no-cache, no-store, must-revalidate',
)