For driver Development (Behavior-driven DEVELOPMENT,BDD) is an excellent development model. It helps developers develop a good habit of getting a day off the sun, avoiding or even eliminating the "last minute" situation, so it's great to improve the quality of your code. The test structure and design form which is combined with Gherkin grammar make it very easy to read all the members of the team including non-technical staff.
All code must be tested, which means that system artifacts are minimized or even zero on-line. This needs to be matched to the complete test suite, which controls the software behavior as a whole, enabling the inspection and maintenance to be carried out in an orderly fashion. This is the charm of BDD, is not it exciting?
What is BDD?
The concept and theory of BDD is derived from TDD (test-driven development), and the theoretical key to TDD is to write tests before coding. The difference is that in addition to using unit tests for fine-grained testing, the acceptance test (acceptance tests) is used throughout the process. Next we'll take a lettuce test framework to explain.
The BDD process can be summarized briefly as:
- Write a defect acceptance test
- Write a bug unit test
- Make unit tests Pass
- Refactoring
- Make the acceptance test pass
In each function, repeat the above steps if necessary.
BDD in Agile development
In agile development, BDD is a duck's-in-the-box.
If a project's new capabilities and requirements change every two weeks, the team needs to work with fast-paced testing and coding. Acceptance and unit testing in Python can help achieve that goal.
The test is well known for using an English-format "feature" profile that contains tests and individual tests. The benefit is that the entire project team is involved, with the exception of developers and non-technical members who are not involved in the actual testing process, such as managers and business analysts.
Feature files are written in accordance with the full-readable rules, enabling both technical and non-technical members to be clearly understood and received. If only unit tests are included, there is a risk that demand analysis may not be comprehensive or that consensus will not be reached. The greatest advantage of acceptance testing is the applicability, regardless of the size of the project can be freely.
Gherkin syntax
Typically, Gherkin is used to write the acceptance test, gherkin from the cucumber Framework, written by the Ruby language. The Gherkin syntax is simple, and the following 8 points are used primarily in lettuce Python to define features and tests:
- Given hypothesis
- When time
- Then next
- And and
- Feature Features:
- Background background:
- Scenario Outline Occasion Outline:
Installation
Use the Python common PIP install statement to complete the installation of the lettuce package:
$ pip Install lettuce
$ lettuce/path/to/example.feature is used to run tests. You can run only one test file at a time, or submit a directory name to run all the files in the directory.
To make testing easier to write and use, we recommend that you install the nosetests as well:
$ pip Install nose
Properties file
The feature file is written in English and the content is the scope of the program covered by the test. It also includes a test creation task. In other words, in addition to writing tests, you have to regulate yourself to write good documentation on every aspect of the program. The advantage of doing this is to make yourself aware of the code and what to do next. As the size of the project expands, the importance of the document becomes apparent, such as reviewing a feature or backtracking on a calling API.
Next, you will create an attribute file in conjunction with one of the instances in TDD. This example is a simple calculator written by Python, and it shows the basic wording of the acceptance test. The recommendation for directory composition is to create two folders, one for the app to place code files such as calculator.py, and the other for tests to place the attributes folder.
Calculator.py:class Calculator (object): def add (self, x, y): number_types = (int, long, float, complex) if I Sinstance (x, Number_types) and Isinstance (Y, number_types): return x + y else: raise ValueError
Feature file Calculator.feature in the Tests/features directory
Feature:as a writer for NetTuts I wish to demonstrate how easy writing acceptance Tests in Python really are. Background: Given I am using the calculator scenario:calculate 2 plus 2 on our calculator Given I input "2" a DD "2" then I should see "4"
It is not difficult to see from this example that the description of the characteristic file is very straightforward and can be understood by all the members.
Three highlights of the feature file:
- Feature Block (feature block): This section describes the program content covered by the test group. No code is executed here, but it allows the reader to understand what feature tests are going on.
- Background Block (background block): Executes before each scene (Scenario) chunk in the feature file. This is similar to how the Setup () method is used to write code for creation, such as condition and location authoring.
- Scenario block (scene block): This is used to define the test. The first line is used as a description of the document again, followed by the specific content of the test. Isn't it easy to write tests in this style?
Step (Steps) file
In addition to the feature file, the step file is also required, which is "the moment to Witness miracles". Obviously, the feature file itself will not produce any results; it requires the step file to execute the code one by one mapping with Python in turn for the final result output. The regular expression is applied here.
Regular expressions? Wouldn't it be too complicated? In fact, in the BDD world, regular expressions are often used to catch entire strings or fetch variables from a row. So practice makes perfect.
Regular expressions? Isn't it too complicated to use in tests? In the lettuce is not, but is very simple.
The following is the preparation of the corresponding step file:
From lettuce import *from nose.tools import assert_equalsfrom app.calculator Import calculator @step (U ' I am using the Calculator ') def select_calc (step): print (' Attempting to use calculator ... ') World.calc = calculator () @ Step (U ' I input "([^"]*) "Add" ([^ "]*)" ') def given_i_input_group1_add_group1 (step, x, y): World.result = World.calc.add (int (x), int (y)) @step (U ' I should see "([^"]+) "') def result (step, Expected_result): Actual_ result = World.result assert_equals (int (expected_result), Actual_result)
The first part of the file is the standard import notation. For example, the calculator access and import of the Lettuce tool, as well as the import of Assert_equals assertion method in the Nosetest package. Next, you can begin to define the steps for each line of the feature file. As mentioned earlier, regular expressions are often used to extract the entire string, except that it is sometimes necessary to access the variable in a row.
In this example, the @step plays the role of decoding and extracting, and the U-letter means performing the expression in Unicode encoding. This is followed by using regular expressions to match the referenced content, which is the number to add.
The variable name is then passed to the Python method, which can be arbitrarily defined, using X and Y as the passed-in variable name for the Calculator Add method.
It is also necessary to introduce the use of the world variable. World is a global container that allows variables to be used in different steps of the same scene. Otherwise, all variables correspond only to the method in which they are available. For example, the result of the Add method is stored in a step, and the result is determined by a step outside the other.
Execution of attributes
After both the feature file and the step file are complete, you can then run the test to see if it can be passed. The lettuce execution method of the built-in Test runner is very simple, for example
Lettuce test/features/calculator.feature: $ lettuce tests/features/calculator.feature Feature:as a writer for NetTuts # Tests/features/calculator.feature:1 I wish to demonstrate # Tests/features/calculator.feature:2 how Easy Writing acceptance Tests # Tests/features/calculator.feature:3 in Python really are. # tests/features/calculator.feature:4 Background: Given I am using the calculator # tests/features/ Steps.py:6 Given I am using the calculator # tests/features/steps.py:6 scenario:calculate 2 plus 2 on our CA Lculator # tests/features/calculator.feature:9 Given I Input "2" Add "2" # tests/features/steps.py:11 Then I should see "4" # tests/features/steps.py:16 1 feature (1 passed) 1 scenario (1 passed) 2 steps (2 passed)
The output of the lettuce is very neat, it clearly shows which line of the character file code is executed, and then the successfully executed row is highlighted in green. It also shows the running attribute file and the line number, which is helpful for finding the feature file defect line when the test fails. The end of the output is an attribute, a scene, the number of steps performed, and a summary of the number of results. All the tests in this example have passed. But what would lettuce do if there was an error?
First you have to modify the calculator.py code to change the Add method to two-digit subtraction:
Class Calculator (object): def add (self, x, y): number_types = (int, long, float, complex) if Isinstance (x, Nu Mber_types) and Isinstance (Y, number_types): return x-y else: raise ValueError
Run again and see how lettuce is explaining the error:
$ lettuce Tests/features/calculator.feature Feature:as a writer for NetTuts # tests/features/calculator.feature: 1 I wish to demonstrate # Tests/features/calculator.feature:2 what easy writing acceptance tests # tests/ Features/calculator.feature:3 in Python really is. # tests/features/calculator.feature:4 Background:given I am using the calculator # Tests/features/steps.py:6 Giv En I am using the calculator # Tests/features/steps.py:6 Scenario:calculate 2 plus 2 on our calculator # TESTS/FEA Tures/calculator.feature:9 Given I input "2" Add "2" # Tests/features/steps.py:11 then I should see "4" # tests/features/steps.py:16 Traceback (most recent): File "/users/user/.virtualenvs/bdd-in-python/lib/py thon2.7/site-packages/lettuce/core.py ", line 144, in __call__ ret = self.function (Self.step, *args, **kw) File"/User s/user/documents/articles-nettuts/bdd_in_python/tests/features/steps.py ", line 18, in result assert_equals (int (expected_result), Actual_result) File "/system/library/frameworks/python.framework/ve rsions/2.7/lib/python2.7/unittest/case.py ", line 515, in Assertequal Assertion_func (first, second, msg=msg) File"/Sy stem/library/frameworks/python.framework/versions/2.7/lib/python2.7/unittest/case.py ", line 508, in _ Baseassertequal raise Self.failureexception (msg) Assertionerror:4! = 0 1 feature (0 passed) 1 scenario (0 passed) 2 Ste PS (1 failed, 1 passed) List of failed Scenarios:Scenario:Calculate 2 plus 2 on our calculator # Tests/features/calculat Or.feature:9
Obviously, the actual result 0 is inconsistent with the expected result of 4. Lettuce clearly shows the problem, and then it's time to debug the error until it passes.
Other tools
There are a number of different tools for similar testing in Python, which are basically derived from cucumber. For example:
- Behave: This is a cucumber interface. Documentation is complete, keep up to date, there are a lot of supporting tools.
- Freshen: Another cucumber interface, the companion website has the complete tutorial and the instance, installs the method all is the simple pip way.
No matter what tool to use, as long as the use of a tool proficiency, other natural can digest. Being familiar with the tutorial documentation is the first step to success.
Advantages
Code refactoring with confidence
The advantages of using a complete test suite are obvious. Finding a powerful test suite will allow you to refactor your code with less effort and confidence.
As the scale of the project grows, the lack of effective tools can make backtracking and refactoring difficult. If a complete set of acceptance tests corresponds to each feature one by one, the changes will be made in an orderly and non-turbulent manner without damaging the existing functional modules.
All the people can participate in the test, will be able to greatly improve the team combat effectiveness, the first to move towards the same goal. Programmers can devote their energies to precise goals, avoiding the need to get out of control, and testers can perform one by one review of feature files to achieve the ultimate in testing. Finally, a virtuous cycle is formed that makes every feature of the program perfectly delivered.
Review
In combination with the above process and tools, we have achieved good results in the teams that have worked in the past. The BDD development approach allows the entire team to stay focused, maintain confidence, stay active, and minimize potential errors.