Testing functions using pytest in a separate python file doesn’t work and instead calls the main function of the main file

I am trying to simply test an ASCII art program that is used to convert from RLE to ASCII art, and vice versa. However, unlike in other cases, when I run the test file, it for some reasons runs the main function of the actual file, and not the main function of the test file.

Here is my project.py code:

def main():
    while True:
        print("Please choose one of the following: (Type the number to choose)")
        print("[1] Enter RLE")
        print("[2] Display ASCII art")
        print("[3] Convert to ASCII art")
        print("[4] Convert to RLE")
        print("[5] Quit")

        option = input("Enter number: ")

        if option == "1":
            enterRLE()
        elif option == "2":
            displayASCIIart()
        elif option == "3":
            converttoASCIIart()
        elif option == "4":
            converttoRLE()
        elif option == "5":
            print("Program quit successfully.")
            break
        else:
            print("Invalid option. Please choose a valid option.")


def enterRLE():
    lines = int(input("How many lines do you want to enter? "))

    while lines <= 2:
        print("You must enter more than 2 lines. Please try again.")
        lines = int(input("How many lines do you want to enter? "))

    list1 = []
    for _ in range(lines):
        data = input("Enter one line at a time: ")
        list1.append(data)

    for word in list1:
        decompressed_data = ""
        j = 0
        while j < len(word):
            number = int(word[j] + word[j+1])
            char = word[j + 2]
            decompressed_data += char * number
            j += 3
        print(decompressed_data)


def displayASCIIart():
    filename = input("Enter name of file which contains ASCII art: ")
    with open(filename, "r") as f:
        contents = f.read()
        print(contents)


def converttoASCIIart():
    filename = input("Enter name of file that contains RLE compressed data: ")
    with open(filename, "r") as f:
        for line in f:
            word = line.strip()
            decompressed_data = ""
            i = 0
            while i < len(word):
                if word[i:i+2].isdigit() and len(word[i:]) >= 3:
                    number = int(word[i] + word[i+1])
                    char = word[i + 2]
                    decompressed_data += char * number
                    i += 3
                else:
                    decompressed_data += word[i]
                    i += 1
            print(decompressed_data)


def converttoRLE():
    filename = input("Enter name of file that contains ASCII art: ")

    uncompressed_length = 0
    compressed_length = 0

    with open(filename, "r") as reader:
        with open("RLE.txt", "w") as writing:
            for line in reader:
                uncompressed_length += len(line.strip())

                compressed_line = ""
                i = 0
                while i < len(line):
                    count = 1
                    while i + 1 < len(line) and line[i] == line[i + 1]:
                        i += 1
                        count += 1
                    if count < 10:
                        compressed_line += "0" + str(count) + line[i]
                    else:
                        compressed_line += str(count) + line[i]
                    i += 1

                compressed_length += len(compressed_line)

                writing.write(compressed_line + "\n")

    difference = uncompressed_length - compressed_length
    print("Difference is " + str(abs(difference)))

main()

This is my test_project.py code:

from project import enterRLE, converttoASCIIart, converttoRLE
import pytest

def main():
    test_enterRLE()
    test_converttoASCIIart()
    test_converttoRLE()


def test_enterRLE(monkeypatch):
    monkeypatch.setattr('builtins.input', lambda _: "3\n3\n4\n2A2B3C\n")
    assert enterRLE() == "AABBBCCC\n"

def test_converttoASCIIart(monkeypatch):
    monkeypatch.setattr('builtins.input', lambda _: "compressed_data\n")
    assert converttoASCIIart() == "AAABBBCCC\n"

def test_converttoRLE(monkeypatch):
    monkeypatch.setattr('builtins.input', lambda _: "ascii_art\n")
    assert converttoRLE() == "03A\n02B\n03C\n"

if __name__ == "__main__":
    main()

Now, when I run the test file, it’s as if I am running the main file; my ASCII menu simply shows up.

What I want to happen is for simply for nothing to happen if everything is correct, and for an error to show up if one of the assert statements is false. This is how I always usually use pytest to test my files.

  • 2

    you import project. And in project.py, you unconditionally run main(). If you don’t want that to happen, don’t run main(), or perhaps, put it behind an if __name__ == "__main__":... guard, which you curiously put in the test file but not the actual project.py

    – 

Leave a Comment