From bcaec3c5bb465860210db35bcc15653561963cce Mon Sep 17 00:00:00 2001 From: Jeremy Bowman Date: Mon, 6 Aug 2018 16:52:11 -0400 Subject: [PATCH] TE-2525 nose.tools removal part 1/2 --- .../djangoapps/enrollment/tests/test_api.py | 18 +- .../djangoapps/enrollment/tests/test_data.py | 30 +-- .../test/test_static_replace.py | 58 ++-- .../djangoapps/util/tests/test_date_utils.py | 71 ++--- .../xmodule/modulestore/tests/factories.py | 5 +- .../modulestore/tests/test_modulestore.py | 15 +- .../xmodule/modulestore/tests/test_mongo.py | 252 ++++++++---------- .../xmodule/xmodule/tests/test_stringify.py | 10 +- .../xmodule/tests/test_utils_django.py | 5 +- .../xmodule/xmodule/tests/test_xml_module.py | 70 +++-- .../xmodule/tests/xml/test_inheritance.py | 10 +- .../xmodule/xmodule/tests/xml/test_policy.py | 8 +- .../tests/discussion/test_discussion.py | 5 +- .../tests/studio/test_studio_rerun.py | 3 +- lms/djangoapps/discussion/tests/test_views.py | 3 +- .../django_comment_client/base/tests.py | 25 +- .../instructor/tests/test_access.py | 26 +- lms/djangoapps/instructor/tests/test_api.py | 6 +- .../instructor_analytics/tests/test_csvs.py | 6 +- .../tests/test_distributions.py | 6 +- .../commands/tests/test_verify_student.py | 7 +- .../verify_student/tests/test_models.py | 44 ++- .../verify_student/tests/test_services.py | 16 +- .../test/test_lms_result_processor.py | 2 - .../user_api/accounts/tests/test_api.py | 21 +- .../djangoapps/user_api/tests/test_helpers.py | 10 +- 26 files changed, 322 insertions(+), 410 deletions(-) diff --git a/common/djangoapps/enrollment/tests/test_api.py b/common/djangoapps/enrollment/tests/test_api.py index edc70a35ba..80da9023ef 100644 --- a/common/djangoapps/enrollment/tests/test_api.py +++ b/common/djangoapps/enrollment/tests/test_api.py @@ -4,10 +4,10 @@ Tests for student enrollment. import unittest import ddt +import pytest from django.conf import settings from django.test.utils import override_settings from mock import Mock, patch -from nose.tools import raises from course_modes.models import CourseMode from enrollment import api @@ -84,19 +84,19 @@ class EnrollmentTest(CacheIsolationTestCase): ['verified'], ['verified', 'professional'], ) - @raises(CourseModeNotFoundError) def test_enroll_no_mode_error(self, course_modes): # Add a fake course enrollment information to the fake data API fake_data_api.add_course(self.COURSE_ID, course_modes=course_modes) # Enroll in the course and verify that we raise CourseModeNotFoundError - api.add_enrollment(self.USERNAME, self.COURSE_ID) + with pytest.raises(CourseModeNotFoundError): + api.add_enrollment(self.USERNAME, self.COURSE_ID) - @raises(CourseModeNotFoundError) def test_prof_ed_enroll(self): # Add a fake course enrollment information to the fake data API fake_data_api.add_course(self.COURSE_ID, course_modes=['professional']) # Enroll in the course and verify the URL we get sent to - api.add_enrollment(self.USERNAME, self.COURSE_ID, mode='verified') + with pytest.raises(CourseModeNotFoundError): + api.add_enrollment(self.USERNAME, self.COURSE_ID, mode='verified') @ddt.data( # Default (no course modes in the database) @@ -131,11 +131,11 @@ class EnrollmentTest(CacheIsolationTestCase): self.assertEquals(result['mode'], mode) self.assertFalse(result['is_active']) - @raises(EnrollmentNotFoundError) def test_unenroll_not_enrolled_in_course(self): # Add a fake course enrollment information to the fake data API fake_data_api.add_course(self.COURSE_ID, course_modes=['honor']) - api.update_enrollment(self.USERNAME, self.COURSE_ID, mode='honor', is_active=False) + with pytest.raises(EnrollmentNotFoundError): + api.update_enrollment(self.USERNAME, self.COURSE_ID, mode='honor', is_active=False) @ddt.data( # Simple test of honor and verified. @@ -209,10 +209,10 @@ class EnrollmentTest(CacheIsolationTestCase): self.assertEquals(3, len(result['course_modes'])) @override_settings(ENROLLMENT_DATA_API='foo.bar.biz.baz') - @raises(EnrollmentApiLoadError) def test_data_api_config_error(self): # Enroll in the course and verify the URL we get sent to - api.add_enrollment(self.USERNAME, self.COURSE_ID, mode='audit') + with pytest.raises(EnrollmentApiLoadError): + api.add_enrollment(self.USERNAME, self.COURSE_ID, mode='audit') def test_caching(self): # Add fake course enrollment information to the fake data API diff --git a/common/djangoapps/enrollment/tests/test_data.py b/common/djangoapps/enrollment/tests/test_data.py index 9936148477..9009fb121e 100644 --- a/common/djangoapps/enrollment/tests/test_data.py +++ b/common/djangoapps/enrollment/tests/test_data.py @@ -6,9 +6,9 @@ import datetime import unittest import ddt +import pytest from django.conf import settings from mock import patch -from nose.tools import raises from pytz import UTC from course_modes.models import CourseMode @@ -300,9 +300,9 @@ class EnrollmentDataTest(ModuleStoreTestCase): enrollment_attr = data.get_enrollment_attributes(self.user.username, unicode(self.course.id)) self.assertEqual(enrollment_attr[0], enrollment_attributes[0]) - @raises(CourseNotFoundError) def test_non_existent_course(self): - data.get_course_enrollment_info("this/is/bananas") + with pytest.raises(CourseNotFoundError): + data.get_course_enrollment_info("this/is/bananas") def _create_course_modes(self, course_modes, course=None): """Create the course modes required for a test. """ @@ -314,35 +314,35 @@ class EnrollmentDataTest(ModuleStoreTestCase): mode_display_name=mode_slug, ) - @raises(UserNotFoundError) def test_enrollment_for_non_existent_user(self): - data.create_course_enrollment("some_fake_user", unicode(self.course.id), 'honor', True) + with pytest.raises(UserNotFoundError): + data.create_course_enrollment("some_fake_user", unicode(self.course.id), 'honor', True) - @raises(CourseNotFoundError) def test_enrollment_for_non_existent_course(self): - data.create_course_enrollment(self.user.username, "some/fake/course", 'honor', True) + with pytest.raises(CourseNotFoundError): + data.create_course_enrollment(self.user.username, "some/fake/course", 'honor', True) - @raises(CourseEnrollmentClosedError) @patch.object(CourseEnrollment, "enroll") def test_enrollment_for_closed_course(self, mock_enroll): mock_enroll.side_effect = EnrollmentClosedError("Bad things happened") - data.create_course_enrollment(self.user.username, unicode(self.course.id), 'honor', True) + with pytest.raises(CourseEnrollmentClosedError): + data.create_course_enrollment(self.user.username, unicode(self.course.id), 'honor', True) - @raises(CourseEnrollmentFullError) @patch.object(CourseEnrollment, "enroll") def test_enrollment_for_full_course(self, mock_enroll): mock_enroll.side_effect = CourseFullError("Bad things happened") - data.create_course_enrollment(self.user.username, unicode(self.course.id), 'honor', True) + with pytest.raises(CourseEnrollmentFullError): + data.create_course_enrollment(self.user.username, unicode(self.course.id), 'honor', True) - @raises(CourseEnrollmentExistsError) @patch.object(CourseEnrollment, "enroll") def test_enrollment_for_enrolled_course(self, mock_enroll): mock_enroll.side_effect = AlreadyEnrolledError("Bad things happened") - data.create_course_enrollment(self.user.username, unicode(self.course.id), 'honor', True) + with pytest.raises(CourseEnrollmentExistsError): + data.create_course_enrollment(self.user.username, unicode(self.course.id), 'honor', True) - @raises(UserNotFoundError) def test_update_for_non_existent_user(self): - data.update_course_enrollment("some_fake_user", unicode(self.course.id), is_active=False) + with pytest.raises(UserNotFoundError): + data.update_course_enrollment("some_fake_user", unicode(self.course.id), is_active=False) def test_update_for_non_existent_course(self): enrollment = data.update_course_enrollment(self.user.username, "some/fake/course", is_active=False) diff --git a/common/djangoapps/static_replace/test/test_static_replace.py b/common/djangoapps/static_replace/test/test_static_replace.py index 759e50abad..e9c3779dcd 100644 --- a/common/djangoapps/static_replace/test/test_static_replace.py +++ b/common/djangoapps/static_replace/test/test_static_replace.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- """Tests for static_replace""" +from __future__ import print_function import re from cStringIO import StringIO @@ -10,7 +11,6 @@ import pytest from django.test import override_settings from django.utils.http import urlencode, urlquote from mock import Mock, patch -from nose.tools import assert_equals, assert_false, assert_true # pylint: disable=no-name-in-module from opaque_keys.edx.keys import CourseKey from PIL import Image @@ -54,21 +54,17 @@ def encode_unicode_characters_in_url(url): def test_multi_replace(): course_source = '"/course/file.png"' - assert_equals( - replace_static_urls(STATIC_SOURCE, DATA_DIRECTORY), + assert replace_static_urls(STATIC_SOURCE, DATA_DIRECTORY) == \ replace_static_urls(replace_static_urls(STATIC_SOURCE, DATA_DIRECTORY), DATA_DIRECTORY) - ) - assert_equals( - replace_course_urls(course_source, COURSE_KEY), + assert replace_course_urls(course_source, COURSE_KEY) == \ replace_course_urls(replace_course_urls(course_source, COURSE_KEY), COURSE_KEY) - ) def test_process_url(): def processor(__, prefix, quote, rest): # pylint: disable=missing-docstring return quote + 'test' + prefix + rest + quote - assert_equals('"test/static/file.png"', process_static_urls(STATIC_SOURCE, processor)) + assert process_static_urls(STATIC_SOURCE, processor) == '"test/static/file.png"' def test_process_url_data_dir_exists(): @@ -77,7 +73,7 @@ def test_process_url_data_dir_exists(): def processor(original, prefix, quote, rest): # pylint: disable=unused-argument,missing-docstring return quote + 'test' + rest + quote - assert_equals(base, process_static_urls(base, processor, data_dir=DATA_DIRECTORY)) + assert process_static_urls(base, processor, data_dir=DATA_DIRECTORY) == base def test_process_url_no_match(): @@ -85,14 +81,14 @@ def test_process_url_no_match(): def processor(__, prefix, quote, rest): # pylint: disable=missing-docstring return quote + 'test' + prefix + rest + quote - assert_equals('"test/static/file.png"', process_static_urls(STATIC_SOURCE, processor)) + assert process_static_urls(STATIC_SOURCE, processor) == '"test/static/file.png"' @patch('django.http.HttpRequest', autospec=True) def test_static_urls(mock_request): mock_request.build_absolute_uri = lambda url: 'http://' + url result = make_static_urls_absolute(mock_request, STATIC_SOURCE) - assert_equals(result, '\"http:///static/file.png\"') + assert result == '\"http:///static/file.png\"' @patch('static_replace.staticfiles_storage', autospec=True) @@ -100,7 +96,7 @@ def test_storage_url_exists(mock_storage): mock_storage.exists.return_value = True mock_storage.url.return_value = '/static/file.png' - assert_equals('"/static/file.png"', replace_static_urls(STATIC_SOURCE, DATA_DIRECTORY)) + assert replace_static_urls(STATIC_SOURCE, DATA_DIRECTORY) == '"/static/file.png"' mock_storage.exists.assert_called_once_with('file.png') mock_storage.url.assert_called_once_with('file.png') @@ -110,7 +106,7 @@ def test_storage_url_not_exists(mock_storage): mock_storage.exists.return_value = False mock_storage.url.return_value = '/static/data_dir/file.png' - assert_equals('"/static/data_dir/file.png"', replace_static_urls(STATIC_SOURCE, DATA_DIRECTORY)) + assert replace_static_urls(STATIC_SOURCE, DATA_DIRECTORY) == '"/static/data_dir/file.png"' mock_storage.exists.assert_called_once_with('file.png') mock_storage.url.assert_called_once_with('data_dir/file.png') @@ -127,13 +123,11 @@ def test_mongo_filestore(mock_get_excluded_extensions, mock_get_base_url, mock_m mock_get_excluded_extensions.return_value = ['foobar'] # No namespace => no change to path - assert_equals('"/static/data_dir/file.png"', replace_static_urls(STATIC_SOURCE, DATA_DIRECTORY)) + assert replace_static_urls(STATIC_SOURCE, DATA_DIRECTORY) == '"/static/data_dir/file.png"' # Namespace => content url - assert_equals( - '"' + mock_static_content.get_canonicalized_asset_path.return_value + '"', + assert '"' + mock_static_content.get_canonicalized_asset_path.return_value + '"' == \ replace_static_urls(STATIC_SOURCE, DATA_DIRECTORY, course_id=COURSE_KEY) - ) mock_static_content.get_canonicalized_asset_path.assert_called_once_with(COURSE_KEY, 'file.png', u'', ['foobar']) @@ -146,10 +140,10 @@ def test_data_dir_fallback(mock_storage, mock_modulestore, mock_settings): mock_storage.url.side_effect = Exception mock_storage.exists.return_value = True - assert_equals('"/static/data_dir/file.png"', replace_static_urls(STATIC_SOURCE, DATA_DIRECTORY)) + assert replace_static_urls(STATIC_SOURCE, DATA_DIRECTORY) == '"/static/data_dir/file.png"' mock_storage.exists.return_value = False - assert_equals('"/static/data_dir/file.png"', replace_static_urls(STATIC_SOURCE, DATA_DIRECTORY)) + assert replace_static_urls(STATIC_SOURCE, DATA_DIRECTORY) == '"/static/data_dir/file.png"' def test_raw_static_check(): @@ -157,10 +151,10 @@ def test_raw_static_check(): Make sure replace_static_urls leaves alone things that end in '.raw' """ path = '"/static/foo.png?raw"' - assert_equals(path, replace_static_urls(path, DATA_DIRECTORY)) + assert replace_static_urls(path, DATA_DIRECTORY) == path text = 'text
= minimum_calls # now verify the number of actual calls is less than (or equal to) the expected maximum - assert_less_equal(call_count, maximum_calls) + assert call_count <= maximum_calls def mongo_uses_error_check(store): diff --git a/common/lib/xmodule/xmodule/modulestore/tests/test_modulestore.py b/common/lib/xmodule/xmodule/modulestore/tests/test_modulestore.py index ba3d54bfc0..9ad1f88f0d 100644 --- a/common/lib/xmodule/xmodule/modulestore/tests/test_modulestore.py +++ b/common/lib/xmodule/xmodule/modulestore/tests/test_modulestore.py @@ -3,7 +3,6 @@ Defines a test function, check_has_course_method, useful in various modulestore This file should potentially be renamed "utilties" since this file contains no tests. """ -from nose.tools import assert_equals, assert_true, assert_false # pylint: disable=no-name-in-module def check_has_course_method(modulestore, locator, locator_key_fields): @@ -12,11 +11,11 @@ def check_has_course_method(modulestore, locator, locator_key_fields): for ignore_case in [True, False]: # should find the course with exact locator - assert_true(modulestore.has_course(locator, ignore_case)) + assert modulestore.has_course(locator, ignore_case) for key_field in locator_key_fields: if getattr(locator, key_field): - locator_changes_that_should_not_be_found = [ # pylint: disable=invalid-name + locator_changes_that_should_not_be_found = [ # replace value for one of the keys {key_field: 'fake'}, # add a character at the end @@ -26,10 +25,7 @@ def check_has_course_method(modulestore, locator, locator_key_fields): ] for changes in locator_changes_that_should_not_be_found: search_locator = locator.replace(**changes) - assert_false( - modulestore.has_course(search_locator), - error_message.format(search_locator, ignore_case) - ) + assert not modulestore.has_course(search_locator), error_message.format(search_locator, ignore_case) # test case [in]sensitivity locator_case_changes = [ @@ -41,8 +37,5 @@ def check_has_course_method(modulestore, locator, locator_key_fields): search_locator = locator.replace(**changes) # if ignore_case is true, the course would be found with a different-cased course locator. # if ignore_case is false, the course should NOT found given an incorrectly-cased locator. - assert_equals( - modulestore.has_course(search_locator, ignore_case) is not None, - ignore_case, + assert (modulestore.has_course(search_locator, ignore_case) is not None) == ignore_case, \ error_message.format(search_locator, ignore_case) - ) diff --git a/common/lib/xmodule/xmodule/modulestore/tests/test_mongo.py b/common/lib/xmodule/xmodule/modulestore/tests/test_mongo.py index 0d0c33418d..c639d5b735 100644 --- a/common/lib/xmodule/xmodule/modulestore/tests/test_mongo.py +++ b/common/lib/xmodule/xmodule/modulestore/tests/test_mongo.py @@ -4,12 +4,11 @@ Unit tests for the Mongo modulestore # pylint: disable=protected-access # pylint: disable=no-name-in-module # pylint: disable=bad-continuation -from nose.tools import assert_equals, assert_raises, \ - assert_not_equals, assert_false, assert_true, assert_greater, assert_is_instance, assert_is_none from django.test import TestCase # pylint: enable=E0611 from path import Path as path import pymongo +import pytest import logging import shutil from tempfile import mkdtemp @@ -34,7 +33,6 @@ from xmodule.modulestore.xml_exporter import export_course_to_xml from xmodule.modulestore.xml_importer import import_course_from_xml, perform_xlint from xmodule.contentstore.mongo import MongoContentStore -from nose.tools import assert_in from xmodule.exceptions import NotFoundError from xmodule.x_module import XModuleMixin from xmodule.modulestore.mongo.base import as_draft @@ -202,7 +200,7 @@ class TestMongoModuleStore(TestMongoModuleStoreBase): def test_init(self): '''Make sure the db loads''' ids = list(self.connection[DB][COLLECTION].find({}, {'_id': True})) - assert_greater(len(ids), 12) + assert len(ids) > 12 def test_mongo_modulestore_type(self): store = DraftModuleStore( @@ -210,14 +208,14 @@ class TestMongoModuleStore(TestMongoModuleStoreBase): {'host': HOST, 'db': DB, 'port': PORT, 'collection': COLLECTION}, FS_ROOT, RENDER_TEMPLATE, default_class=DEFAULT_CLASS ) - assert_equals(store.get_modulestore_type(''), ModuleStoreEnum.Type.mongo) + assert store.get_modulestore_type('') == ModuleStoreEnum.Type.mongo @patch('xmodule.tabs.CourseTab.from_json', side_effect=mock_tab_from_json) def test_get_courses(self, _from_json): '''Make sure the course objects loaded properly''' courses = self.draft_store.get_courses() - assert_equals(len(courses), 6) + assert len(courses) == 6 course_ids = [course.id for course in courses] for course_key in [ @@ -232,15 +230,15 @@ class TestMongoModuleStore(TestMongoModuleStoreBase): ['guestx', 'foo', 'bar'], ] ]: - assert_in(course_key, course_ids) + assert course_key in course_ids course = self.draft_store.get_course(course_key) - assert_not_none(course) - assert_true(self.draft_store.has_course(course_key)) + assert course is not None + assert self.draft_store.has_course(course_key) mix_cased = CourseKey.from_string( '/'.join([course_key.org.upper(), course_key.course.upper(), course_key.run.lower()]) ) - assert_false(self.draft_store.has_course(mix_cased)) - assert_true(self.draft_store.has_course(mix_cased, ignore_case=True)) + assert not self.draft_store.has_course(mix_cased) + assert self.draft_store.has_course(mix_cased, ignore_case=True) @patch('xmodule.tabs.CourseTab.from_json', side_effect=mock_tab_from_json) def test_get_org_courses(self, _from_json): @@ -249,7 +247,7 @@ class TestMongoModuleStore(TestMongoModuleStoreBase): """ courses = self.draft_store.get_courses(org='guestx') - assert_equals(len(courses), 1) + assert len(courses) == 1 course_ids = [course.id for course in courses] for course_key in [ @@ -258,10 +256,10 @@ class TestMongoModuleStore(TestMongoModuleStoreBase): ['guestx', 'foo', 'bar'] ] ]: - assert_in(course_key, course_ids) + assert course_key in course_ids courses = self.draft_store.get_courses(org='edX') - assert_equals(len(courses), 5) + assert len(courses) == 5 course_ids = [course.id for course in courses] for course_key in [ @@ -274,7 +272,7 @@ class TestMongoModuleStore(TestMongoModuleStoreBase): ['edX', 'toy', '2012_Fall'], ] ]: - assert_in(course_key, course_ids) + assert course_key in course_ids def test_no_such_course(self): """ @@ -289,13 +287,13 @@ class TestMongoModuleStore(TestMongoModuleStoreBase): ] ]: course = self.draft_store.get_course(course_key) - assert_is_none(course) - assert_false(self.draft_store.has_course(course_key)) + assert course is None + assert not self.draft_store.has_course(course_key) mix_cased = CourseKey.from_string( '/'.join([course_key.org.lower(), course_key.course.upper(), course_key.run.upper()]) ) - assert_false(self.draft_store.has_course(mix_cased)) - assert_false(self.draft_store.has_course(mix_cased, ignore_case=True)) + assert not self.draft_store.has_course(mix_cased) + assert not self.draft_store.has_course(mix_cased, ignore_case=True) def test_get_mongo_course_with_split_course_key(self): """ @@ -322,79 +320,59 @@ class TestMongoModuleStore(TestMongoModuleStoreBase): """ lib_key = LibraryLocator("TestOrg", "TestLib") result = self.draft_store.has_course(lib_key) - assert_false(result) + assert not result def test_loads(self): - assert_not_none( - self.draft_store.get_item(BlockUsageLocator(CourseLocator('edX', 'toy', '2012_Fall', deprecated=True), - 'course', '2012_Fall', deprecated=True)) - ) + assert self.draft_store.get_item(BlockUsageLocator(CourseLocator('edX', 'toy', '2012_Fall', deprecated=True), + 'course', '2012_Fall', deprecated=True)) is not None - assert_not_none( - self.draft_store.get_item(BlockUsageLocator(CourseLocator('edX', 'simple', '2012_Fall', deprecated=True), - 'course', '2012_Fall', deprecated=True)), - ) + assert self.draft_store.get_item(BlockUsageLocator(CourseLocator('edX', 'simple', '2012_Fall', deprecated=True), + 'course', '2012_Fall', deprecated=True)) is not None - assert_not_none( - self.draft_store.get_item(BlockUsageLocator(CourseLocator('edX', 'toy', '2012_Fall', deprecated=True), - 'video', 'Welcome', deprecated=True)), - ) + assert self.draft_store.get_item(BlockUsageLocator(CourseLocator('edX', 'toy', '2012_Fall', deprecated=True), + 'video', 'Welcome', deprecated=True)) is not None def test_unicode_loads(self): """ Test that getting items from the test_unicode course works """ - assert_not_none( - self.draft_store.get_item( - BlockUsageLocator(CourseLocator('edX', 'test_unicode', '2012_Fall', deprecated=True), - 'course', '2012_Fall', deprecated=True)), - ) + assert self.draft_store.get_item( + BlockUsageLocator(CourseLocator('edX', 'test_unicode', '2012_Fall', deprecated=True), + 'course', '2012_Fall', deprecated=True)) is not None # All items with ascii-only filenames should load properly. - assert_not_none( - self.draft_store.get_item( - BlockUsageLocator(CourseLocator('edX', 'test_unicode', '2012_Fall', deprecated=True), - 'video', 'Welcome', deprecated=True)), - ) - assert_not_none( - self.draft_store.get_item( - BlockUsageLocator(CourseLocator('edX', 'test_unicode', '2012_Fall', deprecated=True), - 'video', 'Welcome', deprecated=True)), - ) - assert_not_none( - self.draft_store.get_item( - BlockUsageLocator(CourseLocator('edX', 'test_unicode', '2012_Fall', deprecated=True), - 'chapter', 'Overview', deprecated=True)), - ) + assert self.draft_store.get_item( + BlockUsageLocator(CourseLocator('edX', 'test_unicode', '2012_Fall', deprecated=True), + 'video', 'Welcome', deprecated=True)) is not None + assert self.draft_store.get_item( + BlockUsageLocator(CourseLocator('edX', 'test_unicode', '2012_Fall', deprecated=True), + 'video', 'Welcome', deprecated=True)) is not None + assert self.draft_store.get_item( + BlockUsageLocator(CourseLocator('edX', 'test_unicode', '2012_Fall', deprecated=True), + 'chapter', 'Overview', deprecated=True)) is not None def test_find_one(self): - assert_not_none( - self.draft_store._find_one( - BlockUsageLocator(CourseLocator('edX', 'toy', '2012_Fall', deprecated=True), - 'course', '2012_Fall', deprecated=True)), - ) + assert self.draft_store._find_one( + BlockUsageLocator(CourseLocator('edX', 'toy', '2012_Fall', deprecated=True), + 'course', '2012_Fall', deprecated=True)) is not None - assert_not_none( - self.draft_store._find_one( - BlockUsageLocator(CourseLocator('edX', 'simple', '2012_Fall', deprecated=True), - 'course', '2012_Fall', deprecated=True)), - ) + assert self.draft_store._find_one( + BlockUsageLocator(CourseLocator('edX', 'simple', '2012_Fall', deprecated=True), + 'course', '2012_Fall', deprecated=True)) is not None - assert_not_none( - self.draft_store._find_one(BlockUsageLocator(CourseLocator('edX', 'toy', '2012_Fall', deprecated=True), - 'video', 'Welcome', deprecated=True)), - ) + assert self.draft_store._find_one(BlockUsageLocator(CourseLocator('edX', 'toy', '2012_Fall', deprecated=True), + 'video', 'Welcome', deprecated=True)) is not None def test_xlinter(self): ''' Run through the xlinter, we know the 'toy' course has violations, but the number will continue to grow over time, so just check > 0 ''' - assert_not_equals(perform_xlint(DATA_DIR, ['toy']), 0) + assert perform_xlint(DATA_DIR, ['toy']) != 0 def test_get_courses_has_no_templates(self): courses = self.draft_store.get_courses() for course in courses: - assert_false( + self.assertFalse( course.location.org == 'edx' and course.location.course == 'templates', '{0} is a template course'.format(course) ) @@ -406,64 +384,58 @@ class TestMongoModuleStore(TestMongoModuleStoreBase): location = BlockUsageLocator(CourseLocator('edX', 'toy', '2012_Fall', deprecated=True), 'course', '2012_Fall', deprecated=True) course_content, __ = self.content_store.get_all_content_for_course(location.course_key) - assert_true(len(course_content) > 0) + assert len(course_content) > 0 filter_params = _build_requested_filter('Images') filtered_course_content, __ = self.content_store.get_all_content_for_course( location.course_key, filter_params=filter_params) - assert_true(len(filtered_course_content) < len(course_content)) + assert len(filtered_course_content) < len(course_content) # a bit overkill, could just do for content[0] for content in course_content: assert not content.get('locked', False) asset_key = AssetLocator._from_deprecated_son(content.get('content_son', content['_id']), location.run) assert not self.content_store.get_attr(asset_key, 'locked', False) attrs = self.content_store.get_attrs(asset_key) - assert_in('uploadDate', attrs) + assert 'uploadDate' in attrs assert not attrs.get('locked', False) self.content_store.set_attr(asset_key, 'locked', True) assert self.content_store.get_attr(asset_key, 'locked', False) attrs = self.content_store.get_attrs(asset_key) - assert_in('locked', attrs) + assert 'locked' in attrs assert attrs['locked'] is True self.content_store.set_attrs(asset_key, {'miscel': 99}) - assert_equals(self.content_store.get_attr(asset_key, 'miscel'), 99) + assert self.content_store.get_attr(asset_key, 'miscel') == 99 asset_key = AssetLocator._from_deprecated_son( course_content[0].get('content_son', course_content[0]['_id']), location.run ) - assert_raises( - AttributeError, self.content_store.set_attr, asset_key, - 'md5', 'ff1532598830e3feac91c2449eaa60d6' - ) - assert_raises( - AttributeError, self.content_store.set_attrs, asset_key, - {'foo': 9, 'md5': 'ff1532598830e3feac91c2449eaa60d6'} - ) - assert_raises( - NotFoundError, self.content_store.get_attr, - BlockUsageLocator(CourseLocator('bogus', 'bogus', 'bogus'), 'asset', 'bogus'), - 'displayname' - ) - assert_raises( - NotFoundError, self.content_store.set_attr, - BlockUsageLocator(CourseLocator('bogus', 'bogus', 'bogus'), 'asset', 'bogus'), - 'displayname', 'hello' - ) - assert_raises( - NotFoundError, self.content_store.get_attrs, - BlockUsageLocator(CourseLocator('bogus', 'bogus', 'bogus'), 'asset', 'bogus') - ) - assert_raises( - NotFoundError, self.content_store.set_attrs, - BlockUsageLocator(CourseLocator('bogus', 'bogus', 'bogus'), 'asset', 'bogus'), - {'displayname': 'hello'} - ) - assert_raises( - NotFoundError, self.content_store.set_attrs, - BlockUsageLocator(CourseLocator('bogus', 'bogus', 'bogus', deprecated=True), - 'asset', None, deprecated=True), - {'displayname': 'hello'} - ) + with pytest.raises(AttributeError): + self.content_store.set_attr(asset_key, 'md5', 'ff1532598830e3feac91c2449eaa60d6') + with pytest.raises(AttributeError): + self.content_store.set_attrs(asset_key, {'foo': 9, 'md5': 'ff1532598830e3feac91c2449eaa60d6'}) + with pytest.raises(NotFoundError): + self.content_store.get_attr( + BlockUsageLocator(CourseLocator('bogus', 'bogus', 'bogus'), 'asset', 'bogus'), + 'displayname' + ) + with pytest.raises(NotFoundError): + self.content_store.set_attr( + BlockUsageLocator(CourseLocator('bogus', 'bogus', 'bogus'), 'asset', 'bogus'), + 'displayname', 'hello' + ) + with pytest.raises(NotFoundError): + self.content_store.get_attrs(BlockUsageLocator(CourseLocator('bogus', 'bogus', 'bogus'), 'asset', 'bogus')) + with pytest.raises(NotFoundError): + self.content_store.set_attrs( + BlockUsageLocator(CourseLocator('bogus', 'bogus', 'bogus'), 'asset', 'bogus'), + {'displayname': 'hello'} + ) + with pytest.raises(NotFoundError): + self.content_store.set_attrs( + BlockUsageLocator(CourseLocator('bogus', 'bogus', 'bogus', deprecated=True), + 'asset', None, deprecated=True), + {'displayname': 'hello'} + ) @patch('xmodule.tabs.CourseTab.from_json', side_effect=mock_tab_from_json) def test_get_courses_for_wiki(self, _from_json): @@ -472,11 +444,11 @@ class TestMongoModuleStore(TestMongoModuleStoreBase): """ for course_number in self.courses: course_locations = self.draft_store.get_courses_for_wiki(course_number) - assert_equals(len(course_locations), 1) - assert_equals(CourseKey.from_string('/'.join(['edX', course_number, '2012_Fall'])), course_locations[0]) + assert len(course_locations) == 1 + assert CourseKey.from_string('/'.join(['edX', course_number, '2012_Fall'])) == course_locations[0] course_locations = self.draft_store.get_courses_for_wiki('no_such_wiki') - assert_equals(len(course_locations), 0) + assert len(course_locations) == 0 # set toy course to share the wiki with simple course toy_course = self.draft_store.get_course(CourseKey.from_string('edX/toy/2012_Fall')) @@ -485,13 +457,13 @@ class TestMongoModuleStore(TestMongoModuleStoreBase): # now toy_course should not be retrievable with old wiki_slug course_locations = self.draft_store.get_courses_for_wiki('toy') - assert_equals(len(course_locations), 0) + assert len(course_locations) == 0 # but there should be two courses with wiki_slug 'simple' course_locations = self.draft_store.get_courses_for_wiki('simple') - assert_equals(len(course_locations), 2) + assert len(course_locations) == 2 for course_number in ['toy', 'simple']: - assert_in(CourseKey.from_string('/'.join(['edX', course_number, '2012_Fall'])), course_locations) + assert CourseKey.from_string('/'.join(['edX', course_number, '2012_Fall'])) in course_locations # configure simple course to use unique wiki_slug. simple_course = self.draft_store.get_course(CourseKey.from_string('edX/simple/2012_Fall')) @@ -499,8 +471,8 @@ class TestMongoModuleStore(TestMongoModuleStoreBase): self.draft_store.update_item(simple_course, ModuleStoreEnum.UserID.test) # it should be retrievable with its new wiki_slug course_locations = self.draft_store.get_courses_for_wiki('edX.simple.2012_Fall') - assert_equals(len(course_locations), 1) - assert_in(CourseKey.from_string('edX/simple/2012_Fall'), course_locations) + assert len(course_locations) == 1 + assert CourseKey.from_string('edX/simple/2012_Fall') in course_locations @XBlock.register_temp_plugin(ReferenceTestXBlock, 'ref_test') def test_reference_converters(self): @@ -544,20 +516,20 @@ class TestMongoModuleStore(TestMongoModuleStoreBase): def check_xblock_fields(): def check_children(xblock): for child in xblock.children: - assert_is_instance(child, UsageKey) + assert isinstance(child, UsageKey) course = self.draft_store.get_course(course_key) check_children(course) refele = self.draft_store.get_item(self.refloc) check_children(refele) - assert_is_instance(refele.reference_link, UsageKey) - assert_greater(len(refele.reference_list), 0) + assert isinstance(refele.reference_link, UsageKey) + assert len(refele.reference_list) > 0 for ref in refele.reference_list: - assert_is_instance(ref, UsageKey) - assert_greater(len(refele.reference_dict), 0) + assert isinstance(ref, UsageKey) + assert len(refele.reference_dict) > 0 for ref in refele.reference_dict.itervalues(): - assert_is_instance(ref, UsageKey) + assert isinstance(ref, UsageKey) def check_mongo_fields(): def get_item(location): @@ -565,17 +537,17 @@ class TestMongoModuleStore(TestMongoModuleStoreBase): def check_children(payload): for child in payload['definition']['children']: - assert_is_instance(child, basestring) + assert isinstance(child, basestring) refele = get_item(self.refloc) check_children(refele) - assert_is_instance(refele['definition']['data']['reference_link'], basestring) - assert_greater(len(refele['definition']['data']['reference_list']), 0) + assert isinstance(refele['definition']['data']['reference_link'], basestring) + assert len(refele['definition']['data']['reference_list']) > 0 for ref in refele['definition']['data']['reference_list']: - assert_is_instance(ref, basestring) - assert_greater(len(refele['metadata']['reference_dict']), 0) + assert isinstance(ref, basestring) + assert len(refele['metadata']['reference_dict']) > 0 for ref in refele['metadata']['reference_dict'].itervalues(): - assert_is_instance(ref, basestring) + assert isinstance(ref, basestring) setup_test() check_xblock_fields() @@ -608,7 +580,7 @@ class TestMongoModuleStore(TestMongoModuleStoreBase): don't export it to the static default location """ course = self.draft_store.get_course(CourseKey.from_string('edX/toy/2012_Fall')) - assert_true(course.course_image, 'just_a_test.jpg') + assert course.course_image == 'just_a_test.jpg' root_dir = path(mkdtemp()) self.addCleanup(shutil.rmtree, root_dir) @@ -797,25 +769,25 @@ class TestMongoKeyValueStore(TestCase): self.kvs = MongoKeyValueStore(self.data, self.parent, self.children, self.metadata) def test_read(self): - assert_equals(self.data['foo'], self.kvs.get(KeyValueStore.Key(Scope.content, None, None, 'foo'))) - assert_equals(self.parent, self.kvs.get(KeyValueStore.Key(Scope.parent, None, None, 'parent'))) - assert_equals(self.children, self.kvs.get(KeyValueStore.Key(Scope.children, None, None, 'children'))) - assert_equals(self.metadata['meta'], self.kvs.get(KeyValueStore.Key(Scope.settings, None, None, 'meta'))) + assert self.kvs.get(KeyValueStore.Key(Scope.content, None, None, 'foo')) == self.data['foo'] + assert self.kvs.get(KeyValueStore.Key(Scope.parent, None, None, 'parent')) == self.parent + assert self.kvs.get(KeyValueStore.Key(Scope.children, None, None, 'children')) == self.children + assert self.kvs.get(KeyValueStore.Key(Scope.settings, None, None, 'meta')) == self.metadata['meta'] def test_read_invalid_scope(self): for scope in (Scope.preferences, Scope.user_info, Scope.user_state): key = KeyValueStore.Key(scope, None, None, 'foo') - with assert_raises(InvalidScopeError): + with pytest.raises(InvalidScopeError): self.kvs.get(key) - assert_false(self.kvs.has(key)) + assert not self.kvs.has(key) def test_read_non_dict_data(self): self.kvs = MongoKeyValueStore('xml_data', self.parent, self.children, self.metadata) - assert_equals('xml_data', self.kvs.get(KeyValueStore.Key(Scope.content, None, None, 'data'))) + assert self.kvs.get(KeyValueStore.Key(Scope.content, None, None, 'data')) == 'xml_data' def _check_write(self, key, value): self.kvs.set(key, value) - assert_equals(value, self.kvs.get(key)) + assert self.kvs.get(key) == value def test_write(self): yield (self._check_write, KeyValueStore.Key(Scope.content, None, None, 'foo'), 'new_data') @@ -829,19 +801,19 @@ class TestMongoKeyValueStore(TestCase): def test_write_invalid_scope(self): for scope in (Scope.preferences, Scope.user_info, Scope.user_state): - with assert_raises(InvalidScopeError): + with pytest.raises(InvalidScopeError): self.kvs.set(KeyValueStore.Key(scope, None, None, 'foo'), 'new_value') def _check_delete_default(self, key, default_value): self.kvs.delete(key) - assert_equals(default_value, self.kvs.get(key)) + assert self.kvs.get(key) == default_value assert self.kvs.has(key) def _check_delete_key_error(self, key): self.kvs.delete(key) - with assert_raises(KeyError): + with pytest.raises(KeyError): self.kvs.get(key) - assert_false(self.kvs.has(key)) + assert not self.kvs.has(key) def test_delete(self): yield (self._check_delete_key_error, KeyValueStore.Key(Scope.content, None, None, 'foo')) @@ -850,7 +822,7 @@ class TestMongoKeyValueStore(TestCase): def test_delete_invalid_scope(self): for scope in (Scope.preferences, Scope.user_info, Scope.user_state, Scope.parent): - with assert_raises(InvalidScopeError): + with pytest.raises(InvalidScopeError): self.kvs.delete(KeyValueStore.Key(scope, None, None, 'foo')) diff --git a/common/lib/xmodule/xmodule/tests/test_stringify.py b/common/lib/xmodule/xmodule/tests/test_stringify.py index e6910509c3..371dccd25a 100644 --- a/common/lib/xmodule/xmodule/tests/test_stringify.py +++ b/common/lib/xmodule/xmodule/tests/test_stringify.py @@ -1,22 +1,22 @@ """ Tests stringify functions used in xmodule html """ -from nose.tools import assert_equals # pylint: disable=no-name-in-module from lxml import etree +from openedx.core.lib.tests import attr from xmodule.stringify import stringify_children +@attr(shard=1) def test_stringify(): - shard = 1 text = 'Hi
there Bruce!
' html = '''{0}'''.format(text) xml = etree.fromstring(html) out = stringify_children(xml) - assert_equals(out, text) + assert out == text +@attr(shard=1) def test_stringify_again(): - shard = 1 html = r"""A voltage source is non-linear!
@@ -43,4 +43,4 @@ def test_stringify_again(): # Tracking strange content repeating bug # Should appear once - assert_equals(out.count("But it is "), 1) + assert out.count("But it is ") == 1 diff --git a/common/lib/xmodule/xmodule/tests/test_utils_django.py b/common/lib/xmodule/xmodule/tests/test_utils_django.py index f79d3b5a04..e659809c4b 100644 --- a/common/lib/xmodule/xmodule/tests/test_utils_django.py +++ b/common/lib/xmodule/xmodule/tests/test_utils_django.py @@ -1,6 +1,5 @@ """Tests for methods defined in util/django.py""" from xmodule.util.xmodule_django import get_current_request, get_current_request_hostname -from nose.tools import assert_is_none from unittest import TestCase @@ -14,10 +13,10 @@ class UtilDjangoTests(TestCase): """ Since we are running outside of Django assert that get_current_request returns None """ - assert_is_none(get_current_request()) + assert get_current_request() is None def test_get_current_request_hostname(self): """ Since we are running outside of Django assert that get_current_request_hostname returns None """ - assert_is_none(get_current_request_hostname()) + assert get_current_request_hostname() is None diff --git a/common/lib/xmodule/xmodule/tests/test_xml_module.py b/common/lib/xmodule/xmodule/tests/test_xml_module.py index f5d1b96de7..3d7178f506 100644 --- a/common/lib/xmodule/xmodule/tests/test_xml_module.py +++ b/common/lib/xmodule/xmodule/tests/test_xml_module.py @@ -4,7 +4,6 @@ import unittest from mock import Mock -from nose.tools import assert_equals, assert_not_equals, assert_true, assert_false, assert_in, assert_not_in # pylint: disable=no-name-in-module from opaque_keys.edx.locator import BlockUsageLocator, CourseLocator from xblock.field_data import DictFieldData @@ -376,21 +375,20 @@ class TestSerialize(unittest.TestCase): shard = 1 def test_serialize(self): - assert_equals('null', serialize_field(None)) - assert_equals('-2', serialize_field(-2)) - assert_equals('2', serialize_field('2')) - assert_equals('-3.41', serialize_field(-3.41)) - assert_equals('2.589', serialize_field('2.589')) - assert_equals('false', serialize_field(False)) - assert_equals('false', serialize_field('false')) - assert_equals('fAlse', serialize_field('fAlse')) - assert_equals('hat box', serialize_field('hat box')) - assert_equals('{"bar": "hat", "frog": "green"}', serialize_field({'bar': 'hat', 'frog': 'green'})) - assert_equals('[3.5, 5.6]', serialize_field([3.5, 5.6])) - assert_equals('["foo", "bar"]', serialize_field(['foo', 'bar'])) - assert_equals('2012-12-31T23:59:59Z', serialize_field("2012-12-31T23:59:59Z")) - assert_equals('1 day 12 hours 59 minutes 59 seconds', - serialize_field("1 day 12 hours 59 minutes 59 seconds")) + assert serialize_field(None) == 'null' + assert serialize_field(-2) == '-2' + assert serialize_field('2') == '2' + assert serialize_field(-3.41) == '-3.41' + assert serialize_field('2.589') == '2.589' + assert serialize_field(False) == 'false' + assert serialize_field('false') == 'false' + assert serialize_field('fAlse') == 'fAlse' + assert serialize_field('hat box') == 'hat box' + assert serialize_field({'bar': 'hat', 'frog': 'green'}) == '{"bar": "hat", "frog": "green"}' + assert serialize_field([3.5, 5.6]) == '[3.5, 5.6]' + assert serialize_field(['foo', 'bar']) == '["foo", "bar"]' + assert serialize_field("2012-12-31T23:59:59Z") == '2012-12-31T23:59:59Z' + assert serialize_field("1 day 12 hours 59 minutes 59 seconds") == '1 day 12 hours 59 minutes 59 seconds' class TestDeserialize(unittest.TestCase): @@ -400,7 +398,7 @@ class TestDeserialize(unittest.TestCase): """ Asserts the result of deserialize_field. """ - assert_equals(expected, deserialize_field(self.field_type(), arg)) + assert deserialize_field(self.field_type(), arg) == expected def assertDeserializeNonString(self): """ @@ -603,20 +601,20 @@ class TestXmlAttributes(XModuleXmlImportTest): shard = 1 def test_unknown_attribute(self): - assert_false(hasattr(CourseDescriptor, 'unknown_attr')) + assert not hasattr(CourseDescriptor, 'unknown_attr') course = self.process_xml(CourseFactory.build(unknown_attr='value')) - assert_false(hasattr(course, 'unknown_attr')) - assert_equals('value', course.xml_attributes['unknown_attr']) + assert not hasattr(course, 'unknown_attr') + assert course.xml_attributes['unknown_attr'] == 'value' def test_known_attribute(self): - assert_true(hasattr(CourseDescriptor, 'show_calculator')) + assert hasattr(CourseDescriptor, 'show_calculator') course = self.process_xml(CourseFactory.build(show_calculator='true')) - assert_true(course.show_calculator) - assert_not_in('show_calculator', course.xml_attributes) + assert course.show_calculator + assert 'show_calculator' not in course.xml_attributes def test_rerandomize_in_policy(self): # Rerandomize isn't a basic attribute of Sequence - assert_false(hasattr(SequenceDescriptor, 'rerandomize')) + assert not hasattr(SequenceDescriptor, 'rerandomize') root = SequenceFactory.build(policy={'rerandomize': 'never'}) ProblemFactory.build(parent=root) @@ -624,15 +622,15 @@ class TestXmlAttributes(XModuleXmlImportTest): seq = self.process_xml(root) # Rerandomize is added to the constructed sequence via the InheritanceMixin - assert_equals('never', seq.rerandomize) + assert seq.rerandomize == 'never' # Rerandomize is a known value coming from policy, and shouldn't appear # in xml_attributes - assert_not_in('rerandomize', seq.xml_attributes) + assert 'rerandomize' not in seq.xml_attributes def test_attempts_in_policy(self): # attempts isn't a basic attribute of Sequence - assert_false(hasattr(SequenceDescriptor, 'attempts')) + assert not hasattr(SequenceDescriptor, 'attempts') root = SequenceFactory.build(policy={'attempts': '1'}) ProblemFactory.build(parent=root) @@ -641,38 +639,38 @@ class TestXmlAttributes(XModuleXmlImportTest): # attempts isn't added to the constructed sequence, because # it's not in the InheritanceMixin - assert_false(hasattr(seq, 'attempts')) + assert not hasattr(seq, 'attempts') # attempts is an unknown attribute, so we should include it # in xml_attributes so that it gets written out (despite the misleading # name) - assert_in('attempts', seq.xml_attributes) + assert 'attempts' in seq.xml_attributes def check_inheritable_attribute(self, attribute, value): # `attribute` isn't a basic attribute of Sequence - assert_false(hasattr(SequenceDescriptor, attribute)) + assert not hasattr(SequenceDescriptor, attribute) # `attribute` is added by InheritanceMixin - assert_true(hasattr(InheritanceMixin, attribute)) + assert hasattr(InheritanceMixin, attribute) root = SequenceFactory.build(policy={attribute: str(value)}) ProblemFactory.build(parent=root) # InheritanceMixin will be used when processing the XML - assert_in(InheritanceMixin, root.xblock_mixins) + assert InheritanceMixin in root.xblock_mixins seq = self.process_xml(root) - assert_equals(seq.unmixed_class, SequenceDescriptor) - assert_not_equals(type(seq), SequenceDescriptor) + assert seq.unmixed_class == SequenceDescriptor + assert type(seq) != SequenceDescriptor # `attribute` is added to the constructed sequence, because # it's in the InheritanceMixin - assert_equals(value, getattr(seq, attribute)) + assert getattr(seq, attribute) == value # `attribute` is a known attribute, so we shouldn't include it # in xml_attributes - assert_not_in(attribute, seq.xml_attributes) + assert attribute not in seq.xml_attributes def test_inheritable_attributes(self): self.check_inheritable_attribute('days_early_for_beta', 2) diff --git a/common/lib/xmodule/xmodule/tests/xml/test_inheritance.py b/common/lib/xmodule/xmodule/tests/xml/test_inheritance.py index 7c50cd4304..7c401bb5a9 100644 --- a/common/lib/xmodule/xmodule/tests/xml/test_inheritance.py +++ b/common/lib/xmodule/xmodule/tests/xml/test_inheritance.py @@ -1,8 +1,6 @@ """ Test that inherited fields work correctly when parsing XML """ -from nose.tools import assert_equals, assert_in # pylint: disable=no-name-in-module - from xmodule.tests.xml import XModuleXmlImportTest from xmodule.tests.xml.factories import CourseFactory, SequenceFactory, ProblemFactory, XmlImportFactory @@ -22,13 +20,13 @@ class TestInheritedFieldParsing(XModuleXmlImportTest): ProblemFactory.build(parent=sequence) course = self.process_xml(root) - assert_equals(None, course.days_early_for_beta) + assert course.days_early_for_beta is None sequence = course.get_children()[0] - assert_equals(None, sequence.days_early_for_beta) + assert sequence.days_early_for_beta is None problem = sequence.get_children()[0] - assert_equals(None, problem.days_early_for_beta) + assert problem.days_early_for_beta is None def test_video_attr(self): """ @@ -46,4 +44,4 @@ class TestInheritedFieldParsing(XModuleXmlImportTest): } ) video_block = self.process_xml(video) - assert_in('garbage', video_block.xml_attributes) + assert 'garbage' in video_block.xml_attributes diff --git a/common/lib/xmodule/xmodule/tests/xml/test_policy.py b/common/lib/xmodule/xmodule/tests/xml/test_policy.py index 9c77c14980..3820c42c4a 100644 --- a/common/lib/xmodule/xmodule/tests/xml/test_policy.py +++ b/common/lib/xmodule/xmodule/tests/xml/test_policy.py @@ -2,7 +2,7 @@ Tests that policy json files import correctly when loading XML """ -from nose.tools import assert_equals, assert_raises # pylint: disable=no-name-in-module +import pytest from xmodule.tests.xml.factories import CourseFactory from xmodule.tests.xml import XModuleXmlImportTest @@ -18,7 +18,7 @@ class TestPolicy(XModuleXmlImportTest): # Policy files are json, and thus the values aren't passed through 'deserialize_field' # Therefor, the string 'null' is passed unchanged to the Float field, which will trigger # a ValueError - with assert_raises(ValueError): + with pytest.raises(ValueError): course = self.process_xml(CourseFactory.build(policy={'days_early_for_beta': 'null'})) # Trigger the exception by looking at the imported data @@ -26,7 +26,7 @@ class TestPolicy(XModuleXmlImportTest): def test_course_policy(self): course = self.process_xml(CourseFactory.build(policy={'days_early_for_beta': None})) - assert_equals(None, course.days_early_for_beta) + assert course.days_early_for_beta is None course = self.process_xml(CourseFactory.build(policy={'days_early_for_beta': 9})) - assert_equals(9, course.days_early_for_beta) + assert course.days_early_for_beta == 9 diff --git a/common/test/acceptance/tests/discussion/test_discussion.py b/common/test/acceptance/tests/discussion/test_discussion.py index 1ab253385c..ed0dd9469d 100644 --- a/common/test/acceptance/tests/discussion/test_discussion.py +++ b/common/test/acceptance/tests/discussion/test_discussion.py @@ -6,7 +6,7 @@ import datetime from unittest import skip from uuid import uuid4 -from nose.tools import nottest +import pytest from pytz import UTC from common.test.acceptance.fixtures.course import CourseFixture, XBlockFixtureDesc @@ -1052,9 +1052,8 @@ class InlineDiscussionTest(UniqueCourseTest): self.discussion_page = InlineDiscussionPage(self.browser, self.discussion_id) self.additional_discussion_page = InlineDiscussionPage(self.browser, self.additional_discussion_id) - # This test is too flaky to run at all. TNL-6215 @attr('a11y') - @nottest + @pytest.mark.skip(reason='This test is too flaky to run at all. TNL-6215') def test_inline_a11y(self): """ Tests Inline Discussion for accessibility issues. diff --git a/common/test/acceptance/tests/studio/test_studio_rerun.py b/common/test/acceptance/tests/studio/test_studio_rerun.py index e27739db11..46c66b14db 100644 --- a/common/test/acceptance/tests/studio/test_studio_rerun.py +++ b/common/test/acceptance/tests/studio/test_studio_rerun.py @@ -5,7 +5,6 @@ Acceptance tests for Studio related to course reruns. import random from bok_choy.promise import EmptyPromise -from nose.tools import assert_in from base_studio_test import StudioCourseTest from common.test.acceptance.fixtures.course import XBlockFixtureDesc @@ -85,7 +84,7 @@ class CourseRerunTest(StudioCourseTest): EmptyPromise(finished_processing, "Rerun finished processing", try_interval=5, timeout=60).fulfill() - assert_in(course_run, self.dashboard_page.course_runs) + assert course_run in self.dashboard_page.course_runs self.dashboard_page.click_course_run(course_run) outline_page = CourseOutlinePage(self.browser, *course_info) diff --git a/lms/djangoapps/discussion/tests/test_views.py b/lms/djangoapps/discussion/tests/test_views.py index e454e19e22..6375a448f2 100644 --- a/lms/djangoapps/discussion/tests/test_views.py +++ b/lms/djangoapps/discussion/tests/test_views.py @@ -9,7 +9,6 @@ from django.test.client import Client, RequestFactory from django.test.utils import override_settings from django.utils import translation from mock import ANY, Mock, call, patch -from nose.tools import assert_true from six import text_type from course_modes.models import CourseMode @@ -97,7 +96,7 @@ class ViewsExceptionTestCase(UrlResetMixin, ModuleStoreTestCase): # Log the student in self.client = Client() - assert_true(self.client.login(username=uname, password=password)) + assert self.client.login(username=uname, password=password) config = ForumsConfig.current() config.enabled = True diff --git a/lms/djangoapps/django_comment_client/base/tests.py b/lms/djangoapps/django_comment_client/base/tests.py index 693840ac70..b38de85beb 100644 --- a/lms/djangoapps/django_comment_client/base/tests.py +++ b/lms/djangoapps/django_comment_client/base/tests.py @@ -12,7 +12,6 @@ from django.urls import reverse from django.test.client import RequestFactory from eventtracking.processors.exceptions import EventEmissionExit from mock import ANY, Mock, patch -from nose.tools import assert_equal, assert_true from opaque_keys.edx.keys import CourseKey from six import text_type @@ -256,7 +255,7 @@ class ViewsTestCaseMixin(object): CourseEnrollmentFactory(user=self.moderator, course_id=self.course.id) self.moderator.roles.add(Role.objects.get(name="Moderator", course_id=self.course.id)) - assert_true(self.client.login(username='student', password=self.password)) + assert self.client.login(username='student', password=self.password) def _setup_mock_request(self, mock_request, include_depth=False): """ @@ -321,7 +320,7 @@ class ViewsTestCaseMixin(object): url = reverse('create_thread', kwargs={'commentable_id': 'i4x-MITx-999-course-Robot_Super_Course', 'course_id': unicode(self.course_id)}) response = self.client.post(url, data=thread) - assert_true(mock_request.called) + assert mock_request.called expected_data = { 'thread_type': 'discussion', 'body': u'this is a post', @@ -342,7 +341,7 @@ class ViewsTestCaseMixin(object): headers=ANY, timeout=5 ) - assert_equal(response.status_code, 200) + assert response.status_code == 200 def update_thread_helper(self, mock_request): """ @@ -483,7 +482,7 @@ class ViewsTestCase( CourseEnrollmentFactory(user=self.moderator, course_id=self.course.id) self.moderator.roles.add(Role.objects.get(name="Moderator", course_id=self.course.id)) - assert_true(self.client.login(username='student', password=self.password)) + assert self.client.login(username='student', password=self.password) @contextmanager def assert_discussion_signals(self, signal, user=None): @@ -779,7 +778,7 @@ class ViewsTestCase( 'course_id': unicode(self.course_id) }) response = self.client.post(url) - assert_true(mock_request.called) + assert mock_request.called call_list = [ ( @@ -813,7 +812,7 @@ class ViewsTestCase( assert mock_request.call_args_list == call_list - assert_equal(response.status_code, 200) + assert response.status_code == 200 def test_un_flag_thread_open(self, mock_request): self.un_flag_thread(mock_request, False) @@ -857,7 +856,7 @@ class ViewsTestCase( 'course_id': unicode(self.course_id) }) response = self.client.post(url) - assert_true(mock_request.called) + assert mock_request.called call_list = [ ( @@ -891,7 +890,7 @@ class ViewsTestCase( assert mock_request.call_args_list == call_list - assert_equal(response.status_code, 200) + assert response.status_code == 200 def test_flag_comment_open(self, mock_request): self.flag_comment(mock_request, False) @@ -929,7 +928,7 @@ class ViewsTestCase( 'course_id': unicode(self.course_id) }) response = self.client.post(url) - assert_true(mock_request.called) + assert mock_request.called call_list = [ ( @@ -963,7 +962,7 @@ class ViewsTestCase( assert mock_request.call_args_list == call_list - assert_equal(response.status_code, 200) + assert response.status_code == 200 def test_un_flag_comment_open(self, mock_request): self.un_flag_comment(mock_request, False) @@ -1001,7 +1000,7 @@ class ViewsTestCase( 'course_id': unicode(self.course_id) }) response = self.client.post(url) - assert_true(mock_request.called) + assert mock_request.called call_list = [ ( @@ -1035,7 +1034,7 @@ class ViewsTestCase( assert mock_request.call_args_list == call_list - assert_equal(response.status_code, 200) + assert response.status_code == 200 @ddt.data( ('upvote_thread', 'thread_id', 'thread_voted'), diff --git a/lms/djangoapps/instructor/tests/test_access.py b/lms/djangoapps/instructor/tests/test_access.py index 1024b6e85e..2c374bf016 100644 --- a/lms/djangoapps/instructor/tests/test_access.py +++ b/lms/djangoapps/instructor/tests/test_access.py @@ -2,7 +2,7 @@ Test instructor.access """ -from nose.tools import raises +import pytest from django_comment_common.models import FORUM_ROLE_MODERATOR, Role from lms.djangoapps.instructor.access import allow_access, list_with_level, revoke_access, update_forum_role @@ -74,15 +74,15 @@ class TestInstructorAccessAllow(SharedModuleStoreTestCase): allow_access(self.course, user, 'beta') self.assertTrue(CourseBetaTesterRole(self.course.id).has_user(user)) - @raises(ValueError) def test_allow_badlevel(self): user = UserFactory() - allow_access(self.course, user, 'robot-not-a-level') + with pytest.raises(ValueError): + allow_access(self.course, user, 'robot-not-a-level') - @raises(Exception) def test_allow_noneuser(self): user = None - allow_access(self.course, user, 'staff') + with pytest.raises(Exception): + allow_access(self.course, user, 'staff') @attr(shard=1) @@ -117,10 +117,10 @@ class TestInstructorAccessRevoke(SharedModuleStoreTestCase): revoke_access(self.course, user, 'beta') self.assertFalse(CourseBetaTesterRole(self.course.id).has_user(user)) - @raises(ValueError) def test_revoke_badrolename(self): user = UserFactory() - revoke_access(self.course, user, 'robot-not-a-level') + with pytest.raises(ValueError): + revoke_access(self.course, user, 'robot-not-a-level') @attr(shard=1) @@ -155,10 +155,10 @@ class TestInstructorAccessForum(SharedModuleStoreTestCase): update_forum_role(self.course.id, user, FORUM_ROLE_MODERATOR, 'allow') self.assertIn(user, self.mod_role.users.all()) - @raises(Role.DoesNotExist) def test_allow_badrole(self): user = UserFactory.create() - update_forum_role(self.course.id, user, 'robot-not-a-real-role', 'allow') + with pytest.raises(Role.DoesNotExist): + update_forum_role(self.course.id, user, 'robot-not-a-real-role', 'allow') def test_revoke(self): user = self.moderators[0] @@ -177,12 +177,12 @@ class TestInstructorAccessForum(SharedModuleStoreTestCase): update_forum_role(self.course.id, user, FORUM_ROLE_MODERATOR, 'revoke') self.assertNotIn(user, self.mod_role.users.all()) - @raises(Role.DoesNotExist) def test_revoke_badrole(self): user = self.moderators[0] - update_forum_role(self.course.id, user, 'robot-not-a-real-role', 'allow') + with pytest.raises(Role.DoesNotExist): + update_forum_role(self.course.id, user, 'robot-not-a-real-role', 'allow') - @raises(ValueError) def test_bad_mode(self): user = UserFactory() - update_forum_role(self.course.id, user, FORUM_ROLE_MODERATOR, 'robot-not-a-mode') + with pytest.raises(ValueError): + update_forum_role(self.course.id, user, FORUM_ROLE_MODERATOR, 'robot-not-a-mode') diff --git a/lms/djangoapps/instructor/tests/test_api.py b/lms/djangoapps/instructor/tests/test_api.py index c5594eb88e..29d0df8ced 100644 --- a/lms/djangoapps/instructor/tests/test_api.py +++ b/lms/djangoapps/instructor/tests/test_api.py @@ -11,6 +11,7 @@ import shutil import tempfile import ddt +import pytest from boto.exception import BotoServerError from django.conf import settings from django.contrib.auth.models import User @@ -23,7 +24,6 @@ from django.test.utils import override_settings from pytz import UTC from django.utils.translation import ugettext as _ from mock import Mock, NonCallableMock, patch -from nose.tools import raises from opaque_keys.edx.keys import CourseKey from opaque_keys.edx.locator import UsageKey from six import text_type @@ -4187,10 +4187,10 @@ class TestInstructorAPIHelpers(TestCase): output = 'i4x://MITx/6.002x/problem/L2Node1' self.assertEqual(unicode(msk_from_problem_urlname(course_id, name)), output) - @raises(ValueError) def test_msk_from_problem_urlname_error(self): args = ('notagoodcourse', 'L2Node1') - msk_from_problem_urlname(*args) + with pytest.raises(ValueError): + msk_from_problem_urlname(*args) def get_extended_due(course, unit, user): diff --git a/lms/djangoapps/instructor_analytics/tests/test_csvs.py b/lms/djangoapps/instructor_analytics/tests/test_csvs.py index 801bf664fd..8a82bb0bab 100644 --- a/lms/djangoapps/instructor_analytics/tests/test_csvs.py +++ b/lms/djangoapps/instructor_analytics/tests/test_csvs.py @@ -1,7 +1,7 @@ """ Tests for analytics.csvs """ +import pytest from django.test import TestCase -from nose.tools import raises from instructor_analytics.csvs import create_csv_response, format_dictlist, format_instances @@ -124,6 +124,6 @@ class TestAnalyticsFormatInstances(TestCase): self.assertEqual(header, []) self.assertEqual(datarows, [[] for _ in xrange(len(self.instances))]) - @raises(AttributeError) def test_format_instances_response_nonexistantfeature(self): - format_instances(self.instances, ['robot_not_a_real_feature']) + with pytest.raises(AttributeError): + format_instances(self.instances, ['robot_not_a_real_feature']) diff --git a/lms/djangoapps/instructor_analytics/tests/test_distributions.py b/lms/djangoapps/instructor_analytics/tests/test_distributions.py index 78d89a21bb..ca2f0d0c7e 100644 --- a/lms/djangoapps/instructor_analytics/tests/test_distributions.py +++ b/lms/djangoapps/instructor_analytics/tests/test_distributions.py @@ -1,7 +1,7 @@ """ Tests for analytics.distributions """ +import pytest from django.test import TestCase -from nose.tools import raises from opaque_keys.edx.locator import CourseLocator from instructor_analytics.distributions import AVAILABLE_PROFILE_FEATURES, profile_distribution @@ -26,11 +26,11 @@ class TestAnalyticsDistributions(TestCase): self.ces = [CourseEnrollment.enroll(user, self.course_id) for user in self.users] - @raises(ValueError) def test_profile_distribution_bad_feature(self): feature = 'robot-not-a-real-feature' self.assertNotIn(feature, AVAILABLE_PROFILE_FEATURES) - profile_distribution(self.course_id, feature) + with pytest.raises(ValueError): + profile_distribution(self.course_id, feature) def test_profile_distribution_easy_choice(self): feature = 'gender' diff --git a/lms/djangoapps/verify_student/management/commands/tests/test_verify_student.py b/lms/djangoapps/verify_student/management/commands/tests/test_verify_student.py index f7b4d12cd6..e224012e66 100644 --- a/lms/djangoapps/verify_student/management/commands/tests/test_verify_student.py +++ b/lms/djangoapps/verify_student/management/commands/tests/test_verify_student.py @@ -8,7 +8,6 @@ from django.conf import settings from django.core.management import call_command from django.test import TestCase from mock import patch -from nose.tools import assert_equals from common.test.utils import MockS3Mixin from lms.djangoapps.verify_student.models import SoftwareSecurePhotoVerification @@ -59,8 +58,8 @@ class TestVerifyStudentCommand(MockS3Mixin, TestCase): with patch('lms.djangoapps.verify_student.models.requests.post', new=mock_software_secure_post_error): self.create_and_submit("RetryRick") # check to make sure we had two successes and two failures; otherwise we've got problems elsewhere - assert_equals(len(SoftwareSecurePhotoVerification.objects.filter(status="submitted")), 1) - assert_equals(len(SoftwareSecurePhotoVerification.objects.filter(status='must_retry')), 2) + assert len(SoftwareSecurePhotoVerification.objects.filter(status="submitted")) == 1 + assert len(SoftwareSecurePhotoVerification.objects.filter(status='must_retry')) == 2 call_command('retry_failed_photo_verifications') attempts_to_retry = SoftwareSecurePhotoVerification.objects.filter(status='must_retry') - assert_equals(bool(attempts_to_retry), False) + assert not attempts_to_retry diff --git a/lms/djangoapps/verify_student/tests/test_models.py b/lms/djangoapps/verify_student/tests/test_models.py index c55a097206..be256b584b 100644 --- a/lms/djangoapps/verify_student/tests/test_models.py +++ b/lms/djangoapps/verify_student/tests/test_models.py @@ -11,11 +11,6 @@ from django.conf import settings from django.test import TestCase from freezegun import freeze_time from mock import patch -from nose.tools import ( # pylint: disable=no-name-in-module - assert_equals, - assert_raises, - assert_true -) from opaque_keys.edx.keys import CourseKey from testfixtures import LogCapture @@ -68,10 +63,7 @@ def mock_software_secure_post(url, headers=None, data=None, **kwargs): "UserPhoto", "UserPhotoKey", ] for key in EXPECTED_KEYS: - assert_true( - data_dict.get(key), - "'{}' must be present and not blank in JSON submitted to Software Secure".format(key) - ) + assert data_dict.get(key) # The keys should be stored as Base64 strings, i.e. this should not explode data_dict["PhotoIDKey"].decode("base64") @@ -151,20 +143,20 @@ class TestPhotoVerification(TestVerification, MockS3Mixin, ModuleStoreTestCase): """ user = UserFactory.create() attempt = SoftwareSecurePhotoVerification(user=user) - assert_equals(attempt.status, "created") + self.assertEqual(attempt.status, "created") # These should all fail because we're in the wrong starting state. - assert_raises(VerificationException, attempt.submit) - assert_raises(VerificationException, attempt.approve) - assert_raises(VerificationException, attempt.deny) + self.assertRaises(VerificationException, attempt.submit) + self.assertRaises(VerificationException, attempt.approve) + self.assertRaises(VerificationException, attempt.deny) # Now let's fill in some values so that we can pass the mark_ready() call attempt.mark_ready() - assert_equals(attempt.status, "ready") + self.assertEqual(attempt.status, "ready") # ready (can't approve or deny unless it's "submitted") - assert_raises(VerificationException, attempt.approve) - assert_raises(VerificationException, attempt.deny) + self.assertRaises(VerificationException, attempt.approve) + self.assertRaises(VerificationException, attempt.deny) DENY_ERROR_MSG = '[{"photoIdReasons": ["Not provided"]}]' @@ -182,13 +174,13 @@ class TestPhotoVerification(TestVerification, MockS3Mixin, ModuleStoreTestCase): attempt.approve() # approved - assert_raises(VerificationException, attempt.submit) + self.assertRaises(VerificationException, attempt.submit) attempt.approve() # no-op attempt.system_error("System error") # no-op, something processed it without error attempt.deny(DENY_ERROR_MSG) # denied - assert_raises(VerificationException, attempt.submit) + self.assertRaises(VerificationException, attempt.submit) attempt.deny(DENY_ERROR_MSG) # no-op attempt.system_error("System error") # no-op, something processed it without error attempt.approve() @@ -209,7 +201,7 @@ class TestPhotoVerification(TestVerification, MockS3Mixin, ModuleStoreTestCase): user.profile.name = u"Rusty \u01B4" - assert_equals(u"Clyde \u01B4", attempt.name) + self.assertEqual(u"Clyde \u01B4", attempt.name) def create_and_submit(self): """Helper method to create a generic submission and send it.""" @@ -228,18 +220,18 @@ class TestPhotoVerification(TestVerification, MockS3Mixin, ModuleStoreTestCase): """Test that we set our status correctly after a submission.""" # Basic case, things go well. attempt = self.create_and_submit() - assert_equals(attempt.status, "submitted") + self.assertEqual(attempt.status, "submitted") # We post, but Software Secure doesn't like what we send for some reason with patch('lms.djangoapps.verify_student.models.requests.post', new=mock_software_secure_post_error): attempt = self.create_and_submit() - assert_equals(attempt.status, "must_retry") + self.assertEqual(attempt.status, "must_retry") # We try to post, but run into an error (in this case a network connection error) with patch('lms.djangoapps.verify_student.models.requests.post', new=mock_software_secure_post_unavailable): with LogCapture('lms.djangoapps.verify_student.models') as logger: attempt = self.create_and_submit() - assert_equals(attempt.status, "must_retry") + self.assertEqual(attempt.status, "must_retry") logger.check( ('lms.djangoapps.verify_student.models', 'ERROR', 'Software Secure submission failed for user %s, setting status to must_retry' @@ -349,10 +341,10 @@ class TestPhotoVerification(TestVerification, MockS3Mixin, ModuleStoreTestCase): attempt.approve() # Validate data before retirement - assert_equals(attempt.name, user.profile.name) - assert_equals(attempt.photo_id_image_url, 'https://example.com/test/image/img.jpg') - assert_equals(attempt.face_image_url, 'https://example.com/test/face/img.jpg') - assert_equals(attempt.photo_id_key, 'there_was_an_attempt') + self.assertEqual(attempt.name, user.profile.name) + self.assertEqual(attempt.photo_id_image_url, 'https://example.com/test/image/img.jpg') + self.assertEqual(attempt.face_image_url, 'https://example.com/test/face/img.jpg') + self.assertEqual(attempt.photo_id_key, 'there_was_an_attempt') # Retire User attempt_again = SoftwareSecurePhotoVerification(user=user) diff --git a/lms/djangoapps/verify_student/tests/test_services.py b/lms/djangoapps/verify_student/tests/test_services.py index 43999288bf..2d4e6f5be0 100644 --- a/lms/djangoapps/verify_student/tests/test_services.py +++ b/lms/djangoapps/verify_student/tests/test_services.py @@ -3,17 +3,9 @@ Tests for the service classes in verify_student. """ -from datetime import timedelta - import ddt from django.conf import settings from mock import patch -from nose.tools import ( - assert_equals, - assert_false, - assert_is_none, - assert_true -) from common.test.utils import MockS3Mixin from lms.djangoapps.verify_student.models import SoftwareSecurePhotoVerification, SSOVerification, ManualVerification @@ -47,11 +39,11 @@ class TestIDVerificationService(MockS3Mixin, ModuleStoreTestCase): for status in ["created", "ready", "denied", "submitted", "must_retry"]: attempt.status = status attempt.save() - assert_false(IDVerificationService.user_is_verified(user), status) + self.assertFalse(IDVerificationService.user_is_verified(user), status) attempt.status = "approved" attempt.save() - assert_true(IDVerificationService.user_is_verified(user), attempt.status) + self.assertTrue(IDVerificationService.user_is_verified(user), attempt.status) def test_user_has_valid_or_pending(self): """ @@ -65,14 +57,14 @@ class TestIDVerificationService(MockS3Mixin, ModuleStoreTestCase): for status in ["created", "ready", "denied"]: attempt.status = status attempt.save() - assert_false(IDVerificationService.user_has_valid_or_pending(user), status) + self.assertFalse(IDVerificationService.user_has_valid_or_pending(user), status) # Any of these, and we are. Note the benefit of the doubt we're giving # -- must_retry, and submitted both count until we hear otherwise for status in ["submitted", "must_retry", "approved"]: attempt.status = status attempt.save() - assert_true(IDVerificationService.user_has_valid_or_pending(user), status) + self.assertTrue(IDVerificationService.user_has_valid_or_pending(user), status) def test_user_status(self): # test for correct status when no error returned diff --git a/lms/lib/courseware_search/test/test_lms_result_processor.py b/lms/lib/courseware_search/test/test_lms_result_processor.py index 492f223c28..d50d1c0cba 100644 --- a/lms/lib/courseware_search/test/test_lms_result_processor.py +++ b/lms/lib/courseware_search/test/test_lms_result_processor.py @@ -60,8 +60,6 @@ class LmsSearchResultProcessorTestCase(ModuleStoreTestCase): ) def setUp(self): - # from nose.tools import set_trace - # set_trace() super(LmsSearchResultProcessorTestCase, self).setUp() self.build_course() diff --git a/openedx/core/djangoapps/user_api/accounts/tests/test_api.py b/openedx/core/djangoapps/user_api/accounts/tests/test_api.py index 33d3bcba67..f36357e578 100644 --- a/openedx/core/djangoapps/user_api/accounts/tests/test_api.py +++ b/openedx/core/djangoapps/user_api/accounts/tests/test_api.py @@ -15,7 +15,6 @@ from django.core import mail from django.test import TestCase from django.test.client import RequestFactory from mock import Mock, patch -from nose.tools import raises from six import iteritems from openedx.core.djangoapps.site_configuration.tests.factories import SiteFactory @@ -391,34 +390,34 @@ class AccountCreationActivationAndPasswordChangeTest(TestCase): with self.assertRaises(AccountUsernameInvalid): create_account(long_username, self.PASSWORD, self.EMAIL) - @raises(AccountEmailInvalid) @ddt.data(*INVALID_EMAILS) def test_create_account_invalid_email(self, invalid_email): - create_account(self.USERNAME, self.PASSWORD, invalid_email) + with pytest.raises(AccountEmailInvalid): + create_account(self.USERNAME, self.PASSWORD, invalid_email) - @raises(AccountPasswordInvalid) @ddt.data(*INVALID_PASSWORDS) def test_create_account_invalid_password(self, invalid_password): - create_account(self.USERNAME, invalid_password, self.EMAIL) + with pytest.raises(AccountPasswordInvalid): + create_account(self.USERNAME, invalid_password, self.EMAIL) - @raises(AccountPasswordInvalid) def test_create_account_username_password_equal(self): # Username and password cannot be the same - create_account(self.USERNAME, self.USERNAME, self.EMAIL) + with pytest.raises(AccountPasswordInvalid): + create_account(self.USERNAME, self.USERNAME, self.EMAIL) - @raises(AccountRequestError) @ddt.data(*INVALID_USERNAMES) def test_create_account_invalid_username(self, invalid_username): - create_account(invalid_username, self.PASSWORD, self.EMAIL) + with pytest.raises(AccountRequestError): + create_account(invalid_username, self.PASSWORD, self.EMAIL) def test_create_account_prevent_auth_user_writes(self): with pytest.raises(UserAPIInternalError, message=SYSTEM_MAINTENANCE_MSG): with waffle().override(PREVENT_AUTH_USER_WRITES, True): create_account(self.USERNAME, self.PASSWORD, self.EMAIL) - @raises(UserNotAuthorized) def test_activate_account_invalid_key(self): - activate_account(u'invalid') + with pytest.raises(UserNotAuthorized): + activate_account(u'invalid') def test_activate_account_prevent_auth_user_writes(self): activation_key = create_account(self.USERNAME, self.PASSWORD, self.EMAIL) diff --git a/openedx/core/djangoapps/user_api/tests/test_helpers.py b/openedx/core/djangoapps/user_api/tests/test_helpers.py index f55459a864..ac6c11f4e2 100644 --- a/openedx/core/djangoapps/user_api/tests/test_helpers.py +++ b/openedx/core/djangoapps/user_api/tests/test_helpers.py @@ -5,10 +5,10 @@ import json import re import mock import ddt +import pytest from django import forms from django.http import HttpRequest, HttpResponse from django.test import TestCase -from nose.tools import raises from six import text_type from ..helpers import ( @@ -42,16 +42,16 @@ def intercepted_function(raise_error=None): class InterceptErrorsTest(TestCase): """Tests for the decorator that intercepts errors.""" - @raises(FakeOutputException) def test_intercepts_errors(self): - intercepted_function(raise_error=FakeInputException) + with pytest.raises(FakeOutputException): + intercepted_function(raise_error=FakeInputException) def test_ignores_no_error(self): intercepted_function() - @raises(ValueError) def test_ignores_expected_errors(self): - intercepted_function(raise_error=ValueError) + with pytest.raises(ValueError): + intercepted_function(raise_error=ValueError) @mock.patch('openedx.core.djangoapps.user_api.helpers.LOGGER') def test_logs_errors(self, mock_logger):