pytest: Migrate unittest/nose to Pytest fixtures

Even though Pytest supports xunit style setups, unittest and nose
tests, this support is limited and may be dropped in the future
releases. Worst of all is that the mixing of various test
frameworks results in weird conflicts and of course, is not widely
tested.

This is a part of work to remove the mixing of test idioms in the
IPA's test suite:
1) replace unittest.TestCase subclasses
2) replace unittest test controls (SkipTest, fail, etc.)
3) replace unittest assertions

Related: https://pagure.io/freeipa/issue/7989
Signed-off-by: Stanislav Levin <slev@altlinux.org>
Reviewed-By: Christian Heimes <cheimes@redhat.com>
This commit is contained in:
Stanislav Levin 2019-10-15 13:24:11 +03:00 committed by Alexander Bokovoy
parent 292d686c0b
commit fec66942d4
25 changed files with 887 additions and 888 deletions

View File

@ -25,7 +25,6 @@ from __future__ import absolute_import
import distutils.spawn
import os
import unittest
import pytest
@ -69,6 +68,6 @@ class cmdline_test(XMLRPC_test):
'Command %r not available' % original_command
)
if not server_available:
raise unittest.SkipTest(
pytest.skip(
'Server not available: %r' % api.env.xmlrpc_uri
)

View File

@ -5,7 +5,6 @@ import shlex
import subprocess
import sys
import tempfile
import unittest
import six
@ -45,8 +44,8 @@ class TestCLIParsing:
try:
api.Command[command_name](**kw)
except errors.NetworkError:
raise unittest.SkipTest('%r: Server not available: %r' %
(self.__module__, api.env.xmlrpc_uri))
pytest.skip('%r: Server not available: %r' %
(self.__module__, api.env.xmlrpc_uri))
@contextlib.contextmanager
def fake_stdin(self, string_in):
@ -124,7 +123,7 @@ class TestCLIParsing:
try:
self.run_command('dnszone_add', idnsname=TEST_ZONE)
except errors.NotFound:
raise unittest.SkipTest('DNS is not configured')
pytest.skip('DNS is not configured')
try:
self.run_command('dnsrecord_add',
dnszoneidnsname=TEST_ZONE,
@ -152,7 +151,7 @@ class TestCLIParsing:
try:
self.run_command('dnszone_add', idnsname=TEST_ZONE)
except errors.NotFound:
raise unittest.SkipTest('DNS is not configured')
pytest.skip('DNS is not configured')
try:
records = (u'1 1 E3B72BA346B90570EED94BE9334E34AA795CED23',
u'2 1 FD2693C1EFFC11A8D2BE57229212A04B45663791')
@ -232,7 +231,7 @@ class TestCLIParsing:
self.run_command(
'dnszone_add', idnsname=TEST_ZONE)
except errors.NotFound:
raise unittest.SkipTest('DNS is not configured')
pytest.skip('DNS is not configured')
try:
self.run_command(
'dnsrecord_add',

View File

@ -23,7 +23,6 @@ Test the `ipaserver/install/ldapupdate.py` module.
from __future__ import absolute_import
import os
import unittest
import pytest
@ -50,20 +49,20 @@ The DM password needs to be set in ~/.ipa/.dmpw
@pytest.mark.tier0
@pytest.mark.needs_ipaapi
class test_update(unittest.TestCase):
class TestUpdate:
"""
Test the LDAP updater.
"""
def setUp(self):
@pytest.fixture(autouse=True)
def update_setup(self, request):
fqdn = installutils.get_fqdn()
pwfile = api.env.dot_ipa + os.sep + ".dmpw"
if os.path.isfile(pwfile):
fp = open(pwfile, "r")
self.dm_password = fp.read().rstrip()
fp.close()
with open(pwfile, "r") as fp:
self.dm_password = fp.read().rstrip()
else:
raise unittest.SkipTest("No directory manager password")
pytest.skip("No directory manager password")
self.updater = LDAPUpdate(dm_password=self.dm_password, sub_dict={})
self.ld = ipaldap.LDAPClient.from_hostname_secure(fqdn)
self.ld.simple_bind(bind_dn=ipaldap.DIRMAN_DN,
@ -71,14 +70,15 @@ class test_update(unittest.TestCase):
self.testdir = os.path.abspath(os.path.dirname(__file__))
if not os.path.isfile(os.path.join(self.testdir,
"0_reset.update")):
raise unittest.SkipTest("Unable to find test update files")
pytest.skip("Unable to find test update files")
self.container_dn = DN(self.updater._template_str('cn=test, cn=accounts, $SUFFIX'))
self.user_dn = DN(self.updater._template_str('uid=tuser, cn=test, cn=accounts, $SUFFIX'))
def tearDown(self):
if self.ld:
self.ld.unbind()
def fin():
if self.ld:
self.ld.unbind()
request.addfinalizer(fin)
def test_0_reset(self):
"""
@ -91,13 +91,13 @@ class test_update(unittest.TestCase):
# Just means the entry doesn't exist yet
modified = True
self.assertTrue(modified)
assert modified
with self.assertRaises(errors.NotFound):
with pytest.raises(errors.NotFound):
self.ld.get_entries(
self.container_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
with self.assertRaises(errors.NotFound):
with pytest.raises(errors.NotFound):
self.ld.get_entries(
self.user_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
@ -108,33 +108,33 @@ class test_update(unittest.TestCase):
modified = self.updater.update([os.path.join(self.testdir,
"1_add.update")])
self.assertTrue(modified)
assert modified
entries = self.ld.get_entries(
self.container_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
self.assertEqual(len(entries), 1)
assert len(entries) == 1
entry = entries[0]
objectclasses = entry.get('objectclass')
for item in ('top', 'nsContainer'):
self.assertTrue(item in objectclasses)
assert item in objectclasses
self.assertEqual(entry.single_value['cn'], 'test')
assert entry.single_value['cn'] == 'test'
entries = self.ld.get_entries(
self.user_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
self.assertEqual(len(entries), 1)
assert len(entries) == 1
entry = entries[0]
objectclasses = entry.get('objectclass')
for item in ('top', 'person', 'posixaccount', 'krbprincipalaux', 'inetuser'):
self.assertTrue(item in objectclasses)
assert item in objectclasses
self.assertEqual(entry.single_value['loginshell'],
platformconstants.DEFAULT_ADMIN_SHELL)
self.assertEqual(entry.single_value['sn'], 'User')
self.assertEqual(entry.single_value['uid'], 'tuser')
self.assertEqual(entry.single_value['cn'], 'Test User')
actual = entry.single_value['loginshell']
assert actual == platformconstants.DEFAULT_ADMIN_SHELL
assert entry.single_value['sn'] == 'User'
assert entry.single_value['uid'] == 'tuser'
assert entry.single_value['cn'] == 'Test User'
def test_2_update(self):
@ -143,13 +143,13 @@ class test_update(unittest.TestCase):
"""
modified = self.updater.update([os.path.join(self.testdir,
"2_update.update")])
self.assertTrue(modified)
assert modified
entries = self.ld.get_entries(
self.user_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
self.assertEqual(len(entries), 1)
assert len(entries) == 1
entry = entries[0]
self.assertEqual(entry.single_value['gecos'], 'Test User')
assert entry.single_value['gecos'] == 'Test User'
def test_3_update(self):
"""
@ -157,13 +157,13 @@ class test_update(unittest.TestCase):
"""
modified = self.updater.update([os.path.join(self.testdir,
"3_update.update")])
self.assertTrue(modified)
assert modified
entries = self.ld.get_entries(
self.user_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
self.assertEqual(len(entries), 1)
assert len(entries) == 1
entry = entries[0]
self.assertEqual(entry.single_value['gecos'], 'Test User New')
assert entry.single_value['gecos'] == 'Test User New'
def test_4_update(self):
"""
@ -171,13 +171,13 @@ class test_update(unittest.TestCase):
"""
modified = self.updater.update([os.path.join(self.testdir,
"4_update.update")])
self.assertTrue(modified)
assert modified
entries = self.ld.get_entries(
self.user_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
self.assertEqual(len(entries), 1)
assert len(entries) == 1
entry = entries[0]
self.assertEqual(entry.single_value['gecos'], 'Test User New2')
assert entry.single_value['gecos'] == 'Test User New2'
def test_5_update(self):
"""
@ -185,13 +185,15 @@ class test_update(unittest.TestCase):
"""
modified = self.updater.update([os.path.join(self.testdir,
"5_update.update")])
self.assertTrue(modified)
assert modified
entries = self.ld.get_entries(
self.user_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
self.assertEqual(len(entries), 1)
assert len(entries) == 1
entry = entries[0]
self.assertEqual(sorted(entry.get('cn')), sorted(['Test User', 'Test User New']))
actual = sorted(entry.get('cn'))
expected = sorted(['Test User', 'Test User New'])
assert actual == expected
def test_6_update(self):
"""
@ -199,13 +201,13 @@ class test_update(unittest.TestCase):
"""
modified = self.updater.update([os.path.join(self.testdir,
"6_update.update")])
self.assertTrue(modified)
assert modified
entries = self.ld.get_entries(
self.user_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
self.assertEqual(len(entries), 1)
assert len(entries) == 1
entry = entries[0]
self.assertEqual(sorted(entry.get('cn')), sorted(['Test User']))
assert sorted(entry.get('cn')) == sorted(['Test User'])
def test_6_update_1(self):
"""
@ -213,13 +215,13 @@ class test_update(unittest.TestCase):
"""
modified = self.updater.update([os.path.join(self.testdir,
"6_update.update")])
self.assertFalse(modified)
assert not modified
entries = self.ld.get_entries(
self.user_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
self.assertEqual(len(entries), 1)
assert len(entries) == 1
entry = entries[0]
self.assertEqual(sorted(entry.get('cn')), sorted(['Test User']))
assert sorted(entry.get('cn')) == sorted(['Test User'])
def test_7_cleanup(self):
"""
@ -232,13 +234,13 @@ class test_update(unittest.TestCase):
# Just means the entry doesn't exist yet
modified = True
self.assertTrue(modified)
assert modified
with self.assertRaises(errors.NotFound):
with pytest.raises(errors.NotFound):
self.ld.get_entries(
self.container_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
with self.assertRaises(errors.NotFound):
with pytest.raises(errors.NotFound):
self.ld.get_entries(
self.user_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*'])
@ -246,7 +248,7 @@ class test_update(unittest.TestCase):
"""
Test the updater with an unknown keyword (test_8_badsyntax)
"""
with self.assertRaises(BadSyntax):
with pytest.raises(BadSyntax):
self.updater.update(
[os.path.join(self.testdir, "8_badsyntax.update")])
@ -254,6 +256,6 @@ class test_update(unittest.TestCase):
"""
Test the updater with an incomplete line (test_9_badsyntax)
"""
with self.assertRaises(BadSyntax):
with pytest.raises(BadSyntax):
self.updater.update(
[os.path.join(self.testdir, "9_badsyntax.update")])

View File

@ -24,7 +24,8 @@ from __future__ import absolute_import
import os
import re
import unittest
import pytest
from ipaplatform.constants import constants as platformconstants
from ipaplatform.paths import paths
@ -166,8 +167,8 @@ class BaseTestLegacyClient:
def test_login_ipa_user(self):
if not self.master.transport.file_exists('/usr/bin/sshpass'):
raise unittest.SkipTest('Package sshpass not available on %s'
% self.master.hostname)
pytest.skip('Package sshpass not available on %s'
% self.master.hostname)
result = self.master.run_command(
'sshpass -p %s '
@ -183,8 +184,8 @@ class BaseTestLegacyClient:
def test_login_ad_user(self):
if not self.master.transport.file_exists('/usr/bin/sshpass'):
raise unittest.SkipTest('Package sshpass not available on %s'
% self.master.hostname)
pytest.skip('Package sshpass not available on %s'
% self.master.hostname)
testuser = 'testuser@%s' % self.ad.domain.name
result = self.master.run_command(
@ -200,8 +201,8 @@ class BaseTestLegacyClient:
def test_login_disabled_ipa_user(self):
if not self.master.transport.file_exists('/usr/bin/sshpass'):
raise unittest.SkipTest('Package sshpass not available on %s'
% self.master.hostname)
pytest.skip('Package sshpass not available on %s'
% self.master.hostname)
self.clear_sssd_caches()
@ -220,7 +221,7 @@ class BaseTestLegacyClient:
def test_login_disabled_ad_user(self):
if not self.master.transport.file_exists('/usr/bin/sshpass'):
raise unittest.SkipTest('Package sshpass not available on %s'
pytest.skip('Package sshpass not available on %s'
% self.master.hostname)
testuser = 'disabledaduser@%s' % self.ad.domain.name
@ -238,7 +239,7 @@ class BaseTestLegacyClient:
def test_getent_subdomain_ad_user(self):
if not self.ad_subdomain:
raise unittest.SkipTest('AD for the subdomain is not available.')
pytest.skip('AD for the subdomain is not available.')
self.clear_sssd_caches()
testuser = 'subdomaintestuser@%s' % self.ad_subdomain
@ -260,7 +261,7 @@ class BaseTestLegacyClient:
def test_getent_subdomain_ad_group(self):
if not self.ad_subdomain:
raise unittest.SkipTest('AD for the subdomain is not available.')
pytest.skip('AD for the subdomain is not available.')
self.clear_sssd_caches()
testgroup = 'subdomaintestgroup@%s' % self.ad_subdomain
@ -272,7 +273,7 @@ class BaseTestLegacyClient:
def test_id_subdomain_ad_user(self):
if not self.ad_subdomain:
raise unittest.SkipTest('AD for the subdomain is not available.')
pytest.skip('AD for the subdomain is not available.')
self.clear_sssd_caches()
testuser = 'subdomaintestuser@%s' % self.ad_subdomain
@ -297,11 +298,11 @@ class BaseTestLegacyClient:
def test_login_subdomain_ad_user(self):
if not self.ad_subdomain:
raise unittest.SkipTest('AD for the subdomain is not available.')
pytest.skip('AD for the subdomain is not available.')
if not self.master.transport.file_exists('/usr/bin/sshpass'):
raise unittest.SkipTest('Package sshpass not available on %s'
% self.master.hostname)
pytest.skip('Package sshpass not available on %s'
% self.master.hostname)
testuser = 'subdomaintestuser@%s' % self.ad_subdomain
result = self.master.run_command(
@ -317,11 +318,11 @@ class BaseTestLegacyClient:
def test_login_disabled_subdomain_ad_user(self):
if not self.ad_subdomain:
raise unittest.SkipTest('AD for the subdomain is not available.')
pytest.skip('AD for the subdomain is not available.')
if not self.master.transport.file_exists('/usr/bin/sshpass'):
raise unittest.SkipTest('Package sshpass not available on %s'
% self.master.hostname)
pytest.skip('Package sshpass not available on %s'
% self.master.hostname)
testuser = 'subdomaindisabledaduser@%s' % self.ad_subdomain
result = self.master.run_command(
@ -338,7 +339,7 @@ class BaseTestLegacyClient:
def test_getent_treedomain_ad_user(self):
if not self.ad_treedomain:
raise unittest.SkipTest('AD tree root domain is not available.')
pytest.skip('AD tree root domain is not available.')
self.clear_sssd_caches()
testuser = 'treetestuser@{0}'.format(self.ad_treedomain)
@ -356,7 +357,7 @@ class BaseTestLegacyClient:
def test_getent_treedomain_ad_group(self):
if not self.ad_treedomain:
raise unittest.SkipTest('AD tree root domain is not available')
pytest.skip('AD tree root domain is not available')
self.clear_sssd_caches()
testgroup = 'treetestgroup@{0}'.format(self.ad_treedomain)
@ -369,7 +370,7 @@ class BaseTestLegacyClient:
def test_id_treedomain_ad_user(self):
if not self.ad_treedomain:
raise unittest.SkipTest('AD tree root domain is not available')
pytest.skip('AD tree root domain is not available')
self.clear_sssd_caches()
@ -398,10 +399,10 @@ class BaseTestLegacyClient:
def test_login_treedomain_ad_user(self):
if not self.ad_treedomain:
raise unittest.SkipTest('AD tree root domain is not available.')
pytest.skip('AD tree root domain is not available.')
if not self.master.transport.file_exists('/usr/bin/sshpass'):
raise unittest.SkipTest(
pytest.skip(
'Package sshpass not available on {}'.format(
self.master.hostname)
)

View File

@ -3,9 +3,10 @@
from __future__ import absolute_import
import re
import unittest
import textwrap
import pytest
from ipaplatform.constants import constants as platformconstants
from ipaplatform.paths import paths
@ -33,8 +34,8 @@ class BaseTestTrust(IntegrationTest):
@classmethod
def install(cls, mh):
if not cls.master.transport.file_exists('/usr/bin/rpcclient'):
raise unittest.SkipTest("Package samba-client not available "
"on {}".format(cls.master.hostname))
raise pytest.skip("Package samba-client not available "
"on {}".format(cls.master.hostname))
super(BaseTestTrust, cls).install(mh)
cls.ad = cls.ads[0] # pylint: disable=no-member
cls.ad_domain = cls.ad.domain.name

View File

@ -22,7 +22,6 @@ Test the `ipalib.rpc` module.
"""
from __future__ import print_function
import unittest
from xmlrpc.client import Binary, Fault, dumps, loads
import urllib
@ -266,8 +265,8 @@ class test_xml_introspection:
try:
api.Backend.xmlclient.connect()
except (errors.NetworkError, IOError):
raise unittest.SkipTest('%r: Server not available: %r' %
(__name__, api.env.xmlrpc_uri))
pytest.skip('%r: Server not available: %r' %
(__name__, api.env.xmlrpc_uri))
def fin():
ipa_request.destroy_context()
@ -356,8 +355,8 @@ class test_rpcclient_context(PluginTester):
try:
api.Backend.rpcclient.connect(ca_certfile='foo')
except (errors.NetworkError, IOError):
raise unittest.SkipTest('%r: Server not available: %r' %
(__name__, api.env.xmlrpc_uri))
pytest.skip('%r: Server not available: %r' %
(__name__, api.env.xmlrpc_uri))
def fin():
if api.Backend.rpcclient.isconnected():

View File

@ -25,7 +25,6 @@ from __future__ import print_function
import os
import shutil
import tempfile
import unittest
import six
import pytest
@ -103,17 +102,17 @@ class test_TestLang:
result = create_po(self.pot_file, self.po_file, self.mo_file)
if result:
raise unittest.SkipTest(
pytest.skip(
'Unable to create po file "%s" & mo file "%s" from pot '
'file "%s"' % (self.po_file, self.mo_file, self.pot_file)
)
if not os.path.isfile(self.po_file):
raise unittest.SkipTest(
pytest.skip(
'Test po file unavailable: {}'.format(self.po_file))
if not os.path.isfile(self.mo_file):
raise unittest.SkipTest(
pytest.skip(
'Test mo file unavailable: {}'.format(self.mo_file))
self.po_file_iterate = po_file_iterate

View File

@ -17,7 +17,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import unittest
import datetime
import email.utils
import calendar
@ -27,125 +26,127 @@ import pytest
pytestmark = pytest.mark.tier0
class TestParse(unittest.TestCase):
class TestParse:
def test_parse(self):
# Empty string
s = ''
cookies = Cookie.parse(s)
self.assertEqual(len(cookies), 0)
assert len(cookies) == 0
# Invalid single token
s = 'color'
with self.assertRaises(ValueError):
with pytest.raises(ValueError):
cookies = Cookie.parse(s)
# Invalid single token that's keyword
s = 'HttpOnly'
with self.assertRaises(ValueError):
with pytest.raises(ValueError):
cookies = Cookie.parse(s)
# Invalid key/value pair whose key is a keyword
s = 'domain=example.com'
with self.assertRaises(ValueError):
with pytest.raises(ValueError):
cookies = Cookie.parse(s)
# 1 cookie with empty value
s = 'color='
cookies = Cookie.parse(s)
self.assertEqual(len(cookies), 1)
assert len(cookies) == 1
cookie = cookies[0]
self.assertEqual(cookie.key, 'color')
self.assertEqual(cookie.value, '')
self.assertEqual(cookie.domain, None)
self.assertEqual(cookie.path, None)
self.assertEqual(cookie.max_age, None)
self.assertEqual(cookie.expires, None)
self.assertEqual(cookie.secure, None)
self.assertEqual(cookie.httponly, None)
self.assertEqual(str(cookie), "color=")
self.assertEqual(cookie.http_cookie(), "color=;")
assert cookie.key == 'color'
assert cookie.value == ''
assert cookie.domain is None
assert cookie.path is None
assert cookie.max_age is None
assert cookie.expires is None
assert cookie.secure is None
assert cookie.httponly is None
assert str(cookie) == "color="
assert cookie.http_cookie() == "color=;"
# 1 cookie with name/value
s = 'color=blue'
cookies = Cookie.parse(s)
self.assertEqual(len(cookies), 1)
assert len(cookies) == 1
cookie = cookies[0]
self.assertEqual(cookie.key, 'color')
self.assertEqual(cookie.value, 'blue')
self.assertEqual(cookie.domain, None)
self.assertEqual(cookie.path, None)
self.assertEqual(cookie.max_age, None)
self.assertEqual(cookie.expires, None)
self.assertEqual(cookie.secure, None)
self.assertEqual(cookie.httponly, None)
self.assertEqual(str(cookie), "color=blue")
self.assertEqual(cookie.http_cookie(), "color=blue;")
assert cookie.key == 'color'
assert cookie.value == 'blue'
assert cookie.domain is None
assert cookie.path is None
assert cookie.max_age is None
assert cookie.expires is None
assert cookie.secure is None
assert cookie.httponly is None
assert str(cookie) == "color=blue"
assert cookie.http_cookie() == "color=blue;"
# 1 cookie with whose value is quoted
# Use "get by name" utility to extract specific cookie
s = 'color="blue"'
cookie = Cookie.get_named_cookie_from_string(s, 'color')
self.assertIsNotNone(cookie)
self.assertIsNotNone(cookie, Cookie)
self.assertEqual(cookie.key, 'color')
self.assertEqual(cookie.value, 'blue')
self.assertEqual(cookie.domain, None)
self.assertEqual(cookie.path, None)
self.assertEqual(cookie.max_age, None)
self.assertEqual(cookie.expires, None)
self.assertEqual(cookie.secure, None)
self.assertEqual(cookie.httponly, None)
self.assertEqual(str(cookie), "color=blue")
self.assertEqual(cookie.http_cookie(), "color=blue;")
assert cookie is not None, Cookie
assert cookie.key == 'color'
assert cookie.value == 'blue'
assert cookie.domain is None
assert cookie.path is None
assert cookie.max_age is None
assert cookie.expires is None
assert cookie.secure is None
assert cookie.httponly is None
assert str(cookie) == "color=blue"
assert cookie.http_cookie() == "color=blue;"
# 1 cookie with name/value and domain, path attributes.
# Change up the whitespace a bit.
s = 'color =blue; domain= example.com ; path = /toplevel '
cookies = Cookie.parse(s)
self.assertEqual(len(cookies), 1)
assert len(cookies) == 1
cookie = cookies[0]
self.assertEqual(cookie.key, 'color')
self.assertEqual(cookie.value, 'blue')
self.assertEqual(cookie.domain, 'example.com')
self.assertEqual(cookie.path, '/toplevel')
self.assertEqual(cookie.max_age, None)
self.assertEqual(cookie.expires, None)
self.assertEqual(cookie.secure, None)
self.assertEqual(cookie.httponly, None)
self.assertEqual(str(cookie), "color=blue; Domain=example.com; Path=/toplevel")
self.assertEqual(cookie.http_cookie(), "color=blue;")
assert cookie.key == 'color'
assert cookie.value == 'blue'
assert cookie.domain == 'example.com'
assert cookie.path == '/toplevel'
assert cookie.max_age is None
assert cookie.expires is None
assert cookie.secure is None
assert cookie.httponly is None
assert str(cookie) == "color=blue; Domain=example.com; Path=/toplevel"
assert cookie.http_cookie() == "color=blue;"
# 2 cookies, various attributes
s = 'color=blue; Max-Age=3600; temperature=hot; HttpOnly'
cookies = Cookie.parse(s)
self.assertEqual(len(cookies), 2)
assert len(cookies) == 2
cookie = cookies[0]
self.assertEqual(cookie.key, 'color')
self.assertEqual(cookie.value, 'blue')
self.assertEqual(cookie.domain, None)
self.assertEqual(cookie.path, None)
self.assertEqual(cookie.max_age, 3600)
self.assertEqual(cookie.expires, None)
self.assertEqual(cookie.secure, None)
self.assertEqual(cookie.httponly, None)
self.assertEqual(str(cookie), "color=blue; Max-Age=3600")
self.assertEqual(cookie.http_cookie(), "color=blue;")
assert cookie.key == 'color'
assert cookie.value == 'blue'
assert cookie.domain is None
assert cookie.path is None
assert cookie.max_age == 3600
assert cookie.expires is None
assert cookie.secure is None
assert cookie.httponly is None
assert str(cookie) == "color=blue; Max-Age=3600"
assert cookie.http_cookie() == "color=blue;"
cookie = cookies[1]
self.assertEqual(cookie.key, 'temperature')
self.assertEqual(cookie.value, 'hot')
self.assertEqual(cookie.domain, None)
self.assertEqual(cookie.path, None)
self.assertEqual(cookie.max_age, None)
self.assertEqual(cookie.expires, None)
self.assertEqual(cookie.secure, None)
self.assertEqual(cookie.httponly, True)
self.assertEqual(str(cookie), "temperature=hot; HttpOnly")
self.assertEqual(cookie.http_cookie(), "temperature=hot;")
assert cookie.key == 'temperature'
assert cookie.value == 'hot'
assert cookie.domain is None
assert cookie.path is None
assert cookie.max_age is None
assert cookie.expires is None
assert cookie.secure is None
assert cookie.httponly is True
assert str(cookie) == "temperature=hot; HttpOnly"
assert cookie.http_cookie() == "temperature=hot;"
class TestExpires(unittest.TestCase):
def setUp(self):
class TestExpires:
@pytest.fixture(autouse=True)
def expires_setup(self):
# Force microseconds to zero because cookie timestamps only have second resolution
self.now = datetime.datetime.utcnow().replace(microsecond=0)
self.now_timestamp = calendar.timegm(self.now.utctimetuple())
@ -164,233 +165,237 @@ class TestExpires(unittest.TestCase):
# 1 cookie with name/value and no Max-Age and no Expires
s = 'color=blue;'
cookies = Cookie.parse(s)
self.assertEqual(len(cookies), 1)
assert len(cookies) == 1
cookie = cookies[0]
# Force timestamp to known value
cookie.timestamp = self.now
self.assertEqual(cookie.key, 'color')
self.assertEqual(cookie.value, 'blue')
self.assertEqual(cookie.domain, None)
self.assertEqual(cookie.path, None)
self.assertEqual(cookie.max_age, None)
self.assertEqual(cookie.expires, None)
self.assertEqual(cookie.secure, None)
self.assertEqual(cookie.httponly, None)
self.assertEqual(str(cookie), "color=blue")
self.assertEqual(cookie.get_expiration(), None)
assert cookie.key == 'color'
assert cookie.value == 'blue'
assert cookie.domain is None
assert cookie.path is None
assert cookie.max_age is None
assert cookie.expires is None
assert cookie.secure is None
assert cookie.httponly is None
assert str(cookie) == "color=blue"
assert cookie.get_expiration() is None
# Normalize
self.assertEqual(cookie.normalize_expiration(), None)
self.assertEqual(cookie.max_age, None)
self.assertEqual(cookie.expires, None)
self.assertEqual(str(cookie), "color=blue")
assert cookie.normalize_expiration() is None
assert cookie.max_age is None
assert cookie.expires is None
assert str(cookie) == "color=blue"
# 1 cookie with name/value and Max-Age
s = 'color=blue; max-age=%d' % (self.max_age)
cookies = Cookie.parse(s)
self.assertEqual(len(cookies), 1)
assert len(cookies) == 1
cookie = cookies[0]
# Force timestamp to known value
cookie.timestamp = self.now
self.assertEqual(cookie.key, 'color')
self.assertEqual(cookie.value, 'blue')
self.assertEqual(cookie.domain, None)
self.assertEqual(cookie.path, None)
self.assertEqual(cookie.max_age, self.max_age)
self.assertEqual(cookie.expires, None)
self.assertEqual(cookie.secure, None)
self.assertEqual(cookie.httponly, None)
self.assertEqual(str(cookie), "color=blue; Max-Age=%d" % (self.max_age))
self.assertEqual(cookie.get_expiration(), self.age_expiration)
assert cookie.key == 'color'
assert cookie.value == 'blue'
assert cookie.domain is None
assert cookie.path is None
assert cookie.max_age == self.max_age
assert cookie.expires is None
assert cookie.secure is None
assert cookie.httponly is None
assert str(cookie) == "color=blue; Max-Age=%d" % (self.max_age)
assert cookie.get_expiration() == self.age_expiration
# Normalize
self.assertEqual(cookie.normalize_expiration(), self.age_expiration)
self.assertEqual(cookie.max_age, None)
self.assertEqual(cookie.expires, self.age_expiration)
self.assertEqual(str(cookie), "color=blue; Expires=%s" % (self.age_string))
assert cookie.normalize_expiration() == self.age_expiration
assert cookie.max_age is None
assert cookie.expires == self.age_expiration
assert str(cookie) == "color=blue; Expires=%s" % (self.age_string)
# 1 cookie with name/value and Expires
s = 'color=blue; Expires=%s' % (self.expires_string)
cookies = Cookie.parse(s)
self.assertEqual(len(cookies), 1)
assert len(cookies) == 1
cookie = cookies[0]
# Force timestamp to known value
cookie.timestamp = self.now
self.assertEqual(cookie.key, 'color')
self.assertEqual(cookie.value, 'blue')
self.assertEqual(cookie.domain, None)
self.assertEqual(cookie.path, None)
self.assertEqual(cookie.max_age, None)
self.assertEqual(cookie.expires, self.expires)
self.assertEqual(cookie.secure, None)
self.assertEqual(cookie.httponly, None)
self.assertEqual(str(cookie), "color=blue; Expires=%s" % (self.expires_string))
self.assertEqual(cookie.get_expiration(), self.expires)
assert cookie.key == 'color'
assert cookie.value == 'blue'
assert cookie.domain is None
assert cookie.path is None
assert cookie.max_age is None
assert cookie.expires == self.expires
assert cookie.secure is None
assert cookie.httponly is None
assert str(cookie) == "color=blue; Expires=%s" % (self.expires_string)
assert cookie.get_expiration() == self.expires
# Normalize
self.assertEqual(cookie.normalize_expiration(), self.expires)
self.assertEqual(cookie.max_age, None)
self.assertEqual(cookie.expires, self.expires)
self.assertEqual(str(cookie), "color=blue; Expires=%s" % (self.expires_string))
assert cookie.normalize_expiration() == self.expires
assert cookie.max_age is None
assert cookie.expires == self.expires
assert str(cookie) == "color=blue; Expires=%s" % (self.expires_string)
# 1 cookie with name/value witht both Max-Age and Expires, Max-Age takes precedence
s = 'color=blue; Expires=%s; max-age=%d' % (self.expires_string, self.max_age)
cookies = Cookie.parse(s)
self.assertEqual(len(cookies), 1)
assert len(cookies) == 1
cookie = cookies[0]
# Force timestamp to known value
cookie.timestamp = self.now
self.assertEqual(cookie.key, 'color')
self.assertEqual(cookie.value, 'blue')
self.assertEqual(cookie.domain, None)
self.assertEqual(cookie.path, None)
self.assertEqual(cookie.max_age, self.max_age)
self.assertEqual(cookie.expires, self.expires)
self.assertEqual(cookie.secure, None)
self.assertEqual(cookie.httponly, None)
self.assertEqual(str(cookie), "color=blue; Max-Age=%d; Expires=%s" % (self.max_age, self.expires_string))
self.assertEqual(cookie.get_expiration(), self.age_expiration)
assert cookie.key == 'color'
assert cookie.value == 'blue'
assert cookie.domain is None
assert cookie.path is None
assert cookie.max_age == self.max_age
assert cookie.expires == self.expires
assert cookie.secure is None
assert cookie.httponly is None
expected = "color=blue; Max-Age={}; Expires={}".format(
self.max_age, self.expires_string)
assert str(cookie) == expected
assert cookie.get_expiration() == self.age_expiration
# Normalize
self.assertEqual(cookie.normalize_expiration(), self.age_expiration)
self.assertEqual(cookie.max_age, None)
self.assertEqual(cookie.expires, self.age_expiration)
self.assertEqual(str(cookie), "color=blue; Expires=%s" % (self.age_string))
assert cookie.normalize_expiration() == self.age_expiration
assert cookie.max_age is None
assert cookie.expires == self.age_expiration
assert str(cookie) == "color=blue; Expires=%s" % (self.age_string)
# Verify different types can be assigned to the timestamp and
# expires attribute.
cookie = Cookie('color', 'blue')
cookie.timestamp = self.now
self.assertEqual(cookie.timestamp, self.now)
assert cookie.timestamp == self.now
cookie.timestamp = self.now_timestamp
self.assertEqual(cookie.timestamp, self.now)
assert cookie.timestamp == self.now
cookie.timestamp = self.now_string
self.assertEqual(cookie.timestamp, self.now)
assert cookie.timestamp == self.now
self.assertEqual(cookie.expires, None)
assert cookie.expires is None
cookie.expires = self.expires
self.assertEqual(cookie.expires, self.expires)
assert cookie.expires == self.expires
cookie.expires = self.expires_timestamp
self.assertEqual(cookie.expires, self.expires)
assert cookie.expires == self.expires
cookie.expires = self.expires_string
self.assertEqual(cookie.expires, self.expires)
assert cookie.expires == self.expires
class TestInvalidAttributes(unittest.TestCase):
class TestInvalidAttributes:
def test_invalid(self):
# Invalid Max-Age
s = 'color=blue; Max-Age=over-the-hill'
with self.assertRaises(ValueError):
with pytest.raises(ValueError):
Cookie.parse(s)
cookie = Cookie('color', 'blue')
with self.assertRaises(ValueError):
with pytest.raises(ValueError):
cookie.max_age = 'over-the-hill'
# Invalid Expires
s = 'color=blue; Expires=Sun, 06 Xxx 1994 08:49:37 GMT'
with self.assertRaises(ValueError):
with pytest.raises(ValueError):
Cookie.parse(s)
cookie = Cookie('color', 'blue')
with self.assertRaises(ValueError):
with pytest.raises(ValueError):
cookie.expires = 'Sun, 06 Xxx 1994 08:49:37 GMT'
class TestAttributes(unittest.TestCase):
class TestAttributes:
def test_attributes(self):
cookie = Cookie('color', 'blue')
self.assertEqual(cookie.key, 'color')
self.assertEqual(cookie.value, 'blue')
self.assertEqual(cookie.domain, None)
self.assertEqual(cookie.path, None)
self.assertEqual(cookie.max_age, None)
self.assertEqual(cookie.expires, None)
self.assertEqual(cookie.secure, None)
self.assertEqual(cookie.httponly, None)
assert cookie.key == 'color'
assert cookie.value == 'blue'
assert cookie.domain is None
assert cookie.path is None
assert cookie.max_age is None
assert cookie.expires is None
assert cookie.secure is None
assert cookie.httponly is None
cookie.domain = 'example.com'
self.assertEqual(cookie.domain, 'example.com')
assert cookie.domain == 'example.com'
cookie.domain = None
self.assertEqual(cookie.domain, None)
assert cookie.domain is None
cookie.path = '/toplevel'
self.assertEqual(cookie.path, '/toplevel')
assert cookie.path == '/toplevel'
cookie.path = None
self.assertEqual(cookie.path, None)
assert cookie.path is None
cookie.max_age = 400
self.assertEqual(cookie.max_age, 400)
assert cookie.max_age == 400
cookie.max_age = None
self.assertEqual(cookie.max_age, None)
assert cookie.max_age is None
cookie.expires = 'Sun, 06 Nov 1994 08:49:37 GMT'
self.assertEqual(cookie.expires, datetime.datetime(1994, 11, 6, 8, 49, 37))
assert cookie.expires == datetime.datetime(1994, 11, 6, 8, 49, 37)
cookie.expires = None
self.assertEqual(cookie.expires, None)
assert cookie.expires is None
cookie.secure = True
self.assertEqual(cookie.secure, True)
self.assertEqual(str(cookie), "color=blue; Secure")
assert cookie.secure is True
assert str(cookie) == "color=blue; Secure"
cookie.secure = False
self.assertEqual(cookie.secure, False)
self.assertEqual(str(cookie), "color=blue")
assert cookie.secure is False
assert str(cookie) == "color=blue"
cookie.secure = None
self.assertEqual(cookie.secure, None)
self.assertEqual(str(cookie), "color=blue")
assert cookie.secure is None
assert str(cookie) == "color=blue"
cookie.httponly = True
self.assertEqual(cookie.httponly, True)
self.assertEqual(str(cookie), "color=blue; HttpOnly")
assert cookie.httponly is True
assert str(cookie) == "color=blue; HttpOnly"
cookie.httponly = False
self.assertEqual(cookie.httponly, False)
self.assertEqual(str(cookie), "color=blue")
assert cookie.httponly is False
assert str(cookie) == "color=blue"
cookie.httponly = None
self.assertEqual(cookie.httponly, None)
self.assertEqual(str(cookie), "color=blue")
assert cookie.httponly is None
assert str(cookie) == "color=blue"
class TestHTTPReturn(unittest.TestCase):
def setUp(self):
class TestHTTPReturn:
@pytest.fixture(autouse=True)
def http_return_setup(self):
self.url = 'http://www.foo.bar.com/one/two'
def test_no_attributes(self):
cookie = Cookie('color', 'blue')
self.assertTrue(cookie.http_return_ok(self.url))
assert cookie.http_return_ok(self.url)
def test_domain(self):
cookie = Cookie('color', 'blue', domain='www.foo.bar.com')
self.assertTrue(cookie.http_return_ok(self.url))
assert cookie.http_return_ok(self.url)
cookie = Cookie('color', 'blue', domain='.foo.bar.com')
self.assertTrue(cookie.http_return_ok(self.url))
assert cookie.http_return_ok(self.url)
cookie = Cookie('color', 'blue', domain='.bar.com')
self.assertTrue(cookie.http_return_ok(self.url))
assert cookie.http_return_ok(self.url)
cookie = Cookie('color', 'blue', domain='bar.com')
with self.assertRaises(Cookie.URLMismatch):
self.assertTrue(cookie.http_return_ok(self.url))
with pytest.raises(Cookie.URLMismatch):
assert cookie.http_return_ok(self.url)
cookie = Cookie('color', 'blue', domain='bogus.com')
with self.assertRaises(Cookie.URLMismatch):
self.assertTrue(cookie.http_return_ok(self.url))
with pytest.raises(Cookie.URLMismatch):
assert cookie.http_return_ok(self.url)
cookie = Cookie('color', 'blue', domain='www.foo.bar.com')
with self.assertRaises(Cookie.URLMismatch):
self.assertTrue(cookie.http_return_ok('http://192.168.1.1/one/two'))
with pytest.raises(Cookie.URLMismatch):
assert cookie.http_return_ok('http://192.168.1.1/one/two')
def test_path(self):
cookie = Cookie('color', 'blue')
self.assertTrue(cookie.http_return_ok(self.url))
assert cookie.http_return_ok(self.url)
cookie = Cookie('color', 'blue', path='/')
self.assertTrue(cookie.http_return_ok(self.url))
assert cookie.http_return_ok(self.url)
cookie = Cookie('color', 'blue', path='/one')
self.assertTrue(cookie.http_return_ok(self.url))
assert cookie.http_return_ok(self.url)
cookie = Cookie('color', 'blue', path='/oneX')
with self.assertRaises(Cookie.URLMismatch):
self.assertTrue(cookie.http_return_ok(self.url))
with pytest.raises(Cookie.URLMismatch):
assert cookie.http_return_ok(self.url)
def test_expires(self):
now = datetime.datetime.utcnow().replace(microsecond=0)
@ -399,32 +404,34 @@ class TestHTTPReturn(unittest.TestCase):
expires = now + datetime.timedelta(days=1)
cookie = Cookie('color', 'blue', expires=expires)
self.assertTrue(cookie.http_return_ok(self.url))
assert cookie.http_return_ok(self.url)
# expired 1 day ago
expires = now + datetime.timedelta(days=-1)
cookie = Cookie('color', 'blue', expires=expires)
with self.assertRaises(Cookie.Expired):
self.assertTrue(cookie.http_return_ok(self.url))
with pytest.raises(Cookie.Expired):
assert cookie.http_return_ok(self.url)
def test_httponly(self):
cookie = Cookie('color', 'blue', httponly=True)
self.assertTrue(cookie.http_return_ok('http://example.com'))
self.assertTrue(cookie.http_return_ok('https://example.com'))
assert cookie.http_return_ok('http://example.com')
assert cookie.http_return_ok('https://example.com')
with self.assertRaises(Cookie.URLMismatch):
self.assertTrue(cookie.http_return_ok('ftp://example.com'))
with pytest.raises(Cookie.URLMismatch):
assert cookie.http_return_ok('ftp://example.com')
def test_secure(self):
cookie = Cookie('color', 'blue', secure=True)
self.assertTrue(cookie.http_return_ok('https://Xexample.com'))
assert cookie.http_return_ok('https://Xexample.com')
with self.assertRaises(Cookie.URLMismatch):
self.assertTrue(cookie.http_return_ok('http://Xexample.com'))
with pytest.raises(Cookie.URLMismatch):
assert cookie.http_return_ok('http://Xexample.com')
class TestNormalization(unittest.TestCase):
def setUp(self):
class TestNormalization:
@pytest.fixture(autouse=True)
def normalization_setup(self):
# Force microseconds to zero because cookie timestamps only have second resolution
self.now = datetime.datetime.utcnow().replace(microsecond=0)
self.now_timestamp = calendar.timegm(self.now.utctimetuple())
@ -440,58 +447,53 @@ class TestNormalization(unittest.TestCase):
self.expires_string = email.utils.formatdate(self.expires_timestamp, usegmt=True)
def test_path_normalization(self):
self.assertEqual(Cookie.normalize_url_path(''), '/')
self.assertEqual(Cookie.normalize_url_path('foo'), '/')
self.assertEqual(Cookie.normalize_url_path('foo/'), '/')
self.assertEqual(Cookie.normalize_url_path('/foo'), '/')
self.assertEqual(Cookie.normalize_url_path('/foo/'), '/foo')
self.assertEqual(Cookie.normalize_url_path('/Foo/bar'), '/foo')
self.assertEqual(Cookie.normalize_url_path('/foo/baR/'), '/foo/bar')
assert Cookie.normalize_url_path('') == '/'
assert Cookie.normalize_url_path('foo') == '/'
assert Cookie.normalize_url_path('foo/') == '/'
assert Cookie.normalize_url_path('/foo') == '/'
assert Cookie.normalize_url_path('/foo/') == '/foo'
assert Cookie.normalize_url_path('/Foo/bar') == '/foo'
assert Cookie.normalize_url_path('/foo/baR/') == '/foo/bar'
def test_normalization(self):
cookie = Cookie('color', 'blue', expires=self.expires)
cookie.timestamp = self.now_timestamp
self.assertEqual(cookie.domain, None)
self.assertEqual(cookie.path, None)
assert cookie.domain is None
assert cookie.path is None
url = 'http://example.COM/foo'
cookie.normalize(url)
self.assertEqual(cookie.domain, 'example.com')
self.assertEqual(cookie.path, '/')
self.assertEqual(cookie.expires, self.expires)
assert cookie.domain == 'example.com'
assert cookie.path == '/'
assert cookie.expires == self.expires
cookie = Cookie('color', 'blue', max_age=self.max_age)
cookie.timestamp = self.now_timestamp
self.assertEqual(cookie.domain, None)
self.assertEqual(cookie.path, None)
assert cookie.domain is None
assert cookie.path is None
url = 'http://example.com/foo/'
cookie.normalize(url)
self.assertEqual(cookie.domain, 'example.com')
self.assertEqual(cookie.path, '/foo')
self.assertEqual(cookie.expires, self.age_expiration)
assert cookie.domain == 'example.com'
assert cookie.path == '/foo'
assert cookie.expires == self.age_expiration
cookie = Cookie('color', 'blue')
url = 'http://example.com/foo'
cookie.normalize(url)
self.assertEqual(cookie.domain, 'example.com')
self.assertEqual(cookie.path, '/')
assert cookie.domain == 'example.com'
assert cookie.path == '/'
cookie = Cookie('color', 'blue')
url = 'http://example.com/foo/bar'
cookie.normalize(url)
self.assertEqual(cookie.domain, 'example.com')
self.assertEqual(cookie.path, '/foo')
assert cookie.domain == 'example.com'
assert cookie.path == '/foo'
cookie = Cookie('color', 'blue')
url = 'http://example.com/foo/bar/'
cookie.normalize(url)
self.assertEqual(cookie.domain, 'example.com')
self.assertEqual(cookie.path, '/foo/bar')
#-------------------------------------------------------------------------------
if __name__ == '__main__':
unittest.main()
assert cookie.domain == 'example.com'
assert cookie.path == '/foo/bar'

File diff suppressed because it is too large Load Diff

View File

@ -19,72 +19,72 @@
import sys
sys.path.insert(0, ".")
import unittest
import pytest
from ipapython import ipavalidate
pytestmark = pytest.mark.tier0
class TestValidate(unittest.TestCase):
class TestValidate:
def test_validEmail(self):
self.assertEqual(True, ipavalidate.Email("test@freeipa.org"))
self.assertEqual(True, ipavalidate.Email("", notEmpty=False))
assert ipavalidate.Email("test@freeipa.org") is True
assert ipavalidate.Email("", notEmpty=False) is True
def test_invalidEmail(self):
self.assertEqual(False, ipavalidate.Email("test"))
self.assertEqual(False, ipavalidate.Email("test@freeipa"))
self.assertEqual(False, ipavalidate.Email("test@.com"))
self.assertEqual(False, ipavalidate.Email(""))
self.assertEqual(False, ipavalidate.Email(None))
assert ipavalidate.Email("test") is False
assert ipavalidate.Email("test@freeipa") is False
assert ipavalidate.Email("test@.com") is False
assert ipavalidate.Email("") is False
assert ipavalidate.Email(None) is False
def test_validPlain(self):
self.assertEqual(True, ipavalidate.Plain("Joe User"))
self.assertEqual(True, ipavalidate.Plain("Joe O'Malley"))
self.assertEqual(True, ipavalidate.Plain("", notEmpty=False))
self.assertEqual(True, ipavalidate.Plain(None, notEmpty=False))
self.assertEqual(True, ipavalidate.Plain("JoeUser", allowSpaces=False))
self.assertEqual(True, ipavalidate.Plain("JoeUser", allowSpaces=True))
assert ipavalidate.Plain("Joe User") is True
assert ipavalidate.Plain("Joe O'Malley") is True
assert ipavalidate.Plain("", notEmpty=False) is True
assert ipavalidate.Plain(None, notEmpty=False) is True
assert ipavalidate.Plain("JoeUser", allowSpaces=False) is True
assert ipavalidate.Plain("JoeUser", allowSpaces=True) is True
def test_invalidPlain(self):
self.assertEqual(False, ipavalidate.Plain("Joe (User)"))
self.assertEqual(False, ipavalidate.Plain("Joe C. User"))
self.assertEqual(False, ipavalidate.Plain("", notEmpty=True))
self.assertEqual(False, ipavalidate.Plain(None, notEmpty=True))
self.assertEqual(False, ipavalidate.Plain("Joe User", allowSpaces=False))
self.assertEqual(False, ipavalidate.Plain("Joe C. User"))
assert ipavalidate.Plain("Joe (User)") is False
assert ipavalidate.Plain("Joe C. User") is False
assert ipavalidate.Plain("", notEmpty=True) is False
assert ipavalidate.Plain(None, notEmpty=True) is False
assert ipavalidate.Plain("Joe User", allowSpaces=False) is False
assert ipavalidate.Plain("Joe C. User") is False
def test_validString(self):
self.assertEqual(True, ipavalidate.String("Joe User"))
self.assertEqual(True, ipavalidate.String("Joe O'Malley"))
self.assertEqual(True, ipavalidate.String("", notEmpty=False))
self.assertEqual(True, ipavalidate.String(None, notEmpty=False))
self.assertEqual(True, ipavalidate.String("Joe C. User"))
assert ipavalidate.String("Joe User") is True
assert ipavalidate.String("Joe O'Malley") is True
assert ipavalidate.String("", notEmpty=False) is True
assert ipavalidate.String(None, notEmpty=False) is True
assert ipavalidate.String("Joe C. User") is True
def test_invalidString(self):
self.assertEqual(False, ipavalidate.String("", notEmpty=True))
self.assertEqual(False, ipavalidate.String(None, notEmpty=True))
assert ipavalidate.String("", notEmpty=True) is False
assert ipavalidate.String(None, notEmpty=True) is False
def test_validPath(self):
self.assertEqual(True, ipavalidate.Path("/"))
self.assertEqual(True, ipavalidate.Path("/home/user"))
self.assertEqual(True, ipavalidate.Path("../home/user"))
self.assertEqual(True, ipavalidate.Path("", notEmpty=False))
self.assertEqual(True, ipavalidate.Path(None, notEmpty=False))
assert ipavalidate.Path("/") is True
assert ipavalidate.Path("/home/user") is True
assert ipavalidate.Path("../home/user") is True
assert ipavalidate.Path("", notEmpty=False) is True
assert ipavalidate.Path(None, notEmpty=False) is True
def test_invalidPath(self):
self.assertEqual(False, ipavalidate.Path("(foo)"))
self.assertEqual(False, ipavalidate.Path("", notEmpty=True))
self.assertEqual(False, ipavalidate.Path(None, notEmpty=True))
assert ipavalidate.Path("(foo)") is False
assert ipavalidate.Path("", notEmpty=True) is False
assert ipavalidate.Path(None, notEmpty=True) is False
def test_validName(self):
self.assertEqual(True, ipavalidate.GoodName("foo"))
self.assertEqual(True, ipavalidate.GoodName("1foo"))
self.assertEqual(True, ipavalidate.GoodName("foo.bar"))
self.assertEqual(True, ipavalidate.GoodName("foo.bar$"))
assert ipavalidate.GoodName("foo") is True
assert ipavalidate.GoodName("1foo") is True
assert ipavalidate.GoodName("foo.bar") is True
assert ipavalidate.GoodName("foo.bar$") is True
def test_invalidName(self):
self.assertEqual(False, ipavalidate.GoodName("foo bar"))
self.assertEqual(False, ipavalidate.GoodName("foo%bar"))
self.assertEqual(False, ipavalidate.GoodName("*foo"))
self.assertEqual(False, ipavalidate.GoodName("$foo.bar$"))
assert ipavalidate.GoodName("foo bar") is False
assert ipavalidate.GoodName("foo%bar") is False
assert ipavalidate.GoodName("*foo") is False
assert ipavalidate.GoodName("$foo.bar$") is False

View File

@ -4,9 +4,11 @@ from __future__ import print_function
import ipaserver.install.adtrust as adtr
from ipaserver.install.adtrust import set_and_check_netbios_name
from collections import namedtuple
from unittest import TestCase, mock
from unittest import mock
from io import StringIO
import pytest
class ApiMockup:
Backend = namedtuple('Backend', 'ldap2')
@ -14,9 +16,12 @@ class ApiMockup:
env = namedtuple('Environment', 'domain')
class TestNetbiosName(TestCase):
@classmethod
def setUpClass(cls):
class TestNetbiosName:
api = None
@pytest.fixture(autouse=True, scope="class")
def netbiosname_setup(self, request):
cls = request.cls
api = ApiMockup()
ldap2 = namedtuple('LDAP', 'isconnected')
ldap2.isconnected = mock.MagicMock(return_value=True)
@ -25,9 +30,9 @@ class TestNetbiosName(TestCase):
adtr.retrieve_netbios_name = mock.MagicMock(return_value=None)
cls.api = api
@classmethod
def tearDownClass(cls):
adtr.retrieve_netbios_name = cls.api.Calls.retrieve_netbios_name
def fin():
adtr.retrieve_netbios_name = cls.api.Calls.retrieve_netbios_name
request.addfinalizer(fin)
def test_NetbiosName(self):
"""

View File

@ -17,8 +17,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import unittest
import pytest
from ipatests.test_ipaserver.httptest import Unauthorized_HTTP_test
@ -43,7 +41,7 @@ class test_changepw(XMLRPC_test, Unauthorized_HTTP_test):
api.Command['user_add'](uid=testuser, givenname=u'Test', sn=u'User')
api.Command['passwd'](testuser, password=u'old_password')
except errors.ExecutionError as e:
raise unittest.SkipTest(
pytest.skip(
'Cannot set up test user: %s' % e
)

View File

@ -29,7 +29,6 @@ from __future__ import absolute_import
import os
import sys
import unittest
import pytest
import six
@ -92,7 +91,7 @@ class test_ldap:
with open(pwfile, "r") as fp:
dm_password = fp.read().rstrip()
else:
raise unittest.SkipTest(
pytest.skip(
"No directory manager password in %s" % pwfile
)
self.conn = ldap2(api)
@ -118,7 +117,7 @@ class test_ldap:
with open(pwfile, "r") as fp:
dm_password = fp.read().rstrip()
else:
raise unittest.SkipTest(
pytest.skip(
"No directory manager password in %s" % pwfile
)
myapi.Backend.ldap2.connect(bind_dn=DN(('cn', 'Directory Manager')), bind_pw=dm_password)
@ -136,7 +135,7 @@ class test_ldap:
try:
self.conn.connect(autobind=True)
except errors.ACIError:
raise unittest.SkipTest("Only executed as root")
pytest.skip("Only executed as root")
entry_attrs = self.conn.get_entry(self.dn, ['usercertificate'])
cert = entry_attrs.get('usercertificate')[0]
assert cert.serial_number is not None

View File

@ -6,7 +6,8 @@ import os
import shutil
import subprocess
import tempfile
import unittest
import pytest
def _test_password_callback():
@ -15,9 +16,13 @@ def _test_password_callback():
return password
class TestiSecStore(unittest.TestCase):
@classmethod
def setUpClass(cls):
class TestiSecStore:
certdb = None
cert2db = None
@pytest.fixture(autouse=True, scope="class")
def isec_store_setup(self, request):
cls = request.cls
cls.testdir = tempfile.mkdtemp(suffix='ipa-sec-store')
pwfile = os.path.join(cls.testdir, 'pwfile')
with open(pwfile, 'w') as f:
@ -45,9 +50,9 @@ class TestiSecStore(unittest.TestCase):
cwd=cls.testdir
)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.testdir)
def fin():
shutil.rmtree(cls.testdir)
request.addfinalizer(fin)
def test_iSecStore(self):
iss = iSecStore({})

View File

@ -28,8 +28,8 @@ from datetime import datetime
import time
import re
import os
from functools import wraps
import unittest
from urllib.error import URLError
import paramiko
@ -102,8 +102,6 @@ def screenshot(fn):
def screenshot_wrapper(*args, **kwargs):
try:
return fn(*args, **kwargs)
except unittest.SkipTest:
raise
except Exception:
self = args[0]
name = '%s_%s_%s' % (
@ -166,7 +164,7 @@ class UI_driver:
def ui_driver_setup(self, request):
cls = request.cls
if NO_SELENIUM:
raise unittest.SkipTest('Selenium not installed')
pytest.skip('Selenium not installed')
cls.load_config()
@pytest.fixture(autouse=True)
@ -195,9 +193,9 @@ class UI_driver:
with open(path, 'r') as conf:
cls.config = yaml.load(conf)
except yaml.YAMLError as e:
raise unittest.SkipTest("Invalid Web UI config.\n%s" % e)
pytest.skip("Invalid Web UI config.\n%s" % e)
except IOError as e:
raise unittest.SkipTest(
pytest.skip(
"Can't load Web UI test config: %s" % e
)
else:
@ -236,7 +234,7 @@ class UI_driver:
if driver_type == 'remote':
if 'host' not in cls.config:
raise unittest.SkipTest('Selenium server host not configured')
pytest.skip('Selenium server host not configured')
host = cls.config["host"]
if browser == 'chrome':
@ -252,11 +250,11 @@ class UI_driver:
command_executor='http://%s:%d/wd/hub' % (host, port),
desired_capabilities=capabilities)
except URLError as e:
raise unittest.SkipTest(
pytest.skip(
'Error connecting to selenium server: %s' % e
)
except RuntimeError as e:
raise unittest.SkipTest(
pytest.skip(
'Error while establishing webdriver: %s' % e
)
else:
@ -272,11 +270,11 @@ class UI_driver:
ff_log_path = cls.config.get("geckodriver_log_path")
driver = webdriver.Firefox(fp, log_path=ff_log_path)
except URLError as e:
raise unittest.SkipTest(
pytest.skip(
'Error connecting to selenium server: %s' % e
)
except RuntimeError as e:
raise unittest.SkipTest(
pytest.skip(
'Error while establishing webdriver: %s' % e
)
@ -2019,7 +2017,7 @@ class UI_driver:
"""
Skip tests
"""
raise unittest.SkipTest(reason)
pytest.skip(reason)
def assert_text(self, selector, value, parent=None):
"""

View File

@ -36,7 +36,6 @@ from ipaserver.plugins.automember import REBUILD_TASK_CONTAINER
import time
import pytest
import re
import unittest
from pkg_resources import parse_version
try:
@ -263,7 +262,7 @@ def set_automember_process_modify_ops(value):
:param value: can be either on or off
"""
if not have_ldap2:
raise unittest.SkipTest('server plugin not available')
pytest.skip('server plugin not available')
ldap = ldap2(api)
ldap.connect()
plugin_entry = ldap.get_entry(
@ -287,7 +286,7 @@ def wait_automember_rebuild():
If no task is found assume that the task is already finished.
"""
if not have_ldap2:
raise unittest.SkipTest('server plugin not available')
pytest.skip('server plugin not available')
ldap = ldap2(api)
ldap.connect()
@ -897,7 +896,7 @@ class TestAutomemberFindOrphans(XMLRPC_test):
# rebuild fails if 389-ds is older than 1.4.0.22 where unmembering
# feature was implemented: https://pagure.io/389-ds-base/issue/50077
if not have_ldap2:
raise unittest.SkipTest('server plugin not available')
pytest.skip('server plugin not available')
ldap = ldap2(api)
ldap.connect()
rootdse = ldap.get_entry(DN(''), ['vendorVersion'])

View File

@ -23,7 +23,6 @@ from __future__ import print_function, absolute_import
import base64
import os
import unittest
import pytest
import six
@ -57,7 +56,7 @@ def is_db_configured():
if (api.env.xmlrpc_uri == u'http://localhost:8888/ipa/xml' and
not os.path.isfile(aliasdir)):
raise unittest.SkipTest('developer CA not configured in %s' % aliasdir)
pytest.skip('developer CA not configured in %s' % aliasdir)
# Test setup
#
@ -86,9 +85,9 @@ class BaseCert(XMLRPC_test):
@pytest.fixture(autouse=True, scope="class")
def basecert_setup(self, request, xmlrpc_setup):
if 'cert_request' not in api.Command:
raise unittest.SkipTest('cert_request not registered')
pytest.skip('cert_request not registered')
if 'cert_show' not in api.Command:
raise unittest.SkipTest('cert_show not registered')
pytest.skip('cert_show not registered')
is_db_configured()
@ -275,10 +274,10 @@ class test_cert_find(XMLRPC_test):
@pytest.fixture(autouse=True, scope="class")
def certfind_setup(self, request, xmlrpc_setup):
if 'cert_find' not in api.Command:
raise unittest.SkipTest('cert_find not registered')
pytest.skip('cert_find not registered')
if api.env.ra_plugin != 'dogtag':
raise unittest.SkipTest('cert_find for dogtag CA only')
pytest.skip('cert_find for dogtag CA only')
is_db_configured()

View File

@ -20,8 +20,6 @@
Test the `ipaserver/plugins/dns.py` module.
"""
import unittest
from ipalib import api, errors
from ipalib.util import normalize_zone
from ipapython.dnsutil import DNSName
@ -432,10 +430,10 @@ class test_dns(Declarative):
api.Backend.rpcclient.connect()
if not have_ldap2:
raise unittest.SkipTest('server plugin not available')
pytest.skip('server plugin not available')
if get_nameservers_error is not None:
raise unittest.SkipTest(
pytest.skip(
'unable to get list of nameservers (%s)' %
get_nameservers_error
)
@ -446,7 +444,7 @@ class test_dns(Declarative):
)
api.Command['dnszone_del'](zone1)
except errors.NotFound:
raise unittest.SkipTest('DNS is not configured')
pytest.skip('DNS is not configured')
except errors.DuplicateEntry:
pass
@ -3342,10 +3340,10 @@ class test_root_zone(Declarative):
api.Backend.rpcclient.connect()
if not have_ldap2:
raise unittest.SkipTest('server plugin not available')
pytest.skip('server plugin not available')
if get_nameservers_error is not None:
raise unittest.SkipTest(
pytest.skip(
'unable to get list of nameservers (%s)' %
get_nameservers_error
)
@ -3354,7 +3352,7 @@ class test_root_zone(Declarative):
api.Command['dnszone_add'](zone1, idnssoarname=zone1_rname,)
api.Command['dnszone_del'](zone1)
except errors.NotFound:
raise unittest.SkipTest('DNS is not configured')
pytest.skip('DNS is not configured')
except errors.DuplicateEntry:
pass
@ -3426,13 +3424,13 @@ class test_forward_zones(Declarative):
api.Backend.rpcclient.connect()
if not have_ldap2:
raise unittest.SkipTest('server plugin not available')
pytest.skip('server plugin not available')
try:
api.Command['dnszone_add'](zone1, idnssoarname=zone1_rname,)
api.Command['dnszone_del'](zone1)
except errors.NotFound:
raise unittest.SkipTest('DNS is not configured')
pytest.skip('DNS is not configured')
except errors.DuplicateEntry:
pass
@ -4633,13 +4631,13 @@ class test_forward_master_zones_mutual_exlusion(Declarative):
api.Backend.rpcclient.connect()
if not have_ldap2:
raise unittest.SkipTest('server plugin not available')
pytest.skip('server plugin not available')
try:
api.Command['dnszone_add'](zone1, idnssoarname=zone1_rname,)
api.Command['dnszone_del'](zone1)
except errors.NotFound:
raise unittest.SkipTest('DNS is not configured')
pytest.skip('DNS is not configured')
except errors.DuplicateEntry:
pass
@ -5011,13 +5009,13 @@ class test_forwardzone_delegation_warnings(Declarative):
api.Backend.rpcclient.connect()
if not have_ldap2:
raise unittest.SkipTest('server plugin not available')
pytest.skip('server plugin not available')
try:
api.Command['dnszone_add'](zone1, idnssoarname=zone1_rname,)
api.Command['dnszone_del'](zone1)
except errors.NotFound:
raise unittest.SkipTest('DNS is not configured')
pytest.skip('DNS is not configured')
except errors.DuplicateEntry:
pass
@ -5520,17 +5518,17 @@ class test_dns_soa(Declarative):
api.Backend.rpcclient.connect()
if not have_ldap2:
raise unittest.SkipTest('server plugin not available')
pytest.skip('server plugin not available')
if get_nameservers_error is not None:
raise unittest.SkipTest('unable to get list of nameservers (%s)' %
pytest.skip('unable to get list of nameservers (%s)' %
get_nameservers_error)
try:
api.Command['dnszone_add'](zone1,
idnssoarname=zone1_rname,)
api.Command['dnszone_del'](zone1)
except errors.NotFound:
raise unittest.SkipTest('DNS is not configured')
pytest.skip('DNS is not configured')
except errors.DuplicateEntry:
pass

View File

@ -21,8 +21,6 @@ Test adding/removing external members (trusted domain objects) to IPA groups.
These tests are skipped if trust is not established.
"""
import unittest
from ipalib import api
from ipapython.dn import DN
from ipatests.test_xmlrpc import objectclasses
@ -53,7 +51,7 @@ class test_external_members(Declarative):
trusts = api.Command['trust_find']()
if trusts['count'] == 0:
raise unittest.SkipTest('Trust is not established')
pytest.skip('Trust is not established')
cleanup_commands = [
('group_del', [group_name], {}),

View File

@ -1400,7 +1400,7 @@ class test_netgroup(Declarative):
# entries = conn.find_entries('cn=%s' % self.ng_cn,
# base_dn='cn=ng,cn=compat,%s' % api.env.basedn)
# except errors.NotFound:
# raise unittest.SkipTest(
# pytest.skip(
# 'compat and nis are not enabled, skipping test'
# )
# finally:

View File

@ -24,7 +24,6 @@ Test the `ipaserver/plugins/permission.py` module.
from __future__ import print_function
import os
import unittest
from ipalib import api, errors
from ipatests.test_xmlrpc import objectclasses
@ -3445,7 +3444,7 @@ class test_managed_permissions(Declarative):
@pytest.fixture(autouse=True, scope="class")
def managed_perm_setup(self, declarative_setup):
if not have_ldap2:
raise unittest.SkipTest('server plugin not available')
pytest.skip('server plugin not available')
def add_managed_permission(self):
"""Add a managed permission and the corresponding ACI"""

View File

@ -9,7 +9,6 @@ Test the `ipaserver/plugins/stageuser.py` module.
import pytest
import six
import unittest
from collections import OrderedDict
from ipalib import api, errors
@ -327,7 +326,7 @@ class TestStagedUser(XMLRPC_test):
# Directly create the user using ldapmod
# without the posixaccount objectclass
if not have_ldap2:
raise unittest.SkipTest('server plugin not available')
pytest.skip('server plugin not available')
ldap = ldap2(api)
ldap.connect()
ldap.create(

View File

@ -20,8 +20,6 @@
Test the `ipaserver/plugins/trust.py` module.
"""
import unittest
import six
from ipalib import api, errors
@ -54,7 +52,7 @@ class test_trustconfig(Declarative):
try:
api.Command['trustconfig_show'](trust_type=u'ad')
except errors.NotFound:
raise unittest.SkipTest('Trusts are not configured')
pytest.skip('Trusts are not configured')
cleanup_commands = [
('group_del', [testgroup], {}),

View File

@ -21,8 +21,6 @@
Test the `ipaserver/plugins/vault.py` module.
"""
import unittest
import pytest
import six
@ -140,7 +138,7 @@ class test_vault_plugin(Declarative):
api.Backend.rpcclient.connect()
if not api.Command.kra_is_enabled()['result']:
raise unittest.SkipTest('KRA service is not enabled')
pytest.skip('KRA service is not enabled')
cleanup_commands = [
('vault_del', [vault_name], {'continue': True}),

View File

@ -24,7 +24,6 @@ from __future__ import print_function
import datetime
import inspect
import unittest
import contextlib
import pytest
@ -211,9 +210,9 @@ class XMLRPC_test:
@pytest.fixture(autouse=True, scope="class")
def xmlrpc_setup(self, request):
if not server_available:
raise unittest.SkipTest('%r: Server not available: %r' %
(request.cls.__module__,
api.env.xmlrpc_uri))
pytest.skip('%r: Server not available: %r' %
(request.cls.__module__,
api.env.xmlrpc_uri))
if not api.Backend.rpcclient.isconnected():
api.Backend.rpcclient.connect()
@ -320,7 +319,7 @@ class Declarative(XMLRPC_test):
(cmd, args, options) = command
print('Cleanup:', cmd, args, options)
if cmd not in api.Command:
raise unittest.SkipTest(
pytest.skip(
'cleanup command %r not in api.Command' % cmd
)
try:
@ -342,7 +341,7 @@ class Declarative(XMLRPC_test):
(cmd, args, options) = command
options.setdefault('version', self.default_version)
if cmd not in api.Command:
raise unittest.SkipTest('%r not in api.Command' % cmd)
pytest.skip('%r not in api.Command' % cmd)
if isinstance(expected, errors.PublicError):
self.check_exception(nice, cmd, args, options, expected)
elif hasattr(expected, '__call__'):