Use print() function in both Python 2 and Python 3
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Script for force publishing a course
|
||||
"""
|
||||
from __future__ import print_function
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
from opaque_keys import InvalidKeyError
|
||||
from opaque_keys.edx.keys import CourseKey
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Testing indexing of the courseware as it is changed
|
||||
"""
|
||||
from __future__ import print_function
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime
|
||||
@@ -674,7 +675,7 @@ class TestLargeCourseDeletions(MixedWithOptionsTestCase):
|
||||
self._do_test_large_course_deletion(store, load_factor)
|
||||
except: # pylint: disable=bare-except
|
||||
# Catch any exception here to see when we fail
|
||||
print "Failed with load_factor of {}".format(load_factor)
|
||||
print("Failed with load_factor of {}".format(load_factor))
|
||||
|
||||
@skip(("This test is to see how we handle very large courses, to ensure that the delete"
|
||||
"procedure works smoothly - too long to run during the normal course of things"))
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
"""
|
||||
Tests for import_course_from_xml using the mongo modulestore.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
import copy
|
||||
from uuid import uuid4
|
||||
@@ -119,7 +120,7 @@ class ContentStoreImportTest(ModuleStoreTestCase):
|
||||
|
||||
# make sure we have ONE asset in our contentstore ("should_be_imported.html")
|
||||
all_assets, count = content_store.get_all_content_for_course(course.id)
|
||||
print "len(all_assets)=%d" % len(all_assets)
|
||||
print("len(all_assets)=%d" % len(all_assets))
|
||||
self.assertEqual(len(all_assets), 1)
|
||||
self.assertEqual(count, 1)
|
||||
|
||||
@@ -133,7 +134,7 @@ class ContentStoreImportTest(ModuleStoreTestCase):
|
||||
self.assertIsNotNone(content)
|
||||
|
||||
# make sure course.static_asset_path is correct
|
||||
print "static_asset_path = {0}".format(course.static_asset_path)
|
||||
print("static_asset_path = {0}".format(course.static_asset_path))
|
||||
self.assertEqual(course.static_asset_path, 'test_import_course')
|
||||
|
||||
def test_asset_import_nostatic(self):
|
||||
@@ -172,7 +173,7 @@ class ContentStoreImportTest(ModuleStoreTestCase):
|
||||
|
||||
def test_tab_name_imports_correctly(self):
|
||||
_module_store, _content_store, course = self.load_test_import_course()
|
||||
print "course tabs = {0}".format(course.tabs)
|
||||
print("course tabs = {0}".format(course.tabs))
|
||||
self.assertEqual(course.tabs[2]['name'], 'Syllabus')
|
||||
|
||||
def test_import_performance_mongo(self):
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Common utility functions useful throughout the contentstore
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
@@ -93,7 +94,7 @@ def _remove_instructors(course_key):
|
||||
"""
|
||||
In the django layer, remove all the user/groups permissions associated with this course
|
||||
"""
|
||||
print 'removing User permissions from course....'
|
||||
print('removing User permissions from course....')
|
||||
|
||||
try:
|
||||
remove_all_instructors(course_key)
|
||||
|
||||
@@ -10,6 +10,7 @@ file and check it in at the same time as your model changes. To do that,
|
||||
2. ./manage.py lms schemamigration student --auto description_of_your_change
|
||||
3. Add the migration file created in edx-platform/common/djangoapps/student/migrations/
|
||||
"""
|
||||
from __future__ import print_function
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
@@ -2148,12 +2149,12 @@ def get_user(email):
|
||||
|
||||
def user_info(email):
|
||||
user, u_prof = get_user(email)
|
||||
print "User id", user.id
|
||||
print "Username", user.username
|
||||
print "E-mail", user.email
|
||||
print "Name", u_prof.name
|
||||
print "Location", u_prof.location
|
||||
print "Language", u_prof.language
|
||||
print("User id", user.id)
|
||||
print("Username", user.username)
|
||||
print("E-mail", user.email)
|
||||
print("Name", u_prof.name)
|
||||
print("Location", u_prof.location)
|
||||
print("Language", u_prof.language)
|
||||
return user, u_prof
|
||||
|
||||
|
||||
@@ -2170,8 +2171,8 @@ def change_name(email, new_name):
|
||||
|
||||
|
||||
def user_count():
|
||||
print "All users", User.objects.all().count()
|
||||
print "Active users", User.objects.filter(is_active=True).count()
|
||||
print("All users", User.objects.all().count())
|
||||
print("Active users", User.objects.filter(is_active=True).count())
|
||||
return User.objects.all().count()
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Command-line utility to start a stub service.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
import logging
|
||||
import sys
|
||||
import time
|
||||
@@ -37,7 +38,7 @@ def get_args():
|
||||
Exits with a message if arguments are invalid.
|
||||
"""
|
||||
if len(sys.argv) < 3:
|
||||
print USAGE
|
||||
print(USAGE)
|
||||
sys.exit(1)
|
||||
|
||||
service_name = sys.argv[1]
|
||||
@@ -45,8 +46,8 @@ def get_args():
|
||||
config_dict = _parse_config_args(sys.argv[3:])
|
||||
|
||||
if service_name not in SERVICES:
|
||||
print "Unrecognized service '{0}'. Valid choices are: {1}".format(
|
||||
service_name, ", ".join(SERVICES.keys()))
|
||||
print("Unrecognized service '{0}'. Valid choices are: {1}".format(
|
||||
service_name, ", ".join(SERVICES.keys())))
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
@@ -55,7 +56,7 @@ def get_args():
|
||||
raise ValueError
|
||||
|
||||
except ValueError:
|
||||
print "Port '{0}' must be a positive integer".format(port_num)
|
||||
print("Port '{0}' must be a positive integer".format(port_num))
|
||||
sys.exit(1)
|
||||
|
||||
return service_name, port_num, config_dict
|
||||
@@ -77,7 +78,7 @@ def _parse_config_args(args):
|
||||
config_dict[components[0]] = "=".join(components[1:])
|
||||
|
||||
except:
|
||||
print "Warning: could not interpret config value '{0}'".format(config_str)
|
||||
print("Warning: could not interpret config value '{0}'".format(config_str))
|
||||
|
||||
return config_dict
|
||||
|
||||
@@ -87,7 +88,7 @@ def main():
|
||||
Start a server; shut down on keyboard interrupt signal.
|
||||
"""
|
||||
service_name, port_num, config_dict = get_args()
|
||||
print "Starting stub service '{0}' on port {1}...".format(service_name, port_num)
|
||||
print("Starting stub service '{0}' on port {1}...".format(service_name, port_num))
|
||||
|
||||
server = SERVICES[service_name](port_num=port_num)
|
||||
server.config.update(config_dict)
|
||||
@@ -97,7 +98,7 @@ def main():
|
||||
time.sleep(1)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
print "Stopping stub service..."
|
||||
print("Stopping stub service...")
|
||||
|
||||
finally:
|
||||
server.shutdown()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Creates Indexes on contentstore and modulestore databases.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
from django.core.management.base import BaseCommand
|
||||
|
||||
from xmodule.contentstore.django import contentstore
|
||||
@@ -17,4 +18,4 @@ class Command(BaseCommand):
|
||||
def handle(self, *args, **options):
|
||||
contentstore().ensure_indexes()
|
||||
modulestore().ensure_indexes()
|
||||
print 'contentstore and modulestore indexes created!'
|
||||
print('contentstore and modulestore indexes created!')
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
Commandline tool for doing operations on Problems
|
||||
"""
|
||||
from __future__ import unicode_literals
|
||||
from __future__ import print_function
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
@@ -67,7 +68,7 @@ def main():
|
||||
|
||||
def command_show(problem):
|
||||
"""Display the text for this problem"""
|
||||
print problem.get_html()
|
||||
print(problem.get_html())
|
||||
|
||||
|
||||
def command_test(problem):
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Tests the capa shuffle and name-masking."""
|
||||
from __future__ import print_function
|
||||
|
||||
import unittest
|
||||
import textwrap
|
||||
@@ -276,7 +277,7 @@ class CapaShuffleTest(unittest.TestCase):
|
||||
orig_html = problem.get_html()
|
||||
self.assertEqual(orig_html, problem.get_html(), 'should be able to call get_html() twice')
|
||||
html = orig_html.replace('\n', ' ') # avoid headaches with .* matching
|
||||
print html
|
||||
print(html)
|
||||
self.assertRegexpMatches(html, r"<div>.*\[.*'Banana'.*'Apple'.*'Chocolate'.*'Donut'.*\].*</div>.*" +
|
||||
r"<div>.*\[.*'C'.*'A'.*'D'.*'B'.*\].*</div>")
|
||||
# Look at the responses in their authored order
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from __future__ import print_function
|
||||
import codecs
|
||||
import unittest
|
||||
from fractions import Fraction
|
||||
@@ -12,7 +13,7 @@ LOCAL_DEBUG = None
|
||||
def log(msg, output_type=None):
|
||||
"""Logging function for tests"""
|
||||
if LOCAL_DEBUG:
|
||||
print msg
|
||||
print(msg)
|
||||
if output_type == 'html':
|
||||
f.write(msg + '\n<br>\n')
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ values in parameterized problems. For details, see:
|
||||
|
||||
http://en.wikipedia.org/wiki/Electronic_color_code
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
# pylint: disable=invalid-name
|
||||
# r is standard name for a resistor. We would like to use it as such.
|
||||
@@ -91,21 +92,21 @@ def iseia(r, valid_types=(E6, E12, E24)):
|
||||
|
||||
if __name__ == '__main__':
|
||||
# Test cases. All of these should return True
|
||||
print iseia(100) # 100 ohm resistor is EIA
|
||||
print not iseia(101) # 101 is not
|
||||
print not iseia(100.3) # Floating point close to EIA is not EIA
|
||||
print iseia(100.001) # But within floating point error is
|
||||
print iseia(1e5) # We handle big numbers well
|
||||
print iseia(2200) # We handle middle-of-the-list well
|
||||
print(iseia(100)) # 100 ohm resistor is EIA
|
||||
print(not iseia(101)) # 101 is not
|
||||
print(not iseia(100.3)) # Floating point close to EIA is not EIA
|
||||
print(iseia(100.001)) # But within floating point error is
|
||||
print(iseia(1e5)) # We handle big numbers well
|
||||
print(iseia(2200)) # We handle middle-of-the-list well
|
||||
# We can handle 1% components correctly; 2.2k is EIA24, but not EIA48.
|
||||
print not iseia(2200, (E48, E96, E192))
|
||||
print iseia(5490e2, (E48, E96, E192))
|
||||
print iseia(2200)
|
||||
print not iseia(5490e2)
|
||||
print iseia(1e-5) # We handle little numbers well
|
||||
print not iseia("Hello") # Junk handled okay
|
||||
print not iseia(float('NaN'))
|
||||
print not iseia(-1)
|
||||
print not iseia(iseia)
|
||||
print not iseia(float('Inf'))
|
||||
print iseia(0) # Corner case. 0 is a standard resistor value.
|
||||
print(not iseia(2200, (E48, E96, E192)))
|
||||
print(iseia(5490e2, (E48, E96, E192)))
|
||||
print(iseia(2200))
|
||||
print(not iseia(5490e2))
|
||||
print(iseia(1e-5)) # We handle little numbers well
|
||||
print(not iseia("Hello")) # Junk handled okay
|
||||
print(not iseia(float('NaN')))
|
||||
print(not iseia(-1))
|
||||
print(not iseia(iseia))
|
||||
print(not iseia(float('Inf')))
|
||||
print(iseia(0)) # Corner case. 0 is a standard resistor value.
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from __future__ import print_function
|
||||
from xmodule.contentstore.content import StaticContent
|
||||
from .django import contentstore
|
||||
|
||||
@@ -12,13 +13,13 @@ def empty_asset_trashcan(course_locs):
|
||||
# first delete all of the thumbnails
|
||||
thumbs = store.get_all_content_thumbnails_for_course(course_loc)
|
||||
for thumb in thumbs:
|
||||
print "Deleting {0}...".format(thumb)
|
||||
print("Deleting {0}...".format(thumb))
|
||||
store.delete(thumb['_id'])
|
||||
|
||||
# then delete all of the assets
|
||||
assets, __ = store.get_all_content_for_course(course_loc)
|
||||
for asset in assets:
|
||||
print "Deleting {0}...".format(asset)
|
||||
print("Deleting {0}...".format(asset))
|
||||
store.delete(asset['_id'])
|
||||
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
"""
|
||||
Generates fake XML for asset metadata.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
import random
|
||||
from lxml import etree
|
||||
@@ -233,4 +234,4 @@ if __name__ == '__main__':
|
||||
if click is not None:
|
||||
cli() # pylint: disable=no-value-for-parameter
|
||||
else:
|
||||
print "Aborted! Module 'click' is not installed."
|
||||
print("Aborted! Module 'click' is not installed.")
|
||||
|
||||
@@ -4,6 +4,7 @@ Reads the data generated by performance tests and generates a savable
|
||||
report which can be viewed over time to examine the performance effects of code changes on
|
||||
various parts of the system.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
import sqlite3
|
||||
from lxml.builder import E
|
||||
@@ -286,4 +287,4 @@ if __name__ == '__main__':
|
||||
if click is not None:
|
||||
cli() # pylint: disable=no-value-for-parameter
|
||||
else:
|
||||
print "Aborted! Module 'click' is not installed."
|
||||
print("Aborted! Module 'click' is not installed.")
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Factories for use in tests of XBlocks.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
import datetime
|
||||
import functools
|
||||
@@ -584,7 +585,7 @@ def check_sum_of_calls(object_, methods, maximum_calls, minimum_calls=1, include
|
||||
messages.append(" args: {}\n".format(args))
|
||||
messages.append(" kwargs: {}\n\n".format(dict(kwargs)))
|
||||
|
||||
print "".join(messages)
|
||||
print("".join(messages))
|
||||
|
||||
# verify the counter actually worked by ensuring we have counted greater than (or equal to) the minimum calls
|
||||
assert call_count >= minimum_calls
|
||||
|
||||
@@ -20,6 +20,7 @@ Modulestore virtual | XML physical (draft, published)
|
||||
(a, a) | (a, a) | (x, a) | (x, x) | (x, y) | (a, x)
|
||||
(a, b) | (a, b) | (x, b) | (x, x) | (x, y) | (a, x)
|
||||
"""
|
||||
from __future__ import print_function
|
||||
import json
|
||||
import logging
|
||||
import mimetypes
|
||||
@@ -1177,7 +1178,7 @@ def perform_xlint(
|
||||
for err_log in module_store.errored_courses.itervalues():
|
||||
for err_log_entry in err_log.errors:
|
||||
msg = err_log_entry[0]
|
||||
print msg
|
||||
print(msg)
|
||||
if msg.startswith('ERROR:'):
|
||||
err_cnt += 1
|
||||
else:
|
||||
@@ -1220,12 +1221,12 @@ def perform_xlint(
|
||||
)
|
||||
warn_cnt += 1
|
||||
|
||||
print "\n"
|
||||
print "------------------------------------------"
|
||||
print "VALIDATION SUMMARY: {err} Errors {warn} Warnings".format(
|
||||
print("\n")
|
||||
print("------------------------------------------")
|
||||
print("VALIDATION SUMMARY: {err} Errors {warn} Warnings".format(
|
||||
err=err_cnt,
|
||||
warn=warn_cnt
|
||||
)
|
||||
))
|
||||
|
||||
if err_cnt > 0:
|
||||
print(
|
||||
@@ -1239,7 +1240,7 @@ def perform_xlint(
|
||||
"your courseware before importing"
|
||||
)
|
||||
else:
|
||||
print "This course can be imported successfully."
|
||||
print("This course can be imported successfully.")
|
||||
|
||||
return err_cnt
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from __future__ import print_function
|
||||
import json
|
||||
import unittest
|
||||
|
||||
@@ -178,7 +179,7 @@ class ConditionalModuleBasicTest(unittest.TestCase):
|
||||
modules['cond_module'].save()
|
||||
modules['source_module'].is_attempted = "false"
|
||||
ajax = json.loads(modules['cond_module'].handle_ajax('', ''))
|
||||
print "ajax: ", ajax
|
||||
print("ajax: ", ajax)
|
||||
fragments = ajax['fragments']
|
||||
self.assertFalse(any(['This is a secret' in item['content'] for item in fragments]))
|
||||
|
||||
@@ -186,7 +187,7 @@ class ConditionalModuleBasicTest(unittest.TestCase):
|
||||
modules['source_module'].is_attempted = "true"
|
||||
ajax = json.loads(modules['cond_module'].handle_ajax('', ''))
|
||||
modules['cond_module'].save()
|
||||
print "post-attempt ajax: ", ajax
|
||||
print("post-attempt ajax: ", ajax)
|
||||
fragments = ajax['fragments']
|
||||
self.assertTrue(any(['This is a secret' in item['content'] for item in fragments]))
|
||||
|
||||
@@ -232,7 +233,7 @@ class ConditionalModuleXmlTest(unittest.TestCase):
|
||||
|
||||
def get_course(self, name):
|
||||
"""Get a test course by directory name. If there's more than one, error."""
|
||||
print "Importing {0}".format(name)
|
||||
print("Importing {0}".format(name))
|
||||
|
||||
modulestore = XMLModuleStore(DATA_DIR, source_dirs=[name])
|
||||
courses = modulestore.get_courses()
|
||||
@@ -243,11 +244,11 @@ class ConditionalModuleXmlTest(unittest.TestCase):
|
||||
def test_conditional_module(self):
|
||||
"""Make sure that conditional module works"""
|
||||
|
||||
print "Starting import"
|
||||
print("Starting import")
|
||||
course = self.get_course('conditional_and_poll')
|
||||
|
||||
print "Course: ", course
|
||||
print "id: ", course.id
|
||||
print("Course: ", course)
|
||||
print("id: ", course.id)
|
||||
|
||||
def inner_get_module(descriptor):
|
||||
if isinstance(descriptor, BlockUsageLocator):
|
||||
@@ -269,13 +270,13 @@ class ConditionalModuleXmlTest(unittest.TestCase):
|
||||
self.test_system.get_module = inner_get_module
|
||||
|
||||
module = inner_get_module(location)
|
||||
print "module: ", module
|
||||
print "module children: ", module.get_children()
|
||||
print "module display items (children): ", module.get_display_items()
|
||||
print("module: ", module)
|
||||
print("module children: ", module.get_children())
|
||||
print("module display items (children): ", module.get_display_items())
|
||||
|
||||
html = module.render(STUDENT_VIEW).content
|
||||
print "html type: ", type(html)
|
||||
print "html: ", html
|
||||
print("html type: ", type(html))
|
||||
print("html: ", html)
|
||||
html_expect = module.xmodule_runtime.render_template(
|
||||
'conditional_ajax.html',
|
||||
{
|
||||
@@ -288,11 +289,11 @@ class ConditionalModuleXmlTest(unittest.TestCase):
|
||||
self.assertEqual(html, html_expect)
|
||||
|
||||
gdi = module.get_display_items()
|
||||
print "gdi=", gdi
|
||||
print("gdi=", gdi)
|
||||
|
||||
ajax = json.loads(module.handle_ajax('', ''))
|
||||
module.save()
|
||||
print "ajax: ", ajax
|
||||
print("ajax: ", ajax)
|
||||
fragments = ajax['fragments']
|
||||
self.assertFalse(any(['This is a secret' in item['content'] for item in fragments]))
|
||||
|
||||
@@ -304,7 +305,7 @@ class ConditionalModuleXmlTest(unittest.TestCase):
|
||||
|
||||
ajax = json.loads(module.handle_ajax('', ''))
|
||||
module.save()
|
||||
print "post-attempt ajax: ", ajax
|
||||
print("post-attempt ajax: ", ajax)
|
||||
fragments = ajax['fragments']
|
||||
self.assertTrue(any(['This is a secret' in item['content'] for item in fragments]))
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Tests the course modules and their functions"""
|
||||
from __future__ import print_function
|
||||
import ddt
|
||||
import unittest
|
||||
from datetime import datetime, timedelta
|
||||
@@ -214,7 +215,7 @@ class IsNewCourseTestCase(unittest.TestCase):
|
||||
for a, b, assertion in dates:
|
||||
a_score = get_dummy_course(start=a[0], announcement=a[1], advertised_start=a[2]).sorting_score
|
||||
b_score = get_dummy_course(start=b[0], announcement=b[1], advertised_start=b[2]).sorting_score
|
||||
print "Comparing %s to %s" % (a, b)
|
||||
print("Comparing %s to %s" % (a, b))
|
||||
assertion(a_score, b_score)
|
||||
|
||||
start_advertised_settings = [
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
"""
|
||||
Tests of XML export
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
import ddt
|
||||
import lxml.etree
|
||||
@@ -33,7 +34,7 @@ def strip_filenames(descriptor):
|
||||
"""
|
||||
Recursively strips 'filename' from all children's definitions.
|
||||
"""
|
||||
print "strip filename from {desc}".format(desc=text_type(descriptor.location))
|
||||
print("strip filename from {desc}".format(desc=text_type(descriptor.location)))
|
||||
if descriptor._field_data.has(descriptor, 'filename'):
|
||||
descriptor._field_data.delete(descriptor, 'filename')
|
||||
|
||||
@@ -95,12 +96,12 @@ class RoundTripTestCase(unittest.TestCase):
|
||||
""").strip()
|
||||
|
||||
root_dir = path(self.temp_dir)
|
||||
print "Copying test course to temp dir {0}".format(root_dir)
|
||||
print("Copying test course to temp dir {0}".format(root_dir))
|
||||
|
||||
data_dir = path(DATA_DIR)
|
||||
shutil.copytree(data_dir / course_dir, root_dir / course_dir)
|
||||
|
||||
print "Starting import"
|
||||
print("Starting import")
|
||||
initial_import = XMLModuleStore(root_dir, source_dirs=[course_dir], xblock_mixins=(XModuleMixin,))
|
||||
|
||||
courses = initial_import.get_courses()
|
||||
@@ -109,7 +110,7 @@ class RoundTripTestCase(unittest.TestCase):
|
||||
|
||||
# export to the same directory--that way things like the custom_tags/ folder
|
||||
# will still be there.
|
||||
print "Starting export"
|
||||
print("Starting export")
|
||||
file_system = OSFS(root_dir)
|
||||
initial_course.runtime.export_fs = file_system.makedir(course_dir, recreate=True)
|
||||
root = lxml.etree.Element('root')
|
||||
@@ -118,14 +119,14 @@ class RoundTripTestCase(unittest.TestCase):
|
||||
with initial_course.runtime.export_fs.open('course.xml', 'wb') as course_xml:
|
||||
lxml.etree.ElementTree(root).write(course_xml, encoding='utf-8')
|
||||
|
||||
print "Starting second import"
|
||||
print("Starting second import")
|
||||
second_import = XMLModuleStore(root_dir, source_dirs=[course_dir], xblock_mixins=(XModuleMixin,))
|
||||
|
||||
courses2 = second_import.get_courses()
|
||||
self.assertEquals(len(courses2), 1)
|
||||
exported_course = courses2[0]
|
||||
|
||||
print "Checking course equality"
|
||||
print("Checking course equality")
|
||||
|
||||
# HACK: filenames change when changing file formats
|
||||
# during imports from old-style courses. Ignore them.
|
||||
@@ -136,15 +137,15 @@ class RoundTripTestCase(unittest.TestCase):
|
||||
self.assertEquals(initial_course.id, exported_course.id)
|
||||
course_id = initial_course.id
|
||||
|
||||
print "Checking key equality"
|
||||
print("Checking key equality")
|
||||
self.assertItemsEqual(
|
||||
initial_import.modules[course_id].keys(),
|
||||
second_import.modules[course_id].keys()
|
||||
)
|
||||
|
||||
print "Checking module equality"
|
||||
print("Checking module equality")
|
||||
for location in initial_import.modules[course_id].keys():
|
||||
print("Checking", location)
|
||||
print(("Checking", location))
|
||||
self.assertTrue(blocks_are_equivalent(
|
||||
initial_import.modules[course_id][location],
|
||||
second_import.modules[course_id][location]
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import print_function
|
||||
import datetime
|
||||
from tempfile import mkdtemp
|
||||
|
||||
@@ -73,7 +74,7 @@ class BaseCourseTestCase(TestCase):
|
||||
|
||||
def get_course(self, name):
|
||||
"""Get a test course by directory name. If there's more than one, error."""
|
||||
print "Importing {0}".format(name)
|
||||
print("Importing {0}".format(name))
|
||||
|
||||
modulestore = XMLModuleStore(
|
||||
DATA_DIR,
|
||||
@@ -203,7 +204,7 @@ class ImportTestCase(BaseCourseTestCase):
|
||||
Checks to make sure that metadata inheritance on a course descriptor is respected.
|
||||
"""
|
||||
# pylint: disable=protected-access
|
||||
print(descriptor, descriptor._field_data)
|
||||
print((descriptor, descriptor._field_data))
|
||||
self.assertEqual(descriptor.due, ImportTestCase.date.from_json(from_date_string))
|
||||
|
||||
# Check that the child inherits due correctly
|
||||
@@ -222,7 +223,7 @@ class ImportTestCase(BaseCourseTestCase):
|
||||
descriptor.add_xml_to_node(node)
|
||||
|
||||
# Check that the exported xml is just a pointer
|
||||
print("Exported xml:", etree.tostring(node))
|
||||
print(("Exported xml:", etree.tostring(node)))
|
||||
self.assertTrue(is_pointer_tag(node))
|
||||
# but it's a special case course pointer
|
||||
self.assertEqual(node.attrib['course'], COURSE)
|
||||
@@ -441,22 +442,22 @@ class ImportTestCase(BaseCourseTestCase):
|
||||
"""]
|
||||
|
||||
for xml_str in yes:
|
||||
print "should be True for {0}".format(xml_str)
|
||||
print("should be True for {0}".format(xml_str))
|
||||
self.assertTrue(is_pointer_tag(etree.fromstring(xml_str)))
|
||||
|
||||
for xml_str in no:
|
||||
print "should be False for {0}".format(xml_str)
|
||||
print("should be False for {0}".format(xml_str))
|
||||
self.assertFalse(is_pointer_tag(etree.fromstring(xml_str)))
|
||||
|
||||
def test_metadata_inherit(self):
|
||||
"""Make sure that metadata is inherited properly"""
|
||||
|
||||
print "Starting import"
|
||||
print("Starting import")
|
||||
course = self.get_course('toy')
|
||||
|
||||
def check_for_key(key, node, value):
|
||||
"recursive check for presence of key"
|
||||
print "Checking {0}".format(text_type(node.location))
|
||||
print("Checking {0}".format(text_type(node.location)))
|
||||
self.assertEqual(getattr(node, key), value)
|
||||
for c in node.get_children():
|
||||
check_for_key(key, c, value)
|
||||
@@ -525,17 +526,17 @@ class ImportTestCase(BaseCourseTestCase):
|
||||
def test_colon_in_url_name(self):
|
||||
"""Ensure that colons in url_names convert to file paths properly"""
|
||||
|
||||
print "Starting import"
|
||||
print("Starting import")
|
||||
# Not using get_courses because we need the modulestore object too afterward
|
||||
modulestore = XMLModuleStore(DATA_DIR, source_dirs=['toy'])
|
||||
courses = modulestore.get_courses()
|
||||
self.assertEquals(len(courses), 1)
|
||||
course = courses[0]
|
||||
|
||||
print "course errors:"
|
||||
print("course errors:")
|
||||
for (msg, err) in modulestore.get_course_errors(course.id):
|
||||
print msg
|
||||
print err
|
||||
print(msg)
|
||||
print(err)
|
||||
|
||||
chapters = course.get_children()
|
||||
self.assertEquals(len(chapters), 5)
|
||||
@@ -543,12 +544,12 @@ class ImportTestCase(BaseCourseTestCase):
|
||||
ch2 = chapters[1]
|
||||
self.assertEquals(ch2.url_name, "secret:magic")
|
||||
|
||||
print "Ch2 location: ", ch2.location
|
||||
print("Ch2 location: ", ch2.location)
|
||||
|
||||
also_ch2 = modulestore.get_item(ch2.location)
|
||||
self.assertEquals(ch2, also_ch2)
|
||||
|
||||
print "making sure html loaded"
|
||||
print("making sure html loaded")
|
||||
loc = course.id.make_usage_key('html', 'secret:toylab')
|
||||
html = modulestore.get_item(loc)
|
||||
self.assertEquals(html.display_name, "Toy lab")
|
||||
@@ -560,13 +561,13 @@ class ImportTestCase(BaseCourseTestCase):
|
||||
loaded because of unicode filenames, there are appropriate
|
||||
exceptions/errors to that effect."""
|
||||
|
||||
print "Starting import"
|
||||
print("Starting import")
|
||||
modulestore = XMLModuleStore(DATA_DIR, source_dirs=['test_unicode'])
|
||||
courses = modulestore.get_courses()
|
||||
self.assertEquals(len(courses), 1)
|
||||
course = courses[0]
|
||||
|
||||
print "course errors:"
|
||||
print("course errors:")
|
||||
|
||||
# Expect to find an error/exception about characters in "®esources"
|
||||
expect = "InvalidKeyError"
|
||||
@@ -602,7 +603,7 @@ class ImportTestCase(BaseCourseTestCase):
|
||||
for i in (2, 3):
|
||||
video = sections[i]
|
||||
# Name should be 'video_{hash}'
|
||||
print "video {0} url_name: {1}".format(i, video.url_name)
|
||||
print("video {0} url_name: {1}".format(i, video.url_name))
|
||||
self.assertEqual(len(video.url_name), len('video_') + 12)
|
||||
|
||||
def test_poll_and_conditional_import(self):
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Tests stringify functions used in xmodule html
|
||||
"""
|
||||
from __future__ import print_function
|
||||
from lxml import etree
|
||||
from openedx.core.lib.tests import attr
|
||||
from xmodule.stringify import stringify_children
|
||||
@@ -38,8 +39,8 @@ def test_stringify_again():
|
||||
xml = etree.fromstring(html)
|
||||
out = stringify_children(xml)
|
||||
|
||||
print "output:"
|
||||
print out
|
||||
print("output:")
|
||||
print(out)
|
||||
|
||||
# Tracking strange content repeating bug
|
||||
# Should appear once
|
||||
|
||||
@@ -6,6 +6,7 @@ Runs tasks on answers to course problems to validate that code
|
||||
paths actually work.
|
||||
|
||||
"""
|
||||
from __future__ import print_function
|
||||
import json
|
||||
from itertools import chain, cycle, repeat
|
||||
from smtplib import SMTPAuthenticationError, SMTPConnectError, SMTPDataError, SMTPServerDisconnected
|
||||
@@ -152,7 +153,7 @@ class TestBulkEmailInstructorTask(InstructorTaskCourseTestCase):
|
||||
self.assertEquals(len(task_id_list), 1)
|
||||
task_id = task_id_list[0]
|
||||
subtask_status = subtask_status_info.get(task_id)
|
||||
print "Testing subtask status: {}".format(subtask_status)
|
||||
print("Testing subtask status: {}".format(subtask_status))
|
||||
self.assertEquals(subtask_status.get('task_id'), task_id)
|
||||
self.assertEquals(subtask_status.get('attempted'), succeeded + failed)
|
||||
self.assertEquals(subtask_status.get('succeeded'), succeeded)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Generate a report of certificate statuses
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
@@ -56,7 +57,7 @@ class Command(BaseCommand):
|
||||
|
||||
# find students who are active
|
||||
# number of enrolled students = downloadable + notpassing
|
||||
print "Looking up certificate states for {0}".format(options['course'])
|
||||
print("Looking up certificate states for {0}".format(options['course']))
|
||||
enrolled_current = User.objects.filter(
|
||||
courseenrollment__course_id=course_id,
|
||||
courseenrollment__is_active=True
|
||||
@@ -113,14 +114,14 @@ class Command(BaseCommand):
|
||||
)
|
||||
|
||||
# print the heading for the report
|
||||
print "{:>26}".format("course ID"),
|
||||
print ' '.join(["{:>16}".format(heading) for heading in status_headings])
|
||||
print("{:>26}".format("course ID"), end=' ')
|
||||
print(' '.join(["{:>16}".format(heading) for heading in status_headings]))
|
||||
|
||||
# print the report
|
||||
print "{0:>26}".format(text_type(course_id)),
|
||||
print("{0:>26}".format(text_type(course_id)), end=' ')
|
||||
for heading in status_headings:
|
||||
if heading in cert_data[course_id]:
|
||||
print "{:>16}".format(cert_data[course_id][heading]),
|
||||
print("{:>16}".format(cert_data[course_id][heading]), end=' ')
|
||||
else:
|
||||
print " " * 16,
|
||||
print
|
||||
print(" " * 16, end=' ')
|
||||
print()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Views handling read (GET) requests for the Discussion tab and inline discussions.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
import logging
|
||||
from functools import wraps
|
||||
@@ -633,8 +634,8 @@ def followed_threads(request, course_key, user_id):
|
||||
query_params['group_id'] = group_id
|
||||
|
||||
paginated_results = profiled_user.subscribed_threads(query_params)
|
||||
print "\n \n \n paginated results \n \n \n "
|
||||
print paginated_results
|
||||
print("\n \n \n paginated results \n \n \n ")
|
||||
print(paginated_results)
|
||||
query_params['page'] = paginated_results.page
|
||||
query_params['num_pages'] = paginated_results.num_pages
|
||||
user_info = cc.User.from_django_user(request.user).to_dict()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from __future__ import print_function
|
||||
import functools
|
||||
import json
|
||||
import logging
|
||||
@@ -769,7 +770,7 @@ def upload(request, course_id): # ajax upload file to a question or answer
|
||||
except exceptions.PermissionDenied, err:
|
||||
error = unicode(err)
|
||||
except Exception, err:
|
||||
print err
|
||||
print(err)
|
||||
logging.critical(unicode(err))
|
||||
error = _('Error uploading file. Please contact the site administrator. Thank you.')
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
"""
|
||||
Unit tests for instructor.api methods.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
import datetime
|
||||
import functools
|
||||
import io
|
||||
@@ -1220,7 +1221,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest
|
||||
url = reverse('students_update_enrollment', kwargs={'course_id': text_type(self.course.id)})
|
||||
response = self.client.post(url, {'identifiers': self.notenrolled_student.email, 'action': 'enroll',
|
||||
'email_students': False})
|
||||
print "type(self.notenrolled_student.email): {}".format(type(self.notenrolled_student.email))
|
||||
print("type(self.notenrolled_student.email): {}".format(type(self.notenrolled_student.email)))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
# test that the user is now enrolled
|
||||
@@ -1266,7 +1267,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest
|
||||
environ = {'wsgi.url_scheme': protocol}
|
||||
response = self.client.post(url, params, **environ)
|
||||
|
||||
print "type(self.notenrolled_student.email): {}".format(type(self.notenrolled_student.email))
|
||||
print("type(self.notenrolled_student.email): {}".format(type(self.notenrolled_student.email)))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
# test that the user is now enrolled
|
||||
@@ -1419,7 +1420,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest
|
||||
'auto_enroll': True}
|
||||
environ = {'wsgi.url_scheme': protocol}
|
||||
response = self.client.post(url, params, **environ)
|
||||
print "type(self.notregistered_email): {}".format(type(self.notregistered_email))
|
||||
print("type(self.notregistered_email): {}".format(type(self.notregistered_email)))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
# Check the outbox
|
||||
@@ -1467,7 +1468,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest
|
||||
url = reverse('students_update_enrollment', kwargs={'course_id': text_type(self.course.id)})
|
||||
response = self.client.post(url, {'identifiers': self.enrolled_student.email, 'action': 'unenroll',
|
||||
'email_students': False})
|
||||
print "type(self.enrolled_student.email): {}".format(type(self.enrolled_student.email))
|
||||
print("type(self.enrolled_student.email): {}".format(type(self.enrolled_student.email)))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
# test that the user is now unenrolled
|
||||
@@ -1510,7 +1511,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest
|
||||
url = reverse('students_update_enrollment', kwargs={'course_id': text_type(self.course.id)})
|
||||
response = self.client.post(url, {'identifiers': self.enrolled_student.email, 'action': 'unenroll',
|
||||
'email_students': True})
|
||||
print "type(self.enrolled_student.email): {}".format(type(self.enrolled_student.email))
|
||||
print("type(self.enrolled_student.email): {}".format(type(self.enrolled_student.email)))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
# test that the user is now unenrolled
|
||||
@@ -1571,7 +1572,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest
|
||||
url = reverse('students_update_enrollment', kwargs={'course_id': text_type(self.course.id)})
|
||||
response = self.client.post(url,
|
||||
{'identifiers': self.allowed_email, 'action': 'unenroll', 'email_students': True})
|
||||
print "type(self.allowed_email): {}".format(type(self.allowed_email))
|
||||
print("type(self.allowed_email): {}".format(type(self.allowed_email)))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
# test the response data
|
||||
@@ -1696,7 +1697,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest
|
||||
'auto_enroll': True}
|
||||
environ = {'wsgi.url_scheme': protocol}
|
||||
response = self.client.post(url, params, **environ)
|
||||
print "type(self.notregistered_email): {}".format(type(self.notregistered_email))
|
||||
print("type(self.notregistered_email): {}".format(type(self.notregistered_email)))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
# Check the outbox
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
"""
|
||||
Unit tests for instructor.enrollment methods.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
import json
|
||||
from abc import ABCMeta
|
||||
@@ -92,17 +93,17 @@ class TestEnrollmentChangeBase(CacheIsolationTestCase):
|
||||
`email` is an email string
|
||||
"""
|
||||
# initialize & check before
|
||||
print "checking initialization..."
|
||||
print("checking initialization...")
|
||||
eobjs = before_ideal.create_user(self.course_key)
|
||||
before = EmailEnrollmentState(self.course_key, eobjs.email)
|
||||
self.assertEqual(before, before_ideal)
|
||||
|
||||
# do action
|
||||
print "running action..."
|
||||
print("running action...")
|
||||
action(eobjs.email)
|
||||
|
||||
# check after
|
||||
print "checking effects..."
|
||||
print("checking effects...")
|
||||
after = EmailEnrollmentState(self.course_key, eobjs.email)
|
||||
self.assertEqual(after, after_ideal)
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
""" Tests for analytics.distributions """
|
||||
from __future__ import print_function
|
||||
|
||||
import pytest
|
||||
from django.test import TestCase
|
||||
@@ -45,7 +46,7 @@ class TestAnalyticsDistributions(TestCase):
|
||||
feature = 'year_of_birth'
|
||||
self.assertIn(feature, AVAILABLE_PROFILE_FEATURES)
|
||||
distribution = profile_distribution(self.course_id, feature)
|
||||
print distribution
|
||||
print(distribution)
|
||||
self.assertEqual(distribution.type, 'OPEN_CHOICE')
|
||||
self.assertTrue(hasattr(distribution, 'choices_display_names'))
|
||||
self.assertEqual(distribution.choices_display_names, None)
|
||||
@@ -99,7 +100,7 @@ class TestAnalyticsDistributionsNoData(TestCase):
|
||||
feature = 'gender'
|
||||
self.assertIn(feature, AVAILABLE_PROFILE_FEATURES)
|
||||
distribution = profile_distribution(self.course_id, feature)
|
||||
print distribution
|
||||
print(distribution)
|
||||
self.assertEqual(distribution.type, 'EASY_CHOICE')
|
||||
self.assertTrue(hasattr(distribution, 'choices_display_names'))
|
||||
self.assertNotEqual(distribution.choices_display_names, None)
|
||||
@@ -110,7 +111,7 @@ class TestAnalyticsDistributionsNoData(TestCase):
|
||||
feature = 'year_of_birth'
|
||||
self.assertIn(feature, AVAILABLE_PROFILE_FEATURES)
|
||||
distribution = profile_distribution(self.course_id, feature)
|
||||
print distribution
|
||||
print(distribution)
|
||||
self.assertEqual(distribution.type, 'OPEN_CHOICE')
|
||||
self.assertTrue(hasattr(distribution, 'choices_display_names'))
|
||||
self.assertEqual(distribution.choices_display_names, None)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Tests for the rss_proxy views
|
||||
"""
|
||||
from __future__ import print_function
|
||||
from django.urls import reverse
|
||||
from django.test import TestCase
|
||||
from mock import Mock, patch
|
||||
@@ -56,9 +57,9 @@ class RssProxyViewTests(TestCase):
|
||||
"""
|
||||
mock_requests_get.return_value = Mock(status_code=404)
|
||||
resp = self.client.get('%s?url=%s' % (reverse('rss_proxy:proxy'), self.whitelisted_url2))
|
||||
print resp.status_code
|
||||
print resp.content
|
||||
print resp['Content-Type']
|
||||
print(resp.status_code)
|
||||
print(resp.content)
|
||||
print(resp['Content-Type'])
|
||||
self.assertEqual(resp.status_code, 404)
|
||||
self.assertEqual(resp['Content-Type'], 'application/xml')
|
||||
self.assertEqual(resp.content, '')
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Views for the rss_proxy djangoapp.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
import requests
|
||||
from django.conf import settings
|
||||
from django.core.cache import cache
|
||||
@@ -22,8 +23,8 @@ def proxy(request):
|
||||
cache_key = CACHE_KEY_RSS.format(url=url)
|
||||
status_code = 200
|
||||
rss = cache.get(cache_key, '')
|
||||
print cache_key
|
||||
print 'Cached rss: %s' % rss
|
||||
print(cache_key)
|
||||
print('Cached rss: %s' % rss)
|
||||
if not rss:
|
||||
# Go get the RSS from the URL if it was not cached
|
||||
resp = requests.get(url)
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
Script for retiring order that went through cybersource but weren't
|
||||
marked as "purchased" in the db
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
from django.core.management.base import BaseCommand
|
||||
from six import text_type
|
||||
@@ -36,12 +37,12 @@ class Command(BaseCommand):
|
||||
try:
|
||||
order.retire()
|
||||
except (UnexpectedOrderItemStatus, InvalidStatusToRetire) as err:
|
||||
print "Did not retire order {order}: {message}".format(
|
||||
print("Did not retire order {order}: {message}".format(
|
||||
order=order.id, message=text_type(err)
|
||||
)
|
||||
))
|
||||
else:
|
||||
print "retired order {order_id} from status {old_status} to status {new_status}".format(
|
||||
print("retired order {order_id} from status {old_status} to status {new_status}".format(
|
||||
order_id=order.id,
|
||||
old_status=old_status,
|
||||
new_status=order.status,
|
||||
)
|
||||
))
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Django admin commands related to verify_student
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
from django.core.management.base import BaseCommand
|
||||
|
||||
@@ -29,14 +30,14 @@ class Command(BaseCommand):
|
||||
attempts_to_retry = SoftwareSecurePhotoVerification.objects.filter(status='must_retry')
|
||||
force_must_retry = False
|
||||
|
||||
print "Attempting to retry {0} failed PhotoVerification submissions".format(len(attempts_to_retry))
|
||||
print("Attempting to retry {0} failed PhotoVerification submissions".format(len(attempts_to_retry)))
|
||||
for index, attempt in enumerate(attempts_to_retry):
|
||||
print "Retrying submission #{0} (ID: {1}, User: {2})".format(index, attempt.id, attempt.user)
|
||||
print("Retrying submission #{0} (ID: {1}, User: {2})".format(index, attempt.id, attempt.user))
|
||||
|
||||
# Set the attempts status to 'must_retry' so that we can re-submit it
|
||||
if force_must_retry:
|
||||
attempt.status = 'must_retry'
|
||||
|
||||
attempt.submit(copy_id_photo_from=attempt.copy_id_photo_from)
|
||||
print "Retry result: {0}".format(attempt.status)
|
||||
print "Done resubmitting failed photo verifications"
|
||||
print("Retry result: {0}".format(attempt.status))
|
||||
print("Done resubmitting failed photo verifications")
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
Tests the ``notify_credentials`` management command.
|
||||
"""
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
from __future__ import print_function
|
||||
|
||||
from datetime import datetime
|
||||
import mock
|
||||
@@ -39,7 +40,7 @@ class TestNotifyCredentials(TestCase):
|
||||
self.cert2 = GeneratedCertificateFactory(user=self.user, course_id='course-v1:edX+Test+2')
|
||||
with freeze_time(datetime(2017, 3, 1)):
|
||||
self.cert3 = GeneratedCertificateFactory(user=self.user, course_id='course-v1:testX+Test+3')
|
||||
print('self.cert1.modified_date', self.cert1.modified_date)
|
||||
print(('self.cert1.modified_date', self.cert1.modified_date))
|
||||
|
||||
# No factory for these
|
||||
with freeze_time(datetime(2017, 1, 1)):
|
||||
@@ -51,7 +52,7 @@ class TestNotifyCredentials(TestCase):
|
||||
with freeze_time(datetime(2017, 3, 1)):
|
||||
self.grade3 = PersistentCourseGrade.objects.create(user_id=self.user.id, course_id='course-v1:testX+Test+3',
|
||||
percent_grade=1)
|
||||
print('self.grade1.modified', self.grade1.modified)
|
||||
print(('self.grade1.modified', self.grade1.modified))
|
||||
|
||||
@mock.patch(COMMAND_MODULE + '.Command.send_notifications')
|
||||
def test_course_args(self, mock_send):
|
||||
|
||||
@@ -4,6 +4,7 @@ Created on Jan 18, 2013
|
||||
|
||||
@author: brian
|
||||
'''
|
||||
from __future__ import print_function
|
||||
import openid
|
||||
from openid.fetchers import HTTPFetcher, HTTPResponse
|
||||
from urlparse import parse_qs, urlparse
|
||||
@@ -470,4 +471,4 @@ class OpenIdProviderLiveServerTest(LiveServerTestCase):
|
||||
try:
|
||||
super(OpenIdProviderLiveServerTest, cls).tearDownClass()
|
||||
except RuntimeError:
|
||||
print "Warning: Could not shut down test server."
|
||||
print("Warning: Could not shut down test server.")
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Test the heartbeat
|
||||
"""
|
||||
from __future__ import print_function
|
||||
import json
|
||||
|
||||
from django.urls import reverse
|
||||
@@ -24,7 +25,7 @@ class HeartbeatTestCase(ModuleStoreTestCase):
|
||||
|
||||
def test_success(self):
|
||||
response = self.client.get(self.heartbeat_url + '?extended')
|
||||
print response
|
||||
print(response)
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
This file contains helpers for paver commands, Django is not initialized in paver commands.
|
||||
So, django settings, models etc. can not be used here.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
import os
|
||||
|
||||
from path import Path
|
||||
@@ -27,13 +28,13 @@ def get_theme_paths(themes, theme_dirs):
|
||||
for theme in themes:
|
||||
theme_base_dirs = get_theme_base_dirs(theme, theme_dirs)
|
||||
if not theme_base_dirs:
|
||||
print(
|
||||
print((
|
||||
"\033[91m\nSkipping '{theme}': \n"
|
||||
"Theme ({theme}) not found in any of the theme dirs ({theme_dirs}). \033[00m".format(
|
||||
theme=theme,
|
||||
theme_dirs=", ".join(theme_dirs)
|
||||
),
|
||||
)
|
||||
))
|
||||
theme_paths.extend(theme_base_dirs)
|
||||
|
||||
return theme_paths
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Test helpers for Comprehensive Theming.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
from functools import wraps
|
||||
import os
|
||||
@@ -65,16 +66,16 @@ def with_comprehensive_theme_context(theme=None):
|
||||
def dump_theming_info():
|
||||
"""Dump a bunch of theming information, for debugging."""
|
||||
for namespace, lookup in edxmako.LOOKUP.items():
|
||||
print "--- %s: %s" % (namespace, lookup.template_args['module_directory'])
|
||||
print("--- %s: %s" % (namespace, lookup.template_args['module_directory']))
|
||||
for directory in lookup.directories:
|
||||
print " %s" % (directory,)
|
||||
print(" %s" % (directory,))
|
||||
|
||||
print "=" * 80
|
||||
print("=" * 80)
|
||||
for dirname, __, filenames in os.walk(settings.MAKO_MODULE_DIR):
|
||||
print "%s ----------------" % (dir,)
|
||||
print("%s ----------------" % (dir,))
|
||||
for filename in sorted(filenames):
|
||||
if filename.endswith(".pyc"):
|
||||
continue
|
||||
with open(os.path.join(dirname, filename)) as f:
|
||||
content = len(f.read())
|
||||
print " %s: %d" % (filename, content)
|
||||
print(" %s: %d" % (filename, content))
|
||||
|
||||
@@ -9,6 +9,7 @@ Useful when paver or a shell script needs such a value.
|
||||
This handles the one specific use case of the "print_settings" command from
|
||||
django-extensions that we were actually using.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
|
||||
@@ -12,6 +12,7 @@ django-extensions that we were actually using.
|
||||
|
||||
originally from http://www.djangosnippets.org/snippets/828/ by dnordberg
|
||||
"""
|
||||
from __future__ import print_function
|
||||
import logging
|
||||
|
||||
import django
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from __future__ import print_function
|
||||
from contentstore.course_group_config import GroupConfiguration
|
||||
from django.conf import settings
|
||||
from course_modes.models import CourseMode
|
||||
@@ -27,7 +28,7 @@ class Command(BaseCommand):
|
||||
|
||||
module_store = modulestore()
|
||||
|
||||
print "Starting Swap from Auto Track Cohort Pilot command"
|
||||
print("Starting Swap from Auto Track Cohort Pilot command")
|
||||
|
||||
verified_track_cohorts_setting = self._latest_settings()
|
||||
|
||||
@@ -54,8 +55,8 @@ class Command(BaseCommand):
|
||||
raise CommandError("No audit_cohort_names set for MigrateVerifiedTrackCohortsSetting with ID: '%s'"
|
||||
% verified_track_cohorts_setting.id)
|
||||
|
||||
print "Running for MigrateVerifiedTrackCohortsSetting with old_course_key='%s' and rerun_course_key='%s'" % \
|
||||
(verified_track_cohorts_setting.old_course_key, verified_track_cohorts_setting.rerun_course_key)
|
||||
print("Running for MigrateVerifiedTrackCohortsSetting with old_course_key='%s' and rerun_course_key='%s'" % \
|
||||
(verified_track_cohorts_setting.old_course_key, verified_track_cohorts_setting.rerun_course_key))
|
||||
|
||||
# Get the CourseUserGroup IDs for the audit course names from the old course
|
||||
audit_course_user_group_ids = CourseUserGroup.objects.filter(
|
||||
@@ -170,7 +171,7 @@ class Command(BaseCommand):
|
||||
)
|
||||
if (audit_partition_group_access
|
||||
and audit_course_user_group_partition_group.group_id in audit_partition_group_access):
|
||||
print "Queueing XBlock at location: '%s' for Audit Content Group update " % item.location
|
||||
print("Queueing XBlock at location: '%s' for Audit Content Group update " % item.location)
|
||||
set_audit_enrollment_track = True
|
||||
|
||||
# Check the partition and group IDs for the verified course group, if it exists in
|
||||
@@ -191,7 +192,7 @@ class Command(BaseCommand):
|
||||
% (item.location, non_verified_track_access_groups)
|
||||
)
|
||||
if verified_course_user_group_partition_group.group_id in verified_partition_group_access:
|
||||
print "Queueing XBlock at location: '%s' for Verified Content Group update " % item.location
|
||||
print("Queueing XBlock at location: '%s' for Verified Content Group update " % item.location)
|
||||
set_verified_enrollment_track = True
|
||||
|
||||
# Add the enrollment track ids to a group access array
|
||||
@@ -223,7 +224,7 @@ class Command(BaseCommand):
|
||||
for item in items_to_update:
|
||||
module_store.update_item(item, ModuleStoreEnum.UserID.mgmt_command)
|
||||
module_store.publish(item.location, ModuleStoreEnum.UserID.mgmt_command)
|
||||
print "Updated and published XBlock at location: '%s'" % item.location
|
||||
print("Updated and published XBlock at location: '%s'" % item.location)
|
||||
|
||||
# Check if we should delete any partition groups if there are no errors.
|
||||
# If there are errors, none of the xblock items will have been updated,
|
||||
@@ -269,7 +270,7 @@ class Command(BaseCommand):
|
||||
"\t\n".join(errors)
|
||||
)
|
||||
|
||||
print "Finished for MigrateVerifiedTrackCohortsSetting with ID='%s" % verified_track_cohorts_setting.id
|
||||
print("Finished for MigrateVerifiedTrackCohortsSetting with ID='%s" % verified_track_cohorts_setting.id)
|
||||
|
||||
def _latest_settings(self):
|
||||
"""
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
""" Tests for DiscussionXBLock"""
|
||||
from __future__ import print_function
|
||||
from collections import namedtuple
|
||||
import ddt
|
||||
import itertools
|
||||
@@ -108,7 +109,7 @@ class DiscussionXBlockImportExportTests(TestCase):
|
||||
self.assertEqual(block.discussion_category, category_pair.value)
|
||||
self.assertEqual(block.discussion_target, target_pair.value)
|
||||
except AssertionError:
|
||||
print xblock_xml
|
||||
print(xblock_xml)
|
||||
raise
|
||||
|
||||
@mock.patch(DISCUSSION_XBLOCK_LOCATION + ".load_definition_xml")
|
||||
@@ -140,7 +141,7 @@ class DiscussionXBlockImportExportTests(TestCase):
|
||||
self.assertEqual(block.discussion_category, category_pair.value)
|
||||
self.assertEqual(block.discussion_target, target_pair.value)
|
||||
except AssertionError:
|
||||
print xblock_xml, xblock_definition_xml
|
||||
print(xblock_xml, xblock_definition_xml)
|
||||
raise
|
||||
|
||||
def test_export_default_discussion_id(self):
|
||||
|
||||
@@ -7,6 +7,7 @@ run v1 tests only.
|
||||
|
||||
That be the dragon here.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
import pkg_resources
|
||||
|
||||
|
||||
@@ -49,5 +50,5 @@ for entrypoint in pkg_resources.iter_entry_points(group="xblock.test.v0"):
|
||||
if not classname.replace("_", "").isalnum():
|
||||
raise InvalidTestName("Python variables should be letters, numbers, and underscores: " + classname)
|
||||
globals()[classname] = plugin
|
||||
print "Loading XBlock test: " + classname
|
||||
print("Loading XBlock test: " + classname)
|
||||
xblock_loaded = True
|
||||
|
||||
@@ -34,6 +34,7 @@ Our next steps would be to:
|
||||
* Move more blocks out of the platform, and more tests into the
|
||||
blocks themselves.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
import collections
|
||||
import HTMLParser
|
||||
@@ -391,13 +392,13 @@ class XBlockTestCase(XBlockStudentTestCaseMixin,
|
||||
try:
|
||||
ajax_response.data = json.loads(resp.content)
|
||||
except ValueError:
|
||||
print "Invalid JSON response"
|
||||
print "(Often a redirect if e.g. not logged in)"
|
||||
print >>sys.stderr, "Could not load JSON from AJAX call"
|
||||
print >>sys.stderr, "Status:", resp.status_code
|
||||
print >>sys.stderr, "URL:", url
|
||||
print >>sys.stderr, "Block", block_urlname
|
||||
print >>sys.stderr, "Response", repr(resp.content)
|
||||
print("Invalid JSON response")
|
||||
print("(Often a redirect if e.g. not logged in)")
|
||||
print("Could not load JSON from AJAX call", file=sys.stderr)
|
||||
print("Status:", resp.status_code, file=sys.stderr)
|
||||
print("URL:", url, file=sys.stderr)
|
||||
print("Block", block_urlname, file=sys.stderr)
|
||||
print("Response", repr(resp.content), file=sys.stderr)
|
||||
raise
|
||||
ajax_response.status_code = resp.status_code
|
||||
return ajax_response
|
||||
@@ -453,15 +454,15 @@ class XBlockTestCase(XBlockStudentTestCaseMixin,
|
||||
try:
|
||||
escaped_html = xblock_html.split('<')[1].split('>')[1]
|
||||
except IndexError:
|
||||
print >>sys.stderr, "XBlock page could not render"
|
||||
print >>sys.stderr, "(Often, a redirect if e.g. not logged in)"
|
||||
print >>sys.stderr, "URL Name:", repr(urlname)
|
||||
print >>sys.stderr, "Usage ID", repr(usage_id)
|
||||
print >>sys.stderr, "Content", repr(content)
|
||||
print >>sys.stderr, "Split 1", repr(xblock_html.split('<'))
|
||||
print >>sys.stderr, "Dice 1:", repr(xblock_html.split('<')[1])
|
||||
print >> sys.stderr, "Split 2", repr(xblock_html.split('<')[1].split('>'))
|
||||
print >> sys.stderr, "Dice 2", repr(xblock_html.split('<')[1].split('>')[1])
|
||||
print("XBlock page could not render", file=sys.stderr)
|
||||
print("(Often, a redirect if e.g. not logged in)", file=sys.stderr)
|
||||
print("URL Name:", repr(urlname), file=sys.stderr)
|
||||
print("Usage ID", repr(usage_id), file=sys.stderr)
|
||||
print("Content", repr(content), file=sys.stderr)
|
||||
print("Split 1", repr(xblock_html.split('<')), file=sys.stderr)
|
||||
print("Dice 1:", repr(xblock_html.split('<')[1]), file=sys.stderr)
|
||||
print("Split 2", repr(xblock_html.split('<')[1].split('>')), file=sys.stderr)
|
||||
print("Dice 2", repr(xblock_html.split('<')[1].split('>')[1]), file=sys.stderr)
|
||||
raise
|
||||
# Finally, we unescape the contents
|
||||
decoded_html = HTMLParser.HTMLParser().unescape(escaped_html).strip()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Acceptance test tasks
|
||||
"""
|
||||
from __future__ import print_function
|
||||
from optparse import make_option
|
||||
|
||||
from paver.easy import cmdopts, needs
|
||||
@@ -52,13 +53,13 @@ def test_acceptance(options, passthrough_options):
|
||||
'red',
|
||||
'No system specified, running tests for both cms and lms.'
|
||||
)
|
||||
print msg
|
||||
print(msg)
|
||||
if opts['default_store'] not in ['draft', 'split']:
|
||||
msg = colorize(
|
||||
'red',
|
||||
'No modulestore specified, running tests for both draft and split.'
|
||||
)
|
||||
print msg
|
||||
print(msg)
|
||||
|
||||
suite = AcceptanceTestSuite('{} acceptance'.format(opts['system']), **opts)
|
||||
suite.run()
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
Run acceptance tests that use the bok-choy framework
|
||||
https://bok-choy.readthedocs.org/en/latest/
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
import os
|
||||
|
||||
@@ -146,7 +147,7 @@ def run_bokchoy(options, passthrough_options):
|
||||
default_store=test_suite.default_store,
|
||||
)
|
||||
)
|
||||
print msg
|
||||
print(msg)
|
||||
test_suite.run()
|
||||
|
||||
|
||||
@@ -157,12 +158,12 @@ def parse_coverage(report_dir, coveragerc):
|
||||
report_dir.makedirs_p()
|
||||
|
||||
msg = colorize('green', "Combining coverage reports")
|
||||
print msg
|
||||
print(msg)
|
||||
|
||||
sh("coverage combine --rcfile={}".format(coveragerc))
|
||||
|
||||
msg = colorize('green', "Generating coverage reports")
|
||||
print msg
|
||||
print(msg)
|
||||
|
||||
sh("coverage html --rcfile={}".format(coveragerc))
|
||||
sh("coverage xml --rcfile={}".format(coveragerc))
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Internationalization tasks
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
import re
|
||||
import subprocess
|
||||
@@ -169,11 +170,11 @@ def i18n_rtl():
|
||||
"""
|
||||
sh("i18n_tool transifex rtl")
|
||||
|
||||
print "Now generating langugage files..."
|
||||
print("Now generating langugage files...")
|
||||
|
||||
sh("i18n_tool generate --rtl")
|
||||
|
||||
print "Committing translations..."
|
||||
print("Committing translations...")
|
||||
sh('git clean -fdX conf/locale')
|
||||
sh('git add conf/locale')
|
||||
sh('git commit --amend')
|
||||
@@ -187,11 +188,11 @@ def i18n_ltr():
|
||||
"""
|
||||
sh("i18n_tool transifex ltr")
|
||||
|
||||
print "Now generating langugage files..."
|
||||
print("Now generating langugage files...")
|
||||
|
||||
sh("i18n_tool generate --ltr")
|
||||
|
||||
print "Committing translations..."
|
||||
print("Committing translations...")
|
||||
sh('git clean -fdX conf/locale')
|
||||
sh('git add conf/locale')
|
||||
sh('git commit --amend')
|
||||
@@ -216,7 +217,7 @@ def i18n_robot_pull():
|
||||
# TODO: Validate the recently pulled translations, and give a bail option
|
||||
sh('git clean -fdX conf/locale/rtl')
|
||||
sh('git clean -fdX conf/locale/eo')
|
||||
print "\n\nValidating translations with `i18n_tool validate`..."
|
||||
print("\n\nValidating translations with `i18n_tool validate`...")
|
||||
sh("i18n_tool validate")
|
||||
|
||||
con = raw_input("Continue with committing these translations (y/n)? ")
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Tests for paver quality tasks
|
||||
"""
|
||||
from __future__ import print_function
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
@@ -319,7 +320,7 @@ class TestPaverRunQuality(PaverTestCase):
|
||||
with self.assertRaises(SystemExit):
|
||||
pavelib.quality.run_quality("")
|
||||
self.assertRaises(BuildFailure)
|
||||
print self._mock_paver_sh.mock_calls
|
||||
print(self._mock_paver_sh.mock_calls)
|
||||
|
||||
# Test that pylint is called
|
||||
_mock_pylint_violations.assert_called_once_with(clean=False)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Install Python and Node prerequisites.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
@@ -120,7 +121,7 @@ def prereq_cache(cache_name, paths, install_func):
|
||||
post_install_hash = compute_fingerprint(paths)
|
||||
cache_file.write(post_install_hash)
|
||||
else:
|
||||
print '{cache} unchanged, skipping...'.format(cache=cache_name)
|
||||
print('{cache} unchanged, skipping...'.format(cache=cache_name))
|
||||
|
||||
|
||||
def node_prereqs_installation():
|
||||
@@ -151,14 +152,14 @@ def node_prereqs_installation():
|
||||
proc.wait()
|
||||
except BuildFailure, error_text:
|
||||
if cb_error_text in error_text:
|
||||
print "npm install error detected. Retrying..."
|
||||
print("npm install error detected. Retrying...")
|
||||
proc = subprocess.Popen(npm_command, stderr=npm_log_file)
|
||||
proc.wait()
|
||||
else:
|
||||
raise BuildFailure(error_text)
|
||||
print "Successfully installed NPM packages. Log found at {}".format(
|
||||
print("Successfully installed NPM packages. Log found at {}".format(
|
||||
npm_log_file_path
|
||||
)
|
||||
))
|
||||
|
||||
|
||||
def python_prereqs_installation():
|
||||
@@ -182,7 +183,7 @@ def install_node_prereqs():
|
||||
Installs Node prerequisites
|
||||
"""
|
||||
if no_prereq_install():
|
||||
print NO_PREREQ_MESSAGE
|
||||
print(NO_PREREQ_MESSAGE)
|
||||
return
|
||||
|
||||
prereq_cache("Node prereqs", ["package.json"], node_prereqs_installation)
|
||||
@@ -213,7 +214,7 @@ def uninstall_python_packages():
|
||||
"""
|
||||
|
||||
if no_python_uninstall():
|
||||
print NO_PYTHON_UNINSTALL_MESSAGE
|
||||
print(NO_PYTHON_UNINSTALL_MESSAGE)
|
||||
return
|
||||
|
||||
# So that we don't constantly uninstall things, use a hash of the packages
|
||||
@@ -228,7 +229,7 @@ def uninstall_python_packages():
|
||||
with io.open(state_file_path) as state_file:
|
||||
version = state_file.read()
|
||||
if version == expected_version:
|
||||
print 'Python uninstalls unchanged, skipping...'
|
||||
print('Python uninstalls unchanged, skipping...')
|
||||
return
|
||||
|
||||
# Run pip to find the packages we need to get rid of. Believe it or not,
|
||||
@@ -247,7 +248,7 @@ def uninstall_python_packages():
|
||||
break
|
||||
else:
|
||||
# We tried three times and didn't manage to get rid of the pests.
|
||||
print "Couldn't uninstall unwanted Python packages!"
|
||||
print("Couldn't uninstall unwanted Python packages!")
|
||||
return
|
||||
|
||||
# Write our version.
|
||||
@@ -277,7 +278,7 @@ def package_in_frozen(package_name, frozen_output):
|
||||
def install_coverage_prereqs():
|
||||
""" Install python prereqs for measuring coverage. """
|
||||
if no_prereq_install():
|
||||
print NO_PREREQ_MESSAGE
|
||||
print(NO_PREREQ_MESSAGE)
|
||||
return
|
||||
pip_install_req_file(COVERAGE_REQ_FILE)
|
||||
|
||||
@@ -289,7 +290,7 @@ def install_python_prereqs():
|
||||
Installs Python prerequisites.
|
||||
"""
|
||||
if no_prereq_install():
|
||||
print NO_PREREQ_MESSAGE
|
||||
print(NO_PREREQ_MESSAGE)
|
||||
return
|
||||
|
||||
uninstall_python_packages()
|
||||
@@ -323,7 +324,7 @@ def install_prereqs():
|
||||
Installs Node and Python prerequisites
|
||||
"""
|
||||
if no_prereq_install():
|
||||
print NO_PREREQ_MESSAGE
|
||||
print(NO_PREREQ_MESSAGE)
|
||||
return
|
||||
|
||||
if not str2bool(os.environ.get('SKIP_NPM_INSTALL', 'False')):
|
||||
@@ -341,9 +342,9 @@ def log_installed_python_prereqs():
|
||||
|
||||
def print_devstack_warning():
|
||||
if Env.USING_DOCKER: # pragma: no cover
|
||||
print "********************************************************************************"
|
||||
print "* WARNING: Mac users should run this from both the lms and studio shells"
|
||||
print "* in docker devstack to avoid startup errors that kill your CPU."
|
||||
print "* For more details, see:"
|
||||
print "* https://github.com/edx/devstack#docker-is-using-lots-of-cpu-time-when-it-should-be-idle"
|
||||
print "********************************************************************************"
|
||||
print("********************************************************************************")
|
||||
print("* WARNING: Mac users should run this from both the lms and studio shells")
|
||||
print("* in docker devstack to avoid startup errors that kill your CPU.")
|
||||
print("* For more details, see:")
|
||||
print("* https://github.com/edx/devstack#docker-is-using-lots-of-cpu-time-when-it-should-be-idle")
|
||||
print("********************************************************************************")
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
"""
|
||||
Check code quality using pycodestyle, pylint, and diff_quality.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -109,7 +110,7 @@ def find_fixme(options):
|
||||
num_fixme += _count_pylint_violations(
|
||||
"{report_dir}/pylint_fixme.report".format(report_dir=report_dir))
|
||||
|
||||
print "Number of pylint fixmes: " + str(num_fixme)
|
||||
print("Number of pylint fixmes: " + str(num_fixme))
|
||||
|
||||
|
||||
def _get_pylint_violations(systems=ALL_SYSTEMS.split(','), errors_only=False, clean=True):
|
||||
@@ -177,7 +178,7 @@ def run_pylint(options):
|
||||
|
||||
# Print number of violations to log
|
||||
violations_count_str = "Number of pylint violations: " + str(num_violations)
|
||||
print violations_count_str
|
||||
print(violations_count_str)
|
||||
|
||||
# Also write the number of violations to a file
|
||||
with open(Env.METRICS_DIR / "pylint", "w") as f:
|
||||
@@ -294,8 +295,8 @@ def run_pep8(options): # pylint: disable=unused-argument
|
||||
|
||||
# Print number of violations to log
|
||||
violations_count_str = "Number of PEP 8 violations: {count}".format(count=count)
|
||||
print violations_count_str
|
||||
print violations_list
|
||||
print(violations_count_str)
|
||||
print(violations_list)
|
||||
|
||||
# Also write the number of violations to a file
|
||||
with open(Env.METRICS_DIR / "pep8", "w") as f:
|
||||
@@ -327,7 +328,7 @@ def run_complexity():
|
||||
Env.METRICS_DIR.makedirs_p()
|
||||
_prepare_report_dir(complexity_report_dir)
|
||||
|
||||
print "--> Calculating cyclomatic complexity of python files..."
|
||||
print("--> Calculating cyclomatic complexity of python files...")
|
||||
try:
|
||||
sh(
|
||||
"radon cc {system_string} --total-average > {complexity_report}".format(
|
||||
@@ -340,11 +341,11 @@ def run_complexity():
|
||||
complexity_metric,
|
||||
(Env.METRICS_DIR / "python_complexity")
|
||||
)
|
||||
print "--> Python cyclomatic complexity report complete."
|
||||
print "radon cyclomatic complexity score: {metric}".format(metric=str(complexity_metric))
|
||||
print("--> Python cyclomatic complexity report complete.")
|
||||
print("radon cyclomatic complexity score: {metric}".format(metric=str(complexity_metric)))
|
||||
|
||||
except BuildFailure:
|
||||
print "FAILURE: Unable to calculate python-only code-complexity."
|
||||
print("FAILURE: Unable to calculate python-only code-complexity.")
|
||||
|
||||
|
||||
@task
|
||||
@@ -820,7 +821,7 @@ def run_quality(options):
|
||||
_, upper_violations_limit, _, _ = _parse_pylint_options(options)
|
||||
|
||||
# Print total number of violations to log
|
||||
print _lint_output('pylint', count, violations_list, limit=upper_violations_limit)
|
||||
print(_lint_output('pylint', count, violations_list, limit=upper_violations_limit))
|
||||
if count > upper_violations_limit > -1:
|
||||
diff_quality_pass = False
|
||||
failure_reasons.append('Too many total violations.')
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Unit test tasks
|
||||
"""
|
||||
from __future__ import print_function
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
@@ -354,4 +355,4 @@ def diff_coverage(options):
|
||||
)
|
||||
)
|
||||
|
||||
print "\n"
|
||||
print("\n")
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Helper functions for bok_choy test tasks
|
||||
"""
|
||||
from __future__ import print_function
|
||||
import httplib
|
||||
import os
|
||||
import subprocess
|
||||
@@ -36,7 +37,7 @@ def start_servers(options):
|
||||
"""
|
||||
Starts a single server.
|
||||
"""
|
||||
print cmd, logfile
|
||||
print(cmd, logfile)
|
||||
run_background_process(cmd, out_log=logfile, err_log=logfile, cwd=cwd)
|
||||
|
||||
for service, info in Env.BOK_CHOY_SERVERS.iteritems():
|
||||
@@ -115,7 +116,7 @@ def wait_for_test_servers():
|
||||
"red",
|
||||
"Could not contact {} test server".format(service)
|
||||
)
|
||||
print msg
|
||||
print(msg)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
@@ -172,7 +173,7 @@ def check_mongo():
|
||||
"""
|
||||
if not is_mongo_running():
|
||||
msg = colorize('red', "Mongo is not running locally.")
|
||||
print msg
|
||||
print(msg)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
@@ -184,7 +185,7 @@ def check_memcache():
|
||||
"""
|
||||
if not is_memcache_running():
|
||||
msg = colorize('red', "Memcache is not running locally.")
|
||||
print msg
|
||||
print(msg)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
@@ -199,7 +200,7 @@ def check_mysql():
|
||||
return
|
||||
if not is_mysql_running():
|
||||
msg = colorize('red', "MySQL is not running locally.")
|
||||
print msg
|
||||
print(msg)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Class used for defining and running Bok Choy acceptance test suite
|
||||
"""
|
||||
from __future__ import print_function
|
||||
import os
|
||||
from time import sleep
|
||||
from textwrap import dedent
|
||||
@@ -45,7 +46,7 @@ def load_bok_choy_data(options):
|
||||
"""
|
||||
Loads data into database from db_fixtures
|
||||
"""
|
||||
print 'Loading data from json fixtures in db_fixtures directory'
|
||||
print('Loading data from json fixtures in db_fixtures directory')
|
||||
sh(
|
||||
"DEFAULT_STORE={default_store}"
|
||||
" ./manage.py lms --settings {settings} loaddata --traceback"
|
||||
@@ -73,7 +74,7 @@ def load_courses(options):
|
||||
"""
|
||||
if 'imports_dir' in options:
|
||||
msg = colorize('green', "Importing courses from {}...".format(options.imports_dir))
|
||||
print msg
|
||||
print(msg)
|
||||
|
||||
sh(
|
||||
"DEFAULT_STORE={default_store}"
|
||||
@@ -84,7 +85,7 @@ def load_courses(options):
|
||||
)
|
||||
)
|
||||
else:
|
||||
print colorize('blue', "--imports-dir not set, skipping import")
|
||||
print(colorize('blue', "--imports-dir not set, skipping import"))
|
||||
|
||||
|
||||
@task
|
||||
@@ -96,7 +97,7 @@ def update_fixtures():
|
||||
and Jenkins.
|
||||
"""
|
||||
msg = colorize('green', "Updating the Site fixture domains...")
|
||||
print msg
|
||||
print(msg)
|
||||
|
||||
sh(
|
||||
" ./manage.py lms --settings={settings} update_fixtures".format(
|
||||
@@ -114,11 +115,11 @@ def get_test_course(options):
|
||||
"""
|
||||
|
||||
if options.get('imports_dir'):
|
||||
print colorize("green", "--imports-dir specified, skipping fetch of test course")
|
||||
print(colorize("green", "--imports-dir specified, skipping fetch of test course"))
|
||||
return
|
||||
|
||||
if not options.get('should_fetch_course', False):
|
||||
print colorize("green", "--skip-fetch specified, skipping fetch of test course")
|
||||
print(colorize("green", "--skip-fetch specified, skipping fetch of test course"))
|
||||
return
|
||||
|
||||
# Set the imports_dir for use by other tasks
|
||||
@@ -128,7 +129,7 @@ def get_test_course(options):
|
||||
zipped_course = options.imports_dir + 'demo_course.tar.gz'
|
||||
|
||||
msg = colorize('green', "Fetching the test course from github...")
|
||||
print msg
|
||||
print(msg)
|
||||
|
||||
sh(
|
||||
'wget {tar_gz_file} -O {zipped_course}'.format(
|
||||
@@ -138,7 +139,7 @@ def get_test_course(options):
|
||||
)
|
||||
|
||||
msg = colorize('green', "Uncompressing the test course...")
|
||||
print msg
|
||||
print(msg)
|
||||
|
||||
sh(
|
||||
'tar zxf {zipped_course} -C {courses_dir}'.format(
|
||||
@@ -171,7 +172,7 @@ def prepare_bokchoy_run(options):
|
||||
"""
|
||||
if not options.get('fasttest', False):
|
||||
|
||||
print colorize('green', "Generating optimized static assets...")
|
||||
print(colorize('green', "Generating optimized static assets..."))
|
||||
if options.get('log_dir') is None:
|
||||
call_task('update_assets', args=['--settings', 'test_static_optimized'])
|
||||
else:
|
||||
@@ -182,7 +183,7 @@ def prepare_bokchoy_run(options):
|
||||
|
||||
# Ensure the test servers are available
|
||||
msg = colorize('green', "Confirming servers are running...")
|
||||
print msg
|
||||
print(msg)
|
||||
start_servers() # pylint: disable=no-value-for-parameter
|
||||
|
||||
|
||||
@@ -246,7 +247,7 @@ class BokChoyTestSuite(TestSuite):
|
||||
test_utils.clean_test_files()
|
||||
|
||||
msg = colorize('green', "Checking for mongo, memchache, and mysql...")
|
||||
print msg
|
||||
print(msg)
|
||||
check_services()
|
||||
|
||||
if not self.testsonly:
|
||||
@@ -257,7 +258,7 @@ class BokChoyTestSuite(TestSuite):
|
||||
update_fixtures()
|
||||
|
||||
msg = colorize('green', "Confirming servers have started...")
|
||||
print msg
|
||||
print(msg)
|
||||
wait_for_test_servers()
|
||||
try:
|
||||
# Create course in order to seed forum data underneath. This is
|
||||
@@ -267,7 +268,7 @@ class BokChoyTestSuite(TestSuite):
|
||||
"Installing course fixture for forums",
|
||||
CourseFixture('foobar_org', '1117', 'seed_forum', 'seed_foo').install
|
||||
)
|
||||
print 'Forums permissions/roles data has been seeded'
|
||||
print('Forums permissions/roles data has been seeded')
|
||||
except FixtureError:
|
||||
# this means it's already been done
|
||||
pass
|
||||
@@ -281,11 +282,11 @@ class BokChoyTestSuite(TestSuite):
|
||||
# Using testsonly will leave all fixtures in place (Note: the db will also be dirtier.)
|
||||
if self.testsonly:
|
||||
msg = colorize('green', 'Running in testsonly mode... SKIPPING database cleanup.')
|
||||
print msg
|
||||
print(msg)
|
||||
else:
|
||||
# Clean up data we created in the databases
|
||||
msg = colorize('green', "Cleaning up databases...")
|
||||
print msg
|
||||
print(msg)
|
||||
sh("./manage.py lms --settings {settings} flush --traceback --noinput".format(settings=Env.SETTINGS))
|
||||
clear_mongo()
|
||||
|
||||
@@ -315,14 +316,14 @@ class BokChoyTestSuite(TestSuite):
|
||||
"""
|
||||
Infinite loop. Servers will continue to run in the current session unless interrupted.
|
||||
"""
|
||||
print 'Bok-choy servers running. Press Ctrl-C to exit...\n'
|
||||
print 'Note: pressing Ctrl-C multiple times can corrupt system state. Just press it once.\n'
|
||||
print('Bok-choy servers running. Press Ctrl-C to exit...\n')
|
||||
print('Note: pressing Ctrl-C multiple times can corrupt system state. Just press it once.\n')
|
||||
|
||||
while True:
|
||||
try:
|
||||
sleep(10000)
|
||||
except KeyboardInterrupt:
|
||||
print "Stopping bok-choy servers.\n"
|
||||
print("Stopping bok-choy servers.\n")
|
||||
break
|
||||
|
||||
@property
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
A class used for defining and running test suites
|
||||
"""
|
||||
from __future__ import print_function
|
||||
import sys
|
||||
import subprocess
|
||||
|
||||
@@ -38,7 +39,7 @@ class TestSuite(object):
|
||||
|
||||
i.e. Checking for and defining required directories.
|
||||
"""
|
||||
print "\nSetting up for {suite_name}".format(suite_name=self.root)
|
||||
print("\nSetting up for {suite_name}".format(suite_name=self.root))
|
||||
self.failed_suites = []
|
||||
|
||||
def __exit__(self, exc_type, exc_value, traceback):
|
||||
@@ -51,7 +52,7 @@ class TestSuite(object):
|
||||
|
||||
i.e. Cleaning mongo after the lms tests run.
|
||||
"""
|
||||
print "\nCleaning up after {suite_name}".format(suite_name=self.root)
|
||||
print("\nCleaning up after {suite_name}".format(suite_name=self.root))
|
||||
|
||||
@property
|
||||
def cmd(self):
|
||||
@@ -127,7 +128,7 @@ class TestSuite(object):
|
||||
else:
|
||||
msg = colorize('green', "\n\n{bar}\nNo test failures ".format(bar="=" * 48))
|
||||
|
||||
print msg
|
||||
print(msg)
|
||||
|
||||
def run(self):
|
||||
"""
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Helper functions for test tasks
|
||||
"""
|
||||
from __future__ import print_function
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
@@ -68,7 +69,7 @@ def clean_reports_dir(options):
|
||||
Clean coverage files, to ensure that we don't use stale data to generate reports.
|
||||
"""
|
||||
if getattr(options, 'skip_clean', False):
|
||||
print '--skip-clean is set, skipping...'
|
||||
print('--skip-clean is set, skipping...')
|
||||
return
|
||||
|
||||
# We delete the files but preserve the directory structure
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from __future__ import print_function
|
||||
import json
|
||||
import sys
|
||||
import traceback
|
||||
@@ -14,12 +15,12 @@ else:
|
||||
|
||||
|
||||
def display(message):
|
||||
print '{} - {}'.format(date_string(message['time']), message['event_type'])
|
||||
print('{} - {}'.format(date_string(message['time']), message['event_type']))
|
||||
if message.get('event'):
|
||||
event = json.loads(message['event'])
|
||||
for k in sorted(event):
|
||||
print '\t{}: {}'.format(k, event[k])
|
||||
print
|
||||
print('\t{}: {}'.format(k, event[k]))
|
||||
print()
|
||||
|
||||
while 1:
|
||||
line = sys.stdin.readline()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from __future__ import print_function
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
@@ -104,7 +105,7 @@ def _get_course_data_summary(auth_token, months_restriction, xblock_type_set, ap
|
||||
# print to update the screen for status
|
||||
sys.stdout.write('.')
|
||||
sys.stdout.flush()
|
||||
print 'Processed %d courses' % total_courses
|
||||
print('Processed %d courses' % total_courses)
|
||||
return course_summary_data
|
||||
|
||||
|
||||
@@ -159,15 +160,15 @@ def _get_block_types_from_json_file(xblock_json_file):
|
||||
set: A set of strings for all the types that are available in the configuration file
|
||||
"""
|
||||
if not os.path.isfile(xblock_json_file):
|
||||
print 'xBlock configuration file does not exist: %s' % xblock_json_file
|
||||
print('xBlock configuration file does not exist: %s' % xblock_json_file)
|
||||
sys.exit(2)
|
||||
with open(xblock_json_file, 'r') as json_file:
|
||||
type_set = set()
|
||||
try:
|
||||
json_data = json.loads(json_file.read())
|
||||
except ValueError as e:
|
||||
print 'xBlock configuration file does not match the expected layout and is ' \
|
||||
'missing "data" list: %s' % xblock_json_file
|
||||
print('xBlock configuration file does not match the expected layout and is ' \
|
||||
'missing "data" list: %s' % xblock_json_file)
|
||||
sys.exit(text_type(e))
|
||||
if 'data' in json_data:
|
||||
xblock_type_list = json_data['data']
|
||||
@@ -175,8 +176,8 @@ def _get_block_types_from_json_file(xblock_json_file):
|
||||
type_set.add(xblock['name'])
|
||||
return type_set
|
||||
else:
|
||||
print 'xBlock configuration file does not match the expected layout and is ' \
|
||||
'missing "data" list: %s' % xblock_json_file
|
||||
print('xBlock configuration file does not match the expected layout and is ' \
|
||||
'missing "data" list: %s' % xblock_json_file)
|
||||
sys.exit(2)
|
||||
|
||||
|
||||
@@ -374,7 +375,7 @@ if __name__ == "__main__":
|
||||
# Get User access token
|
||||
token = get_access_token(username, password, oauth2_client_id, api_root)
|
||||
if token is None:
|
||||
print 'Failed to retrieve user token for user: %s ' % username
|
||||
print('Failed to retrieve user token for user: %s ' % username)
|
||||
sys.exit(2)
|
||||
|
||||
# Collect course data and write CSV reports
|
||||
@@ -384,4 +385,4 @@ if __name__ == "__main__":
|
||||
if len(course_data) > 0:
|
||||
write_block_summary_report(course_data)
|
||||
write_course_block_detail_report(course_data)
|
||||
print 'Start time: %s Total run time: %s' % (str(start_time), str(datetime.now() - start_time))
|
||||
print('Start time: %s Total run time: %s' % (str(start_time), str(datetime.now() - start_time)))
|
||||
|
||||
Reference in New Issue
Block a user