Q:

Pytest Fizzbuzz code

I have this fizzbuzz code but as a pytest beginner I'm struggling to work out how to test it:
def fizzbuzz(nn): 
    for num in range(1,nn+1):
        if num % 3 == 0 and num % 5 == 0:
            print "FizzBuzz"
        elif num % 3 == 0:
            print "Fizz"
        elif num % 5 == 0:
            print "Buzz"
        else:
            print  num

I want to test the fizzbuzz(3) =='Fizz' and fizzbuzz(7)== 7
Please help me.
Thanks

A:

In general, testing is a lot easier if you consider how to test your code while writing it. In this case, you can make testing easier by allowing output to go somewhere other than stdout.
from cStringIO import StringIO
import sys
def fizzbuzz(nn, out=sys.stdout): 
    for num in range(1,nn+1):
        if num % 3 == 0 and num % 5 == 0:
            out.write("FizzBuzz\n")
        elif num % 3 == 0:
            out.write("Fizz\n")
        elif num % 5 == 0:
            out.write("Buzz\n")
        else:
            out.write("{}\n".format(num))

def test_three():
    out = StringIO()
    fizzbuzz(3, out)
    assert out.getvalue() == "1\n2\nFizz\n"

def test_seven():
    out = StringIO()
    fizzbuzz(7, out)
    assert out.getvalue() == "1\n2\nFizz\n4\nBuzz\nFizz\n7\n"

fizzbuzz(3) should not produce only Fizz. If you want to test the output for individual values, now you need to refactor. For example, you might choose to write your code like this:
import sys

def fizzbuzz_num(num, out=sys.stdout): 
    if num % 3 == 0 and num % 5 == 0:
        return "FizzBuzz"
    elif num % 3 == 0:
        return "Fizz"
    elif num % 5 == 0:
        return "Buzz"
    else:
        return str(num)

def fizzbuzz(nn, out=sys.stdout): 
    for num in range(1,nn+1):
        out.write(fizzbuzz_num(num) + "\n")

def test_three():
    assert fizzbuzz_num(3) == "Fizz"

def test_seven():
    assert fizzbuzz_num(7) == "7"

Probably overkill for such a simple chunk of code, but modularization really helps when it comes to testing.

