-1

This code keeps reading input until 0 is given. The numbers are put in array l. I want to count the max element.

#main.py
if __name__ == "__main__":

    l = list()

    while True:
        x = int(input())
        if x == 0:
            break
        else:
            l.append(x)

    maxi = max(l)
    count = 0
    for i in range(len(l)):
        if l[i] == maxi:
            count += 1
    print(count)

How to write pytest for this? Actually 2 tests. I want it to be in good TDD manner.

first test case: 1 7 9 0 answer should be 1

2nd test case: 1 3 3 1 0 answer should be 2

for the 1st case:

import pytest


from main import main_function


assert(main_function([1, 7, 9, 0])) == 1

I dont know how to make my test case accept input as in actual function main.py

ERJAN
  • 23,696
  • 23
  • 72
  • 146

1 Answers1

1

The pytest way of testing, and the generally accepted best engineering practice, would be to separate the logic of calculating the count of the max element from the logic of reading input from the command line.

This lets you test count_of_highest_element by passing various lists and asserting on the result. This also lets you re-use the logic elsewhere.

You would need to do additional testing to make sure the function that accepts command line input is behaving correctly. There are existing questions that ask about how to do that correctly.

N.B. I'd suggest reading up on how Pytest is designed to work. Tests are intended to be a collection of properly named functions, and classes, not raw asserts. Note how your test script isn't actually using anything imported from the Pytest module.

sphennings
  • 998
  • 10
  • 22