Skip to content

Commit 4a4d889

Browse files
committed
fix: config file mail test for python 2.7
1 parent 8f713d9 commit 4a4d889

File tree

1 file changed

+16
-18
lines changed

1 file changed

+16
-18
lines changed

test/mail.py

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -30,29 +30,23 @@
3030
"""
3131
import mock
3232
import logging
33+
import sys
3334
from mock.mock import MagicMock
3435

35-
from unittest.mock import mock_open
36+
if sys.version_info[0] >= 3:
37+
from unittest.mock import mock_open
38+
elif sys.version_info[0] >= 2:
39+
from mock import mock_open
3640

3741
from vsc.install.testing import TestCase
3842

3943
from email.mime.text import MIMEText
4044
from vsc.utils.mail import VscMail
4145

42-
cfgfile = """
43-
[main]
44-
mail_host = config_host
45-
mail_port = 789
46-
smtp_auth_user = config_user
47-
smtp_auth_password = config_passwd
48-
smtp_use_starttls = 1
49-
"""
50-
51-
class TestVscMail(TestCase):
46+
class TestVscMailConfig(TestCase):
5247

5348

54-
@mock.patch("builtins.open", new_callable=mock_open, read_data=cfgfile)
55-
def test_config_file(self, mock_file):
49+
def test_config_file(self):
5650

5751
mail_host = "mailhost.domain"
5852
mail_port = 123
@@ -70,18 +64,21 @@ def test_config_file(self, mock_file):
7064
self.assertEqual(mail.mail_host, mail_host)
7165
self.assertEqual(mail.mail_port, mail_port)
7266

73-
mock_file = MagicMock()
74-
mock_file.return_value = """
67+
cfgfile = """
7568
[main]
7669
mail_host = config_host
7770
mail_port = 789
7871
smtp_auth_user = config_user
7972
smtp_auth_password = config_passwd
8073
smtp_use_starttls = 1
8174
"""
82-
mock_open.return_value = mock_file
83-
84-
mail = VscMail(mail_config="blah")
75+
# based on https://stackoverflow.com/questions/1289894/how-do-i-mock-an-open-used-in-a-with-statement-using-the-mock-framework-in-pyth/34677735#34677735
76+
if sys.version_info[0] >= 3:
77+
with mock.patch("builtins.open", mock_open(read_data=cfgfile)):
78+
mail = VscMail(mail_config="blah")
79+
elif sys.version_info[0] >= 2:
80+
with mock.patch("__builtin__.open", mock_open(read_data=cfgfile)):
81+
mail = VscMail(mail_config="blah")
8582

8683
logging.warning("mail.mail_host: %s", mail.mail_host)
8784

@@ -92,6 +89,7 @@ def test_config_file(self, mock_file):
9289
self.assertEqual(mail.smtp_use_starttls, '1')
9390

9491

92+
class TestVscMail(TestCase):
9593
@mock.patch('vsc.utils.mail.smtplib')
9694
@mock.patch('vsc.utils.mail.ssl')
9795
def test_send(self, mock_ssl, mock_smtplib):

0 commit comments

Comments
 (0)