3.4. Step - 04 : Add implementation and pass¶
Let’s add steps so that addition is successful..
libmath.py
The actual implementation.
# libmath.py class libMath(object): def __init__(self): self.num1 = 0 self.num2 = 0 self.value = 0 def doStoreNum1Num2(self, num1, num2): self.num1 = num1 self.num2 = num2 def doAdd(self): self.value = self.num1 + self.num2 def getValue(self): return self.value
features/simple-addition.feature
remains as is.# features/sample-addition.feature Feature: Simple Addition Showcase simple addition for the BDD Book. Scenario: Addition of single digit numbers Given I have '1' and '3' When I add them Then The result must be '4' Scenario: Addition of double digit numbers Given I have '70' and '29' When I add them Then The result must be '99'
features/environment.py
Let’s add a hook to create a new libMath object before each scenario.
# environment.py import libmath def before_scenario(context, scenario): """ Let's start with a new clean object before every test. """ context.math = libmath.libMath()
features/steps/steps_addition.py
Calls the actual libMath for the expected behaviour
# features/steps/steps_addition.py from behave import given, when, then @given(u"I have '{num1:d}' and '{num2:d}'") def given_i_have(context, num1, num2): context.math.doStoreNum1Num2(num1, num2) @when(u"I add them") def when_i_add(context): context.math.doAdd() @then(u"The result must be '{value:d}'") def then_the_result_must_be(context, value): actual_value = context.math.getValue() assert value == actual_value, "Expected %d got %d"%(value, actual_value)
With above contents, if we run behave:
behave --no-timings --no-source
We can see that everything is successful:
Feature: Simple Addition
Showcase simple addition for the BDD Book.
Scenario: Addition of single digit numbers
Given I have '1' and '3'
When I add them
Then The result must be '4'
Scenario: Addition of double digit numbers
Given I have '70' and '29'
When I add them
Then The result must be '99'
1 feature passed, 0 failed, 0 skipped
2 scenarios passed, 0 failed, 0 skipped
6 steps passed, 0 failed, 0 skipped, 0 undefined
Took 0m0.001s