lundi 3 août 2020

Python: None and Try Except

I am making a test harness for a budget program. The individual purchases are represented with the Item class. If the class is initialized incorrectly, I want to return None. However, when I run my test harness, it doesn't detect the variable as being None. Why is the test harness not detecting the Item as None?

def __init__(self, nameItem, costItem):

    try: 

        if costItem < 0.00 or type(nameItem) is not str:
            self = None
        else:

            if len(nameItem) < 1:
                self = None
            else:
                self.name = nameItem
                self.cost = round(costItem,2)

                if self.name == None or self.cost == None:
                    self = None
    except:
        self = None
#Test Case

currentTest = currentTest + 1
    print("Test" ,currentTest,":Create invalid item using negative cost.")
    try:
        testItem = Item("Coffee",-1.00)
        if testItem is None:
            print("Made None value when given incorrect data:TEST PASSED")
            passTests = passTests + 1
        else:
            raise TypeError
    except TypeError:
        print("Error when creating item, created item instead of detecing error:TEST FAILED")
        failedTests.insert(failedCount,currentTest)
        failedCount = failedCount + 1
    except:
        print("Error when conducting test:TEST FAILED")
        failedTests.insert(failedCount,currentTest)
        failedCount = failedCount + 1

Aucun commentaire:

Enregistrer un commentaire