1

I am writing unit tests for my scraper project. Here is my function:

def last_date_method(self) -> datetime.datetime:
    """
    Returns date from json file (if date and file exist)
    Returns date if date not in file but file exist
    Returns a date and create a file if file not exist
    :return: datetime.datetime
    """

    try:
        with open(os.path.join(THIS_DIR, "data_file.json"), mode='r') as json_file:
            try:
                data = datetime.datetime.strptime(json.load(json_file)[self.site],
                                                  '%Y-%m-%d %H:%M:%S')
                return data

            except:
                return datetime.datetime(1970, 1, 1)
    except:
        with open(os.path.join(THIS_DIR, "data_file.json"), mode='a') as json_file:
            json.dump({}, json_file)
            json_file.close()

            return datetime.datetime(1970, 1, 1)

I also have a method:

def check_if_actuall(self) -> bool:
    """ Checks if new comics is available """

    return self.last_date >= self.get_site_date()

I want test it so I think I should mock a data_file.json return, or at least mock my self.last_date. In code below I can mock a self.get_site_date return, but I don't know how to mock self.last_date or return of JSON:

def test_check_if_actuall(self):

    with patch.object(ScraperLefthandedtoons, 'get_site_date', return_value=datetime.datetime(2018, 2, 27)):
        lht = ScraperLefthandedtoons()
        self.assertTrue(lht.check_if_actuall())
Md. Fazlul Hoque
  • 15,806
  • 5
  • 12
  • 32
HGH
  • 49
  • 6
  • Does this answer your question? [How do I mock an open used in a with statement (using the Mock framework in Python)?](https://stackoverflow.com/questions/1289894/how-do-i-mock-an-open-used-in-a-with-statement-using-the-mock-framework-in-pyth) – Boris Verkhovskiy Aug 14 '21 at 22:51
  • Someone left a correct comment but now i cant see it idk why – HGH Aug 14 '21 at 22:53
  • what did it say? – Boris Verkhovskiy Aug 14 '21 at 22:54
  • somethin similiar to your link but for me it was more clearly, but still i dont know how to create a mock class instance with some methods result customed by me. – HGH Aug 14 '21 at 22:56
  • It helps me in 50% but i have problem if i want mock a class instance and mock a file in one test. – HGH Aug 14 '21 at 23:20

0 Answers0