停留在模拟输入上

问题描述 投票:0回答:1

所以,我正在尝试编写一个罗马数字转换器。以前从未使用过单元测试,但是到目前为止,这是我所拥有的。我只是想测试“ DLXII”的值为562。它仅在主程序中运行。但是,每次我尝试使用(python -m unittest test_roman_numerals)进行测试时,它只会运行该程序,并且我必须输入“ DLXII”进行测试,除非这是测试的工作方式。我试图使测试功能自动为我做。谢谢。

roman_numerals.py

class RomanNumeral: 
"""A class to represent our roman numerals or integers."""
def __init__(self, number): 
    """Initializes the user's input, a counter, and standard values for each roman numeral."""
    self.number = number
    self.int_num = 0 # counter
    self.rom_dict = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000} 

def roman_to_int(self): # Probably better to use a linked list here.
    """Takes in user_input in roman numerals and return the equivalent integer."""
    rom_values = list(self.rom_dict.items())
    for i in range(len(self.number) - 1): 
        for j in range(len(rom_values)): 
            if self.number[i] == rom_values[j][0]: 
                self.int_num += rom_values[j][1] 
                for k in range(j+1, len(rom_values)):
                    if self.number[i+1] == rom_values[k][0]:
                        self.int_num -= 2*rom_values[j][1] 
    for l in range(len(rom_values)):
        if self.number[-1] == rom_values[l][0]:
            self.int_num += rom_values[l][1]  
    return self.int_num 

def isroman(self):
    """Checks if user input is a roman numeral."""
    for i in self.number:
            if i not in self.rom_dict.keys():
                return False
    return True

def roman_or_int(self):
    """Checks if user input is a roman numeral, integer, or not."""
    if self.IXC_triple_rules() is True:
        return False
    elif self.isroman():
        print(self.roman_to_int())
    elif self.number.isdigit():
        print("number")
    else:
        print("Entry is neither roman numerals or integers.")

def IXC_triple_rules(self):
    """Tag if user input has more than 3 I, X, or C."""
    if "IIII" in self.number or "XXXX" in self.number or "CCCC" in self.number:
        print("You cannot have more than three I, X, or Cs in a row")
        return True

def non_subtractive_numberals(self):
    """Tag for V, L, and D. Can never be subtracted."""

user_input = input("Enter a number in roman numerals: ")
x = RomanNumeral(user_input)
x.roman_or_int()

test_roman_numerals.py

import unittest
from unittest.mock import patch

from roman_numerals import RomanNumeral

class TestRomanNumerals(unittest.TestCase): #sublcass of test case class
    """A test class for our Roman numerals."""

    @patch('builtins.input', return_value="DLXII")
    def test_roman_to_int(self, mock_input):
        result = RomanNumeral("DLXII").roman_to_int()
        self.assertEqual(result, 562)
python mocking python-unittest roman-numerals
1个回答
0
投票

[您需要将顶级代码放在__main__块下,否则每次导入文件(包括在测试中)将被执行:

if __name__ == '__main__':
    user_input = input("Enter a number in roman numerals: ")
    x = RomanNumeral(user_input)
    x.roman_or_int()
© www.soinside.com 2019 - 2024. All rights reserved.