Search code examples
pythonunit-testingin-memory-database

Trying to compare Home Object to String Object in unit testing


I'm trying to test whether a method works or not in my unit testing. As seen in the code below in my error, I'm trying to compare my Home Object to my String Object and when printing out both of them, they are certainly equal to each other. My question is how do I change my Home Object to be a String Object or my String Object to be a Home Object so the test passes. Also if it helps this is in-memory database testing too. Thanks!

Unit testing code

from unittest import TestCase
from main import ContactApp
from database import CombinedDatabase, Home, Person, Location, Contact

     class TestContactApp(TestCase):
         def test_commit_data(self):
         url = CombinedDatabase.construct_in_memory_url()
         contact_database = CombinedDatabase(url)
         contact_database.ensure_tables_exist()
         session = contact_database.create_session()
         home_address = Home(address='3069 U St.')
         patient1 = Person(patient_name='Mike Piazza')
         ContactApp.commit_data(session, str(patient1), str(home_address), '456324A', 96.4, 'USA',  'Nebraska', 'Omaha', '54229')
         actual = session.query(Home).one()
         actual2 = session.query(Person).one()
         print(home_address, actual.address)
         self.assertEqual(home_address, actual.address)
         self.assertEqual(patient1, actual2.patient_name)

Error

<database.Home object at 0x7fe4ae20ce48> <database.Home object at 0x7fe4ae20ce48>
#printed out objects

<database.Home object at 0x7fe4ae20ce48> != <database.Home object at 0x7fe4ae20ce48>

<database.Home object at 0x7fe4ae20ce48>
<database.Home object at 0x7fe4ae20ce48>
<Click to see difference>

Traceback (most recent call last):
  File "/home/cse/Pycharmedu2019.1.1/pycharm-edu-2019.1.1/helpers/pycharm/teamcity/diff_tools.py", line 32, in _patched_equals
old(self, first, second, msg)
  File "/usr/lib64/python3.6/unittest/case.py", line 829, in assertEqual
assertion_func(first, second, msg=msg)
  File "/usr/lib64/python3.6/unittest/case.py", line 822, in _baseAssertEqual
raise self.failureException(msg)
AssertionError: <database.Home object at 0x7fe4ae20ce48> != '<database.Home object at 0x7fe4ae20ce48>'

Solution

  • You can convert your Home object into a String by defining a __str__ method. This will get called whenever you run str(home):

    class Home:
        def __init__(self, address):
            self.address = address
    
        def __str__(self):
            return self.address
    
    
    def main():
        address = '3069 U St.'
        my_home = Home(address=address)
        print(my_home)  # Prints '3069 U St.' because printing converts to a String
        print(my_home == address)  # False, because my_home is a Home, not a String
        print(str(my_home) == address)  # True, because we defined the __str__ method
    

    If you don't want to convert it to a string every time, you can also move that logic into the __eq__ method, which will get called whenever you test for equality:

    class Home:
        def __init__(self, address):
            self.address = address
    
        def __eq__(self, other):
            if isinstance(other, str):
                return other == self.address
            elif isinstance(other, Home):
                return other.address == self.address
            else:
                return False
    
    
    def main():
        address = '3069 U St.'
        my_home = Home(address=address)
        print(my_home == address)  # True, because we redefined what equality means