Python Basic Tutorial Summary 14--test

Source: Internet
Author: User

1. Test first, then encode

It is also important to establish tests on the various parts of the program (this is also known as unit testing). Test Drive Programming: Test-driven programming

1) Precise Requirements Description:

The idea of programming is to start by writing a test program and then write a program that can be tested. The test program is your requirement description, which helps you to develop the program without deviating from the requirements
Example: Write a module that includes a function that uses a given width and height to calculate the rectangular area. Before you start coding, you should first write a unit test that includes examples with several clear answers:

1  fromAreaImportRect_area2 3Height = 34Width =45Correct_answer = 126Answer =Rect_area (height, width)7 ifAnswer = =Correct_answer:8     Print 'Test passed'9 Else:Ten     Print 'Test failed'

2) Plan for change:

Automated testing, in addition to giving great help in writing programs, avoids adding errors when implementing modifications

Code Coverage--coverage is an important part of testing knowledge. It is possible to run the test without running all of the code, even in the ideal case (ideally it should be to run all possible states of the program, using all possible inputs, but this is unlikely). One of the goals of an excellent test program group is to have a good coverage, one way to achieve this goal is to use the coverage tool, which measures the percentage of code that actually runs during the test. There is currently no standardized coverage tool available, and searching for "Python test coverage" will find a few tools available. One of them is the trace.py program.

3) 4 Steps of the test:

A: Identify the new features needed. You can record it first, and then write a test for it.
B: Write the feature's profile code so that the program can run without any syntax errors, but the test will fail. It is important to see that the test fails, so that you can determine that the test will fail. If there is an error in the test code, it is possible that the test will succeed regardless of any situation, so that nothing is tested. Again: before trying to make the test successful, you should see it fail
C: Write a dummy code for the profile of the feature (dummy codes), which can meet the test requirements. Do not implement the function accurately, just ensure that the test can be passed. This allows you to always pass the test at development time (except when you run the test for the first time), even when the functionality is initially implemented.
D: Now rewrite (or refactor, refactor) the code so that it does what it should do, so that the test is always refactored
  

2. Test Tools

The modules in the standard library can help us automate the testing process:
Unitest: Universal Testing Framework
Doctest: Simple modules that are used for checking documents, but are also good at writing unit tests

1) Doctest: The session of the interactive interpreter can be a useful form of writing a document string (docstring) to a document. Suppose I write a function that evaluates to the square of a number and adds an example to its document string:

  1  def      3< /span>  squares a number and returns the result.    5   > >> Square (2)   6   4   7   >>> Square (3)   8   9   9   10  return  x*x 

Some text is also included in the document string. What does this have to do with testing? Assume that the square function is defined in the My_math module (that is, a file called my_math.py). You can then add the following code at the bottom:

1 defSquare (x):2     " "3 squares A number and returns the result.4 5 >>> Square (2)6 47 >>> Square (3)8 99     " "Ten     returnx*x One  A if __name__=='__main__': -     ImportDoctest.my_math -Doctest.testmod (My_math)

The Doctest.testmod function reads all the document strings from a module, finds all the text that looks like an example entered in the interactive interpreter, and then checks to see if the example meets the instance requirements (if you want to practice "test first, post code" programming, the UnitTest framework is a better choice)

To get more input, you can set the-V (meaning verbose, verbose) option switch for the script: $ python my_math.py-v

2) UnitTest: Doctest is easy to use, UnitTest (the Java-based popular test framework JUnit) is more flexible and powerful.  

Suppose you want to write a module My_math, which includes a function product that calculates the product. Where do you start? For testing, of course (in file test_my_math.py) is using the TestCase class in the UnitTest module

1 #simple testing using the UnitTest framework2 ImportUnitTest, My_math3 4 classproducttestcase (unittest. TestCase):5 6     deftestintegers (self):7          forXinchRange ( -10,10):8              forYinchRange ( -10,10):9p =my_math.product (x, y)TenSelf.failunless (p = = X*y,'Tnteger multiplication Failed') One  A  -     deftestfloats (self): -          forXinchRange ( -10,10): the              forYinchRange ( -10,10): -x = x/10.0 -y = y/10.0 -p =my_math.product (x, y) +Self.failunless (p = = X*y,'Float multiplication Failed') -  + #The Unittest.main function is responsible for running the test, which instantiates all the testcase subclasses and runs all the methods that begin with the name Test A if __name__=='__main__': Unitteset.main ()

If you define a method called Startup and teardown, they will be executed before and after each test method run, so that you can use these methods to provide general initialization and cleanup code for all tests, which is called a testing fixture (test fixture)

3: Something other than unit testing:
Source code Inspection and analysis: Source code checking is a way to look for common errors or problems in your code (a bit like the compiler handles static languages, but it's far worse). Analysis is the way to find out how fast the program runs. The subject of this chapter is discussed in this order because the golden rule "makes it work, make it better and make it faster". Unit tests allow the program to work, source code checks can make the program better, and finally, the analysis will make the program faster.

1) Use Pychecker and pylint to check the source code

2) Analysis: Before trying to get the code to speed up, there is a very important rule to note (and the KISS principle, Keep it Small and simple, which makes it small and easy, or Yagni principle, you Ain ' t gonna need it, that does not need it)-- Immature optimization is the source of all evil.
Ken Thompson, one of the inventors of Unix, said, "When in doubt, be poor." In other words, don't worry too much about clever algorithms or beautiful optimization techniques if you don't need them in particular. If the program is fast enough, the value of clean, simple, and understandable code is much higher than a slightly faster program.

If it has to be optimized, then it should definitely be analyzed before doing anything else. This is because it is difficult to estimate where the bottleneck is, unless your program is very simple. The standard library already contains an analysis module called profile (there is also a faster embedded C language version called Hotshot). Using the parser is very simple, so it's OK to call its Run method with a string argument.

>>> Import profile>>> from My_math import product>>> profile.run (' product (+) ')

This prints out information, including the number of functions and method calls, and the time spent on each function. If you provide a file name, such as ' My_math.profile ' to run as the second argument, the result is saved to the file. You can then use the Pastats module to check the results of the analysis:

>>> import pstats>>> p = pstats. Stats (' My_math.profile ')

The standard library also contains a module named Timeit, which is an easy way to test the run time of a python small code segment

Python Basic Tutorial Summary 14--test

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.