Let us try to solve the problems of Mock Exam of CPSAT Python. In this blog we would be attempting Question 2 of Mock Exam 1.
Q2. Open http://www.wikipedia.org and write PyTest/WebDriver test for the following
using Google Chrome:
a. Display on console the number of articles in English and click on “English” link
b. Search for Anna University.
c. Print the ‘Motto in English’ part in the console and ensure it has the word ‘Knowledge’ in it
- Visit http://www.wikipedia.org
- We need to get the no. of English articles
- Capture xpath xpressions for English and no. of articles web elements
- Print no. of English Articles
- Click on English Link
- Need to search for Anna University in the searchbox
- get the xpath for search box
- In the Result page, we need to get text for the motto
We will automate the test by using
- Selenium package
- PyTest library which is used as a unit testing framework along with python
- PyCharm IDE (Integrated Development Environment)
We create a python file whose name starts with “test_” and having extension of .py like test_Question_02.py.
In this section we import the modules that we are going to use subsequently in our test script eg. time, webdriver etc
Inside setup method usually we carry out all the preparatory activities like setting driver properties, instantiating Chrome/Firefox Browser instance and maximise window and optionally setting the waits. It could be considered as an ordinary python method
Towards the end, we should release our resources like closing the driver instance is performed through another python method teardown() method.
Pytest test methods
Now we would be writing test methods and these pytest test should follow the specific nomenclature and name of each method must start with test_* .
Test_wiki() is the test method written for this purpose and code walkthrough is as follows
- Open the URL in the Chrome
- Print the no, of English Articles
Locate the no. of articles below English Link and find corresponding Web Element and subsequently text attribute of the webelement(Line21)
- Click on English Link
- Search “Anna University” in the Search Box
- Finding and print the Motto Text
- Validating if Motto Text contains the Word ‘Knowledge’
We may use in keyword to validate if a String contains any Substring (Line41)
Now to run our tests, we need to configure pytest as our default test runner (for details please refer https://www.jetbrains.com/help/pycharm/pytest.html ).
We can run pytest in either of the two ways described below.
- Open a terminal in pycharm and run at command prompt (>pytest test_Question_02.py )
- Right click on test_Question_02.py file on left panel, and Run ‘PyTest ……….’ As shown below
We have gone through step-by-step process to automate the Question2 of the Mock Exam 1 for CPSAT-Python through selenium automation for Chrome Browser using pytest in python.
The complete python file may be referred at below link