Skip to content

Commit f93c35c

Browse files
authored
Merge pull request #59 from jetbrains-academy/third_module_translation
Third module translation
2 parents d5518d9 + 2683ffd commit f93c35c

File tree

4 files changed

+45
-45
lines changed

4 files changed

+45
-45
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,38 @@
1-
<h2>Проверка элемента на странице</h2>
1+
<h2>Checking an element on a page</h2>
22

3-
<p>Чтобы выводить адекватное сообщение об ошибке, мы будем все проверки осуществлять с помощью assert и перехватывать исключения.</p>
3+
<p>To display an appropriate error message, we will perform all checks using assert and catch the exceptions.</p>
44

5-
<p>Для этого напишем вспомогательный метод поиска элемента в нашей базовой странице BasePage, который будет возвращать нам <code>True</code> или <code>False</code>. Можно сделать это по-разному (с настройкой явных или неявных ожиданий). Сейчас воспользуемся неявным ожиданием.</p>
5+
<p>For this purpose, let's write a helper method to find an element on our BasePage, which will return either <code>True</code> or <code>False</code>. This can be done in various ways (with explicit or implicit waits). For now, let's use implicit waiting.</p>
66

7-
<p>1. В конструктор BasePage добавим команду для неявного ожидания со значением по умолчанию в 10:</p>
7+
<p>1. In the constructor of BasePage, let's add a command for implicit waiting with a default value of 10:</p>
88

99
<pre><code class="language-python">def __init__(self, browser, url, timeout=10):
1010
self.browser = browser
1111
self.url = url
1212
self.browser.implicitly_wait(timeout)</code></pre>
1313

14-
<p>2. Теперь в этом же классе реализуем метод <code>is_element_present</code>, в котором будем перехватывать исключение. В него будем передавать два аргумента: <em>как </em>искать (css, id, xpath и тд) и собственно <em>что </em>искать (строку-селектор). </p>
14+
<p>2. Now, in the same class, we'll implement the <code>is_element_present</code> method, where we will catch the exception. We will pass two arguments to it: <em>how </em>to search (css, id, xpath, etc.) and <em>what </em>to search for (the selector string). </p>
1515

16-
<p>Чтобы перехватывать исключение, нужна конструкция <code>try/except</code>: </p>
16+
<p>To catch the exception, we need a <code>try/except</code> construct: </p>
1717

1818
<pre><code class="language-python">def is_element_present(self, how, what):
1919
try:
2020
self.browser.find_element(how, what)
21-
except (имя исключения):
21+
except (name of exception):
2222
return False
2323
return True</code></pre>
2424

25-
<p>Чтобы импортировать нужное нам исключение, в самом верху файла нужно указать: </p>
25+
<p>To import the required exception, you need to specify the following at the very top of the file: </p>
2626

27-
<pre><code>from selenium.common.exceptions import имя_исключения</code></pre>
27+
<pre><code>from selenium.common.exceptions import exception_name</code></pre>
2828

29-
<p>Отлично! Теперь для всех проверок, что элемент действительно присутствует на странице, мы можем использовать этот метод. </p>
29+
<p>Great! Now, we can use this method for all checks on the presence of an element on the page. </p>
3030

31-
<p>3. Теперь модифицируем метод проверки ссылки на логин так, чтобы он выдавал адекватное сообщение об ошибке: </p>
31+
<p>3. Now, let's modify the method for checking the login link so that it provides an appropriate error message: </p>
3232

3333
<pre><code>def should_be_login_link(self):
3434
assert self.is_element_present(By.CSS_SELECTOR, "#login_link_invalid"), "Login link is not presented"</code></pre>
3535

36-
<p>Запустите тесты и посмотрите, что вывод об ошибке стал более понятным: </p>
36+
<p>Run the tests and see that the error output has become more understandable: </p>
3737

3838
<pre><code>pytest -v --tb=line --language=en test_main_page.py</code></pre>
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,33 @@
1-
<p><strong>Важно! </strong>В этом уроке мы напишем самостоятельно простую реализацию паттерна Page Object.
2-
А в следующих уроках уже рассмотрим существующие фреймворки и то,
3-
как они могут облегчить нам жизнь. Сейчас самая главная задача &mdash;
4-
осознать принципы работы.&nbsp;</p>
1+
<p><strong>Important! </strong>In this lesson, we will write a simple implementation of the Page Object pattern.
2+
In the following lessons, we will explore existing frameworks and the ways
3+
they can make our lives easier. Right now, the most crucial task
4+
is to understand the principles of their work.&nbsp;</p>
55

