Exesize

Форк
0
/
tests.py 
246 строк · 8.1 Кб
1
from http import HTTPStatus
2
from telnetlib import EC
3

4
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
5
from django.core import mail as email
6
from django.test import TestCase, Client
7
from django.test.utils import override_settings
8
from django.urls import reverse
9
from selenium.webdriver.common.by import By
10
from selenium.webdriver.firefox.webdriver import WebDriver
11
from selenium.webdriver.support import expected_conditions as EC
12
from selenium.webdriver.support.wait import WebDriverWait
13

14
import mainapp
15
from authapp import models
16
from authapp.models import User
17
# pages_tests
18
from config import settings
19
from mainapp import tasks
20
from mainapp.models import Courses
21
from mainapp.models import News
22
from mainapp import models
23

24

25
class TestMainPageSmoke(TestCase):
26

27
    def test_page_open(self):
28
        url = reverse("mainapp:home")
29
        result = self.client.get(url)
30
        self.assertEqual(result.status_code, HTTPStatus.OK)
31

32

33
class NewsTestCase(TestCase):
34
    def setUp(self) -> None:
35
        for i in range(10):
36
            News.objects.create(
37
                title=f'News{i}',
38
                preambule=f'Preambule{i}',
39
                body=f'Body{i}'
40
            )
41

42
        User.objects.create_superuser(username='django', password='geekbrains')
43
        self.client_with_auth = Client()
44
        auth_url = reverse('authapp:login')
45
        self.client_with_auth.post(
46
            auth_url, {'username': 'django', 'password': 'geekbrains'}
47
        )
48

49
    def test_open_page(self):
50
        url = reverse('mainapp:news')
51
        result = self.client.get(url)
52
        self.assertEqual(result.status_code, HTTPStatus.OK)
53

54
    def test_open_page_detail(self):
55
        news_obj = mainapp.models.News.objects.first()
56
        url = reverse('mainapp:news_detail', args=[news_obj.pk])
57
        result = self.client.get(url)
58
        self.assertEqual(result.status_code, HTTPStatus.OK)
59

60
    def test_failed_open_add_by_anonim(self):
61
        url = reverse('mainapp:news_create')
62
        result = self.client.get(url)
63
        self.assertEqual(result.status_code, HTTPStatus.FOUND)
64

65
    def test_page_open_news_crete_by_admin(self):
66
        path = reverse("mainapp:news_create")
67
        result = self.client_with_auth.get(path)
68
        self.assertEqual(result.status_code, HTTPStatus.OK)
69

70
    def test_create_in_web(self):
71
        counter_before = models.News.objects.count()
72
        path = reverse("mainapp:news_create")
73
        self.client_with_auth.post(
74
            path,
75
            data={
76
                "title": "NewTestNews001",
77
                "preambule": "NewTestNews001",
78
                "body": "NewTestNews001",
79
            },
80
        )
81

82
        self.assertGreater(mainapp.models.News.objects.count(), counter_before)
83

84
    def test_page_open_update_deny_access(self):
85
        news_obj = mainapp.models.News.objects.first()
86
        url = reverse("mainapp:news_update", args=[news_obj.pk])
87
        result = self.client.get(url)
88
        self.assertEqual(result.status_code, HTTPStatus.FOUND)
89

90
    def test_update_in_web(self):
91
        new_title = "NewTestTitle001"
92
        news_obj = mainapp.models.News.objects.first()
93
        self.assertNotEqual(news_obj.title, new_title)
94
        path = reverse("mainapp:news_update", args=[news_obj.pk])
95
        result = self.client_with_auth.post(
96
            path,
97
            data={
98
                "title": new_title,
99
                "preambule": news_obj.preambule,
100
                "body": news_obj.body,
101
            },
102
        )
103
        self.assertEqual(result.status_code, HTTPStatus.FOUND)
104
        news_obj.refresh_from_db()
105
        self.assertEqual(news_obj.title, new_title)
106

107
    def test_delete_in_web(self):
108
        news_obj = mainapp.models.News.objects.first()
109
        path = reverse("mainapp:news_delete", args=[news_obj.pk])
110
        self.client_with_auth.post(path)
111
        news_obj.refresh_from_db()
112
        self.assertTrue(news_obj.deleted)
113

114

115
#  email_test
116

117
class TestTaskMailSend(TestCase):
118

119
    def test_mail_send(self):
120
        for i in range(1, 5):
121
            User.objects.create_superuser(
122
                username=f'Random{i}',
123
                email=f'Email{i}',
124
                age=i,
125
                avatar=f'Avatar{i}'
126
            )
