I have made a calculator. Now I have to make that calculator following classes and functions so that later I can apply the assert method to it. This is the calculator program following classes and functions but the assert method will not be applied to it.
I don't know if it is because the calculator program is wrong, or simply because I don't understand.
Thanks!
class Calculator:
"""Create your own calculator."""
def __init__(self, num1, num2):
"""Ask the numbers with which we are going to operate."""
self.num1 = int(num1)
self.num2 = int(num2)
def sums(self):
"""Perform the sum operation."""
summ = self.num1 + self.num2
print("The result of the sum is: ", sum)
return sum
def subtracts(self):
"""Perform the subtract operation."""
sub = self.num1 - self.num2
print("The result of the subtraction is: ", subtract)
return subtract
def multiply(self):
"""Perform the multiply operation."""
mult = self.num1 * self.num2
print("The result of the multiplication is: ", mult)
return mult
def divide(self):
"""Perform the divide operation."""
div = self.num1 / self.num2
print("The result of the division is: ", div)
return div
----------------------------
import unittest
from calculator_poo import Calculator
class TestCalculadora(unittest.TestCase):
"""Tests for 'calculator_poo.py'"""
def test_multiply(self):
"""works?"""
fx = multiply()
self.assertEqual(f("3*5')
unittest.main()
Giving a second answer, because the previous one did not elaborate on what the code does.
The declaration of the testclass you gave looks alright, but the use of assertEqual is incorrect in your code. assertEqual(val1, val2) requires 2 values / objects and tests them for equality. There are other assert functions that check for anything you want (see https://docs.python.org/3/library/unittest.html#test-cases for a detailed list of possible asserts).
In order to use assertEqual() you first have to create a Calculator object, on which the test is performed (this is because your Calculator class is working with class variables num1 and num2). You can then compare the result of that Calulator's multiply function with the expected output:
def test_multiply(self):
self.assertEqual(Calculator(3,5).multiply(), 15)
cal = Calculator(3, 5)
self.assertEqual(cal.multiply(), 15)
Note that you can either initialize a Calculator object inline and directly use it (first line) or explicitly declare it in local scope (lines 2&3). The latter has no real use here though, as your calculator is bound to the numbers it was initialized with.
You now can add further test functions for the other functions of the Calculator class.
Coming back to the sum
keyword: You need to update the return and print-statements to the new variable name as well.