66

7-
<p>Для начала сделаем базовую страницу, от которой будут унаследованы все остальные классы.
8-
В ней мы опишем&nbsp;вспомогательные методы для работы с вебдрайвером.</p>
7+
<p>To start, let's create a base page from which all other classes will be inherited.
8+
In it, we will describe auxiliary methods for working with the web driver.</p>
99

10-
<p>1. В файле <code>base_page.py</code> создайте класс с названием <code>BasePage</code>.&nbsp;</p>
10+
<p>1. In the <code>base_page.py</code> file, create a class named <code>BasePage</code>.&nbsp;</p>
1111

12-
<p>В Python такие вещи делаются с помощью следующей конструкции:&nbsp;</p>
12+
<p>In Python, such things are done using the following construct:&nbsp;</p>
1313

1414
<pre>
1515
<code>class BasePage:</code></pre>
1616

17-
<p>2. Теперь в наш класс нужно добавить методы.
18-
Первым делом добавим <em>конструктор &mdash;&nbsp;</em>метод, который вызывается, когда мы создаем объект. Конструктор объявляется ключевым словом <code>__init__</code>. В него в качестве параметров мы передаем экземпляр драйвера и url адрес. Внутри конструктора сохраняем эти данные как аттрибуты нашего класса. Получается примерно так:&nbsp;</p>
17+
<p>2. Now we need to add methods to our class.
18+
First of all, let's add a <em>constructor &mdash;&nbsp;</em>a method that is called when we create an object. A constructor is declared with the keyword <code>__init__</code>. As parameters, we pass an instance of the driver and the URL address. Inside the constructor, we save this data as attributes of our class. It looks like this:&nbsp;</p>
1919

2020
<pre>
2121
<code class="language-python">def __init__(self, browser, url):
2222
self.browser = browser
2323
self.url = url</code></pre>
2424

25-
<p>3. Теперь добавим еще один&nbsp;метод open. Он должен открывать нужную страницу в браузере, используя метод get().</p>
25+
<p>3. Now let's add another method, open. It should open the required page in the browser using the get() method.</p>
2626

27-
<p>Объявите ниже в том же классе:</p>
27+
<p>Declare the following in the same class:</p>
2828

2929
<pre>
3030
<code class="language-python">def open(self):</code></pre>
3131

32-
<p>и реализуйте этот метод: нужна всего одна строка.
32+
<p>And implement this method: it only needs one line.
3333
&nbsp;</p>
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,25 @@
1-
<h2>Page Object для главной страницы сайта</h2>
1+
<h2>Page Object for the main page of the website</h2>
22

3-
<p>Теперь реализуем Page Object, который будет связан с главной страницей интернет-магазина. </p>
3+
<p>Now let's implement a Page Object that will be associated with the main page of the online store. </p>
44

5-
<p>1. Откройте файл <code>main_page.py</code> </p>
5+
<p>1. Open the file <code>main_page.py</code> </p>
66

7-
<p>2. В нем создайте класс  <code>MainPage</code>. Его нужно сделать наследником класса <code>BasePage</code>. Класс-предок в Python указывается в скобках: </p>
7+
<p>2. In it, create a class <code>MainPage</code>. It needs to inherit from the <code>BasePage</code> class. The parent class in Python is specified in parentheses: </p>
88

99
<pre><code>class MainPage(BasePage): </code></pre>
1010

11-
<p>таким образом, класс MainPage будет иметь доступ ко всем атрибутам и методам своего класса-предка. </p>
11+
<p>This way, the MainPage class will have access to all the attributes and methods of its parent class. </p>
1212

13-
<p>3. Перенесите метод из предыдущего урока в класс <code>MainPage</code>:</p>
13+
<p>3. Copy the method from the previous lesson into the <code>MainPage</code> class:</p>
1414

1515
<pre><code>def go_to_login_page(browser):
1616
   login_link = browser.find_element(By.CSS_SELECTOR, "#login_link")