127

128
        message_body = "test_message_text"
129
        user_obj = models.User.objects.first()
130
        tasks.send_feedback_to_email(message_body, user_obj.pk)
131
        self.assertEqual(email.outbox[0].body, message_body)
132

133

134
# cashes_page_testing
135

136
class CoursesDetailTest(TestCase):
137

138
    def setUp(self) -> None:
139
        super().setUp()
140
        for i in range(0, 5):
141
            Courses.objects.create(
142
                name=f'name {i}',
143
                description=f'description {i}',
144
                cost=i
145
            )
146
        self.client = Client()
147

148
    @override_settings(CACHES={'default': {'BACKEND': 'django.core.cache.backends.dummy.DummyCache', }})
149
    def test_page_course_detail_open(self):
150
        course_obj = Courses.objects.first()
151
        url = reverse("mainapp:courses_detail", args=[course_obj.pk])
152
        result = self.client.get(url)
153
        self.assertEqual(result.status_code, HTTPStatus.OK)
154

155

156
# selenium
157

158

159
class TestNewsSelenium(StaticLiveServerTestCase):
160

161
    def setUp(self):
162
        for i in range(1, 5):
163
            User.objects.create_superuser(
164
                username=f'Random{i}',
165
                email=f'Email{i}',
166
                age=i,
167
                avatar=f'Avatar{i}'
168
            )
169
        for i in range(10):
170
            News.objects.create(
171
                title=f'News{i}',
172
                preambule=f'Preambule{i}',
173
                body=f'Body{i}'
174
            )
175
        User.objects.create_superuser(username='admin', password='geekbrains')
176
        self.client_with_auth = Client()
177
        auth_url = reverse('authapp:login')
178
        self.client_with_auth.post(
179
            auth_url, {'username': 'admin', 'password': 'geekbrains'}
180
        )
181
        super().setUp()
182
        self.selenium = WebDriver(
183
            executable_path=settings.SELENIUM_DRIVER_PATH_FF
184
        )
185
        self.selenium.implicitly_wait(10)
186
        # Login
187
        self.selenium.get(f"{self.live_server_url}{reverse('authapp:login')}")
188
        button_enter = WebDriverWait(self.selenium, 5).until(
189
            EC.visibility_of_element_located(
190
                (By.CSS_SELECTOR, '[type="submit"]')
191
            )
192
        )
193
        self.selenium.find_element_by_name("username").send_keys("admin")
194
        self.selenium.find_element_by_name("password").send_keys("geekbrains")
195
        button_enter.click()
196
        # Wait for footer
197
        WebDriverWait(self.selenium, 5).until(
198
            EC.visibility_of_element_located((By.CLASS_NAME, "mt-auto"))
199
        )
200

201
    def test_create_button_clickable(self):
202

203
        path_list = f"{self.live_server_url}{reverse('mainapp:news')}"
204
        path_add = reverse("mainapp:news_create")
205

206
        self.selenium.get(path_list)
207
        button_create = WebDriverWait(self.selenium, 5).until(
208
            EC.visibility_of_element_located(
209
                (By.CSS_SELECTOR, f'[href="{path_add}"]')
210
            )
211
        )
212
        print("Trying to click button ...")
213
        button_create.click()  # Test that button clickable
214
        WebDriverWait(self.selenium, 5).until(
215
            EC.visibility_of_element_located((By.ID, "id_title"))
216
        )
217
        print("Button clickable!")
218

219
    # With no element - test will be failed
220
    # WebDriverWait(self.selenium, 5).until(
221
    # EC.visibility_of_element_located((By.ID, "id_title111"))
222
    # )
223
    def test_pick_color(self):
224

225
        path = f"{self.live_server_url}{reverse('mainapp:home')}"
226
        self.selenium.get(path)
227
        navbar_el = WebDriverWait(self.selenium, 5).until(
228
            EC.visibility_of_element_located((By.CLASS_NAME, "navbar"))
229
        )
230
        try:
231
            self.assertEqual(
232
                navbar_el.value_of_css_property("background-color"),
233
                "rgb(255, 255, 155)",
234
            )
235
        except AssertionError:
236
            with open(
237
                    "var/screenshots/001_navbar_el_scrnsht.png", "wb"
238
            ) as outf:
239
                outf.write(navbar_el.screenshot_as_png)
240
        raise
241

242
    def tearDown(self):
243

244
        # Close browser
245
        self.selenium.quit()
246
        super().tearDown()
247

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.