0

I want to test part of code that copes for python 2/3 differences with urlparse. Below is a sample code. I am trying to run my unit test in python3 and want to unit test part of ImportError code.

sample.py

try:
    from urllib.parse import urlparse
except ImportError:
    from urlparse import urlparse


def add_num(a, b):
return a + b

Below is what I tried, but I am not able to hit the ImportError

test_sample.py

import sample
import mock
import sys

def test_urlparse():
    with mock.patch.dict(sys.modules, {'urlparse': None}):
        sample.add_num(1, 2)

How can we unit test this ? Thanks in advance

Lijju Mathew
  • 1,911
  • 6
  • 20
  • 26
  • You have to patch `sys.modules` *before* you import `sample`. By the time you use `mock.patch.dict`, `sys.modules` already contains an entry for `urlparse`. Changing that entry doesn't trigger a second import. – chepner Oct 04 '22 at 13:52

0 Answers0