TTD in Expert Python programming

Source: Internet
Author: User
Tags integer division

Test-driven Development Principles
TDD consists of writing test cases that cover a desired feature and then writing thefeature itself. In other words, the usage examples is written before the codeeven exists.
For example, a developer who's asked to write a function that provides the averagevalue of a sequence of numbers would first write a few examples on how to use it, and
The expected results:
assert Average (1, 2, 3) = = 2
assert average (1,-3) = =-1
These examples can be provided by another person as well. From there, the functioncan is implemented until the examples work:
>>> def average (*numbers):
... ..return sum (Numbers)/len (numbers)
...
>>> assert Average (1, 2, 3) = = 2
>>> assert average (1,-3) = =-1
a bug or an unexpected result was A new example of usage the function should be ableTo deal with:
>>> assert Average (0, 1) = = 0.5
Traceback (most recent):
File "<stdin>", line 1, in <module>
Assertionerror
the code can be changed accordingly, until the new test passes:
>>> def average (*numbers):
... ..# makes sure all numbers can be used as floats
... ..numbers = [Float (number) for number in numbers]
... ..return sum (numbers)/float (len (numbers))
...
>>> assert Average (0, 1) = = 0.5
And more cases'll make the code evolve:
>>> Try:
... ..average ()
... except TypeError:
... ..# We want an empty sequence to throw a type error
... ..Pass
...
Traceback (most recent):
File "<stdin>", line 2, in <module>
File "<stdin>", line 3, in average
Zerodivisionerror:integer division or modulo by zero
>>>
>>> def average (*numbers):
... ..if numbers = = ():
... ..Raise TypeError (' You need-provide at '
... ..' least one number ')
... ..numbers = [Float (number) for number in numbers]
... ..return sum (Numbers)/len (numbers)
...
>>> Try:

... ..average ()
... except TypeError:
... ..Pass
...
From there all tests can being gathered in a test function, which is run
every time the code evolves:
>>> def test_average ():
... ..assert Average (1, 2, 3) = = 2
... ..assert average (1,-3) = =-1
...assert Average (0, 1) = = 0.5
...Try:
...average ()
...except TypeError:
...Pass
...
>>> test_average ()
every time a change is made, test_average are changed together with average,Then run again to make sure all cases still work. The usage is to gather all tests inThe tests folder of the current package . Each module can has a corresponding testmodule there.This approach provides a lot of benefits by:
preventing software regression
Improving code quality
providing the best low-level documentation
producing robust code faster


Preventing software Regression
We all face software regression issues in our developer lives. Software regression is anew bug introduced by a. Regressions happen because of the simple factIt is impossible-some point-to-guess what- a-codebase might leadTo . Changing some code might break some other features, and sometimes leads tovicious side effects, such as silently corrupting data.
to avoid regression, the whole set of features software provides should is testedevery time a change occurs.
Opening A codebase to several developers amplifies the problem, sinceWon't is fully aware of all development activities. While have a version controlsystem prevents conflicts, it does not prevent all unwanted interactions.
TDD helps reduce software regression. The whole software can be automaticallytested. this would work as long as each feature have the proper set of
tests. When TDD was properly done, the test base grows together with the codebase. Since a full test campaign can last for quite a long time, it's a good practice todelegate it to a buildbot, which can does the work of the background ( this is describedIn Chapter 8). But local re-launching of the tests should is done manually by theuser, at least for the concerned modules.
Improving Code quality
When a new module, class, or a function are written, a developer focuses on how toWrite it and how to produce the best piece of code he or she can. But while he or she
is concentrating on algorithms, he or she might lose the user's point of View:howAnd when would his or she function be used? is the arguments easy and logical toUse ? is the name of the API right?
This is do by applying the tips described in the previous chapters, such aschoosing Good Names. but the only-to-do it efficiently are to write usageexamples. The developer realizes if the code he or she wrote is logicaland easy to use . Often, the first refactoring occurs right after the module, class, orfunction is finished.
Writing tests, which is use cases for the code, helps in has this user point ofview.  Developers would, therefore, often produce a better code when they use TDD. It is difficult to test gigantic functions this both calculate things as well as has sideeffects. Code that's written with testing-in-mind tends-be-architected more cleanly
and modularly.
providing the best Developer documentation
Tests is the best place for a developer to learn how software works. They is the usecases The code is primarily created for. Reading them provides a quick and deep
insight into how the code works. Sometimes, an example is worth a thousand words. The fact that these tests is always up to date with the codebase makes them the best
Developer documentation A piece of software can have. Tests don ' t go stale in thesame-documentation does, otherwise they would fail.
producing robust Code Faster
Writing without tests leads to extensive debugging sessions. A Bug in one part of thesoftware might is felt in a distant part of the that software. Since you don ' t know
blame, spend an inordinate amount of time debugging. It ' s better to fight smallBugs one at a time if a test fails, because you'll have a better clue as to where the
real problem is. and testing is often and the debugging because it is coding.
If You measure the time taken to fix the code together with the time taken to writeit, it'll usually is longer than the time a TDD approach would take. this isn'tobvious when you start a new piece of code. this was because the time taken to set uptest environment and write the first few tests is extremely long compared to theTime taken just to write the first pieces of code.
But there is some test environments that is really hard-to-set up. For instance,When your code interacts with a LDAP or an SQL Server, writing tests are notobvious at all. this are covered in the Fakes and Mocks sections in this chapter.




TTD in Expert Python programming

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.