Test-driven development in Python

微信扫一扫,分享到朋友圈

Test-driven development in Python

How do i write a test, to Test for the default behavior (of a method ) of printing a range that we give it? Below is my attempt. Pasted code from my implementation file and the test case file.

class FizzBuzzService:
def print_number(self, num):
    for i in range(num):
        print(i, end=' ')

import unittest
from app.logic import FizzBuzzService

class FizzBuzzServiceTestCases(unittest.TestCase):
    def setUp(self):
    """
    Create an instance of fizz_buzz_service
    """
    self.fizzbuzz = FizzBuzzService()

    def test_it_prints_a_number(self):
    """
    Test for the default behavior of printing the range that we give
    fizz_buzz_service
    """
    number_range = range(10)
    self.assertEqual(self.fizzbuzz.print_number(10), print(*number_range))

For me at least TDD is about finding a good design as much as it’s about testing. As you’ve seen, testing for things like output is hard.

printing like this is known as a side effect – put simply it’s doing something not based solely on the input parameter to the method. My solution would be to make print_number less side effecty, then test it like that. If you need to print it you can write another function higher up that prints, the output of print_number, but contains no meaningful logic other than that, which doesn’t really need testing. Here’s an example with your code changed to not have a side effect (it’s one of several possible alternatives)

class FizzBuzzService:
def print_number(self, num):
    for i in range(num):
        yield i

import unittest

class FizzBuzzServiceTestCases(unittest.TestCase):
    def setUp(self):
    """
    Create an instance of fizz_buzz_service
    """
    self.fizzbuzz = FizzBuzzService()

def test_it_prints_a_number(self):
    """
    Test for the default behavior of printing the range that we give
    fizz_buzz_service
    """
    number_range = range(10)
    output = []
    for x in self.fizzbuzz.print_number(10):
        output.append(x)
    self.assertEqual(range(10), output)

Preparing the fetch instruction in db2

上一篇

CentOS 7.2下MySQL主从复制配置

下一篇

你也可能喜欢

Test-driven development in Python

长按储存图像,分享给朋友