Ed S Ed S - 4 months ago 21
Python Question

How to make a test class or function for fibonacci with pytest?

def fibR(n):
if n==1 or n==2:
return 1
return fib(n-1)+fib(n-2)
print (fibR(5))


How could I make a test class for fibonnaci, for example?

Answer

I stuck your existing code in a file called fib.py:

def fibR(n):
 if n==1 or n==2:
  return 1
 return fibR(n-1)+fibR(n-2)

In the same directory I created a file called test_fib.py:

import pytest
from fib import fibR

def test_fib_1_equals_1():
    assert fibR(1) == 1

def test_fib_2_equals_1():
    assert fibR(2) == 1

def test_fib_6_equals_8():
    assert fibR(6) == 8

If I run py.test in this directory from the command line, I can automatically check the correctness of fibR using these tests:

collected 3 items 

test_fib.py ...

================= 3 passed in 0.01 seconds ===========