TE-2525 nose.tools removal part 1/2

This commit is contained in:
Jeremy Bowman
2018-08-06 16:52:11 -04:00
committed by Jeremy Bowman
parent 70d1ca4740
commit bcaec3c5bb
26 changed files with 322 additions and 410 deletions

View File

@@ -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

View File

@@ -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)

View File

@@ -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 <tag a="/static/js/capa/protex/protex.nocache.js?raw"/><div class="'
assert_equals(path, replace_static_urls(path, text))
assert replace_static_urls(path, text) == path
@pytest.mark.django_db
@@ -177,7 +171,7 @@ def test_static_url_with_query(mock_modulestore, mock_storage):
pre_text = 'EMBED src ="/static/LAlec04_controller.swf?csConfigFile=/static/LAlec04_config.xml&name1=value1&name2=value2"'
post_text = 'EMBED src ="/c4x/org/course/asset/LAlec04_controller.swf?csConfigFile=%2Fc4x%2Forg%2Fcourse%2Fasset%2FLAlec04_config.xml&name1=value1&name2=value2"'
assert_equals(post_text, replace_static_urls(pre_text, DATA_DIRECTORY, COURSE_KEY))
assert replace_static_urls(pre_text, DATA_DIRECTORY, COURSE_KEY) == post_text
def test_regex():
@@ -192,12 +186,12 @@ def test_regex():
regex = _url_replace_regex('/static/')
for s in yes:
print 'Should match: {0!r}'.format(s)
assert_true(re.match(regex, s))
print('Should match: {0!r}'.format(s))
assert re.match(regex, s)
for s in no:
print 'Should not match: {0!r}'.format(s)
assert_false(re.match(regex, s))
print('Should not match: {0!r}'.format(s))
assert not re.match(regex, s)
@patch('static_replace.staticfiles_storage', autospec=True)
@@ -212,7 +206,7 @@ def test_static_url_with_xblock_resource(mock_modulestore, mock_storage):
pre_text = 'EMBED src ="/static/xblock/resources/babys_first.lil_xblock/public/images/pacifier.png"'
post_text = pre_text
assert_equals(post_text, replace_static_urls(pre_text, DATA_DIRECTORY, COURSE_KEY))
assert replace_static_urls(pre_text, DATA_DIRECTORY, COURSE_KEY) == post_text
@patch('static_replace.staticfiles_storage', autospec=True)
@@ -228,7 +222,7 @@ def test_static_url_with_xblock_resource_on_cdn(mock_modulestore, mock_storage):
pre_text = 'EMBED src ="https://example.com/static/xblock/resources/tehehe.xblock/public/images/woo.png"'
post_text = pre_text
assert_equals(post_text, replace_static_urls(pre_text, DATA_DIRECTORY, COURSE_KEY))
assert replace_static_urls(pre_text, DATA_DIRECTORY, COURSE_KEY) == post_text
@ddt.ddt
@@ -567,8 +561,8 @@ class CanonicalContentTest(SharedModuleStoreTestCase):
with check_mongo_calls(mongo_calls):
asset_path = StaticContent.get_canonicalized_asset_path(self.courses[prefix].id, start, base_url, exts)
print expected
print asset_path
print(expected)
print(asset_path)
self.assertIsNotNone(re.match(expected, asset_path))
@ddt.data(
@@ -765,6 +759,6 @@ class CanonicalContentTest(SharedModuleStoreTestCase):
with check_mongo_calls(mongo_calls):
asset_path = StaticContent.get_canonicalized_asset_path(self.courses[prefix].id, start, base_url, exts)
print expected
print asset_path
print(expected)
print(asset_path)
self.assertIsNotNone(re.match(expected, asset_path))

View File

@@ -8,63 +8,52 @@ from datetime import datetime, timedelta, tzinfo
import ddt
from mock import patch
from nose.tools import assert_equals, assert_false # pylint: disable=no-name-in-module
from pytz import utc
from util.date_utils import almost_same_datetime, get_default_time_display, get_time_display, strftime_localized
def test_get_default_time_display():
assert_equals("", get_default_time_display(None))
assert get_default_time_display(None) == ""
test_time = datetime(1992, 3, 12, 15, 3, 30, tzinfo=utc)
assert_equals(
"Mar 12, 1992 at 15:03 UTC",
get_default_time_display(test_time))
assert get_default_time_display(test_time) == "Mar 12, 1992 at 15:03 UTC"
def test_get_dflt_time_disp_notz():
test_time = datetime(1992, 3, 12, 15, 3, 30)
assert_equals(
"Mar 12, 1992 at 15:03 UTC",
get_default_time_display(test_time))
assert get_default_time_display(test_time) == "Mar 12, 1992 at 15:03 UTC"
def test_get_time_disp_ret_empty():
assert_equals("", get_time_display(None))
assert get_time_display(None) == ""
test_time = datetime(1992, 3, 12, 15, 3, 30, tzinfo=utc)
assert_equals("", get_time_display(test_time, ""))
assert get_time_display(test_time, "") == ""
def test_get_time_display():
test_time = datetime(1992, 3, 12, 15, 3, 30, tzinfo=utc)
assert_equals("dummy text", get_time_display(test_time, 'dummy text'))
assert_equals("Mar 12 1992", get_time_display(test_time, '%b %d %Y'))
assert_equals("Mar 12 1992 UTC", get_time_display(test_time, '%b %d %Y %Z'))
assert_equals("Mar 12 15:03", get_time_display(test_time, '%b %d %H:%M'))
assert get_time_display(test_time, 'dummy text') == "dummy text"
assert get_time_display(test_time, '%b %d %Y') == "Mar 12 1992"
assert get_time_display(test_time, '%b %d %Y %Z') == "Mar 12 1992 UTC"
assert get_time_display(test_time, '%b %d %H:%M') == "Mar 12 15:03"
def test_get_time_pass_through():
test_time = datetime(1992, 3, 12, 15, 3, 30, tzinfo=utc)
assert_equals("Mar 12, 1992 at 15:03 UTC", get_time_display(test_time))
assert_equals("Mar 12, 1992 at 15:03 UTC", get_time_display(test_time, None))
assert_equals("Mar 12, 1992 at 15:03 UTC", get_time_display(test_time, "%"))
assert get_time_display(test_time) == "Mar 12, 1992 at 15:03 UTC"
assert get_time_display(test_time, None) == "Mar 12, 1992 at 15:03 UTC"
assert get_time_display(test_time, "%") == "Mar 12, 1992 at 15:03 UTC"
def test_get_time_display_coerce():
test_time_standard = datetime(1992, 1, 12, 15, 3, 30, tzinfo=utc)
test_time_daylight = datetime(1992, 7, 12, 15, 3, 30, tzinfo=utc)
assert_equals("Jan 12, 1992 at 07:03 PST",
get_time_display(test_time_standard, None, coerce_tz="US/Pacific"))
assert_equals("Jan 12, 1992 at 15:03 UTC",
get_time_display(test_time_standard, None, coerce_tz="NONEXISTENTTZ"))
assert_equals("Jan 12 07:03",
get_time_display(test_time_standard, '%b %d %H:%M', coerce_tz="US/Pacific"))
assert_equals("Jul 12, 1992 at 08:03 PDT",
get_time_display(test_time_daylight, None, coerce_tz="US/Pacific"))
assert_equals("Jul 12, 1992 at 15:03 UTC",
get_time_display(test_time_daylight, None, coerce_tz="NONEXISTENTTZ"))
assert_equals("Jul 12 08:03",
get_time_display(test_time_daylight, '%b %d %H:%M', coerce_tz="US/Pacific"))
assert get_time_display(test_time_standard, None, coerce_tz="US/Pacific") == "Jan 12, 1992 at 07:03 PST"
assert get_time_display(test_time_standard, None, coerce_tz="NONEXISTENTTZ") == "Jan 12, 1992 at 15:03 UTC"
assert get_time_display(test_time_standard, '%b %d %H:%M', coerce_tz="US/Pacific") == "Jan 12 07:03"
assert get_time_display(test_time_daylight, None, coerce_tz="US/Pacific") == "Jul 12, 1992 at 08:03 PDT"
assert get_time_display(test_time_daylight, None, coerce_tz="NONEXISTENTTZ") == "Jul 12, 1992 at 15:03 UTC"
assert get_time_display(test_time_daylight, '%b %d %H:%M', coerce_tz="US/Pacific") == "Jul 12 08:03"
class NamelessTZ(tzinfo):
@@ -78,11 +67,9 @@ class NamelessTZ(tzinfo):
def test_get_default_time_display_no_tzname():
assert_equals("", get_default_time_display(None))
assert get_default_time_display(None) == ""
test_time = datetime(1992, 3, 12, 15, 3, 30, tzinfo=NamelessTZ())
assert_equals(
"Mar 12, 1992 at 15:03-0300",
get_default_time_display(test_time))
assert get_default_time_display(test_time) == "Mar 12, 1992 at 15:03-0300"
def test_almost_same_datetime():
@@ -97,19 +84,15 @@ def test_almost_same_datetime():
timedelta(hours=1)
)
assert_false(
almost_same_datetime(
datetime(2013, 5, 3, 11, 20, 30),
datetime(2013, 5, 3, 10, 21, 29)
)
assert not almost_same_datetime(
datetime(2013, 5, 3, 11, 20, 30),
datetime(2013, 5, 3, 10, 21, 29)
)
assert_false(
almost_same_datetime(
datetime(2013, 5, 3, 11, 20, 30),
datetime(2013, 5, 3, 10, 21, 29),
timedelta(minutes=10)
)
assert not almost_same_datetime(
datetime(2013, 5, 3, 11, 20, 30),
datetime(2013, 5, 3, 10, 21, 29),
timedelta(minutes=10)
)

View File

@@ -15,7 +15,6 @@ from uuid import uuid4
from factory import Factory, Sequence, lazy_attribute_sequence, lazy_attribute
from factory.errors import CyclicDefinitionError
from mock import patch
from nose.tools import assert_less_equal, assert_greater_equal
import dogstats_wrapper as dog_stats_api
from opaque_keys.edx.locator import BlockUsageLocator
@@ -596,10 +595,10 @@ def check_sum_of_calls(object_, methods, maximum_calls, minimum_calls=1, include
print "".join(messages)
# verify the counter actually worked by ensuring we have counted greater than (or equal to) the minimum calls
assert_greater_equal(call_count, minimum_calls)
assert call_count >= 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):

View File

@@ -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)
)

View File

@@ -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'))

View File

@@ -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 <div x="foo">there <span>Bruce</span><b>!</b></div>'
html = '''<html a="b" foo="bar">{0}</html>'''.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"""<html name="Voltage Source Answer" >A voltage source is non-linear!
<div align="center">
<img src="/static/images/circuits/voltage-source.png"/>
@@ -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

View File

@@ -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

View File

@@ -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)

View File

@@ -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

View File

@@ -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

View File

@@ -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.

View File

@@ -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)

View File

@@ -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

View File

@@ -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'),

View File

@@ -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')

View File

@@ -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):

View File

@@ -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'])

View File

@@ -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'

View File

@@ -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

View File

@@ -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)

View File

@@ -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

View File

@@ -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()

View File

@@ -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)

View File

@@ -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):