Python instances Write---Test reports and test suites (multiple py files, multiple use cases within 1 py files)

Source: Internet
Author: User



I. A. py file executes the test case in bulk (a. py file under multiple use cases)



If used directly: Unittest.main (), it is executed in alphabetical order,



The use of Suite.addtest (the class name ("Method name"), which is the order of additions, modifications, and deletions, avoids the processing of the test data after the completion of the use cases, which are dependent on each other, and need to be executed in a specific order.


  def test_modifycategory (self):  ...

    def test_addcategory (self): ...

    def test_delcategory (self):  ...

If __name__== "__main__": #unittest. Main ()    suite=unittest. TestSuite ()    suite.addtest (test_category ("Test_addcategory"))
    Suite.addtest (Test_category ("Test_modifycategory"))
    Suite.addtest (Test_category ("Test_delcategory"))


  


Two. How to generate an HTML test report for a single. py file



(Download the htmltestrunner.py file, put it in the Lib directory of the Python installation package, open idle, enter "Import Htmltestrunner" If the error is not indicated, the import is successful)



1. Display the time in the test Report name: (Introduction of the timing package) now=time.strftime ("%y-%m-%d-%h_%m_%s", Time.localtime (Time.time ()))



Time.time (): Gets the current timestamp



Time.ctime (): Gets the current time of the string



Time.localtime (): The Struct_time form of the current time



Time.strftime ("%y-%m-%d-%h_%m_%s", Time.localtime ()): Gets the time in a particular format, usually with this



2.TestSuite is a container. Add test Cases with addtest ()



3.fielname define the path to save the report and the file name



File is the constructor of the file class, file (name[, mode[, Buffering])



The file () function is used to create a file object that has a name called Open (), which is a built-in function. Take a look at its parameters. Its parameters are passed as a string.



Name is the name of the file. Mode is open, and the optional value is R w a U, which represents read (default) write to add patterns that support various line breaks.



If you open the file in W or a mode, it will be created automatically if the file does not exist.



In addition, when you open a file that already exists in W mode, the contents of the original file are emptied because the first file operation is marked at the beginning of the file, and the write operation will undoubtedly erase the original content.



After the pattern character, you can also add a + B t these two identities, respectively, can be read and write to the file and in binary mode, text mode (the default) to open the file.



Used here is file (filename, ' WB '): Open filename in binary format



4.runner define the test report format,stream definition report to write the binary file, title for the report caption, description for the report description, Runner.run () to run the test case, Note Finally, use Fp.close () to close the file! !



5. Add the Chinese comment for the test case: Add after each test method: U "" "Test Case Chinese description" "Can!!!!!!


If __name__== "__main__": #unittest. Main ()    suite=unittest. TestSuite ()
    Suite.addtest (Test_category ("Test_addcategory"))
    Suite.addtest (Test_category ("Test_modifycategory"))
    Suite.addtest (Test_category ("Test_delcategory"))
    
    Filename= ' c:\\users\\dell\\desktop\\2.a. Py a report\\ ' +now+ "category.html"
    
    
    Runner.run (Suite)
    Fp.close ()


The test report is as follows:






Three. How multiple. py files are executed, how to generate a test report, structure optimization



Test report Optimization Ideas: (1) all test cases (including common login) are placed in the Use Case folder (2) The Py file that executes the use case is listed separately (3) All generated reports are placed under the report folder






The file structure is as follows: Create a new __init__.py file (note Double underline, import all the use cases inside), and put all the test cases together in the Test_case folder






Create a new test_all.py execution file with the following code:


# coding = utf-8

import sys
sys.path.append ("\ test_case")
from test_case import *
import unittest
import HTMLTestRunner
import time

#Note that when using the suite, multiple use cases under a single py file are used (class name ("method name")),
#Import multiple py classes, use (py name.class name)

suite = unittest.TestSuite ()
suite.addTest (unittest.makeSuite (category.test_category))
suite.addTest (unittest.makeSuite (product.test_product))

now = time.strftime ("% Y-% m-% d-% H_% M_% S", time.localtime (time.time ()))
filename = ‘C: \\ Users \\ DELL \\ Desktop \\ Report \\’ + now + "test_all.html"
fp = file (filename, ‘wb’)
runner = HTMLTestRunner.HTMLTestRunner (stream = fp, title = u‘Automated test reports for product management and classification management ’, description = u’Test case results’)
runner.run (suite)
fp.close ()





1. If you do not create a __init__.py file, the py file that the use case executes will not find the package that was introduced, here we are going to popularize what was done during the import of the package:



(1) Create a new, empty module (Class) object



(2) Add the object to the module (class) of SYS (System)



(3) Load the added module, which will now look in the current directory, and then look in the path of Python, and create a reference __init__.py is to identify the folder (directory) where it is a reference module!!!!!



2. Add the path of the module through the Sys.path.append (path) to the program, where the relative path is used: \ Use case folder



3. When you re-add a py file to execute together, you need to change two places:



(1) First need to introduce the PY in the __init__.py file



(2) used in the file (test_all.py) of the use case execution: suite.addtest (unittest.makesuite (py name. Class name)) adds the use case under this file and executes the!!!!!



First step simplification: using arrays for loop


all=[category.test_category,product.test_product]
suite=unittest.TestSuite()
for a in all:
    suite.addTest(a)





The second step simplifies: write the above operations specifically into a py file, calling directly



The third simplification: implement automatically find the use Case folder in the Py file, automatically added to the Addtest, (just import the package in __init__.py), do not have to set up two places each time!!!!!!!



The following ideas are implemented:



Using the Testloader: Test Case loader, you can load multiple test cases and return a test suite



Discover=unittest.defaulttestloader.discover (allcase,pattern= ' start_*.py ', top_level_dir=none) found the specified test module under the specified directory, If it is not in the top level directory, you need to specify.



The implementation code is as follows:


# coding = utf-8

import sys
import unittest
import HTMLTestRunner
import time, os

#Note that when using the suite, multiple use cases under a single py file are used (class name ("method name")),
#Import multiple py classes, use (py name.class name)

allcase = ‘C: \\ Users \\ DELL \\ Desktop \\ test_casea’ #Indicate the path to the folder where the py files to be automatically found are located
def createSuite (): #Generate test suite
    testunit = unittest.TestSuite ()
    #Use discover to find all use cases for test_casea in the use case folder
    discover = unittest.defaultTestLoader.discover (allcase, #Find the folder path
    pattern = ‘start _ *. py’, #The name of the module to be tested, a .py file starting with start
    top_level_dir = None) #The top-level directory of the test module, that is, test cases are not placed in a multi-level directory, set to none

    for suite in discover: #Use for to loop out of the suite and recycle out of the case
        for case in suite:
            testunit.addTests (case)
            print testunit
    return testunit

allcasenames = createSuite ()

now = time.strftime ("% Y-% m-% d-% H_% M_% S", time.localtime (time.time ()))
filename = ‘C: \\ Users \\ DELL \\ Desktop \\ Report \\’ + now + "test_all.html"
fp = file (filename, ‘wb’)

runner = HTMLTestRunner.HTMLTestRunner (stream = fp, title = u‘Automated test reports for product management and classification management ’, description = u’Test case results’)
runner.run (allcasenames) #execute case
fp.close () 





You can see the results of the operation as follows:





Four. Summary of issues



As of now, all the contents of the test report are covered, the following describes the problems encountered in the above process:



1.element not visible: There are two elements of similar structure on a page



WORKAROUND: Use full-path XPath (or forward positioning until you can distinguish between elements 1 and 2)



2. The number of search results is empty, be sure to set the wait before and after clicking the Search button, setting the wait is very important!!!!!



3. There are multiple drop-down boxes selected when adding a product, which causes the next overwrite after the last selection, cannot be clicked,



Workaround: Just start using the Ul/li positioning mode when the second item is not visible due to the point two, the first click after the overlay to the secondary, so this method causes the partial item drop-down to fail to empty!!



Therefore, it is best to use Select (driver.find_element_by_id ("Gender")) for select. Select_by_value ("2"), note import Package
From Selenium.webdriver.support.ui import Select



Here are two drop-down boxes: The drop-down box is divided into two types.



(1) option under Select
From Selenium.webdriver.support.ui import Select
...
# Select by index
Select (driver.find_element_by_id ("Gender")). Select_by_index (1)
# Select with value
Select (driver.find_element_by_id ("Gender")). Select_by_value ("2")
# Choose from the option text
Select (driver.find_element_by_id ("Gender")). Select_by_visible_text ("Male")



Note: Select only works on <select> elements (select is only valid for the <select> tab drop-down menu).



(2) Li under UL
To locate the options in the drop-down menu for non-<select> tags, you need two steps to navigate to the drop-down menu and locate the options.
Locate code (select Master):
# Navigate to the drop-down menu first
Drop_down = Driver.find_element_by_css_selector ("Div#select2_container > UL")
# Select from the options in the drop-down menu
drop_down.find_element_by_id ("Li2_input_2"). Click ()



Note: You can also use this method to locate the drop-down menu for the <select> tag.



4. The build report is empty (Python, when installed, the default encoding is ASCII, and when non-ASCII encoding occurs in the program, Python processing often reports such errors)
Unicodedecodeerror: ' ASCII ' codec can ' t decode byte 0xe5 in position 97:ordinal not in range (128)
Create a new sitecustomize.py in the Python lib\site-packages folder, with the following content:
Python code
# Encoding=utf8
Import Sys
Reload (SYS)
Sys.setdefaultencoding (' UTF8 ')
Now restart the Python interpreter, execute sys.getdefaultencoding (), found that the encoding has been set to UTF8, after multiple restarts, the effect is the same, because the system when the Python boot, the file itself, set the system's default encoding, Without the need to manually add a solution to the code each time, is a solution.



As of now, summarize the idea and file architecture of automated testing:



1. Design test Case: (according to the positive thinking, each use cases must form a complete process, including the browser to execute the case, and then close)



Classification management for a. py file: It contains 4 use cases (search, add, modify, delete), in order to reduce the subsequent processing of the test data (such as the new need to delete), product management and so on, there are two py files.



Optimizations for. py Files:



(1) Login modularity, directly referenced in the Setup method



(2) All common modules are placed in the Setup method until you log in to the page you want to test



2. A total of three folders are required:



Test Case folder: Put all the. Py text, and the py file with the use case starts with start and adds a __init__.py file



Report Execution folder: Use Discover to loop the use case, test Report settings



Test report: A file test report dedicated to daily execution



Python instances Write---Test reports and test suites (multiple py files, multiple use cases within 1 py files)


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.