'How to unittest file containing assert __name__ == "__main__"

I want to unit test a piece of code from a module using the Mock testing library.

# File_name: do.py

assert __name__ == "__main__", "This module should NOT be imported."

from disk import Disk

def bool_fun(args):
    res = Disk.disks()
    print(res)
    if args not in res:
        return -1
    return args

The above file contains assert name == "__main__" which is blocking the module from getting import in test file.

# File_name: do_test.py

import unittest
from unittest import mock

import do

class DOTest(unittest.TestCase):

    @mock.patch('do.Disk.disks')
    def test_bool_fun(self, mock_disks):
        args = 4
        mock_disks.return_value = [4,3,2,3,4]
        res = do.bool_fun(args)
        self.assertEqual(res, args)

if __name__ == "__main__":
    unittest.main()

One more helper file which is imported in do.py file,

# File_name: disk.py
import random

class Disk():
    def __init__(self):
        pass

    def disks():
        lis = []
        for i in range(5):
            lis.append(random.randint(1,10))
        return lis

Assuming all files are kept in the same directory, I'm getting below error when trying to test it.

    assert __name__ == "__main__", "This module should NOT be imported."
AssertionError: This module should NOT be imported.

However, it works great if I remove the assert code from do.py file.

Can you please tell me how to test such files containing assert name == "__main__" in it.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source