1717
login_link.click() </code></pre>
1818

19-
<p>Чтобы все работало, надо слегка видоизменить его. В аргументы больше не надо передавать экземпляр браузера, мы его передаем и сохраняем на этапе создания Page Object. Вместо него нужно указать аргумент <code>self</code, чтобы иметь доступ к атрибутам и методам класса: </p>
19+
<p>To make everything work, we need to modify it slightly. There is no need to pass the browser instance as an argument anymore; we pass and save it during the creation of the Page Object. Instead, we need to specify the <code>self</codeargument to have access to the attributes and methods of the class: </p>
2020

2121
<p><code>def go_to_login_page(self):</code></p>
2222

23-
<p>Так как браузер у нас хранится как аргумент класса <code>BasePage</code>, обращаться к нему нужно соответствующим образом с помощью <code>self</code>: </p>
23+
<p>Since our browser is stored as an argument of the <code>BasePage</code> class, you should access it appropriately using <code>self</code>: </p>
2424

2525
<pre><code class="language-python">self.browser.find_element(By.CSS_SELECTOR, "#login_link")</code></pre>
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,35 @@
1-
<h2>Методы-проверки в Page Object</h2>
1+
<h2>Verification methods in Page Object</h2>
22

3-
<p>Давайте теперь автоматизируем другой тест-кейс и посмотрим на его примере, как делать методы-проверки. </p>
3+
<p>Let's now automate another test case and see, through an example, how to create verification methods. </p>
44

5-
<p>Допустим, нам нужно проверять такой сценарий: </p>
5+
<p>Suppose we need to check the following scenario: </p>
66

77
<ol>
8-
<li>Открыть главную страницу </li>
9-
<li>Проверить, что есть ссылка, которая ведет на логин </li>
8+
<li>Open the main page. </li>
9+
<li>Check if there is a link leading to login. </li>
1010
</ol>
1111

12-
<p>Для этого в классе MainPage нужно реализовать метод, который будет проверять наличие ссылки. Обычно все такие методы-проверки называются похожим образом, мы будем называть их should_be_(название элемента). </p>
12+
<p>For this, in the MainPage class, we need to implement a method that will check the presence of the link. Typically, all such verification methods are named similarly; we will call them should_be_(element name). </p>
1313

14-
<p>Итак, в классе MainPage создайте метод <code>should_be_login_link</code>. </p>
14+
<p>So, in the MainPage class, create the method <code>should_be_login_link</code>. </p>
1515

16-
<p>Для первой пробы можно реализовать его самым примитивным образом: </p>
16+
<p>For the first attempt, you can implement it in the simplest way: </p>
1717

1818
<pre><code>def should_be_login_link(self):
1919
self.browser.find_element(By.CSS_SELECTOR, "#login_link_invalid")</code></pre>
2020

21-
<p>Сейчас мы намеренно сделали селектор неправильным, чтобы посмотреть, что именно выдаст тест, если поймает баг. Это хорошая практика: писать сначала красные тесты и только потом делать их зелеными.  </p>
21+
<p>Currently, we intentionally made the selector incorrect to see what the test will report when it catches a bug. This is a good practice: writing red tests first and only then making them green. </p>
2222

23-
<p>Добавляем в файл с тест-кейсами новый тест: </p>
23+
<p>Let's add a new test to the test case file: </p>
2424

2525
<pre><code class="language-python">def test_guest_should_see_login_link(browser):
2626
link = "http://selenium1py.pythonanywhere.com/"
2727
page = MainPage(browser, link)
2828
page.open()
2929
page.should_be_login_link()</code></pre>
3030

31-
<p>Запустите получившийся тест: </p>
31+
<p>Run the resulting test: </p>
3232

3333
<pre><code>pytest -v --tb=line --language=en test_main_page.py</code></pre>
3434

35-
<p>Вывод об ошибке не очень понятный, правда? Разобраться, что именно пошло не так, довольно тяжело. Поэтому в следующем шаге нам нужно будет обработать исключение, которое выбрасывает WebDriver. </p>
35+
<p>The error output is not very clear, right? It's quite challenging to understand what went wrong exactly. Therefore, in the next step, we will need to handle the exception thrown by the WebDriver. </p>

0 commit comments

Comments
 (0)