DOCX

Based on the Python behavior driven development of actual combat!

By Tony Reynolds,2015-08-07 07:58
17 views 0
Based on the Python behavior driven development of actual combat!

    Based on the Python behavior driven development of

    actual combat

    Behavior Driven Development (behaviors - Driven Development, BDD) is a kind of excellent Development mode.Can help developers to form the good habit of nissin daily, to avoid even put an end to "last minute", thus is helpful to improve the quality of the code.With the combination of Gherkin grammar test structure and the design of form, makes to all team members including non-technical has extremely good legibility.

    All code must be tested, which means that when the system is to minimize the defect or even to zero.This needs to be as suitable as a complete test suite, from the overall control software behavior, makes the detection and maintenance can be orderly.This is the charm of BDD, don't move?

    BDD is what?

    The concept and theory of BDD derived from TDD (test driven development), similar to the theory of TDD point is in the code written before test.Difference is in addition to use unit tests for fine granular test, also use tested (acceptance tests) through the beginning and end of the program.Next we will combineLettuceThe test framework to explain.

    BDD process can be simply summarized as follows:

    ; Write a defect acceptance testing

    ; One drawback write unit tests

    ; The unit tests pass

    ; refactoring

    ; To accept the test pass

    In each function, repeat the above steps if necessary.

    BDD in agile development

    In agile development, BDD is more like a duck to water.

    If the project is a new function and new requirement is changed every one or two weeks, so the team needs to cooperate to the fast pace of testing and coding.In Python accept and unit tests can help achieve the goal.

    Tested familiar is to use an English "feature description file format, content is containing test and individual tests.The advantage is that the entire project team involved, in addition to the developers, and managers and business analysts are not unskilled members involved in the actual testing process.

    Properties file write to follow the rules of full readable, clear the technical and non-technical members can understand and receive.If only contains unit tests, is likely to result in demand analysis is not comprehensive or reach a consensus.Acceptance testing is one of the biggest advantages applicability, regardless of project size can with ease.

    Gherkin grammar

    Gherkin is usually used to write acceptance tests, Gherkin fromCucumber frameWritten by the Ruby language.Gherkin grammar is very simple, mainly in the Lettuce Python USES the following definition of 8 PM for features and testing:

    ; Given assumptions

    ; When the time

    ; Then the next step

    ; And with the

    ; Feature:

    ; Background Background:

    ; The Scenario Outline of the Outline occasions:

    The installation

    Using the Python commonly used PIP install statement the Lettuce package installation can be completed:

    $ pip install lettuce

    $lettuce/path/to/example. The feature is used to run the tests.Every time can only run the test file, or submit a directory name to run all the files in the directory.

    In order to make it easier to test writing and use, we recommend to install the nosetests as well:

    $ pip install nose

    Properties file

    Properties files are written in English, content is covered with test program.Test creation are also included in this task.In other words, in addition to the need to write a test, you have to regulate all aspects of yourself program write good documentation.The advantage is to make yourself up and down all the code, clear what to do next.With the expansion of the project, the importance of the document will gradually appear;Such as review a function or to back a call API, and so on.

    Then combining with an instance of TDD create a properties file.The instance is a simple calculator are written in Python, and demonstrates the basic written acceptance testing.Directory of advice is to create two folders, one is the app, used to place code files such as calculator. Py;Another is tests used to place features folder.

    calculator.py

    class Calculator(object):

     def add(self, x, y):

     number_types = (int, long, float, complex)

     if isinstance(x, number_types) and isinstance(y, number_types):

     return x + y

     else:

     raise ValueError

    Tests/the features properties files in the directory calculator. The feature Feature: As a writer for NetTuts

     I wish to demonstrate

     How easy writing Acceptance Tests

     In Python really is.

     Background:

     Given I am using the calculator

     Scenario: Calculate 2 plus 2 on our calculator

     Given I input "2" add "2"

     Then I should see "4"

    From the example it is not hard to see the description of the properties file is very straightforward, can make all the members can see.

    Properties file three main points:

    ; Feature block characteristics (block) : it describes the test groups covered by the content of the

    program.Here does not perform any code, but can make the reader understand what was going on

    the characteristics of the test.

    ; Background block (block) : before the properties file each Scenario (Scenario) block is carried

    out.This is similar to the SetUp () method is used for the preparation of the create code, such as the

    preparation of the condition and location.

    ; Scenario block (Scenario block) : used to define the test here.The first line is used as the document

    again, then is the specific content of the test.In this style isn't writing test is very simple?

    Steps (Steps) files

    In addition to the properties file, also must step file, this is the "witness a miracle moment".Apparently, properties file itself does not make any results;It needs to step file in turn with the Python code execution one-to-one mapping is the final result of the output.Application of here is a regular expression.

    Regular expression?Not be too complicated?In fact in the world of BDD, regular expressions are often used to capture the entire string or from one line to grab a variable.So practice makes perfect.

    Regular expression?In the test is not too complicated to use?Is not in Lettuce, it is very simple.

    The writing of the following are the steps the corresponding files:

    from lettuce import *

    from nose.tools import assert_equals

    from 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)

    File the first part is the import standard way.Such as access to the Calculator and Lettuce tools import, and nosetest package assert_equals concluded that the method of import.Next, you can start the properties file for the step definition for each row.As mentioned earlier, the regular expression often used to extract the entire string, but sometimes need in a line on a visit to a variable.

    @ step in this case, have the effect of decoding extraction;U letters mean in unicode way expression is carried out.Then is to use regular expressions to match the content of the reference, here is the number of additive.

    Then is the Python method was introduced into variables, variable names can be arbitrary definition, here use x and y as the calculator the add method was introduced into the variable name.

    Also need to explain the use of the world variable.World is a global container, making the variables can be used in different steps of the same scene.Otherwise, all variables corresponding to the only method available.For example the add method of the operation result stored in one step, in another outside a step to conclude that the results of.

    Characteristics of execution

    Properties files and steps are completed, you can run the test to see whether through.Built-in Lettuce execution way to test run the machine is very simple, such as 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 is. # 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 calculator # 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 the characteristic documents which line code is executed, then the successful execution of the show with highlight green line.In addition also shows the running properties file and line number, the defect in the properties file for the test failure line search is very helpful.Is at the end of the output characteristics of the scene, the execution of the steps the number as well as by the results of the number of summary.In this case, all test passed.But if an error occurs, how to deal with the Lettuce?

    First the calculator. Py code modifications, changed the add method to two Numbers subtraction:

    class Calculator(object):

     def add(self, x, y):

     number_types = (int, long, float, complex)

     if isinstance(x, number_types) and isinstance(y, number_types):

     return x - y

     else:

     raise ValueError

    To run again, look at how Lettuce to show 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

     How 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

     Given I am using the calculator # tests/features/steps.py:6

     Scenario: Calculate 2 plus 2 on our calculator # 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

     Traceback (most recent call last):

     File

    "/Users/user/.virtualenvs/bdd-in-python/lib/python2.7/site-packages/lettuce/core.py", line 144, in __call__

     ret = self.function(self.step, *args, **kw)

     File "/Users/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/Versions/2.7/lib/python2.7/unittest/case.py", line 515, in assertEqual

     assertion_func(first, second, msg=msg)

     File

    "/System/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 steps (1 failed, 1 passed)

    List of failed scenarios:

     Scenario: Calculate 2 plus 2 on our calculator # tests/features/calculator.feature:9

    Obviously, the actual result 0 4 is inconsistent with expected results.Lettuce clearly shows the problem, the next step is to debug row until by the time wrong.

    Other tools

    In Python also offers many different tools to carry out similar tests, these tools are basic derived from Cucumber.Such as:

    ; Behave: this is a Cucumber interface.Supporting documents are complete, keep update, there are

    quite a fewForm a complete set of tools

    ; Freshen: another Cucumber interface, form a complete set of site has a complete tutorial and

    examples, the installation method is a simple way of PIP.

    No matter what tools to use, just for a tool using the skilled, other natural can achieve mastery through a comprehensive study.Perusal of tutorial document is the first step to success.

    advantages

    Confidently for code refactoring

    The advantages of using a complete test suite is obvious.Find a powerful test suite, can let a code refactoring work get twice the result with half the effort, with confidence.

    With the continuous expansion of the project, if the lack of effective tools, this will bring back and refactoring work difficult.If a complete set of acceptance tests to correspond with each features, then will be able to make changes to work orderly don't crawl, won't cause damage to the existing functional modules.

    Employee can participate as tested, will greatly enhance the combat effectiveness, team working towards the same goal from the start.Programmers can concentrate on accurate target, avoid demand range of spirals out of control.Testers can properties file for review, the test perfectly.Finally a virtuous circle, make each features perfect delivery of the program.

Report this document

For any questions or suggestions please email
cust-service@docsford.com