code
stringlengths
1
1.72M
language
stringclasses
1 value
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for the Dashboard module.""" __author__ = 'Michael Gainer (mgainer@google.com)' import unittest from modules.dashboard import tabs class TabTests(unittest.TestCase): def tearDown(self): tabs.Registry._tabs_by_group.clear() super(TabTests, self).tearDown() def _assert_name_order(self, expected): actual = [t.name for t in tabs.Registry.get_tab_group('group')] self.assertEquals(expected, actual) def test_ordering_unordered_sort_stable(self): tabs.Registry.register('group', 'a', 'A') tabs.Registry.register('group', 'b', 'B') tabs.Registry.register('group', 'c', 'C') tabs.Registry.register('group', 'd', 'D') self._assert_name_order(['a', 'b', 'c', 'd']) def test_force_first(self): tabs.Registry.register('group', 'a', 'A') tabs.Registry.register('group', 'b', 'B') tabs.Registry.register('group', 'c', 'C') tabs.Registry.register('group', 'd', 'D') tabs.Registry.register( 'group', 'e', 'E', placement=tabs.Placement.BEGINNING) self._assert_name_order(['e', 'a', 'b', 'c', 'd']) def test_force_last(self): tabs.Registry.register( 'group', 'e', 'E', placement=tabs.Placement.END) tabs.Registry.register('group', 'a', 'A') tabs.Registry.register('group', 'b', 'B') tabs.Registry.register('group', 'c', 'C') tabs.Registry.register('group', 'd', 'D') self._assert_name_order(['a', 'b', 'c', 'd', 'e']) def test_force_multiple_first(self): tabs.Registry.register( 'group', 'a', 'A', placement=tabs.Placement.BEGINNING) tabs.Registry.register('group', 'b', 'B') tabs.Registry.register('group', 'c', 'C') tabs.Registry.register('group', 'd', 'D') tabs.Registry.register( 'group', 'e', 'E', placement=tabs.Placement.BEGINNING) self._assert_name_order(['a', 'e', 'b', 'c', 'd']) def test_force_multiple_last(self): tabs.Registry.register( 'group', 'a', 'A', placement=tabs.Placement.END) tabs.Registry.register('group', 'b', 'B') tabs.Registry.register('group', 'c', 'C') tabs.Registry.register('group', 'd', 'D') tabs.Registry.register( 'group', 'e', 'E', placement=tabs.Placement.END) self._assert_name_order(['b', 'c', 'd', 'a', 'e']) def test_complex(self): tabs.Registry.register( 'group', 'a', 'A', placement=tabs.Placement.END) tabs.Registry.register( 'group', 'b', 'B', placement=tabs.Placement.MIDDLE) tabs.Registry.register( 'group', 'c', 'C', placement=tabs.Placement.BEGINNING) tabs.Registry.register( 'group', 'd', 'D', placement=tabs.Placement.MIDDLE) tabs.Registry.register( 'group', 'e', 'E', placement=tabs.Placement.BEGINNING) self._assert_name_order(['c', 'e', 'b', 'd', 'a'])
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for common.tags.""" __author__ = 'Mike Gainer (mgainer@google.com)' import datetime import os import unittest import appengine_config from common import utils class CommonUnitTests(unittest.TestCase): # --------------------------- String-to-list. def test_list_parsing(self): self.assertListEqual(['foo'], utils.text_to_list('foo')) self.assertListEqual(['foo'], utils.text_to_list(' foo')) self.assertListEqual(['foo'], utils.text_to_list('foo ')) self.assertListEqual(['foo'], utils.text_to_list(' foo ')) self.assertListEqual(['foo'], utils.text_to_list('foo\t')) self.assertListEqual(['foo'], utils.text_to_list('\tfoo')) self.assertListEqual(['foo'], utils.text_to_list('\tfoo\t')) self.assertListEqual(['foo'], utils.text_to_list('foo ')) self.assertListEqual(['foo'], utils.text_to_list(' foo')) self.assertListEqual(['foo'], utils.text_to_list(' foo ')) self.assertListEqual(['foo'], utils.text_to_list('foo\n')) self.assertListEqual(['foo'], utils.text_to_list('\nfoo')) self.assertListEqual(['foo'], utils.text_to_list('\nfoo\n')) self.assertListEqual(['foo'], utils.text_to_list('foo,')) self.assertListEqual(['foo'], utils.text_to_list(',foo')) self.assertListEqual(['foo'], utils.text_to_list(',foo,')) self.assertListEqual(['foo'], utils.text_to_list(' foo ,\n')) self.assertListEqual(['foo'], utils.text_to_list('\tfoo,\t\n')) self.assertListEqual(['foo'], utils.text_to_list(',foo,\n')) self.assertListEqual(['foo'], utils.text_to_list( '[foo]', utils.BACKWARD_COMPATIBLE_SPLITTER)) self.assertListEqual(['foo'], utils.text_to_list( '[foo],', utils.BACKWARD_COMPATIBLE_SPLITTER)) self.assertListEqual(['foo'], utils.text_to_list( '[foo], ', utils.BACKWARD_COMPATIBLE_SPLITTER)) self.assertListEqual(['foo'], utils.text_to_list( '[foo],\n', utils.BACKWARD_COMPATIBLE_SPLITTER)) self.assertListEqual(['foo'], utils.text_to_list( '[foo], \n', utils.BACKWARD_COMPATIBLE_SPLITTER)) self.assertListEqual(['foo', 'bar'], utils.text_to_list('foo bar')) self.assertListEqual(['foo', 'bar'], utils.text_to_list(' foo bar')) self.assertListEqual(['foo', 'bar'], utils.text_to_list('foo bar ')) self.assertListEqual(['foo', 'bar'], utils.text_to_list('foo\tbar')) self.assertListEqual(['foo', 'bar'], utils.text_to_list('\tfoo\tbar')) self.assertListEqual(['foo', 'bar'], utils.text_to_list('foo\tbar\t')) self.assertListEqual(['foo', 'bar'], utils.text_to_list('foo\nbar\n')) self.assertListEqual(['foo', 'bar'], utils.text_to_list('\nfoo\nbar\n')) self.assertListEqual(['foo', 'bar'], utils.text_to_list('\n foo\n bar\n')) self.assertListEqual(['foo', 'bar'], utils.text_to_list(' \n foo \n bar \n')) self.assertListEqual(['foo', 'bar'], utils.text_to_list( '[foo][bar]', utils.BACKWARD_COMPATIBLE_SPLITTER)) self.assertListEqual(['foo', 'bar'], utils.text_to_list( ' [foo] [bar] ', utils.BACKWARD_COMPATIBLE_SPLITTER)) self.assertListEqual(['foo', 'bar'], utils.text_to_list( '\n[foo]\n[bar]\n', utils.BACKWARD_COMPATIBLE_SPLITTER)) self.assertListEqual(['foo', 'bar'], utils.text_to_list( '\n,[foo],\n[bar],\n', utils.BACKWARD_COMPATIBLE_SPLITTER)) def test_none_split(self): self.assertListEqual([], utils.text_to_list(None)) def test_empty_split(self): self.assertListEqual([], utils.text_to_list('')) def test_all_separators_split(self): self.assertListEqual([], utils.text_to_list(' ,,, \t\t\n\t ')) def test_one_item_split(self): self.assertListEqual(['x'], utils.text_to_list('x')) def test_join_none(self): self.assertEquals('', utils.list_to_text(None)) def test_join_empty(self): self.assertEquals('', utils.list_to_text([])) def test_join_one(self): self.assertEquals('x', utils.list_to_text(['x'])) def test_join_two(self): self.assertEquals('x y', utils.list_to_text(['x', 'y'])) def test_join_split(self): l = ['a', 'b', 'c'] self.assertListEqual(l, utils.text_to_list(utils.list_to_text(l))) def test_split_join(self): text = 'a b c' self.assertEquals(text, utils.list_to_text(utils.text_to_list(text))) class ZipAwareOpenTests(unittest.TestCase): def test_find_in_lib_without_relative_path(self): path = os.path.join( appengine_config.BUNDLE_ROOT, 'lib', 'babel-0.9.6.zip', 'babel', 'localedata', 'root.dat') with self.assertRaises(IOError): open(path) # This fails. with utils.ZipAwareOpen(): data = open(path).read() self.assertEquals(17490, len(data)) data = open(path, 'r').read() self.assertEquals(17490, len(data)) data = open(path, mode='r').read() self.assertEquals(17490, len(data)) data = open(name=path, mode='r').read() self.assertEquals(17490, len(data)) data = open(name=path).read() self.assertEquals(17490, len(data)) with self.assertRaises(IOError): open(path) # This fails again; open has been reset to normal. def test_find_in_lib_with_relative_path(self): path = os.path.join( appengine_config.BUNDLE_ROOT, 'lib', 'markdown-2.5.zip', 'setup.cfg') with self.assertRaises(IOError): open(path) # This fails. with utils.ZipAwareOpen(): data = open(path).read() self.assertEquals(12, len(data)) class ParseTimedeltaTests(unittest.TestCase): def test_parse_empty_string(self): self.assertEquals( utils.parse_timedelta_string(''), datetime.timedelta()) def test_parse_zero(self): self.assertEquals( utils.parse_timedelta_string('0'), datetime.timedelta()) def test_parse_gibberish(self): self.assertEquals( utils.parse_timedelta_string('Amidst the mists and coldest frosts'), datetime.timedelta()) def test_parse_leading_valid_partial_gibberish(self): self.assertEquals( utils.parse_timedelta_string( '5 days and a partridge in a pear tree'), datetime.timedelta(days=5)) def test_parse_trailing_valid_partial_gibberish(self): self.assertEquals( utils.parse_timedelta_string('we will leave in 5 days'), datetime.timedelta(days=0)) def test_parse_units(self): for unit in ('week', 'day', 'hour', 'minute', 'second'): self._test_parse_units(unit) def _test_parse_units(self, unit): expected1 = datetime.timedelta(**{unit + 's': 1}) expected2 = datetime.timedelta(**{unit + 's': 2}) self.assertEquals( utils.parse_timedelta_string('1%s' % unit[0]), expected1) self.assertEquals( utils.parse_timedelta_string('1%s' % unit), expected1) self.assertEquals( utils.parse_timedelta_string('2%ss' % unit), expected2) self.assertEquals( utils.parse_timedelta_string('2 %s' % unit[0]), expected2) self.assertEquals( utils.parse_timedelta_string('1 %s' % unit), expected1) self.assertEquals( utils.parse_timedelta_string('2 %s' % unit), expected2) self.assertEquals( utils.parse_timedelta_string('2 \t\t\n %ss' % unit), expected2) def test_parse_out_of_bounds_handled_successfully(self): self.assertEquals( utils.parse_timedelta_string('86400s'), datetime.timedelta(days=1)) self.assertEquals( utils.parse_timedelta_string('19d, 86400s'), datetime.timedelta(weeks=2, days=6)) def test_parse_combinations(self): self.assertEquals( utils.parse_timedelta_string('3w1d3m'), datetime.timedelta(weeks=3, days=1, minutes=3)) self.assertEquals( utils.parse_timedelta_string('3w, 1d, 3m'), datetime.timedelta(weeks=3, days=1, minutes=3)) self.assertEquals( utils.parse_timedelta_string('3 w 1 d 3 m'), datetime.timedelta(weeks=3, days=1, minutes=3)) self.assertEquals( utils.parse_timedelta_string('3 weeks 1 day 3 minutes'), datetime.timedelta(weeks=3, days=1, minutes=3)) self.assertEquals( utils.parse_timedelta_string('3 weeks, 1 day, 3 minutes'), datetime.timedelta(weeks=3, days=1, minutes=3))
Python
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for common/schema_fields.py.""" __author__ = 'John Orr (jorr@google.com)' import json import unittest from common import schema_fields def remove_whitespace(s): return ''.join(s.split()) class BaseFieldTests(unittest.TestCase): """Base class for the tests on a schema field.""" def assert_json_schema_value(self, expected, field): self.assertEquals( remove_whitespace(expected), remove_whitespace(json.dumps(field.get_json_schema_dict()))) def assert_schema_dict_value(self, expected, field): self.assertEquals( remove_whitespace(expected), remove_whitespace(json.dumps(field._get_schema_dict([])))) class SchemaFieldTests(BaseFieldTests): """Unit tests for common.schema_fields.SchemaField.""" def test_simple_field(self): field = schema_fields.SchemaField('aName', 'aLabel', 'aType') expected = '{"type":"aType"}' self.assert_json_schema_value(expected, field) expected = '[[["_inputex"], {"label": "aLabel"}]]' self.assert_schema_dict_value(expected, field) self.assertEquals('aName', field.name) def test_extra_schema_dict(self): field = schema_fields.SchemaField( 'aName', 'aLabel', 'aType', extra_schema_dict_values={'a': 'A', 'b': 'B'}) expected = '[[["_inputex"], {"a": "A", "b": "B", "label": "aLabel"}]]' self.assert_schema_dict_value(expected, field) def test_uneditable_field(self): field = schema_fields.SchemaField( 'aName', 'aLabel', 'aType', editable=False) expected = '{"type":"aType"}' self.assert_json_schema_value(expected, field) expected = ('[[["_inputex"], {"_type": "uneditable", ' '"label": "aLabel"}]]') self.assert_schema_dict_value(expected, field) self.assertEquals('aName', field.name) def test_hidden_field(self): field = schema_fields.SchemaField('aName', 'aLabel', 'aType', hidden=True) expected = '{"type":"aType"}' self.assert_json_schema_value(expected, field) expected = '[[["_inputex"], {"_type": "hidden", "label": "aLabel"}]]' self.assert_schema_dict_value(expected, field) self.assertEquals('aName', field.name) class FieldArrayTests(BaseFieldTests): """Unit tests for common.schema_fields.FieldArray.""" def test_field_array_with_simple_members(self): array = schema_fields.FieldArray( 'aName', 'aLabel', item_type=schema_fields.SchemaField( 'unusedName', 'field_label', 'aType')) expected = """ { "items": {"type": "aType"}, "type": "array" }""" self.assert_json_schema_value(expected, array) expected = """ [ [["_inputex"],{"label":"aLabel"}], [["items","_inputex"],{"label":"field_label"}] ] """ self.assert_schema_dict_value(expected, array) def test_field_array_with_object_members(self): object_type = schema_fields.FieldRegistry('object_title') object_type.add_property(schema_fields.SchemaField( 'prop_name', 'prop_label', 'prop_type')) field = schema_fields.FieldArray( 'aName', 'aLabel', item_type=object_type) expected = """ { "items": { "type": "object", "id": "object_title", "properties": { "prop_name": {"type":"prop_type"} } }, "type":"array"} """ self.assert_json_schema_value(expected, field) expected = """ [ [["_inputex"],{"label":"aLabel"}], [["items","title"],"object_title"], [["items","properties","prop_name","_inputex"],{"label":"prop_label"}] ] """ self.assert_schema_dict_value(expected, field) def test_extra_schema_dict(self): array = schema_fields.FieldArray( 'aName', 'aLabel', item_type=schema_fields.SchemaField( 'unusedName', 'field_label', 'aType'), extra_schema_dict_values={'a': 'A', 'b': 'B'}) expected = """ [ [["_inputex"],{"a":"A","b":"B","label":"aLabel"}], [["items","_inputex"],{"label":"field_label"}]] """ self.assert_schema_dict_value(expected, array) class FieldRegistryTests(BaseFieldTests): """Unit tests for common.schema_fields.FieldRegistry.""" def test_single_property(self): reg = schema_fields.FieldRegistry( 'registry_name', 'registry_description') reg.add_property(schema_fields.SchemaField( 'field_name', 'field_label', 'property_type', description='property_description')) expected = """ { "properties": { "field_name": { "type": "property_type", "description": "property_description" } }, "type": "object", "id": "registry_name", "description": "registry_description" }""" self.assert_json_schema_value(expected, reg) expected = """ [ [["title"], "registry_name"], [["properties","field_name","_inputex"], { "description": "property_description", "label":"field_label" }] ] """ self.assert_schema_dict_value(expected, reg) def test_single_property_with_select_data(self): reg = schema_fields.FieldRegistry( 'registry_name', 'registry_description') reg.add_property(schema_fields.SchemaField( 'field_name', 'field_label', 'string', select_data=[('a', 'A'), ('b', 'B')])) expected = """ { "properties": { "field_name": { "type": "string" } }, "type": "object", "id": "registry_name", "description": "registry_description" }""" self.assert_json_schema_value(expected, reg) expected = """ [ [["title"],"registry_name"], [["properties","field_name","_inputex"],{ "_type": "select", "choices":[ {"value": "a", "label": "A"}, {"value": "b","label": "B"}], "label":"field_label" }] ] """ self.assert_schema_dict_value(expected, reg) def test_select_data_values_retain_boolean_and_numeric_type_in_json(self): reg = schema_fields.FieldRegistry( 'registry_name', 'registry_description') reg.add_property(schema_fields.SchemaField( 'field_name', 'field_label', 'string', select_data=[(True, 'A'), (12, 'B'), ('c', 'C')])) expected = """ [ [["title"],"registry_name"], [["properties","field_name","_inputex"],{ "_type": "select", "choices":[ {"value": true, "label": "A"}, {"value": 12,"label": "B"}, {"value": "c","label": "C"}], "label":"field_label" }] ] """ self.assert_schema_dict_value(expected, reg) def test_object_with_array_property(self): reg = schema_fields.FieldRegistry( 'registry_name', 'registry_description') reg.add_property(schema_fields.SchemaField( 'field_name', 'field_label', 'field_type', description='field_description')) reg.add_property(schema_fields.FieldArray( 'array_name', 'array_label', item_type=schema_fields.SchemaField( 'unusedName', 'unusedLabel', 'aType'))) expected = """ { "properties": { "field_name": { "type": "field_type", "description": "field_description" }, "array_name": { "items": {"type": "aType"}, "type":"array" } }, "type": "object", "id": "registry_name", "description": "registry_description" } """ self.assert_json_schema_value(expected, reg) def test_extra_schema_dict(self): reg = schema_fields.FieldRegistry( 'aName', 'aLabel', extra_schema_dict_values={'a': 'A', 'b': 'B'}) expected = """ [ [["title"], "aName"], [["_inputex"], {"a": "A", "b": "B"}]] """ self.assert_schema_dict_value(expected, reg) def test_mc_question_schema(self): """The multiple choice question schema is a good end-to-end example.""" mc_question = schema_fields.FieldRegistry( 'MC Question', extra_schema_dict_values={'className': 'mc-question'}) mc_question.add_property( schema_fields.SchemaField('question', 'Question', 'string')) choice_type = schema_fields.FieldRegistry( 'choice', extra_schema_dict_values={'className': 'mc-choice'}) choice_type.add_property( schema_fields.SchemaField('text', 'Text', 'string')) choice_type.add_property( schema_fields.SchemaField('score', 'Score', 'string')) choice_type.add_property( schema_fields.SchemaField('feedback', 'Feedback', 'string')) choices_array = schema_fields.FieldArray( 'choices', 'Choices', item_type=choice_type) mc_question.add_property(choices_array) expected = """ { "type":"object", "id":"MCQuestion", "properties":{ "question":{"type":"string"}, "choices":{ "items":{ "type":"object", "id":"choice", "properties":{ "text":{"type":"string"}, "score":{"type":"string"}, "feedback":{"type":"string"} } }, "type":"array" } } } """ self.assert_json_schema_value(expected, mc_question) expected = """ [ [["title"],"MCQuestion"], [["_inputex"],{"className":"mc-question"}], [["properties","question","_inputex"],{"label":"Question"}], [["properties","choices","_inputex"],{"label":"Choices"}], [["properties","choices","items","title"],"choice"], [["properties","choices","items","_inputex"],{"className":"mc-choice"}], [["properties","choices","items","properties","text","_inputex"],{ "label":"Text" }], [["properties","choices","items","properties","score","_inputex"],{ "label":"Score" }], [["properties","choices","items","properties","feedback","_inputex"],{ "label":"Feedback" }] ] """ self.assert_schema_dict_value(expected, mc_question) def test_validate(self): def fail(value, errors): errors.append(value) registry = schema_fields.FieldRegistry('Test Registry') registry.add_property(schema_fields.SchemaField( 'top_level_bad', 'Top Level Bad Item', 'string', optional=True, validator=fail)) registry.add_property(schema_fields.SchemaField( 'top_level_good', 'Top Level Good Item', 'string', optional=True)) sub_registry = registry.add_sub_registry('child', 'Child Registry') sub_registry.add_property(schema_fields.SchemaField( 'child:bad', 'Top Level Bad Item', 'string', optional=True, validator=fail)) sub_registry.add_property(schema_fields.SchemaField( 'child:good', 'Top Level Good Item', 'string', optional=True)) child_bad_value = 'child_bad_value' top_level_bad_value = 'top_level_bad_value' errors = [] payload = { 'top_level_bad': top_level_bad_value, 'top_level_good': 'top_level_good_value', 'child': { 'bad': child_bad_value, 'good': 'child_good_value', } } registry.validate(payload, errors) self.assertEqual([top_level_bad_value, child_bad_value], errors)
Python
"""Unit tests for the javascript code.""" __author__ = 'John Orr (jorr@google.com)' import os import subprocess import unittest import appengine_config class AllJavaScriptTests(unittest.TestCase): def karma_test(self, test_folder): karma_conf = os.path.join( appengine_config.BUNDLE_ROOT, 'tests', 'unit', 'javascript_tests', test_folder, 'karma.conf.js') self.assertEqual(0, subprocess.call(['karma', 'start', karma_conf])) def test_activity_generic(self): self.karma_test('assets_lib_activity_generic') def test_assessment_tags(self): self.karma_test('modules_assessment_tags') def test_butterbar(self): self.karma_test('assets_lib_butterbar') def test_certificate(self): self.karma_test('modules_certificate') def test_core_tags(self): self.karma_test('modules_core_tags') def test_dashboard(self): self.karma_test('modules_dashboard') def test_oeditor(self): self.karma_test('modules_oeditor') def test_questionnaire(self): self.karma_test('modules_questionnaire') def test_skill_map(self): self.karma_test(os.path.join('modules_skill_map', 'lesson_editor')) self.karma_test( os.path.join('modules_skill_map', 'student_skill_widget'))
Python
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for common/locale.py.""" __author__ = 'Mike Gainer (mgainer@google.com)' import unittest from common import resource from models import courses from models import resources_display from tools import verify class ResourceKeyTests(unittest.TestCase): def setUp(self): super(ResourceKeyTests, self).setUp() resource.Registry.register(resources_display.ResourceAssessment) resource.Registry.register(resources_display.ResourceLink) resource.Registry.register(resources_display.ResourceUnit) def tearDown(self): resource.Registry._RESOURCE_HANDLERS.clear() def test_roundtrip_data(self): key1 = resource.Key(resources_display.ResourceAssessment.TYPE, '23') key2 = resource.Key.fromstring(str(key1)) self.assertEquals(key1.type, key2.type) self.assertEquals(key1.key, key2.key) def test_reject_bad_type(self): with self.assertRaises(AssertionError): resource.Key('BAD_TYPE', '23') with self.assertRaises(AssertionError): resource.Key.fromstring('BAD_TYPE:23') def test_for_unit(self): type_table = [ (verify.UNIT_TYPE_ASSESSMENT, resources_display.ResourceAssessment.TYPE), (verify.UNIT_TYPE_LINK, resources_display.ResourceLink.TYPE), (verify.UNIT_TYPE_UNIT, resources_display.ResourceUnit.TYPE)] for unit_type, key_type in type_table: unit = courses.Unit13() unit.type = unit_type unit.unit_id = 5 key = resources_display.ResourceUnitBase.key_for_unit(unit) self.assertEquals(key_type, key.type) self.assertEquals(5, key.key)
Python
# coding: utf-8 # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Runs all unit tests for GIFT.""" __author__ = 'Boris Roussev (borislavr@google.com)' import os import unittest from pyparsing import ParseException from modules.assessment_tags import gift class SampleQuestionsTest(unittest.TestCase): """Tests a large bank of GIFT questions. Moodle version: 2.7.2+ https://github.com/moodle/moodle/blob/master/question/format/gift/ """ def test_sample_questions(self): questions = self._get_sample_questions() self.assertEqual(28, len(questions)) for question in questions: result = gift.GiftParser.parse(question)[0] question = gift.to_dict(result) assert 'question' in question def _get_sample_questions(self): curr_dir = os.path.dirname(os.path.realpath(__file__)) fn = 'gift_examples.txt' path = os.path.join(curr_dir, fn) return open(path, 'rb').read().split('\n\n') class TestEssayAndNumericQuestion(unittest.TestCase): """Tests for parsing Essay and Numeric questions.""" def test_essay_answer(self): answer = '{}' result = gift.GiftParser.essay_answer.parseString(answer) assert not result def test_essay_question(self): task = 'Write a short biography of Dag Hammarskjold.' text = '%s {}' % task result = gift.GiftParser.essay_question.parseString(text)[0] question = gift.to_dict(result[1]) self.assertEqual(task, question['task']) def test_numeric_single_answer(self): result = gift.GiftParser.numeric_answer.parseString('{#1.5:0.1}') self.assertEqual(1.5, result.answer) self.assertEqual(0.1, result.error) result = gift.GiftParser.numeric_answer.parseString('{#-25:2}') self.assertEqual(-25, result.answer) self.assertEqual(2, result.error) def test_numeric_range_answer(self): # test for question w.o. error margin result = gift.GiftParser.numeric_answer.parseString('{#2}') self.assertEqual(2, result.answer) # test range question s = 'What is the value of pi (to 3 decimal places)? {#3.141..3.142}.' result = gift.GiftParser.numeric_question.parseString(s)[0] question = gift.to_dict(result[1]) self.assertEqual(3.141, question['choices'][0]['min']) self.assertEqual(3.142, question['choices'][0]['max']) class TestMatchQuestion(unittest.TestCase): """Tests for parsing Match questions.""" def test_answers(self): result = gift.GiftParser.match_answers.parseString( '{=a->1 = b->2 =c->3}') answers = gift.to_dict(result[0]) self.assertEqual( ['a', 'b', 'c'], [x['lhs'] for x in answers['choices']]) self.assertEqual( ['1', '2', '3'], [x['rhs'] for x in answers['choices']]) def test_min_number_of_matches(self): # there must be at least 3 pairs with self.assertRaises(ParseException): gift.GiftParser.match_answers.parseString('{=a->1 =b->2}') def test_question(self): task = ('Match the following countries with their ' 'corresponding capitals.') text = """ %s { =Canada -> Ottawa =Italy -> Rome =Japan -> Tokyo =India -> New Delhi }""" % task result = gift.GiftParser.match_question.parseString(text)[0] question = gift.to_dict(result[1]) self.assertEqual(task, question['task']) # assert there are four matching clauses self.assertEqual(4, len(question['choices'])) class TestMissingWordQuestion(unittest.TestCase): """Tests for parsing Missing Word questions.""" def test_answers(self): s = '=c ~w1 ~w2}' result = gift.GiftParser.missing_word_answers.parseString(s) answers = gift.to_dict(result[0][1]) self.assertEqual('c', answers[0]['text']) self.assertEqual(100, answers[0]['score']) def test_question(self): s = 'CourseBuilder costs {~lots of money =nothing ~little} to download.' result = gift.GiftParser.missing_word_question.parseString(s) question = gift.to_dict(result[0][1]) self.assertEqual('CourseBuilder costs ', question['prefix']) self.assertEqual(3, len(question['choices'])) class TestShortAnswerQuestion(unittest.TestCase): """Tests for parsing Short Answer questions.""" def test_answer(self): result = gift.GiftParser.short_answer.parseString('=a=')[0] self.assertEqual('a', gift.to_dict(result)['text']) result = gift.GiftParser.short_answer.parseString('=a }')[0] self.assertEqual('a', gift.to_dict(result)['text']) def test_answers(self): s = '=foo =bar}' result = gift.GiftParser.short_answers.parseString(s) choices = gift.to_dict(result[0]) self.assertEqual('foo', choices['choices'][0]['text']) self.assertEqual('bar', choices['choices'][1]['text']) def test_question(self): s = 'Two plus two equals { =four =4}' result = gift.GiftParser.short_answer_question.parseString(s)[0] question = gift.to_dict(result[1]) self.assertEqual('Two plus two equals', question['task']) self.assertEqual('four', question['choices'][0]['text']) self.assertEqual('4', question['choices'][1]['text']) class TestTrueFalseQuestion(unittest.TestCase): """Tests for parsing True-False questions.""" def test_answer(self): r = gift.GiftParser.true_false_answer.parseString('{T}') self.assertEqual(True, r.answer) r = gift.GiftParser.true_false_answer.parseString('{FALSE}') self.assertEqual(False, r.answer) def test_question(self): s = """ // question: 0 name: TrueStatement using {T} style ::TrueStatement about Grant:: Grant was buried in a tomb in New York City.{T} """ result = gift.GiftParser.true_false_question.parseString(s)[0] question = gift.to_dict(result[1]) self.assertEqual('TrueStatement about Grant', question['title']) task = 'Grant was buried in a tomb in New York City.' self.assertEqual(task, question['task']) self.assertEqual(True, question['choices'][0]['text']) class TestMultiChoiceMultipleSelectionQuestion(unittest.TestCase): """Tests for parsing mul-choice questions with multiple correct answers.""" def test_answer(self): result = gift.GiftParser.multi_choice_answer.parseString('~%50% a}')[0] answer = gift.to_dict(result) self.assertEqual(50, answer['score']) self.assertEqual('a', answer['text']) result = gift.GiftParser.multi_choice_answer.parseString( '~%-100% a ~%')[0] answer = gift.to_dict(result) self.assertEqual(-100, answer['score']) self.assertEqual('a', answer['text']) # missing end of answer separator with self.assertRaises(ParseException): gift.GiftParser.multi_choice_answer.parseString('~%100%a') def test_answers_spaces_and_separators(self): tests = [ '~%25%a1~%75%a2~%-100%a3}', '~%25% a1~%75% a2 ~%-100% a3 }', '~%25% a1~%75% a2 ~%-100% a3 }'] for s in tests: result = gift.GiftParser.multi_choice_answers.parseString(s)[0] choices = gift.to_dict(result[1]) self.assertEqual(3, len(choices)) def test_questions(self): task = 'What two people are entombed in Grant\'s tomb?' question = """ %s { ~%-100%No one ~%50%Grant ~%50%Grant's wife ~%-100%Grant's father }""" % task result = gift.GiftParser.multi_choice_question.parseString(question)[0] question = gift.to_dict(result)['question'] self.assertEqual(task, question['task']) self.assertEqual(4, len(question['choices'])) class TestHead(unittest.TestCase): """Tests for parsing question heads.""" def test_title(self): result = gift.GiftParser.title.parseString('::Q1::') self.assertEqual('Q1', result.title) result = gift.GiftParser.title.parseString(':: Q1 ::') self.assertEqual('Q1', result.title) with self.assertRaises(ParseException): gift.GiftParser.title.parseString('Q1::') def test_title_n_task(self): r = gift.GiftParser.task.parseString('Who?{') self.assertEqual('Who?', r.task) class TestMultiChoiceQuestion(unittest.TestCase): """Tests for parsing multiple-choice questions with one correct answer.""" def test_answer(self): result = gift.GiftParser.multi_choice_answer.parseString('= c }')[0] answer = gift.to_dict(result) self.assertEqual('c', answer['text']) result = gift.GiftParser.multi_choice_answer.parseString('~w ~')[0] answer = gift.to_dict(result) self.assertEqual('w', answer['text']) # test missing trailing separator with self.assertRaises(ParseException): gift.GiftParser.multi_choice_answer.parseString('=c') def test_scores_spaces_and_separators(self): result = gift.GiftParser.multi_choice_answers.parseString( '~w1 =c ~w2}')[0] answers = gift.to_dict(result) self.assertEqual([0, 100, 0], [x['score'] for x in answers['choices']]) result = gift.GiftParser.multi_choice_answers.parseString( '=c ~w1 ab~w2}')[0] answers = gift.to_dict(result) self.assertEqual([100, 0, 0], [x['score'] for x in answers['choices']]) self.assertEqual('w1 ab', answers['choices'][1]['text']) s = (' =yellow # right; good! ~red # wrong, ' 'it\'s yellow ~blue # wrong, it\'s yellow }') result = gift.GiftParser.multi_choice_answers.parseString(s)[0] answers = gift.to_dict(result) self.assertEqual('yellow', answers['choices'][0]['text']) self.assertEqual( 'right; good!', answers['choices'][0]['feedback']) def test_questions(self): s = ''' // comment ::Q2:: What's between orange and green in the spectrum? { =yellow # right; good! ~red # wrong, it's yellow ~blue # wrong, it's yellow } ''' result = gift.GiftParser.multi_choice_question.parseString(s)[0] question = gift.to_dict(result)['question'] self.assertEqual('Q2', question['title']) self.assertEqual( "What's between orange and green in the spectrum?", question['task']) self.assertEqual(3, len(question['choices'])) def test_question_long_form(self): s = ''' //Comment line ::Question title :: Question { =A correct answer ~Wrong answer1 #A response to wrong answer1 ~Wrong answer2 #A response to wrong answer2 ~Wrong answer3 #A response to wrong answer3 ~Wrong answer4 #A response to wrong answer4 }''' result = gift.GiftParser.multi_choice_question.parseString(s)[0] question = gift.to_dict(result)['question'] self.assertEqual('Question title', question['title']) self.assertEqual('Question', question['task']) self.assertEqual(5, len(question['choices'])) self.assertEqual( [100, 0, 0, 0, 0], [x['score'] for x in question['choices']]) def test_question_short_form(self): s = ('Question{= A correct answer ~Wrong answer1 ~Wrong answer2 ' '~Wrong answer3 ~Wrong answer4 }') result = gift.GiftParser.multi_choice_question.parseString(s)[0] question = gift.to_dict(result)['question'] self.assertEqual('Question', question['task']) self.assertEqual(5, len(question['choices'])) self.assertEqual( [100, 0, 0, 0, 0], [x['score'] for x in question['choices']]) class TestCreateManyGiftQuestion(unittest.TestCase): """Tests for parsing and converting ``a list of GIFT questions.""" def test_create_many(self): gift_text = """ ::t1:: q1? {~%30% c1 #fb1 ~%70% c2 ~c3 # fb3} ::t2:: q2? {=c1 #c1fb ~w1a #w1afb ~w1b # w1bfb} ::t3:: q4? {T} ::t4:: q4? {F #fb} ::t5:: Who's buried in Grant's tomb?{=Grant =Ulysses S. Grant =Ulysses Grant} ::t6:: Two plus two equals {=four =4} ::t7:: When was Ulysses S. Grant born?{#1822:5} """ questions = gift.GiftParser.parse_questions(gift_text) assert all(questions) self.assertEqual( ['multi_choice'] * 4 + ['short_answer'] * 3, [x['type'] for x in questions])
Python
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for mapreduce jobs.""" __author__ = 'juliaoh@google.com (Julia Oh)' import unittest from models import transforms from tools.etl import mapreduce class HistogramTests(unittest.TestCase): def test_get_bin_number(self): bucket_size = 30 histogram = mapreduce.Histogram(bucket_size) self.assertEquals(histogram._get_bin_number(0), 0) self.assertEquals(histogram._get_bin_number(bucket_size), 0) self.assertEquals(histogram._get_bin_number(bucket_size + 1), 1) self.assertEquals(histogram._get_bin_number(bucket_size * 2), 1) self.assertEquals(histogram._get_bin_number((bucket_size * 2) + 1), 2) def test_get_bin_number_throws_value_error_for_negative_input(self): histogram = mapreduce.Histogram(30) self.assertRaises(ValueError, histogram._get_bin_number, -1) def test_add(self): histogram = mapreduce.Histogram(30) histogram.add(0) histogram.add(1) histogram.add(31) histogram.add(60) histogram.add(61) histogram.add(123) self.assertEquals(histogram._values, {0: 2, 1: 2, 2: 1, 4: 1}) def test_to_list(self): histogram = mapreduce.Histogram(30) histogram.add(0) histogram.add(1) histogram.add(31) histogram.add(60) histogram.add(61) histogram.add(123) self.assertEquals(histogram.to_list(), [2, 2, 1, 0, 1]) histogram = mapreduce.Histogram(30) histogram.add(121) self.assertEquals(histogram.to_list(), [0, 0, 0, 0, 1]) def test_to_list_returns_empty_list(self): histogram = mapreduce.Histogram(30) self.assertEquals(histogram.to_list(), []) class FlattenJsonTests(unittest.TestCase): def test_empty_json_flattened_returns_empty_json(self): empty_json = transforms.loads(transforms.dumps({})) flattened_json = mapreduce.CsvGenerator._flatten_json(empty_json) self.assertEquals(empty_json, flattened_json) def test_flat_json_flattened_returns_same_json(self): flat_json = transforms.loads( transforms.dumps({'foo': 1, 'bar': 2, 'quz': 3})) flattened_json = mapreduce.CsvGenerator._flatten_json(flat_json) self.assertEquals(flat_json, flattened_json) def test_nested_json_flattens_correctly(self): dict1 = dict(aaa=111) dict2 = dict(aa=11, bb=22, cc=transforms.dumps(dict1)) dict3 = dict(a=transforms.dumps(dict2), b=2) json = transforms.loads(transforms.dumps(dict3)) flattened_json = mapreduce.CsvGenerator._flatten_json(json) result_json = transforms.loads( transforms.dumps( {'a_aa': '11', 'a_bb': '22', 'b': '2', 'a_cc_aaa': '111'})) self.assertEquals(result_json, flattened_json) def test_malformed_json_flattens_correctly(self): json_text = """ {"rows": [ {"foo": "bar", "good_json": "{'bee': 'bum',}", "bad_json": "{''"} ],} """ _dict = transforms.loads(json_text, strict=False) _flat = mapreduce.CsvGenerator._flatten_json(_dict.get('rows')[0]) assert 3 == len(_flat.items()) assert 'bar' == _flat.get('foo') assert 'bum' == _flat.get('good_json_bee') assert '{\'\'' == _flat.get('bad_json')
Python
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for the Workflow class in models.courses.""" __author__ = 'Sean Lip (sll@google.com)' import unittest import yaml from models.courses import LEGACY_HUMAN_GRADER_WORKFLOW from models.courses import Workflow DATE_FORMAT_ERROR = ( 'dates should be formatted as YYYY-MM-DD hh:mm (e.g. 1997-07-16 19:20) and ' 'be specified in the UTC timezone.' ) ERROR_HEADER = 'Error validating workflow specification: ' MISSING_KEYS_PREFIX = 'missing key(s) for a human-reviewed assessment:' class DateTimeConversionTests(unittest.TestCase): """Unit tests for datetime conversion.""" def test_valid_datetime(self): """Valid datetimes should be converted without problems.""" workflow = Workflow('') date_obj = workflow._convert_date_string_to_datetime('2012-03-21 12:30') self.assertEqual(date_obj.year, 2012) self.assertEqual(date_obj.month, 3) self.assertEqual(date_obj.day, 21) self.assertEqual(date_obj.hour, 12) self.assertEqual(date_obj.minute, 30) def test_invalid_datetime(self): """Valid datetimes should be converted without problems.""" invalid_date_strs = [ 'abc', '2012-13-31 12:30', '2012-12-31T12:30', '2012-13-31 12:30+0100'] workflow = Workflow('') for date_str in invalid_date_strs: with self.assertRaises(Exception): workflow._convert_date_string_to_datetime(date_str) def test_no_timezone_set(self): """Parsed date strings should contain no timezone information.""" workflow = Workflow('') date_obj = workflow._convert_date_string_to_datetime('2012-03-21 12:30') self.assertIsNone(date_obj.tzinfo) class WorkflowValidationTests(unittest.TestCase): """Unit tests for workflow object validation.""" def setUp(self): self.errors = [] self.valid_human_review_workflow_dict = yaml.safe_load( LEGACY_HUMAN_GRADER_WORKFLOW) def assert_matching_errors(self, expected, actual): """Prepend the error prefix to the error messages, then compare them.""" formatted_errors = [] for error in expected: formatted_errors.append('%s%s' % (ERROR_HEADER, error)) self.assertEqual(formatted_errors, actual) def to_yaml(self, adict): """Convert a dict to YAML.""" return yaml.safe_dump(adict) def test_empty_string(self): """Validation should fail on an empty string.""" workflow = Workflow('') workflow.validate(self.errors) self.assert_matching_errors(['missing key: grader.'], self.errors) def test_invalid_string(self): """Validation should fail for invalid YAML strings.""" workflow = Workflow('(') workflow.validate(self.errors) self.assertTrue(self.errors) def test_not_dict(self): """Validation should fail for non-dict YAML strings.""" yaml_strs = ['- first\n- second', 'grader'] for yaml_str in yaml_strs: self.errors = [] workflow = Workflow(yaml_str) workflow.validate(self.errors) self.assert_matching_errors( ['expected the YAML representation of a dict'], self.errors) def test_missing_grader_key(self): """Validation should fail for missing grader key.""" workflow = Workflow(self.to_yaml({'not_grader': 'human'})) workflow.validate(self.errors) self.assert_matching_errors(['missing key: grader.'], self.errors) def test_auto_grader(self): """Validation should pass for an auto-graded assessment.""" workflow = Workflow(self.to_yaml({'grader': 'auto'})) workflow.validate(self.errors) self.assertFalse(self.errors) def test_empty_submission_date_in_grader(self): """Validation should pass for empty submission date.""" workflow = Workflow(self.to_yaml( {'grader': 'auto', 'submission_due_date': ''})) workflow.validate(self.errors) self.assertFalse(self.errors) def test_invalid_human_grader(self): """Validation should fail for invalid human grading specifications.""" workflow = Workflow(self.to_yaml({'grader': 'human'})) workflow.validate(self.errors) self.assert_matching_errors([ '%s matcher, review_min_count, review_window_mins, ' 'submission_due_date, review_due_date.' % MISSING_KEYS_PREFIX], self.errors) self.errors = [] workflow = Workflow(self.to_yaml( {'grader': 'human', 'matcher': 'peer'} )) workflow.validate(self.errors) self.assert_matching_errors([ '%s review_min_count, review_window_mins, submission_due_date, ' 'review_due_date.' % MISSING_KEYS_PREFIX], self.errors) def test_invalid_review_min_count(self): """Validation should fail for bad review_min_count values.""" workflow_dict = self.valid_human_review_workflow_dict workflow_dict['review_min_count'] = 'test_string' workflow = Workflow(self.to_yaml(workflow_dict)) workflow.validate(self.errors) self.assert_matching_errors( ['review_min_count should be an integer.'], self.errors) self.errors = [] workflow_dict['review_min_count'] = -1 workflow = Workflow(self.to_yaml(workflow_dict)) workflow.validate(self.errors) self.assert_matching_errors( ['review_min_count should be a non-negative integer.'], self.errors) self.errors = [] workflow_dict['review_min_count'] = 0 workflow = Workflow(self.to_yaml(workflow_dict)) workflow.validate(self.errors) self.assertFalse(self.errors) def test_invalid_review_window_mins(self): """Validation should fail for bad review_window_mins values.""" workflow_dict = self.valid_human_review_workflow_dict workflow_dict['review_window_mins'] = 'test_string' workflow = Workflow(self.to_yaml(workflow_dict)) workflow.validate(self.errors) self.assert_matching_errors( ['review_window_mins should be an integer.'], self.errors) self.errors = [] workflow_dict['review_window_mins'] = -1 workflow = Workflow(self.to_yaml(workflow_dict)) workflow.validate(self.errors) self.assert_matching_errors( ['review_window_mins should be a non-negative integer.'], self.errors) self.errors = [] workflow_dict['review_window_mins'] = 0 workflow = Workflow(self.to_yaml(workflow_dict)) workflow.validate(self.errors) self.assertFalse(self.errors) def test_invalid_date(self): """Validation should fail for invalid dates.""" workflow_dict = self.valid_human_review_workflow_dict workflow_dict['submission_due_date'] = 'test_string' workflow = Workflow(self.to_yaml(workflow_dict)) workflow.validate(self.errors) self.assert_matching_errors([DATE_FORMAT_ERROR], self.errors) self.errors = [] workflow_dict = self.valid_human_review_workflow_dict workflow_dict['review_due_date'] = 'test_string' workflow = Workflow(self.to_yaml(workflow_dict)) workflow.validate(self.errors) self.assert_matching_errors([DATE_FORMAT_ERROR], self.errors) def test_submission_date_after_review_date_fails(self): """Validation should fail if review date precedes submission date.""" workflow_dict = self.valid_human_review_workflow_dict workflow_dict['submission_due_date'] = '2013-03-14 12:00' workflow_dict['review_due_date'] = '2013-03-13 12:00' workflow = Workflow(self.to_yaml(workflow_dict)) workflow.validate(self.errors) self.assert_matching_errors( ['submission due date should be earlier than review due date.'], self.errors) def test_multiple_errors(self): """Validation should fail with multiple errors when appropriate.""" workflow_dict = self.valid_human_review_workflow_dict workflow_dict['submission_due_date'] = '2013-03-14 12:00' workflow_dict['review_due_date'] = '2013-03-13 12:00' workflow_dict['review_window_mins'] = 'hello' workflow = Workflow(self.to_yaml(workflow_dict)) workflow.validate(self.errors) self.assert_matching_errors( ['review_window_mins should be an integer; submission due date ' 'should be earlier than review due date.'], self.errors) def test_valid_human_grader(self): """Validation should pass for valid human grading specifications.""" workflow_dict = self.valid_human_review_workflow_dict workflow = Workflow(self.to_yaml(workflow_dict)) workflow.validate(self.errors) self.assertFalse(self.errors)
Python
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for the transforms functions.""" __author__ = 'John Orr (jorr@google.com)' import datetime import unittest from common import schema_fields from models import transforms def wrap_properties(properties): return {'properties': properties} class JsonToDictTests(unittest.TestCase): def test_missing_optional_fields_are_allowed(self): schema = wrap_properties( {'opt_field': {'type': 'boolean', 'optional': 'true'}}) result = transforms.json_to_dict({}, schema) self.assertEqual(len(result), 0) def test_missing_required_fields_are_rejected(self): schema = wrap_properties( {'req_field': {'type': 'boolean', 'optional': 'false'}}) try: transforms.json_to_dict({}, schema) self.fail('Expected ValueError') except ValueError as e: self.assertEqual(str(e), 'Missing required attribute: req_field') schema = wrap_properties( {'req_field': {'type': 'boolean'}}) try: transforms.json_to_dict({}, schema) self.fail('Expected ValueError') except ValueError as e: self.assertEqual(str(e), 'Missing required attribute: req_field') def test_convert_boolean(self): schema = wrap_properties({'field': {'type': 'boolean'}}) source = {'field': True} result = transforms.json_to_dict(source, schema) self.assertEqual(len(result), 1) self.assertEqual(result['field'], True) def test_convert_string_to_boolean(self): schema = wrap_properties({'field': {'type': 'boolean'}}) source = {'field': 'true'} result = transforms.json_to_dict(source, schema) self.assertEqual(len(result), 1) self.assertEqual(result['field'], True) def test_reject_bad_boolean(self): schema = wrap_properties({'field': {'type': 'boolean'}}) source = {'field': 'cat'} try: transforms.json_to_dict(source, schema) self.fail('Expected ValueException') except ValueError as e: self.assertEqual(str(e), 'Bad boolean value for field: cat') def test_convert_number(self): schema = wrap_properties({'field': {'type': 'number'}}) source = {'field': 3.14} result = transforms.json_to_dict(source, schema) self.assertEqual(len(result), 1) self.assertEqual(result['field'], 3.14) def test_convert_string_to_number(self): schema = wrap_properties({'field': {'type': 'number'}}) source = {'field': '3.14'} result = transforms.json_to_dict(source, schema) self.assertEqual(len(result), 1) self.assertEqual(result['field'], 3.14) def test_reject_bad_number(self): schema = wrap_properties({'field': {'type': 'number'}}) source = {'field': 'cat'} try: transforms.json_to_dict(source, schema) self.fail('Expected ValueException') except ValueError as e: self.assertEqual(str(e), 'could not convert string to float: cat') def test_convert_date(self): schema = wrap_properties({'field': {'type': 'date'}}) source = {'field': '2005/03/01'} result = transforms.json_to_dict(source, schema) self.assertEqual(len(result), 1) self.assertEqual(result['field'], datetime.date(2005, 3, 1)) source = {'field': '2005-03-01'} result = transforms.json_to_dict(source, schema) self.assertEqual(result['field'], datetime.date(2005, 3, 1)) def test_reject_bad_dates(self): schema = wrap_properties({'field': {'type': 'date'}}) source = {'field': '2005/02/31'} try: transforms.json_to_dict(source, schema) self.fail('Expected ValueException') except ValueError as e: self.assertEqual(str(e), 'day is out of range for month') schema = wrap_properties({'field': {'type': 'date'}}) source = {'field': 'cat'} try: transforms.json_to_dict(source, schema) self.fail('Expected ValueException') except ValueError as e: self.assertEqual( str(e), 'time data \'cat\' does not match format \'%s\'' % transforms.ISO_8601_DATE_FORMAT) def test_convert_datetime(self): schema = wrap_properties({'field': {'type': 'datetime'}}) source = {'field': '2005/03/01 20:30'} result = transforms.json_to_dict(source, schema) self.assertEqual(len(result), 1) self.assertEqual( result['field'], datetime.datetime(2005, 3, 1, 20, 30, 0)) source = {'field': '2005-03-01 20:30:19'} result = transforms.json_to_dict(source, schema) self.assertEqual( result['field'], datetime.datetime(2005, 3, 1, 20, 30, 19)) source = {'field': '2005-03-01 20:30:19Z'} result = transforms.json_to_dict(source, schema) self.assertEqual( result['field'], datetime.datetime(2005, 3, 1, 20, 30, 19)) source = {'field': '2005-03-01T20:30:19.123456Z'} result = transforms.json_to_dict(source, schema) self.assertEqual( result['field'], datetime.datetime(2005, 3, 1, 20, 30, 19, 123456)) def test_reject_bad_datetimes(self): schema = wrap_properties({'field': {'type': 'datetime'}}) source = {'field': '2005/02/31 20:30'} try: transforms.json_to_dict(source, schema) self.fail('Expected ValueException') except ValueError as e: self.assertEqual(str(e), 'day is out of range for month') schema = wrap_properties({'field': {'type': 'datetime'}}) source = {'field': 'cat'} try: transforms.json_to_dict(source, schema) self.fail('Expected ValueException') except ValueError as e: self.assertEqual( str(e), 'time data \'cat\' does not match format \'%s\'' % transforms.ISO_8601_DATETIME_FORMAT) def test_nulls(self): for type_name in transforms.JSON_TYPES: schema = wrap_properties({'field': {'type': type_name}}) source = {'field': None} ret = transforms.json_to_dict(source, schema, permit_none_values=True) self.assertIn('field', ret) self.assertIsNone(ret['field']) class StringValueConversionTests(unittest.TestCase): def test_value_to_string(self): assert transforms.value_to_string(True, bool) == 'True' assert transforms.value_to_string(False, bool) == 'False' assert transforms.value_to_string(None, bool) == 'False' def test_string_to_value(self): assert transforms.string_to_value('True', bool) assert transforms.string_to_value('1', bool) assert transforms.string_to_value(1, bool) assert not transforms.string_to_value('False', bool) assert not transforms.string_to_value('0', bool) assert not transforms.string_to_value('5', bool) assert not transforms.string_to_value(0, bool) assert not transforms.string_to_value(5, bool) assert not transforms.string_to_value(None, bool) assert transforms.string_to_value('15', int) == 15 assert transforms.string_to_value(15, int) == 15 assert transforms.string_to_value(None, int) == 0 assert transforms.string_to_value('foo', str) == 'foo' assert transforms.string_to_value(None, str) == str('') class JsonParsingTests(unittest.TestCase): def test_json_trailing_comma_in_dict_fails(self): json_text = '{"foo": "bar",}' try: transforms.loads(json_text) raise Exception('Expected to fail') except ValueError: pass def test_json_trailing_comma_in_array_fails(self): json_text = '{"foo": ["bar",]}' try: transforms.loads(json_text) raise Exception('Expected to fail') except ValueError: pass def test_non_strict_mode_parses_json(self): json_text = '{"foo": "bar", "baz": ["bum",],}' _json = transforms.loads(json_text, strict=False) assert _json.get('foo') == 'bar' class SchemaValidationTests(unittest.TestCase): def test_mandatory_scalar_missing(self): reg = schema_fields.FieldRegistry('Test') reg.add_property(schema_fields.SchemaField( 'a_string', 'A String', 'string')) complaints = transforms.validate_object_matches_json_schema( {}, reg.get_json_schema_dict()) self.assertEqual( complaints, ['Missing mandatory value at Test.a_string']) def test_mandatory_scalar_present(self): reg = schema_fields.FieldRegistry('Test') reg.add_property(schema_fields.SchemaField( 'a_string', 'A String', 'string')) complaints = transforms.validate_object_matches_json_schema( {'a_string': ''}, reg.get_json_schema_dict()) self.assertEqual(complaints, []) def test_optional_scalar_missing(self): reg = schema_fields.FieldRegistry('Test') reg.add_property(schema_fields.SchemaField( 'a_string', 'A String', 'string', optional=True)) complaints = transforms.validate_object_matches_json_schema( {}, reg.get_json_schema_dict()) self.assertEqual(complaints, []) def test_optional_scalar_present(self): reg = schema_fields.FieldRegistry('Test') reg.add_property(schema_fields.SchemaField( 'a_string', 'A String', 'string', optional=True)) complaints = transforms.validate_object_matches_json_schema( {'a_string': ''}, reg.get_json_schema_dict()) self.assertEqual(complaints, []) def test_non_struct_where_struct_expected(self): reg = schema_fields.FieldRegistry('Test') reg.add_property(schema_fields.SchemaField( 'a_string', 'A String', 'string')) complaints = transforms.validate_object_matches_json_schema( 123, reg.get_json_schema_dict()) self.assertEqual( complaints, ['Expected a dict at Test, but had <type \'int\'>']) def test_malformed_url(self): reg = schema_fields.FieldRegistry('Test') reg.add_property(schema_fields.SchemaField( 'a_url', 'A URL', 'url')) complaints = transforms.validate_object_matches_json_schema( {'a_url': 'not really a URL, is it?'}, reg.get_json_schema_dict()) self.assertEqual( complaints, ['Value "not really a URL, is it?" ' 'is not well-formed according to is_valid_url']) def test_valid_url(self): reg = schema_fields.FieldRegistry('Test') reg.add_property(schema_fields.SchemaField( 'a_url', 'A URL', 'url')) complaints = transforms.validate_object_matches_json_schema( {'a_url': 'http://x.com'}, reg.get_json_schema_dict()) self.assertEqual(complaints, []) def test_malformed_date(self): reg = schema_fields.FieldRegistry('Test') reg.add_property(schema_fields.SchemaField( 'a_date', 'A Date', 'date')) complaints = transforms.validate_object_matches_json_schema( {'a_date': 'not really a date string, is it?'}, reg.get_json_schema_dict()) self.assertEqual( complaints, ['Value "not really a date string, is it?" ' 'is not well-formed according to is_valid_date']) def test_valid_date(self): reg = schema_fields.FieldRegistry('Test') reg.add_property(schema_fields.SchemaField( 'a_date', 'A Date', 'date')) complaints = transforms.validate_object_matches_json_schema( {'a_date': '2014-12-17'}, reg.get_json_schema_dict()) self.assertEqual(complaints, []) def test_malformed_datetime(self): reg = schema_fields.FieldRegistry('Test') reg.add_property(schema_fields.SchemaField( 'a_datetime', 'A Datetime', 'datetime')) complaints = transforms.validate_object_matches_json_schema( {'a_datetime': 'not really a datetime string, is it?'}, reg.get_json_schema_dict()) self.assertEqual( complaints, ['Value "not really a datetime string, is it?" ' 'is not well-formed according to is_valid_datetime']) def test_valid_datetime(self): reg = schema_fields.FieldRegistry('Test') reg.add_property(schema_fields.SchemaField( 'a_datetime', 'A Datetime', 'datetime')) complaints = transforms.validate_object_matches_json_schema( {'a_datetime': '2014-12-17T14:10:09.222333Z'}, reg.get_json_schema_dict()) self.assertEqual(complaints, []) def test_unexpected_member(self): reg = schema_fields.FieldRegistry('Test') reg.add_property(schema_fields.SchemaField( 'a_string', 'A String', 'string')) complaints = transforms.validate_object_matches_json_schema( {'a_string': '', 'a_number': 456}, reg.get_json_schema_dict()) self.assertEqual(complaints, ['Unexpected member "a_number" in Test']) def test_arrays_are_implicitly_optional(self): reg = schema_fields.FieldRegistry('Test') reg.add_property(schema_fields.FieldArray( 'scalar_array', 'Scalar Array', item_type=schema_fields.SchemaField( 'a_string', 'A String', 'string'))) complaints = transforms.validate_object_matches_json_schema( {}, reg.get_json_schema_dict()) self.assertEqual(complaints, []) def test_empty_array(self): reg = schema_fields.FieldRegistry('Test') reg.add_property(schema_fields.FieldArray( 'scalar_array', 'Scalar Array', item_type=schema_fields.SchemaField( 'a_string', 'A String', 'string'))) complaints = transforms.validate_object_matches_json_schema( {'scalar_array': []}, reg.get_json_schema_dict()) self.assertEqual(complaints, []) def test_array_with_valid_content(self): reg = schema_fields.FieldRegistry('Test') reg.add_property(schema_fields.FieldArray( 'scalar_array', 'Scalar Array', item_type=schema_fields.SchemaField( 'a_string', 'A String', 'string'))) complaints = transforms.validate_object_matches_json_schema( {'scalar_array': ['foo', 'bar', 'baz']}, reg.get_json_schema_dict()) self.assertEqual(complaints, []) def test_array_with_bad_members(self): reg = schema_fields.FieldRegistry('Test') reg.add_property(schema_fields.FieldArray( 'scalar_array', 'Scalar Array', item_type=schema_fields.SchemaField( 'a_string', 'A String', 'string'))) complaints = transforms.validate_object_matches_json_schema( {'scalar_array': ['foo', 123, 'bar', 456, 'baz']}, reg.get_json_schema_dict()) self.assertEqual( complaints, ['Expected <type \'basestring\'> at Test.scalar_array[1], ' 'but instead had <type \'int\'>', 'Expected <type \'basestring\'> at Test.scalar_array[3], ' 'but instead had <type \'int\'>']) def test_dicts_implicitly_optional(self): reg = schema_fields.FieldRegistry('Test') sub_registry = schema_fields.FieldRegistry('subregistry') sub_registry.add_property(schema_fields.SchemaField( 'name', 'Name', 'string', description='user name')) sub_registry.add_property(schema_fields.SchemaField( 'city', 'City', 'string', description='city name')) reg.add_sub_registry('sub_registry', title='Sub Registry', description='a sub-registry', registry=sub_registry) complaints = transforms.validate_object_matches_json_schema( {}, reg.get_json_schema_dict()) self.assertEqual(complaints, []) def test_nested_dict(self): reg = schema_fields.FieldRegistry('Test') sub_registry = schema_fields.FieldRegistry('subregistry') sub_registry.add_property(schema_fields.SchemaField( 'name', 'Name', 'string', description='user name')) sub_registry.add_property(schema_fields.SchemaField( 'city', 'City', 'string', description='city name')) reg.add_sub_registry('sub_registry', title='Sub Registry', description='a sub-registry', registry=sub_registry) complaints = transforms.validate_object_matches_json_schema( {'sub_registry': {'name': 'John Smith', 'city': 'Back East'}}, reg.get_json_schema_dict()) self.assertEqual(complaints, []) def test_nested_dict_missing_items(self): reg = schema_fields.FieldRegistry('Test') sub_registry = schema_fields.FieldRegistry('subregistry') sub_registry.add_property(schema_fields.SchemaField( 'name', 'Name', 'string', description='user name')) sub_registry.add_property(schema_fields.SchemaField( 'city', 'City', 'string', description='city name')) reg.add_sub_registry('sub_registry', title='Sub Registry', description='a sub-registry', registry=sub_registry) complaints = transforms.validate_object_matches_json_schema( {'sub_registry': {}}, reg.get_json_schema_dict()) self.assertEqual( complaints, ['Missing mandatory value at Test.sub_registry.name', 'Missing mandatory value at Test.sub_registry.city']) def test_array_of_dict(self): sub_registry = schema_fields.FieldRegistry('subregistry') sub_registry.add_property(schema_fields.SchemaField( 'name', 'Name', 'string', description='user name')) sub_registry.add_property(schema_fields.SchemaField( 'city', 'City', 'string', description='city name')) reg = schema_fields.FieldRegistry('Test') reg.add_property(schema_fields.FieldArray( 'struct_array', 'Struct Array', item_type=sub_registry)) complaints = transforms.validate_object_matches_json_schema( {'struct_array': [ {'name': 'One', 'city': 'Two'}, None, {'name': 'Three'}, {'city': 'Four'} ]}, reg.get_json_schema_dict()) self.assertEqual( complaints, ['Found None at Test.struct_array[1]', 'Missing mandatory value at Test.struct_array[2].city', 'Missing mandatory value at Test.struct_array[3].name'])
Python
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for common.tags.""" __author__ = 'John Orr (jorr@google.com)' import unittest from xml.etree import cElementTree from common import tags class CustomTagTests(unittest.TestCase): """Unit tests for the custom tag functionality.""" def setUp(self): class SimpleTag(tags.BaseTag): def render(self, unused_arg, unused_handler): return cElementTree.Element('SimpleTag') class ComplexTag(tags.BaseTag): def render(self, unused_arg, unused_handler): return cElementTree.XML( '<Complex><Child>Text</Child></Complex>') class ReRootTag(tags.BaseTag): def render(self, node, unused_handler): elt = cElementTree.Element('Re') root = cElementTree.Element('Root') elt.append(root) for child in node: root.append(child) return elt class CounterTag(tags.ContextAwareTag): """A tag which counts its occurences in the page.""" def render(self, unused_node, context): context.env['count'] = context.env.get('count', 0) + 1 elt = cElementTree.Element('Count') elt.text = context.env['count'] return elt def rollup_header_footer(self, context): return ( cElementTree.XML( '<div>%s</div>' % context.env.get('count', 0)), cElementTree.XML('<div>foot</div>')) def new_get_tag_bindings(): return { 'simple': SimpleTag, 'complex': ComplexTag, 'reroot': ReRootTag, 'count': CounterTag} self.old_get_tag_bindings = tags.get_tag_bindings tags.get_tag_bindings = new_get_tag_bindings self.mock_handler = object() def tearDown(self): tags.get_tag_bindings = self.old_get_tag_bindings def test_empty_text_is_passed(self): safe_dom = tags.html_to_safe_dom(None, self.mock_handler) self.assertEquals('', str(safe_dom)) def test_none_is_treated_as_empty(self): safe_dom = tags.html_to_safe_dom(None, self.mock_handler) self.assertEquals('', str(safe_dom)) def test_plain_text_is_passed(self): safe_dom = tags.html_to_safe_dom( 'This is plain text.', self.mock_handler) self.assertEquals('This is plain text.', str(safe_dom)) def test_mix_of_plain_text_and_tags_is_passed(self): html = 'This is plain text<br/>on several<br/>lines' safe_dom = tags.html_to_safe_dom(html, self.mock_handler) self.assertEquals(html, str(safe_dom)) def test_svg_tag_is_accepted(self): html = '<svg></svg>' safe_dom = tags.html_to_safe_dom(html, self.mock_handler) self.assertEquals(html, str(safe_dom)) def test_simple_tag_is_replaced(self): html = '<div><simple></simple></div>' safe_dom = tags.html_to_safe_dom(html, self.mock_handler) self.assertEquals('<div><SimpleTag></SimpleTag></div>', str(safe_dom)) def test_replaced_tag_preserves_tail_text(self): html = '<div><simple></simple>Tail text</div>' safe_dom = tags.html_to_safe_dom(html, self.mock_handler) self.assertEquals( '<div><SimpleTag></SimpleTag>Tail text</div>', str(safe_dom)) def test_simple_tag_consumes_children(self): html = '<div><simple><p>child1</p></simple></div>' safe_dom = tags.html_to_safe_dom(html, self.mock_handler) self.assertEquals( '<div><SimpleTag></SimpleTag></div>', str(safe_dom)) def test_complex_tag_preserves_its_own_children(self): html = '<div><complex/></div>' safe_dom = tags.html_to_safe_dom(html, self.mock_handler) self.assertEquals( '<div><Complex><Child>Text</Child></Complex></div>', str(safe_dom)) def test_reroot_tag_puts_children_in_new_root(self): html = '<div><reroot><p>one</p><p>two</p></reroot></div>' safe_dom = tags.html_to_safe_dom(html, self.mock_handler) self.assertEquals( '<div><Re><Root><p>one</p><p>two</p></Root></Re></div>', str(safe_dom)) def test_chains_of_tags(self): html = '<div><reroot><p><simple></p></reroot></div>' safe_dom = tags.html_to_safe_dom(html, self.mock_handler) self.assertEquals( '<div><Re><Root><p><SimpleTag></SimpleTag></p></Root></Re></div>', str(safe_dom)) def test_scripts_are_not_escaped(self): html = '<script>alert("2"); var a = (1 < 2 && 2 > 1);</script>' safe_dom = tags.html_to_safe_dom(html, self.mock_handler) self.assertEquals(html, str(safe_dom)) def test_context_aware_tags(self): html = '<div><count></count><simple></simple><count></count></div>' safe_dom = tags.html_to_safe_dom(html, self.mock_handler) self.assertEqual( ( '<div>2</div><div><Count>1</Count><SimpleTag></SimpleTag>' '<Count>2</Count></div><div>foot</div>' ), str(safe_dom))
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for the anaytics internals in models/analytics/*.py.""" __author__ = 'Mike Gainer (mgainer@google.com)' import collections import datetime import unittest import jinja2 from common import jinja_utils from models import analytics from models import data_sources from models import jobs #------------------------------------------------------------------------------- # Mock objects to simulate models/jobs subsystem class MockAppContext(object): def __init__(self, namespace_name): self._namespace_name = namespace_name def get_namespace_name(self): return self._namespace_name class MockJobEntity(object): def __init__(self, status=jobs.STATUS_CODE_STARTED, output=None): self._status = status self._output = output self._updated_on = datetime.datetime.utcnow() def complete(self, output): self._complete(output, jobs.STATUS_CODE_COMPLETED) def fail(self, output): self._complete(output, jobs.STATUS_CODE_FAILED) def _complete(self, output, status): self._output = output self._status = status now = datetime.datetime.utcnow() self._execution_time_sec = int((now - self._updated_on).total_seconds()) self._updated_on = now def start(self): self._status = jobs.STATUS_CODE_STARTED self._updated_on = datetime.datetime.utcnow() @property def output(self): return self._output @property def status_code(self): return self._status @property def has_finished(self): return self._status in ( jobs.STATUS_CODE_COMPLETED, jobs.STATUS_CODE_FAILED) @property def updated_on(self): return self._updated_on @property def execution_time_sec(self): return self._execution_time_sec class MockJobBase(jobs.DurableJobBase): _jobs = {} # Mock persistent store @classmethod def clear_jobs(cls): cls._jobs.clear() def __init__(self, app_context): super(MockJobBase, self).__init__(app_context) def submit(self): job = self.load() if not job: job = self._create_job() if job.has_finished: job.start() def load(self): return self._jobs.get(self._get_name(), None) @classmethod def _create_job(cls): job = MockJobEntity() cls._jobs[cls._get_name()] = job return job @classmethod def _get_name(cls): return cls.__name__ def cancel(self): job = self.load() if job and not job.has_finished: job.fail('Canceled') #------------------------------------------------------------------------------- # Mock objects to simulate page-display level constructs class MockXsrfCreator(object): def create_xsrf_token(self, action): return 'xsrf_' + action class MockHandler(object): def __init__(self, app_context): self._templates = {} self._app_context = app_context self.request = collections.namedtuple('X', ['url'])('/foo/bar/baz') def get_template(self, template_name, template_dirs): jinja_environment = jinja_utils.create_jinja_environment( loader=jinja2.FileSystemLoader(template_dirs)) return jinja_environment.get_template(template_name) @property def app_context(self): return self._app_context #------------------------------------------------------------------------------- # Generators and data source classes for use in visualizations. class GenOne(MockJobBase): @staticmethod def get_description(): return 'gen one' class GenTwo(MockJobBase): @staticmethod def get_description(): return 'gen two' class GenThree(MockJobBase): @staticmethod def get_description(): return 'gen three' class NoGenSource(data_sources.SynchronousQuery): @staticmethod def fill_values(app_context, template_values): template_values['no_gen_source'] = 'no_gen_value' class OneGenSource(data_sources.SynchronousQuery): @staticmethod def required_generators(): return [GenOne] @staticmethod def fill_values(app_context, template_values, gen_one_job): template_values['one_gen_source_gen_one'] = ( gen_one_job.output) class TwoGenSource(data_sources.SynchronousQuery): @staticmethod def required_generators(): return [GenOne, GenTwo] @staticmethod def fill_values(app_context, template_values, gen_one_job, gen_two_job): template_values['two_gen_source_gen_one'] = ( gen_one_job.output) template_values['two_gen_source_gen_two'] = ( gen_two_job.output) class ThreeGenSource(data_sources.SynchronousQuery): @staticmethod def required_generators(): return [GenOne, GenTwo, GenThree] @staticmethod def fill_values(app_context, template_values, gen_one_job, gen_two_job, gen_three_job): template_values['three_gen_source_gen_one'] = ( gen_one_job.output) template_values['three_gen_source_gen_two'] = ( gen_two_job.output) template_values['three_gen_source_gen_three'] = ( gen_three_job.output) data_sources.Registry.register(NoGenSource) data_sources.Registry.register(OneGenSource) data_sources.Registry.register(TwoGenSource) data_sources.Registry.register(ThreeGenSource) #------------------------------------------------------------------------------- # Actual tests. class AnalyticsTests(unittest.TestCase): def setUp(self): analytics.by_name.clear() MockJobBase.clear_jobs() self._mock_app_context = MockAppContext('testing') self._mock_handler = MockHandler(self._mock_app_context) self._mock_xsrf = MockXsrfCreator() def _generate_analytics_page(self, visualizations): return analytics.generate_display_html( self._mock_handler, self._mock_xsrf, visualizations) def _run_generators_for_visualizations(self, app_context, visualizations): for gen_class in analytics.utils._generators_for_visualizations( visualizations): gen_class(app_context).submit() def _cancel_generators_for_visualizations(self, app_context, visualizations): for gen_class in analytics.utils._generators_for_visualizations( visualizations): gen_class(app_context).cancel() def test_illegal_name(self): with self.assertRaisesRegexp(ValueError, 'name "A" must contain only'): analytics.Visualization('A', 'Foo', 'foo.html') with self.assertRaisesRegexp(ValueError, 'name " " must contain only'): analytics.Visualization(' ', 'Foo', 'foo.html') with self.assertRaisesRegexp(ValueError, 'name "#" must contain only'): analytics.Visualization('#', 'Foo', 'foo.html') def test_illegal_generator(self): with self.assertRaisesRegexp( ValueError, 'All data source classes used in visualizations must be'): analytics.Visualization('foo', 'foo', 'foo', [MockHandler]) def test_no_generator_display(self): name = 'no_generator' analytic = analytics.Visualization( name, name, 'models_analytics_section.html', [NoGenSource]) result = self._generate_analytics_page([analytic]) # Statistic reports result to page self.assertIn('no_generator_no_gen_source: "no_gen_value"', result) # Statistic does not have a run/cancel button; it has no generators # which depend on jobs. self.assertNotIn('gdb-run-analytic-simple', result) self.assertNotIn('gdb-cancel-analytic-simple', result) def test_generator_run_cancel_state_display(self): name = 'foo' analytic = analytics.Visualization( name, name, 'models_analytics_section.html', [OneGenSource]) result = self._generate_analytics_page([analytic]) self.assertIn('Statistics for gen one have not been', result) self.assertIn('Update Statistic', result) self.assertIn('action=run_visualizations', result) self._run_generators_for_visualizations(self._mock_app_context, [analytic]) result = self._generate_analytics_page([analytic]) self.assertIn('Job for gen one statistics started at', result) self.assertIn('Cancel Statistic Calculation', result) self.assertIn('action=cancel_visualizations', result) self._cancel_generators_for_visualizations(self._mock_app_context, [analytic]) result = self._generate_analytics_page([analytic]) self.assertIn('There was an error updating gen one statistics', result) self.assertIn('<pre>Canceled</pre>', result) self.assertIn('Update Statistic', result) self.assertIn('action=run_visualizations', result) self._run_generators_for_visualizations(self._mock_app_context, [analytic]) result = self._generate_analytics_page([analytic]) self.assertIn('Job for gen one statistics started at', result) self.assertIn('Cancel Statistic Calculation', result) self.assertIn('action=cancel_visualizations', result) GenOne(self._mock_app_context).load().complete('run_state_display') result = self._generate_analytics_page([analytic]) self.assertIn('Statistics for gen one were last updated at', result) self.assertIn('in about 0 sec', result) self.assertIn('Update Statistic', result) self.assertIn('action=run_visualizations', result) self.assertIn('foo_one_gen_source_gen_one: "run_state_display"', result) def test_multiple_visualizationsmultiple_generators_multiple_sources(self): visualizations = [] visualizations.append(analytics.Visualization( 'trivial', 'Trivial Statistics', 'models_analytics_section.html', [NoGenSource])) visualizations.append(analytics.Visualization( 'simple', 'Simple Statistics', 'models_analytics_section.html', [OneGenSource])) visualizations.append(analytics.Visualization( 'complex', 'Complex Statistics', 'models_analytics_section.html', [NoGenSource, OneGenSource, TwoGenSource, ThreeGenSource])) self._run_generators_for_visualizations(self._mock_app_context, visualizations) # Verify that not-all generators are running, but that 'complex' # is still not reporting data, as the generator it's relying on # (GenThree) is still running. GenOne(self._mock_app_context).load().complete('gen_one_data') GenTwo(self._mock_app_context).load().complete('gen_two_data') result = self._generate_analytics_page(visualizations) self.assertIn('simple_one_gen_source_gen_one: "gen_one_data"', result) self.assertIn('Statistics for gen one were last updated', result) self.assertIn('Statistics for gen two were last updated', result) self.assertIn('Job for gen three statistics started at', result) self.assertNotIn('complex_three_gen_source', result) # Finish last generator; should now have all data from all sources. GenThree(self._mock_app_context).load().complete('gen_three_data') result = self._generate_analytics_page(visualizations) self.assertIn('trivial_no_gen_source: "no_gen_value"', result) self.assertIn('simple_one_gen_source_gen_one: "gen_one_data"', result) self.assertIn('complex_no_gen_source: "no_gen_value"', result) self.assertIn('complex_one_gen_source_gen_one: "gen_one_data"', result) self.assertIn('complex_two_gen_source_gen_one: "gen_one_data"', result) self.assertIn('complex_two_gen_source_gen_two: "gen_two_data"', result) self.assertIn('complex_three_gen_source_gen_one: "gen_one_data"', result) self.assertIn('complex_three_gen_source_gen_two: "gen_two_data"', result) self.assertIn('complex_three_gen_source_gen_three: "gen_three_data"', result) # Verify that we _don't_ have data for sections that didn't specify # that source. self.assertIn('trivial_one_gen_source_gen_one: ""', result) self.assertIn('simple_no_gen_source: ""', result) # We should have all headers self.assertIn('<h3>Trivial Statistics</h3>', result) self.assertIn('<h3>Simple Statistics</h3>', result) self.assertIn('<h3>Complex Statistics</h3>', result) # And submission forms for analytics w/ generators self.assertNotIn( '<input type="hidden" name="visualization" value="trivial"', result) self.assertIn( '<input type="hidden" name="visualization" value="simple"', result) self.assertIn( '<input type="hidden" name="visualization" value="complex"', result)
Python
# -*- coding: utf-8 -*- # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for the Search module.""" __author__ = 'Ellis Michael (emichael@google.com)' import re import robotparser import urlparse from functional import actions from modules.search import resources from google.appengine.api import urlfetch VALID_PAGE_URL = 'http://valid.null/' VALID_PAGE = """<html> <head> <title>Test Page</title> <script> alert('test'); </script> <style> body { font-size: 12px; } </style> </head> <body> Lorem ipsum <strong> dolor </strong> sit. <a href="index.php?query=bibi%20quid">Ago gratias tibi</a>. <a>Cogito ergo sum.</a> <a href="//partial.null/"> Partial link </a> <a href="ftp://absolute.null/"> Absolute link </a> <a href="http://pdf.null/"> PDF </a> <a href="http://link.null/"> Link </a> </body> </html>""" VALID_PAGE_ROBOTS = ('User-agent: *', 'Allow: /') LINKED_PAGE_URL = 'http://link.null/' LINKED_PAGE = """<a href="http://distance2link.null/"> What hath God wrought? </a>""" SECOND_LINK_PAGE_URL = 'http://distance2link.null/' SECOND_LINK_PAGE = """Something went terribly wrong. ABORT""" UNICODE_PAGE_URL = 'http://unicode.null/' UNICODE_PAGE = """<html> <head> <title>‘Quoted string’</title> </head> <body> Russell's Paradox: <br/> ∃ y∀ x(x∈ y ⇔ P(x)) <br/> Let P(x)=~(x∈ x), x=y. <br/> y∈ y ⇔ ~(y∈ y) </body> </html>""" PDF_URL = 'http://pdf.null/' XML_DOC_URL = 'http://xml.null/' XML_DOC = """<document attribute="foo"> <childNode> Text content. </childNode> </document>""" YOUTUBE_TRANSCRIPT_URL = (resources.YOUTUBE_TIMED_TEXT_URL + '?.*name=Name%20of%20track.*$') YOUTUBE_TRANSCRIPT = """<transcript> <text start="3.14" dur="6.28"> Apple, lemon, cherry... </text> <text start="20.0" dur="20.0"> It&#39;s a test. </text> </transcript>""" GDATA_DOC_URL = resources.YOUTUBE_DATA_URL GDATA_DOC = """<?xml version='1.0' encoding='UTF-8'?> <entry xmlns='http://www.w3.org/2005/Atom' xmlns:media='http://search.yahoo.com/mrss/'> <title type="text"> Medicus Quis </title> <media:thumbnail url="http://thumbnail.null"/> </entry>""" YOUTUBE_TRANSCRIPT_LIST_URL = (resources.YOUTUBE_TIMED_TEXT_URL + '?.*type=list.*$') YOUTUBE_TRANSCRIPT_LIST = """<transcript_list docid="123456789"> <track id="0" name="Name of track" lang_code="en" lang_original="English" lang_translated="English" lang_default="true" /> </transcript_list>""" BANNED_PAGE_URL = 'http://banned.null/' BANNED_PAGE = 'Should not be accessed' BANNED_PAGE_ROBOTS = ('User-agent: *', 'Disallow: /') class SearchTestBase(actions.TestBase): """Unit tests for all search functionality.""" pages = {VALID_PAGE_URL + '$': # Using $ to prevent erroneous matches (VALID_PAGE, 'text/html'), urlparse.urljoin(VALID_PAGE_URL, '/robots.txt'): (VALID_PAGE_ROBOTS, 'text/html'), LINKED_PAGE_URL + '$': (LINKED_PAGE, 'text/html'), urlparse.urljoin(LINKED_PAGE_URL, '/robots.txt'): (VALID_PAGE_ROBOTS, 'text/html'), SECOND_LINK_PAGE_URL + '$': (SECOND_LINK_PAGE, 'text/html'), urlparse.urljoin(SECOND_LINK_PAGE_URL, '/robots.txt'): (VALID_PAGE_ROBOTS, 'text/html'), PDF_URL: (VALID_PAGE, 'application/pdf'), UNICODE_PAGE_URL + '$': (UNICODE_PAGE, 'text/html charset=utf-8'), urlparse.urljoin(UNICODE_PAGE_URL, '/robots.txt'): (VALID_PAGE_ROBOTS, 'text/html'), XML_DOC_URL + '$': (XML_DOC, 'text/xml'), urlparse.urljoin(XML_DOC_URL, '/robots.txt'): (VALID_PAGE_ROBOTS, 'text/html'), YOUTUBE_TRANSCRIPT_URL: (YOUTUBE_TRANSCRIPT, 'text/xml'), GDATA_DOC_URL: (GDATA_DOC, 'text/xml'), YOUTUBE_TRANSCRIPT_LIST_URL: (YOUTUBE_TRANSCRIPT_LIST, 'text/xml'), # The default Power Searching course has notes in this domain 'http://www.google.com/robots.txt': (VALID_PAGE_ROBOTS, 'text/html'), BANNED_PAGE_URL + '$': (BANNED_PAGE, 'text/html'), urlparse.urljoin(BANNED_PAGE_URL, '/robots.txt'): (BANNED_PAGE_ROBOTS, 'text/html'), } def setUp(self): """Do all of the necessary monkey patching to test search.""" super(SearchTestBase, self).setUp() def return_doc(url): """Monkey patch for URL fetching.""" class Response(object): def __init__(self, code, content_type, content): self.status_code = code self.headers = {} self.headers['Content-type'] = content_type self.content = content for pattern in self.pages: if re.match(pattern, url): page_data = self.pages[pattern] body = page_data[0] content_type = page_data[1] break else: body = VALID_PAGE content_type = 'text/html' result = Response(200, content_type, body) return result self.swap(urlfetch, 'fetch', return_doc) class FakeRobotParser(robotparser.RobotFileParser): """Monkey patch for robot parser.""" def read(self): parts = urlparse.urlsplit(self.url) if not (parts.netloc and parts.scheme): raise IOError response = urlfetch.fetch(self.url) self.parse(response.content) self.swap(robotparser, 'RobotFileParser', FakeRobotParser) class ParserTests(SearchTestBase): """Unit tests for the search HTML Parser.""" def setUp(self): super(ParserTests, self).setUp() self.parser = resources.ResourceHTMLParser(VALID_PAGE_URL) self.parser.feed(VALID_PAGE) def test_found_tokens(self): content = self.parser.get_content() for text in ['Lorem', 'ipsum', 'dolor']: self.assertIn(text, content) def test_no_false_matches(self): content = self.parser.get_content() for text in ['Loremipsum', 'ipsumdolor', 'tibiCogito', 'sit.Ago']: self.assertNotIn(text, content) def test_ignored_fields(self): content = self.parser.get_content() for text in ['alert', 'font-size', 'body', 'script', 'style']: self.assertNotIn(text, content) def test_links(self): links = self.parser.get_links() self.assertIn('http://valid.null/index.php?query=bibi%20quid', links) self.assertIn('http://partial.null/', links) self.assertIn('ftp://absolute.null/', links) self.assertEqual(len(links), 5) def test_unopened_tag(self): self.parser = resources.ResourceHTMLParser('') self.parser.feed('Lorem ipsum </script> dolor sit.') content = self.parser.get_content() for text in ['Lorem', 'ipsum', 'dolor', 'sit']: self.assertIn(text, content) def test_title(self): self.assertEqual('Test Page', self.parser.get_title()) def test_get_parser_allowed(self): self.parser = resources.get_parser_for_html(VALID_PAGE_URL) content = self.parser.get_content() self.assertIn('Cogito ergo sum', content) with self.assertRaises(resources.URLNotParseableException): self.parser = resources.get_parser_for_html(BANNED_PAGE_URL) content = self.parser.get_content() self.assertNotIn('accessed', content) def test_bad_urls(self): for url in ['http://', 'invalid.null', '//invalid.null', '//', 'invalid', '?test=1', 'invalid?test=1']: with self.assertRaises(resources.URLNotParseableException): self.parser = resources.get_parser_for_html(url) content = self.parser.get_content() self.assertNotIn('impsum', content) def test_unicode_page(self): self.parser = resources.get_parser_for_html(UNICODE_PAGE_URL) content = self.parser.get_content() self.assertIn('Paradox', content) title = self.parser.get_title() self.assertIn('Quoted string', title) def test_xml_parser(self): dom = resources.get_minidom_from_xml(XML_DOC_URL) self.assertEqual('foo', dom.getElementsByTagName( 'document')[0].attributes['attribute'].value) self.assertIn('Text content.', dom.getElementsByTagName( 'childNode')[0].firstChild.nodeValue)
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Setup for tests exercising visualization displays.""" __author__ = 'Mike Gainer (mgainer@google.com)' from common import schema_fields from controllers import utils from models import analytics from models import custom_modules from models import data_sources from modules.dashboard import tabs class FakeDataSource(data_sources.AbstractRestDataSource): _exception = None _log_critical = None _page_number = None @classmethod def get_context_class(cls): return data_sources.DbTableContext @classmethod def get_schema(cls, *args, **kwargs): reg = schema_fields.FieldRegistry( 'Bogus', description='bogus') reg.add_property(schema_fields.SchemaField( 'bogus', 'Bogus', 'integer', description='Fake schema')) return reg.get_json_schema_dict()['properties'] @classmethod def set_fetch_values_page_number(cls, page_number=None): """For testing. Force fetch_values to return a specific page number.""" cls._page_number = page_number @classmethod def set_fetch_values_exception(cls): """For testing. Force fetch_values to raise an exception.""" cls._exception = True @classmethod def set_fetch_values_log_critical(cls): """For testing. Force fetch_values to log an error message.""" cls._log_critical = True @classmethod def fetch_values(cls, _app_context, _source_context, _schema, log, page_number): if cls._exception: cls._exception = None raise ValueError('Error for testing') if cls._log_critical: cls._log_critical = None log.critical('Error for testing') if cls._page_number is not None: if cls._page_number != page_number: log.warning('Stopping at last page %d' % cls._page_number) page_number = cls._page_number cls._page_number = None return [ {'name': 'Snoopy', 'score': 10, 'page_number': page_number}, {'name': 'Linus', 'score': 8}, {'name': 'Lucy', 'score': 3}, {'name': 'Schroeder', 'score': 5}, ], page_number class ExamsDataSource(FakeDataSource): @classmethod def get_name(cls): return 'exams' @classmethod def get_title(cls): return 'Exams' @classmethod def get_default_chunk_size(cls): return 0 # Not paginated class PupilsDataSource(FakeDataSource): @classmethod def get_name(cls): return 'pupils' @classmethod def get_title(cls): return 'Pupils' class AnswersDataSource(FakeDataSource): @classmethod def get_name(cls): return 'fake_answers' @classmethod def get_title(cls): return 'Fake Answers' class ForceResponseHandler(utils.ApplicationHandler): """REST service to allow tests to affect the behavior of FakeDataSource.""" URL = '/fake_data_source_response' PARAM_DATA_SOURCE = 'data_source' PARAM_ACTION = 'action' PARAM_PAGE_NUMBER = 'page_number' ACTION_PAGE_NUMBER = 'page_number' ACTION_LOG_CRITICAL = 'log_critical' ACTION_EXCEPTION = 'exception' def post(self): data_source_classes = { 'exams': ExamsDataSource, 'pupils': PupilsDataSource, 'fake_answers': AnswersDataSource, } data_source = data_source_classes[ self.request.get(ForceResponseHandler.PARAM_DATA_SOURCE)] action = self.request.get(ForceResponseHandler.PARAM_ACTION) if action == ForceResponseHandler.ACTION_PAGE_NUMBER: data_source.set_fetch_values_page_number( int(self.request.get(ForceResponseHandler.PARAM_PAGE_NUMBER))) elif action == ForceResponseHandler.ACTION_LOG_CRITICAL: data_source.set_fetch_values_log_critical() elif action == ForceResponseHandler.ACTION_EXCEPTION: data_source.set_fetch_values_exception() else: self.response.set_status(400) self.response.write('Malformed Request') return def register_on_enable(): data_sources.Registry.register(ExamsDataSource) data_sources.Registry.register(PupilsDataSource) data_sources.Registry.register(AnswersDataSource) exams = analytics.Visualization( 'exams', 'Exams', 'fake_visualizations.html', [ExamsDataSource]) pupils = analytics.Visualization( 'pupils', 'Pupils', 'fake_visualizations.html', [PupilsDataSource]) scoring = analytics.Visualization( 'scoring', 'Scoring', 'fake_visualizations.html', [ExamsDataSource, PupilsDataSource, AnswersDataSource]) tabs.Registry.register('analytics', 'exams', 'Exams', [exams]) tabs.Registry.register('analytics', 'pupils', 'Pupils', [pupils]) tabs.Registry.register('analytics', 'scoring', 'Scoring', [scoring]) def register_module(): """Dynamically registered module providing fake analytics for testing.""" namespaced_handlers = [(ForceResponseHandler.URL, ForceResponseHandler)] return custom_modules.Module( 'FakeVisualizations', 'Provide visualizations requiring simple, ' 'paginated, and multiple data streams for testing.', [], namespaced_handlers, register_on_enable, None)
Python
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Performance test for a peer review system. WARNING! Use this script to test load Course Builder. This is very dangerous feature, be careful, because anyone can impersonate super user of your Course Builder instance; use only if you have to perform specific load testing Keep in mind: - when repeatedly running tests and creating new test namespaces, flush memcache Here is how to run: - update /controllers/sites.py and enable CAN_IMPERSONATE - navigate to the root directory of the app - run a command line by typing: python tests/integration/load_test.py \ --thread_count=5 \ --start_uid=1 \ https://mycourse.appspot.com If you use http instead of https, your tests will fail because your requests will instantly be redirected (which can confound GET vs POST, for example). """ __author__ = 'Pavel Simakov (psimakov@google.com)' import argparse import cookielib import json import logging import random import re import sys import threading import time import urllib import urllib2 # The unit id for the peer review assignment in the default course. LEGACY_REVIEW_UNIT_ID = 'ReviewAssessmentExample' # command line arguments parser PARSER = argparse.ArgumentParser() PARSER.add_argument( 'base_url', help=('Base URL of the course you want to test'), type=str) PARSER.add_argument( '--start_uid', help='Initial value for unique thread identifier.', default=1, type=int) PARSER.add_argument( '--thread_count', help='Number of concurrent threads for executing the test.', default=1, type=int) PARSER.add_argument( '--iteration_count', help='Number of iterations for executing the test. Each thread of each ' 'iteration acts as a unique user with the uid equal to:' 'start_uid + thread_count * iteration_index.', default=1, type=int) def assert_contains(needle, haystack): if needle not in haystack: raise Exception('Expected to find term: %s\n%s', needle, haystack) def assert_does_not_contain(needle, haystack): if needle in haystack: raise Exception('Did not expect to find term: %s\n%s', needle, haystack) def assert_equals(expected, actual): if expected != actual: raise Exception('Expected equality of %s and %s.', expected, actual) class WebSession(object): """A class that allows navigation of web pages keeping cookie session.""" PROGRESS_LOCK = threading.Lock() MAX_RETRIES = 3 RETRY_SLEEP_SEC = 3 GET_COUNT = 0 POST_COUNT = 0 RETRY_COUNT = 0 PROGRESS_BATCH = 10 RESPONSE_TIME_HISTOGRAM = [0, 0, 0, 0, 0, 0] def __init__(self, uid, common_headers=None): if common_headers is None: common_headers = {} self.uid = uid self.common_headers = common_headers self.cj = cookielib.CookieJar() self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj)) @classmethod def increment_duration_bucket(cls, index): cls.RESPONSE_TIME_HISTOGRAM[index] += 1 @classmethod def update_duration(cls, duration): if duration > 30: cls.increment_duration_bucket(0) elif duration > 15: cls.increment_duration_bucket(1) elif duration > 7: cls.increment_duration_bucket(2) elif duration > 3: cls.increment_duration_bucket(3) elif duration > 1: cls.increment_duration_bucket(4) else: cls.increment_duration_bucket(5) @classmethod def log_progress(cls, force=False): update = ((cls.GET_COUNT + cls.POST_COUNT) % ( cls.PROGRESS_BATCH) == 0) if update or force: logging.info( 'GET/POST:[%s, %s], RETRIES:[%s], SLA:%s', cls.GET_COUNT, cls.POST_COUNT, cls.RETRY_COUNT, cls.RESPONSE_TIME_HISTOGRAM) def get_cookie_value(self, name): for cookie in self.cj: if cookie.name == name: return cookie.value return None def is_soft_error(self, http_error): """Checks if HTTPError is due to starvation of frontend instances.""" body = http_error.fp.read() # this is the text specific to the front end instance starvation, which # is a retriable error for both GET and POST; normal HTTP error 500 has # this specific text '<h1>500 Internal Server Error</h1>' if http_error.code == 500 and '<h1>Error: Server Error</h1>' in body: return True logging.error( 'Non-retriable HTTP %s error:\n%s', http_error.code, body) return False def open(self, request, hint): """Executes any HTTP request.""" start_time = time.time() try: try_count = 0 while True: try: return self.opener.open(request) except urllib2.HTTPError as he: if ( try_count < WebSession.MAX_RETRIES and self.is_soft_error(he)): try_count += 1 with WebSession.PROGRESS_LOCK: WebSession.RETRY_COUNT += 1 time.sleep(WebSession.RETRY_SLEEP_SEC) continue raise he except Exception as e: logging.info( 'Error in session %s executing: %s', self.uid, hint) raise e finally: with WebSession.PROGRESS_LOCK: self.update_duration(time.time() - start_time) def get(self, url, expected_code=200): """HTTP GET.""" with WebSession.PROGRESS_LOCK: WebSession.GET_COUNT += 1 self.log_progress() request = urllib2.Request(url) for key, value in self.common_headers.items(): request.add_header(key, value) response = self.open(request, 'GET %s' % url) assert_equals(expected_code, response.code) return response.read() def post(self, url, args_dict, expected_code=200): """HTTP POST.""" with WebSession.PROGRESS_LOCK: WebSession.POST_COUNT += 1 self.log_progress() data = None if args_dict: data = urllib.urlencode(args_dict) request = urllib2.Request(url, data) for key, value in self.common_headers.items(): request.add_header(key, value) response = self.open(request, 'POST %s' % url) assert_equals(expected_code, response.code) return response.read() class TaskThread(threading.Thread): """Runs a task in a separate thread.""" def __init__(self, func, name=None): super(TaskThread, self).__init__() self.func = func self.exception = None self.name = name @classmethod def start_all_tasks(cls, tasks): """Starts all tasks.""" for task in tasks: task.start() @classmethod def check_all_tasks(cls, tasks): """Checks results of all tasks; fails on the first exception found.""" failed_count = 0 for task in tasks: while True: # Timeouts should happen after 30 seconds. task.join(30) if task.isAlive(): logging.info('Still waiting for: %s.', task.name) continue else: break if task.exception: failed_count += 1 if failed_count: raise Exception('Tasks failed: %s', failed_count) @classmethod def execute_task_list(cls, tasks): """Starts all tasks and checks the results.""" cls.start_all_tasks(tasks) cls.check_all_tasks(tasks) def run(self): try: self.func() except Exception as e: # pylint: disable=broad-except logging.error('Error in %s: %s', self.name, e) self.exc_info = sys.exc_info() raise self.exc_info[1], None, self.exc_info[2] class LoadTest(object): """Parent for all load tests.""" def __init__(self, base_url, uid): self.uid = uid self.host = base_url # this is an impersonation identity for the actor thread self.email = 'load_test_bot_%s@example.com' % self.uid self.name = 'Load Test Bot #%s' % self.uid # begin web session impersonate_header = { 'email': self.email, 'user_id': u'impersonation-%s' % self.uid} self.session = WebSession( uid=uid, common_headers={'Gcb-Impersonate': json.dumps(impersonate_header)}) def get_hidden_field(self, name, body): # The "\s*" denotes arbitrary whitespace; sometimes, this tag is split # across multiple lines in the HTML. # pylint: disable=anomalous-backslash-in-string reg = re.compile( '<input type="hidden" name="%s"\s* value="([^"]*)">' % name) # pylint: enable=anomalous-backslash-in-string return reg.search(body).group(1) def register_if_has_to(self): """Performs student registration action.""" body = self.session.get('%s/' % self.host) assert_contains('Logout', body) if 'href="register"' not in body: body = self.session.get('%s/student/home' % self.host) assert_contains(self.email, body) assert_contains(self.name, body) return False body = self.session.get('%s/register' % self.host) xsrf_token = self.get_hidden_field('xsrf_token', body) data = {'xsrf_token': xsrf_token, 'form01': self.name} body = self.session.post('%s/register' % self.host, data) body = self.session.get('%s/' % self.host) assert_contains('Logout', body) assert_does_not_contain('href="register"', body) return True class PeerReviewLoadTest(LoadTest): """A peer review load test.""" def run(self): self.register_if_has_to() self.submit_peer_review_assessment_if_possible() while self.count_completed_reviews() < 2: self.request_and_do_a_review() def get_js_var(self, name, body): reg = re.compile('%s = \'([^\']*)\';\n' % name) return reg.search(body).group(1) def get_draft_review_url(self, body): """Returns the URL of a draft review on the review dashboard.""" # The "\s*" denotes arbitrary whitespace; sometimes, this tag is split # across multiple lines in the HTML. # pylint: disable=anomalous-backslash-in-string reg = re.compile( '<a href="([^"]*)">Assignment [0-9]+</a>\s*\(Draft\)') # pylint: enable=anomalous-backslash-in-string result = reg.search(body) if result is None: return None return result.group(1) def submit_peer_review_assessment_if_possible(self): """Submits the peer review assessment.""" body = self.session.get( '%s/assessment?name=%s' % (self.host, LEGACY_REVIEW_UNIT_ID)) assert_contains('You may only submit this assignment once', body) if 'Submitted assignment' in body: # The assignment was already submitted. return True assessment_xsrf_token = self.get_js_var('assessmentXsrfToken', body) answers = [ {'index': 0, 'type': 'regex', 'value': 'Answer 0 by %s' % self.email}, {'index': 1, 'type': 'choices', 'value': self.uid}, {'index': 2, 'type': 'regex', 'value': 'Answer 2 by %s' % self.email}, ] data = { 'answers': json.dumps(answers), 'assessment_type': LEGACY_REVIEW_UNIT_ID, 'score': 0, 'xsrf_token': assessment_xsrf_token, } body = self.session.post('%s/answer' % self.host, data) assert_contains('Review peer assignments', body) return True def request_and_do_a_review(self): """Request a new review, wait for it to be granted, then submit it.""" review_dashboard_url = ( '%s/reviewdashboard?unit=%s' % (self.host, LEGACY_REVIEW_UNIT_ID)) completed = False while not completed: # Get peer review dashboard and inspect it. body = self.session.get(review_dashboard_url) assert_contains('Assignments for your review', body) assert_contains('Review a new assignment', body) # Pick first pending review if any or ask for a new review. draft_review_url = self.get_draft_review_url(body) if draft_review_url: # There is a pending review. Choose it. body = self.session.get( '%s/%s' % (self.host, draft_review_url)) else: # Request a new assignment to review. assert_contains('xsrf_token', body) xsrf_token = self.get_hidden_field('xsrf_token', body) data = { 'unit_id': LEGACY_REVIEW_UNIT_ID, 'xsrf_token': xsrf_token, } body = self.session.post(review_dashboard_url, data) # It is possible that we fail to get a new review because the # old one is now visible, but was not yet visible when we asked # for the dashboard page. if ( 'You must complete all assigned reviews before you ' 'can request a new one.' in body): continue # It is possible that no submissions available for review yet. # Wait for a while until they become available on the dashboard # page. if 'Back to the review dashboard' not in body: assert_contains('Assignments for your review', body) # Sleep for a random number of seconds between 1 and 4. time.sleep(1.0 + random.random() * 3.0) continue # Submit the review. review_xsrf_token = self.get_js_var('assessmentXsrfToken', body) answers = [ {'index': 0, 'type': 'choices', 'value': 0}, {'index': 1, 'type': 'regex', 'value': 'Review 0 by %s' % self.email}, ] data = { 'answers': json.dumps(answers), 'assessment_type': None, 'is_draft': 'false', 'key': self.get_js_var('assessmentGlobals.key', body), 'score': 0, 'unit_id': LEGACY_REVIEW_UNIT_ID, 'xsrf_token': review_xsrf_token, } body = self.session.post('%s/review' % self.host, data) assert_contains('Your review has been submitted', body) return True def count_completed_reviews(self): """Counts the number of reviews that the actor has completed.""" review_dashboard_url = ( '%s/reviewdashboard?unit=%s' % (self.host, LEGACY_REVIEW_UNIT_ID)) body = self.session.get(review_dashboard_url) num_completed = body.count('(Completed)') return num_completed class WelcomeNotificationLoadTest(LoadTest): """Tests registration confirmation notifications. You must enable notifications in the target course for this test to be meaningful. You must also swap the test class that's instantiated in run_all, below. """ def run(self): self.register_if_has_to() def run_all(args): """Runs test scenario in multiple threads.""" if args.thread_count < 1 or args.thread_count > 256: raise Exception('Please use between 1 and 256 threads.') start_time = time.time() logging.info('Started testing: %s', args.base_url) logging.info('base_url: %s', args.base_url) logging.info('start_uid: %s', args.start_uid) logging.info('thread_count: %s', args.thread_count) logging.info('iteration_count: %s', args.iteration_count) logging.info('SLAs are [>30s, >15s, >7s, >3s, >1s, <1s]') try: for iteration_index in range(0, args.iteration_count): logging.info('Started iteration: %s', iteration_index) tasks = [] WebSession.PROGRESS_BATCH = args.thread_count for index in range(0, args.thread_count): test = PeerReviewLoadTest( args.base_url, ( args.start_uid + iteration_index * args.thread_count + index)) task = TaskThread( test.run, name='PeerReviewLoadTest-%s' % index) tasks.append(task) try: TaskThread.execute_task_list(tasks) except Exception as e: logging.info('Failed iteration: %s', iteration_index) raise e finally: WebSession.log_progress(force=True) logging.info('Done! Duration (s): %s', time.time() - start_time) if __name__ == '__main__': logging.basicConfig(level=logging.INFO) run_all(PARSER.parse_args())
Python
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Page objects used in functional tests for Course Builder.""" __author__ = [ 'John Orr (jorr@google.com)' ] import re import time from selenium.common import exceptions from selenium.webdriver.common import action_chains from selenium.webdriver.common import by from selenium.webdriver.common import keys from selenium.webdriver.support import expected_conditions as ec from selenium.webdriver.support import select from selenium.webdriver.support import wait DEFAULT_TIMEOUT = 15 def get_parent_element(web_element): return web_element.find_element_by_xpath('..') class PageObject(object): """Superclass to hold shared logic used by page objects.""" def __init__(self, tester): self._tester = tester def get(self, url, can_retry=True): if can_retry: tries = 10 else: tries = 1 while tries > 0: tries -= 1 self._tester.driver.get(url) if 'The website may be down' in self._tester.driver.page_source: time.sleep(5) continue return raise exceptions.TimeoutException( 'Timeout waiting for %s page to load', url) def wait(self, timeout=None): if timeout is None: timeout = DEFAULT_TIMEOUT return wait.WebDriverWait(self._tester.driver, timeout) def find_element_by_css_selector(self, selector, index=None): if index is None: return self._tester.driver.find_element_by_css_selector(selector) else: return self._tester.driver.find_elements_by_css_selector( selector)[index] def find_element_by_id(self, elt_id): return self._tester.driver.find_element_by_id(elt_id) def find_element_by_link_text(self, text, index=None): if index is None: return self._tester.driver.find_element_by_link_text(text) else: return self._tester.driver.find_elements_by_link_text(text)[index] def find_element_by_name(self, name): return self._tester.driver.find_element_by_name(name) def expect_status_message_to_be(self, value): self.wait().until( ec.text_to_be_present_in_element( (by.By.ID, 'gcb-butterbar-message'), value)) def wait_until_status_message_hidden(self): self.wait().until( ec.invisibility_of_element_located( (by.By.ID, 'gcb-butterbar-message'))) return self def go_back(self): self._tester.driver.back() return self def switch_to_alert(self): """Waits for an alert and switches the focus to it""" self.wait().until(ec.alert_is_present(), 'Time out waiting') return self._tester.driver.switch_to_alert() def where_am_i(self): """Returns the last part of the current url, after /.""" if '/' in self._tester.driver.current_url: return self._tester.driver.current_url.split('/')[-1] return None class EditorPageObject(PageObject): """Page object for pages which wait for the editor to finish loading.""" def __init__(self, tester): super(EditorPageObject, self).__init__(tester) def successful_butter_bar(unused_driver): butter_bar_message = self.find_element_by_id( 'gcb-butterbar-message') return 'Success' in butter_bar_message.text or ( not butter_bar_message.is_displayed()) self.wait().until(successful_butter_bar) def set_status(self, status): select.Select(self.find_element_by_name( 'is_draft')).select_by_visible_text(status) return self def click_save(self, link_text='Save', status_message='Saved'): self.find_element_by_link_text(link_text).click() self.expect_status_message_to_be(status_message) return self def _close_and_return_to(self, continue_page): self.find_element_by_link_text('Close').click() return continue_page(self._tester) class DashboardEditor(EditorPageObject): """A base class for the editors accessed from the Dashboard.""" def click_close(self): return self._close_and_return_to(DashboardPage) class RootPage(PageObject): """Page object to model the interactions with the root page.""" def _add_default_course_if_needed(self, base_url): """Setup default read-only course if not yet setup.""" # check default course is deployed self.get(base_url + '/') if 'Power Searching with Google' in self._tester.driver.page_source: return # deploy it LoginPage(self._tester).login('test@example.com', admin=True) self.get(base_url + '/admin/global?tab=settings') AdminSettingsPage(self._tester).click_override( 'gcb_courses_config' ).set_status('Active').click_save() self.get(base_url + '/admin/global?tab=courses') self.find_element_by_link_text('Logout').click() def load(self, base_url): self._add_default_course_if_needed(base_url) self.get(base_url + '/') return self def load_welcome_page(self, base_url): self.click_login( ).login( 'test@example.com', admin=True ) self.get(base_url + '/admin/welcome') return WelcomePage(self._tester) def click_login(self): self.find_element_by_link_text('Login').click() return LoginPage(self._tester) def click_dashboard(self): self.find_element_by_link_text('Dashboard').click() return DashboardPage(self._tester) def click_announcements(self): self.find_element_by_link_text('Announcements').click() return AnnouncementsPage(self._tester) def click_register(self): self.find_element_by_link_text('Register').click() return RegisterPage(self._tester) class WelcomePage(PageObject): def click_explore_sample_course(self): self.find_element_by_id('explore').click() return DashboardPage(self._tester) class RegisterPage(PageObject): """Page object to model the registration page.""" def enroll(self, name): enroll = self.find_element_by_name('form01') enroll.send_keys(name) enroll.submit() return self def verify_enrollment(self): self._tester.assertTrue( 'Thank you for registering' in self.find_element_by_css_selector( '.gcb-top-content').text) return self def click_course(self): self.find_element_by_link_text('Course').click() return RootPage(self._tester) class AnnouncementsPage(PageObject): """Page object to model the announcements page.""" def click_add_new(self): self.find_element_by_css_selector( '#gcb-add-announcement > button').click() return AnnouncementsEditorPage(self._tester) def verify_announcement(self, title=None, date=None, body=None): """Verify that the announcement has the given fields.""" if title: self._tester.assertEquals( title, self._tester.driver.find_elements_by_css_selector( 'div.gcb-aside h2')[0].text) if date: self._tester.assertEquals( date, self._tester.driver.find_elements_by_css_selector( 'div.gcb-aside p')[0].text) if body: self._tester.assertEquals( body, self._tester.driver.find_elements_by_css_selector( 'div.gcb-aside p')[1].text) return self class AnnouncementsEditorPage(EditorPageObject): """Page to model the announcements editor.""" def enter_fields(self, title=None, date=None, body=None): """Enter title, date, and body into the announcement form.""" if title: title_el = self.find_element_by_name('title') title_el.clear() title_el.send_keys(title) if date: date_el = self.find_element_by_name('date') date_el.clear() date_el.send_keys(date) if body: body_el = self.find_element_by_name('html') body_el.clear() body_el.send_keys(body) return self def click_close(self): return self._close_and_return_to(AnnouncementsPage) class LoginPage(PageObject): """Page object to model the interactions with the login page.""" def login(self, login, admin=False): email = self.find_element_by_id('email') email.clear() email.send_keys(login) if admin: self.find_element_by_id('admin').click() self.find_element_by_id('submit-login').click() return RootPage(self._tester) class DashboardPage(PageObject): """Page object to model the interactions with the dashboard landing page.""" def load(self, base_url, name): self.get('/'.join([base_url, name, 'dashboard'])) return self def verify_read_only_course(self): self._tester.assertEquals( 'Read-only course.', self.find_element_by_id('gcb-butterbar-message').text) return self def verify_selected_tab(self, tab_text): tab = self.find_element_by_link_text(tab_text) self._tester.assertEquals('selected', tab.get_attribute('class')) def verify_not_publicly_available(self): self._tester.assertEquals( 'The course is not publicly available.', self.find_element_by_id('gcb-butterbar-message').text) return self def click_admin(self): self.find_element_by_link_text('Site Admin').click() return AdminPage(self._tester) def click_import(self): self.find_element_by_css_selector('#import_course').click() return Import(self._tester) def click_add_unit(self): self.find_element_by_css_selector('#add_unit > button').click() return AddUnit(self._tester, AddUnit.CREATION_MESSAGE) def click_edit_unit(self, unit_title): self.find_element_by_link_text(unit_title).click() self.find_element_by_link_text('Edit Unit').click() return AddUnit(self._tester, AddUnit.LOADED_MESSAGE) def click_add_assessment(self): self.find_element_by_css_selector('#add_assessment > button').click() return AddAssessment(self._tester) def click_add_link(self): self.find_element_by_css_selector('#add_link > button').click() return AddLink(self._tester) def click_add_lesson(self): self.find_element_by_css_selector( 'div.course-outline li.add-lesson button').click() return AddLesson(self._tester) def click_assets(self): self.find_element_by_link_text('Assets').click() return AssetsPage(self._tester) def click_settings(self): self.find_element_by_link_text('Settings').click() self.find_element_by_link_text('Homepage').click() return SettingsPage(self._tester) def verify_course_outline_contains_unit(self, unit_title): self.find_element_by_link_text(unit_title) return self def click_on_course_outline_components(self, title): self.find_element_by_link_text(title).click() return LessonPage(self._tester) def click_analytics(self, name): self.find_element_by_link_text('Analytics').click() self.find_element_by_link_text(name).click() return AnalyticsPage(self._tester) def click_course(self): self.find_element_by_css_selector( 'div.course-outline div.course div.name a').click() return RootPage(self._tester) def click_i18n(self): self.find_element_by_link_text('I18N').click() return self class CourseContentPage(RootPage): """Page object for viewing course content.""" def _find_question(self, question_batch_id, question_text): questions = self._tester.driver.find_elements_by_css_selector( '[data-question-batch-id="%s"] .qt-mc-question.qt-standalone' % question_batch_id) if not questions: raise AssertionError('No questions in batch "%s" found' % question_batch_id) for question in questions: if (question.find_element_by_css_selector('.qt-question').text == question_text): return question raise AssertionError('No questions in batch "%s" ' % question_batch_id + 'matched "%s"' % question_text) def set_answer_for_mc_question(self, question_batch_id, question_text, answer): question = self._find_question(question_batch_id, question_text) choices = question.find_elements_by_css_selector( '.qt-choices > *') for choice in choices: if choice.text == answer: choice.find_element_by_css_selector( 'input[type="radio"]').click() return self raise AssertionError( 'No answer to question "%s" ' % question_text + 'in batch "%s" ' + question_batch_id + 'had an answer matching "%s"' % answer) def submit_question_batch(self, question_batch_id, button_text): buttons = self._tester.driver.find_elements_by_css_selector( 'div[data-question-batch-id="%s"] .qt-check-answer-button' % question_batch_id) for button in buttons: if button_text in button.text: button.click() if question_batch_id.startswith('L'): return self else: return AssessmentConfirmationPage(self._tester) raise AssertionError('No button found matching "%s"' % button_text) class LessonPage(CourseContentPage): """Object specific to Lesson behavior.""" def verify_correct_submission(self, question_batch_id, question_text): question = self._find_question(question_batch_id, question_text) text = question.find_element_by_css_selector('.qt-feedback').text if text == 'Yes, the answer is correct.': return self raise Exception('Incorrect answer submitted') def verify_incorrect_submission(self, question_batch_id, question_text): question = self._find_question(question_batch_id, question_text) text = question.find_element_by_css_selector('.qt-feedback').text if text == 'No, the answer is incorrect.': return self raise Exception('Correct answer submitted') def verify_correct_grading(self, question_batch_id): report = self.find_element_by_css_selector( '.qt-grade-report[data-question-batch-id="%s"]' % question_batch_id) if report.text == 'Your score is: 1/1': return self raise Exception('Incorrect answer submitted') def verify_incorrect_grading(self, question_batch_id): report = self.find_element_by_css_selector( '.qt-grade-report[data-question-batch-id="%s"]' % question_batch_id) if report.text == 'Your score is: 0/1': return self raise Exception('Correct answer submitted') def play_video(self, instanceid): self._tester.driver.execute_script( 'document.getElementById("%s").play();' % instanceid) time.sleep(1) # Let the video get started before we do anything else. return self def pause_video(self, instanceid): self._tester.driver.execute_script( 'document.getElementById("%s").pause();' % instanceid) return self def wait_for_video_state(self, instanceid, attribute, desired_state, max_patience): def in_desired_state(driver): state = driver.execute_script( 'return document.getElementById("%s").%s' % ( instanceid, attribute)) return state == desired_state self.wait(timeout=max_patience).until(in_desired_state) return self class AssessmentConfirmationPage(RootPage): def verify_correct_submission(self): completion_p = self.find_element_by_css_selector( '.gcb-top-content[role="heading"]') if 'Your score for this assessment is 100%' not in completion_p.text: raise AssertionError('Success indication not found in "%s"' % completion_p.text) return self def verify_incorrect_submission(self): completion_p = self.find_element_by_css_selector( '.gcb-top-content[role="heading"]') if 'Your score for this assessment is 0%' not in completion_p.text: raise AssertionError('Failure indication not found in "%s"' % completion_p.text) return self def return_to_unit(self): self.find_element_by_link_text('Return to Unit').click() return LessonPage(self._tester) class SettingsPage(PageObject): """Page object for the dashboard's course settings tab.""" def __init__(self, tester): super(SettingsPage, self).__init__(tester) def successful_load(unused_driver): tab = self.find_element_by_link_text('Homepage') print tab, tab.get_attribute('class'), tab.get_attribute('href') return 'selected' == tab.get_attribute('class') self.wait().until(successful_load) def click_course_options(self): self.find_element_by_css_selector( '#edit_course_settings > button').click() return CourseOptionsEditorPage(self._tester) class CourseOptionsEditorPage(EditorPageObject): """Page object for the dashboard's course ioptions sub tab.""" def click_close(self): return self._close_and_return_to(SettingsPage) def click_close_and_confirm(self): self.find_element_by_link_text('Close').click() self._tester.driver.switch_to_alert().accept() time.sleep(0.2) return SettingsPage(self._tester) def set_course_name(self, name): course_title_input = self.find_element_by_name('course:title') course_title_input.clear() course_title_input.send_keys(name) return self class AssetsPage(PageObject): """Page object for the dashboard's assets tab.""" def click_sub_tab(self, text): self.find_element_by_link_text(text).click() return self def click_upload(self): self.find_element_by_link_text('Upload to assets/img').click() return AssetsEditorPage(self._tester) def verify_image_file_by_name(self, name): self.find_element_by_link_text(name) # throw exception if not found return self def verify_no_image_file_by_name(self, name): self.wait().until(ec.visibility_of_element_located(( by.By.XPATH, '//h3[starts-with(.,\'Images & Documents\')]'))) try: self.find_element_by_link_text(name) # throw exception if not found raise AssertionError('Found file %s which should be absent' % name) except exceptions.NoSuchElementException: pass return self def click_edit_image(self, name): get_parent_element( self.find_element_by_link_text(name) ).find_element_by_css_selector('a.md-mode-edit').click() return ImageEditorPage(self._tester) def click_add_short_answer(self): self.find_element_by_link_text('Add Short Answer').click() return ShortAnswerEditorPage(self._tester) def click_add_multiple_choice(self): self.find_element_by_link_text('Add Multiple Choice').click() return MultipleChoiceEditorPage(self._tester) def click_add_question_group(self): self.find_element_by_link_text('Add Question Group').click() return QuestionEditorPage(self._tester) def click_edit_short_answer(self, name): raise NotImplementedError def click_edit_mc_question(self): raise NotImplementedError def verify_question_exists(self, description): """Verifies question description exists on list of question banks.""" tds = self._tester.driver.find_elements_by_css_selector( '#gcb-main-content tbody td') for td in tds: try: self._tester.assertEquals(description, td.text) return self except AssertionError: continue raise AssertionError(description + ' not found') def click_question_preview(self): self.find_element_by_css_selector( '#gcb-main-content tbody td .md-visibility').click() return self def verify_question_preview(self, question_text): """Verifies contents of question preview.""" def load_modal_iframe(driver): try: driver.switch_to_frame( driver.find_element_by_css_selector('#modal-window iframe')) except exceptions.NoSuchFrameException: return False else: return True self.wait().until(load_modal_iframe) question = self._tester.driver.find_element_by_css_selector( '.qt-question') self._tester.assertEquals(question_text, question.text) self._tester.driver.switch_to_default_content() self._tester.driver.find_element_by_css_selector( '#modal-window .close-button').click() return self def click_add_label(self): self.find_element_by_link_text('Add Label').click() return LabelEditorPage(self._tester) def verify_label_present(self, title): self.find_element_by_id('label_' + title) # Exception if not found. return self def verify_label_not_present(self, title): try: self.find_element_by_id('label_' + title) # Exception if not found. raise AssertionError('Unexpectedly found label %s' % title) except exceptions.NoSuchElementException: pass return self def click_edit_label(self, title): self.find_element_by_id('label_' + title).click() return LabelEditorPage(self._tester) def click_outline(self): self.find_element_by_link_text('Outline').click() return DashboardPage(self._tester) class AssetsEditorPage(DashboardEditor): """Page object for upload image page.""" def select_file(self, path): self.find_element_by_name('file').send_keys(path) return self def click_upload_and_expect_saved(self): self.find_element_by_link_text('Upload').click() self.expect_status_message_to_be('Saved.') # Page automatically redirects after successful save. self.wait().until(ec.title_contains('Assets')) return AssetsPage(self._tester) class QuestionEditorPage(EditorPageObject): """Abstract superclass for page objects for add/edit questions pages.""" def set_question(self, question): question_el = self.find_element_by_name('question') question_el.clear() question_el.send_keys(question) return self def set_description(self, description): question_el = self.find_element_by_name('description') question_el.clear() question_el.send_keys(description) return self def click_close(self): return self._close_and_return_to(AssetsPage) class MultipleChoiceEditorPage(QuestionEditorPage): """Page object for editing multiple choice questions.""" def click_add_a_choice(self): self.find_element_by_link_text('Add a choice').click() return self def set_answer(self, n, answer): answer_el = self.find_element_by_id('gcbRteField-' + str(2 * n + 1)) answer_el.clear() answer_el.send_keys(answer) return self def click_allow_only_one_selection(self): raise NotImplementedError def click_allow_multiple_selections(self): raise NotImplementedError class ShortAnswerEditorPage(QuestionEditorPage): """Page object for editing short answer questions.""" def click_add_an_answer(self): self.find_element_by_link_text('Add an answer').click() return self def set_score(self, n, score): score_el = self.find_element_by_name('graders[%d]score' % n) score_el.clear() score_el.send_key(score) def set_response(self, n, response): response_el = self.find_element_by_name('graders[%d]response' % n) response_el.clear() response_el.send_key(response) def click_delete_this_answer(self, n): raise NotImplementedError class LabelEditorPage(EditorPageObject): def set_title(self, text): title_el = self.find_element_by_name('title') title_el.clear() title_el.send_keys(text) return self def verify_title(self, text): title_el = self.find_element_by_name('title') self._tester.assertEqual(text, title_el.get_attribute('value')) return self def set_description(self, description): description_el = self.find_element_by_name('description') description_el.clear() description_el.send_keys(description) return self def verify_description(self, description): description_el = self.find_element_by_name('description') self._tester.assertEqual(description, description_el.get_attribute('value')) return self def set_type(self, type_num): type_el = self.find_element_by_id('_inputex_radioId%d' % type_num) type_el.click() return self def verify_type(self, type_num): type_el = self.find_element_by_id('_inputex_radioId%d' % type_num) self._tester.assertEqual('true', type_el.get_attribute('checked')) return self def click_delete(self): self.find_element_by_link_text('Delete').click() return self def confirm_delete(self): self._tester.driver.switch_to_alert().accept() return AssetsPage(self._tester) def click_close(self): return self._close_and_return_to(AssetsPage) class ImageEditorPage(EditorPageObject): """Page object for the dashboard's view/delete image page.""" def click_delete(self): self.find_element_by_link_text('Delete').click() return self def confirm_delete(self): self._tester.driver.switch_to_alert().accept() return AssetsPage(self._tester) class Import(DashboardEditor): """Page object to model the dashboard's unit/lesson organizer.""" pass class AddLink(DashboardEditor): """Page object to model the dashboard's link editor.""" def __init__(self, tester): super(AddLink, self).__init__(tester) self.expect_status_message_to_be( 'New link has been created and saved.') class CourseContentElement(DashboardEditor): RTE_EDITOR_FORMAT = 'gcbRteField-%d_editor' RTE_TEXTAREA_ID = 'gcbRteField-0' def set_title(self, title): title_el = self.find_element_by_name('title') title_el.clear() title_el.send_keys(title) return self def click_rich_text(self, index=0): self.wait_until_status_message_hidden() el = self.find_element_by_css_selector('div.rte-control', index) self._tester.assertIn('showing-html', el.get_attribute('class')) el.find_element_by_class_name('rich-text').click() self.wait().until(ec.element_to_be_clickable( (by.By.ID, CourseContentElement.RTE_EDITOR_FORMAT % index))) return self def click_plain_text(self, index=None): el = self.find_element_by_css_selector('div.rte-control', index) self._tester.assertIn('showing-rte', el.get_attribute('class')) el.find_element_by_class_name('html').click() return self def click_rte_add_custom_tag(self, index=0): self.find_element_by_link_text( 'Insert Google Course Builder component', index).click() return self def select_rte_custom_tag_type(self, option_text): """Select the given option from the custom content type selector.""" self._ensure_rte_iframe_ready_and_switch_to_it() select_tag = self.find_element_by_name('tag') for option in select_tag.find_elements_by_tag_name('option'): if option.text == option_text: option.click() break else: self._tester.fail('No option "%s" found' % option_text) self.wait().until(ec.element_to_be_clickable( (by.By.PARTIAL_LINK_TEXT, 'Close'))) self._tester.driver.switch_to_default_content() return self def _ensure_rte_iframe_ready_and_switch_to_it(self): self.wait().until( ec.frame_to_be_available_and_switch_to_it('modal-editor-iframe')) # Ensure inputEx has initialized too self.wait().until( ec.element_to_be_clickable( (by.By.PARTIAL_LINK_TEXT, 'Close'))) def set_rte_lightbox_field(self, field_css_selector, value): self._ensure_rte_iframe_ready_and_switch_to_it() field = self.find_element_by_css_selector(field_css_selector) field.clear() field.send_keys(value) self._tester.driver.switch_to_default_content() return self def click_rte_save(self): self._ensure_rte_iframe_ready_and_switch_to_it() self.find_element_by_link_text('Save').click() self._tester.driver.switch_to_default_content() return self def send_rte_text(self, text): # Work around Selenium bug: If focus is in another window # and in a text area, send_keys won't work. Steal focus # immediately before sending keys. # https://code.google.com/p/selenium/issues/detail?id=2977 self._tester.driver.execute_script('window.focus();') textarea = self.find_element_by_id('gcbRteField-0_editor') textarea.click() textarea.send_keys(keys.Keys.HOME) textarea.send_keys(text) return self def doubleclick_rte_element(self, elt_css_selector, index=0): self._tester.driver.switch_to_frame( CourseContentElement.RTE_EDITOR_FORMAT % index) target = self.find_element_by_css_selector(elt_css_selector) action_chains.ActionChains( self._tester.driver).double_click(target).perform() self._tester.driver.switch_to_default_content() return self def ensure_rte_lightbox_field_has_value(self, field_css_selector, value): self._ensure_rte_iframe_ready_and_switch_to_it() self._tester.assertEqual( value, self.find_element_by_css_selector( field_css_selector).get_attribute('value')) self._tester.driver.switch_to_default_content() return self def _get_rte_contents(self): return self.find_element_by_id( CourseContentElement.RTE_TEXTAREA_ID).get_attribute('value') def _get_instanceid_list(self): """Returns a list of the instanceid attrs in the lesson body.""" html = self._get_rte_contents() html_list = html.split(' instanceid="') instanceid_list = [] for item in html_list[1:]: closing_quote_ind = item.find('"') instanceid_list.append(item[:closing_quote_ind]) return instanceid_list def ensure_instanceid_count_equals(self, value): self._tester.assertEqual(value, len(self._get_instanceid_list())) return self def take_snapshot_of_instanceid_list(self, list_to_fill=None): self.instanceid_list_snapshot = self._get_instanceid_list() if list_to_fill is not None: list_to_fill.extend(self.instanceid_list_snapshot) return self def ensure_instanceid_list_matches_last_snapshot(self): self._tester.assertEqual( self.instanceid_list_snapshot, self._get_instanceid_list()) return self def _codemirror_is_ready_builder(self, nth_instance): def codemirror_is_ready(unused_driver): return self._tester.driver.execute_script( "return $('.CodeMirror')[%s]" ".CodeMirror.gcbCodeMirrorMonitor.cmReady;" % nth_instance) return codemirror_is_ready def setvalue_codemirror(self, nth_instance, code_body): self.wait().until(self._codemirror_is_ready_builder(nth_instance)) self._tester.driver.execute_script( "$('.CodeMirror')[%s].CodeMirror.setValue('%s');" % ( nth_instance, code_body)) return self def assert_equal_codemirror(self, nth_instance, expected_code_body): self.wait().until(self._codemirror_is_ready_builder(nth_instance)) actual_code_body = self._tester.driver.execute_script( "return $('.CodeMirror')[%s].CodeMirror.getValue();" % nth_instance) self._tester.assertEqual(expected_code_body, actual_code_body) return self class AddUnit(CourseContentElement): """Page object to model the dashboard's add unit editor.""" CREATION_MESSAGE = 'New unit has been created and saved.' LOADED_MESSAGE = 'Success.' INDEX_UNIT_HEADER = 0 INDEX_UNIT_FOOTER = 1 def __init__(self, tester, expected_message): super(AddUnit, self).__init__(tester) self.expect_status_message_to_be(expected_message) def set_pre_assessment(self, assessment_name): select.Select(self.find_element_by_name( 'pre_assessment')).select_by_visible_text(assessment_name) return self def set_post_assessment(self, assessment_name): select.Select(self.find_element_by_name( 'post_assessment')).select_by_visible_text(assessment_name) return self def set_contents_on_one_page(self, setting): print labels = self._tester.driver.find_elements_by_tag_name('label') one_page_label = None for label in labels: if label.text == 'Show Contents on One Page': one_page_label = label break label_div = one_page_label.find_element_by_xpath('..') checkbox_div = label_div.find_element_by_xpath('..') checkbox = checkbox_div.find_element_by_css_selector( 'input[type="checkbox"]') if checkbox.is_selected() != setting: checkbox.click() return self class AddAssessment(CourseContentElement): """Page object to model the dashboard's assessment editor.""" INDEX_CONTENT = 0 INDEX_REVIEWER_FEEDBACK = 1 def __init__(self, tester): super(AddAssessment, self).__init__(tester) self.expect_status_message_to_be( 'New assessment has been created and saved.') class AddLesson(CourseContentElement): """Page object to model the dashboard's lesson editor.""" def __init__(self, tester): super(AddLesson, self).__init__(tester) self.instanceid_list_snapshot = [] self.expect_status_message_to_be( 'New lesson has been created and saved.') def ensure_lesson_body_textarea_matches_regex(self, regex): rte_contents = self._get_rte_contents() self._tester.assertRegexpMatches(rte_contents, regex) return self def set_questions_are_scored(self): select.Select(self.find_element_by_name( 'scored')).select_by_visible_text('Questions are scored') return self def set_questions_give_feedback(self): select.Select(self.find_element_by_name( 'scored')).select_by_visible_text('Questions only give feedback') return self class AdminPage(PageObject): """Page object to model the interactions with the admimn landing page.""" def click_add_course(self): self.find_element_by_id('add_course').click() return AddCourseEditorPage(self._tester) def click_settings(self): sub_nav_bar = self._tester.driver.find_element_by_css_selector( '.gcb-nav-bar-level-2') sub_nav_bar.find_element_by_link_text('Site Settings').click() return AdminSettingsPage(self._tester) class AdminSettingsPage(PageObject): """Page object for the admin settings.""" def click_override_admin_user_emails(self): self._tester.driver.find_elements_by_css_selector( 'button.gcb-button')[0].click() return ConfigPropertyOverridePage(self._tester) def click_override(self, setting_name): self.find_element_by_id(setting_name).click() return ConfigPropertyOverridePage(self._tester) def verify_admin_user_emails_contains(self, email): self._tester.assertTrue( email in self._tester.driver.find_elements_by_css_selector( 'table.gcb-config tr')[1].find_elements_by_css_selector( 'td')[1].text) class ConfigPropertyOverridePage(EditorPageObject): """Page object for the admin property override editor.""" def clear_value(self): element = self.find_element_by_name('value') element.clear() return self def set_value(self, value): element = self.find_element_by_name('value') if type(value) is bool: current_value = element.get_attribute('value').lower() if str(value).lower() != current_value: checkbox = get_parent_element( element).find_element_by_css_selector('[type="checkbox"]') checkbox.send_keys(' ') # Toggle, iff necessary. else: element.send_keys(value) return self def click_close(self): return self._close_and_return_to(AdminSettingsPage) class AddCourseEditorPage(EditorPageObject): """Page object for the dashboards' add course page.""" def set_fields(self, name=None, title=None, email=None): """Populate the fields in the add course page.""" name_el = self.find_element_by_name('name') title_el = self.find_element_by_name('title') email_el = self.find_element_by_name('admin_email') name_el.clear() title_el.clear() email_el.clear() if name: name_el.send_keys(name) if title: title_el.send_keys(title) if email: email_el.send_keys(email) return self def click_close(self): return self._close_and_return_to(AdminPage) class AnalyticsPage(PageObject): """Page object for analytics sub-tab.""" def wait_until_logs_not_empty(self, data_source): def data_source_logs_not_empty(unused_driver): return self.get_data_source_logs(data_source) self.wait().until(data_source_logs_not_empty) return self def get_data_page_number(self, data_source): # When there is a chart on the page, the chart-drawing animation # takes ~1 sec to complete, which blocks the JS to unpack and paint # the data page numbers. max_wait = time.time() + 10 text = self.find_element_by_id('model_visualizations_dump').text while not text and time.time() < max_wait: time.sleep(0.1) text = self.find_element_by_id('model_visualizations_dump').text numbers = {} for line in text.split('\n'): name, value = line.split('=') numbers[name] = int(value) return numbers[data_source] def get_displayed_page_number(self, data_source): return self.find_element_by_id('gcb_rest_source_page_number_' + data_source).text def get_data_source_logs(self, data_source): return self.find_element_by_id( 'gcb_log_rest_source_' + data_source).text def get_page_level_logs(self): return self.find_element_by_id('gcb_rest_source_errors').text def click(self, data_source, button): name = 'gcb_rest_source_page_request_' + button + '_' + data_source self.find_element_by_id(name).click() def buttons_present(self, data_source): try: self.find_element_by_id('gcb_rest_source_request_zero_' + data_source) return True except exceptions.NoSuchElementException: return False def set_chunk_size(self, data_source, chunk_size): field = self.find_element_by_id( 'gcb_rest_source_chunk_size_' + data_source) field.clear() field.send_keys(str(chunk_size)) def answers_pie_chart_present(self): div = self.find_element_by_id('answers_pie_chart') svgs = div.find_elements_by_tag_name('svg') return len(svgs) > 0 class AppengineAdminPage(PageObject): def __init__(self, tester, base_url, course_name): super(AppengineAdminPage, self).__init__(tester) self._base_url = base_url self._course_name = course_name def get_datastore(self, entity_kind): self.get( self._base_url + '/datastore' + '?namespace=ns_%s' % self._course_name + '&kind=%s' % entity_kind) return DatastorePage(self._tester) class DatastorePage(PageObject): def get_items(self): data_table = self._tester.driver.find_element_by_css_selector( 'table.ae-table') title_elements = data_table.find_elements_by_css_selector( 'table.ae-table th') for index, element in enumerate(title_elements): if element.text.strip() == 'Key': key_index = index rows = data_table.find_elements_by_css_selector('tr') data_urls = [] for row in rows: cells = row.find_elements_by_css_selector('td') if len(cells) > key_index: url = cells[key_index].find_elements_by_tag_name( 'a')[0].get_attribute('href') data_urls.append(url) data = [] for data_url in data_urls: self.get(data_url) rows = self._tester.driver.find_elements_by_css_selector( 'div.ae-settings-block') item = {} data.append(item) for row in rows: labels = row.find_elements_by_tag_name('label') if labels: name = re.sub(r'\(.*\)', '', labels[0].text).strip() value_blocks = row.find_elements_by_tag_name('div') if value_blocks: inputs = value_blocks[0].find_elements_by_tag_name( 'input') if inputs: value = inputs[0].get_attribute('value').strip() else: value = value_blocks[0].text.strip() item[name] = value self._tester.driver.back() return data
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for extra tabs added to the navbar.""" __author__ = 'John Orr (jorr@google.com)' from controllers import sites from models import courses from models import resources_display from models import models from modules.i18n_dashboard.i18n_dashboard import ResourceBundleDAO from modules.i18n_dashboard.i18n_dashboard import ResourceBundleDTO from modules.i18n_dashboard.i18n_dashboard import ResourceBundleKey from tests.functional import actions from google.appengine.api import namespace_manager ADMIN_EMAIL = 'admin@foo.com' COURSE_NAME = 'extra_tabs_course' SENDER_EMAIL = 'sender@foo.com' STUDENT_EMAIL = 'student@foo.com' STUDENT_NAME = 'A. Student' class ExtraTabsTests(actions.TestBase): def setUp(self): super(ExtraTabsTests, self).setUp() self.base = '/' + COURSE_NAME app_context = actions.simple_add_course( COURSE_NAME, ADMIN_EMAIL, 'Extra Tabs Course') self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % COURSE_NAME) self.course = courses.Course(None, app_context) courses.Course.ENVIRON_TEST_OVERRIDES = { 'course': { 'extra_tabs': [ { 'label': 'FAQ', 'position': 'left', 'visibility': 'all', 'url': '', 'content': 'Frequently asked questions'}, { 'label': 'Resources', 'position': 'right', 'visibility': 'student', 'url': 'http://www.example.com', 'content': 'Links to resources'}] } } self.faq_url = 'modules/extra_tabs/render?index=0' actions.login(STUDENT_EMAIL, is_admin=False) actions.register(self, STUDENT_NAME) def tearDown(self): del sites.Registry.test_overrides[sites.GCB_COURSES_CONFIG.name] namespace_manager.set_namespace(self.old_namespace) courses.Course.ENVIRON_TEST_OVERRIDES = {} super(ExtraTabsTests, self).tearDown() def test_extra_tabs_on_navbar_visible_to_students(self): body = self.get('course').body self.assertIn('FAQ', body) self.assertIn('Resources', body) def test_extra_tabs_on_navbar_visible_to_everyone(self): actions.logout() body = self.get('course').body self.assertIn('FAQ', body) self.assertNotIn('Resources', body) def test_extra_tabs_with_url_point_to_target(self): dom = self.parse_html_string(self.get('course').body) resources_el = dom.find('.//div[@id="gcb-nav-x"]//ul/li[5]/a') self.assertEquals('Resources', resources_el.text) self.assertEquals('http://www.example.com', resources_el.attrib['href']) def test_extra_tabs_with_content_point_to_page(self): dom = self.parse_html_string(self.get('course').body) faq_el = dom.find('.//div[@id="gcb-nav-x"]//ul/li[4]/a') self.assertEquals('FAQ', faq_el.text) self.assertEquals(self.faq_url, faq_el.attrib['href']) def test_content_handler_delivers_page(self): self.assertIn('Frequently asked questions', self.get(self.faq_url)) def test_tabs_are_aligned_correctly(self): dom = self.parse_html_string(self.get('course').body) faq_li = dom.find('.//div[@id="gcb-nav-x"]//ul/li[4]') self.assertIsNone(faq_li.attrib.get('class')) resources_li = dom.find('.//div[@id="gcb-nav-x"]//ul/li[5]') self.assertIn('gcb-pull-right', resources_li.attrib['class']) def test_tabs_are_translated(self): courses.Course.ENVIRON_TEST_OVERRIDES['extra_locales'] = { 'availability': 'available', 'locale': 'el'} prefs = models.StudentPreferencesDAO.load_or_create() prefs.locale = 'el' models.StudentPreferencesDAO.save(prefs) bundle = { 'course:extra_tabs:[0]:label': { 'type': 'string', 'source_value': None, 'data': [ {'source_value': 'FAQ', 'target_value': 'faq'}]}, 'course:extra_tabs:[0]:content': { 'type': 'html', 'source_value': 'Frequently asked questions', 'data': [{ 'source_value': 'Frequently asked questions', 'target_value': 'fREQUENTLY aSKED qUESTIONS'}]}} key_el = ResourceBundleKey( resources_display.ResourceCourseSettings.TYPE, 'homepage', 'el') ResourceBundleDAO.save(ResourceBundleDTO(str(key_el), bundle)) dom = self.parse_html_string(self.get('course').body) faq_el = dom.find('.//div[@id="gcb-nav-x"]//ul/li[4]/a') self.assertEquals('faq', faq_el.text) self.assertEquals(self.faq_url, faq_el.attrib['href']) self.assertIn('fREQUENTLY aSKED qUESTIONS', self.get(self.faq_url))
Python
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Functional tests for models.models.""" __author__ = [ 'johncox@google.com (John Cox)', ] import datetime from models import entities from models import entity_transforms from models import transforms from tests.functional import actions from google.appengine.ext import db class FirstChild(entities.BaseEntity): first_kept = db.Property() first_removed = db.Property() _PROPERTY_EXPORT_BLACKLIST = [first_removed] class SecondChild(FirstChild): second_kept = db.Property() second_removed = db.Property() _PROPERTY_EXPORT_BLACKLIST = [second_removed] class MockStudent(entities.BaseEntity): name = db.StringProperty(indexed=False) class_rank = db.IntegerProperty(indexed=False) additional_fields = db.TextProperty(indexed=False) _PROPERTY_EXPORT_BLACKLIST = [ 'name', 'additional_fields.age', 'additional_fields.gender', 'additional_fields.hobby.cost', ] class BaseEntityTestCase(actions.TestBase): # Disable complaints about docstrings for self-documenting tests. def test_for_export_returns_populated_export_entity_with_key(self): first_kept = 'first_kept' second_kept = 'second_kept' second = SecondChild(first_kept=first_kept, second_kept=second_kept) db.put(second) second_export = second.for_export(lambda x: x) self.assertEqual(first_kept, second_export.first_kept) self.assertEqual(second_kept, second_export.second_kept) self.assertEqual(second.key(), second_export.safe_key) def test_for_export_removes_properties_up_inheritance_chain(self): first = FirstChild() second = SecondChild() db.put([first, second]) first_export = first.for_export(lambda x: x) second_export = second.for_export(lambda x: x) self.assertTrue(hasattr(first_export, FirstChild.first_kept.name)) self.assertFalse(hasattr(first_export, FirstChild.first_removed.name)) self.assertTrue(hasattr(second_export, SecondChild.first_kept.name)) self.assertTrue(hasattr(second_export, SecondChild.second_kept.name)) self.assertFalse(hasattr(second_export, SecondChild.first_removed.name)) self.assertFalse( hasattr(second_export, SecondChild.second_removed.name)) def test_blacklist_by_name(self): additional = transforms.dict_to_nested_lists_as_string({ 'age': 37, 'class_goal': 'Completion', 'gender': 'Male', 'hobby': transforms.dict_to_nested_lists_as_string({ 'name': 'woodworking', 'level': 'journeyman', 'cost': 10000, }) }) blacklisted = transforms.dict_to_nested_lists_as_string({ 'class_goal': 'Completion', 'hobby': transforms.dict_to_nested_lists_as_string({ 'name': 'woodworking', 'level': 'journeyman', }) }) mock_student = MockStudent(name='John Smith', class_rank=23, additional_fields=additional) db.put(mock_student) data = mock_student.for_export(lambda x: x) self.assertFalse(hasattr(data, 'name')) self.assertEquals(23, data.class_rank) self.assertEquals(blacklisted, data.additional_fields) class ExportEntityTestCase(actions.TestBase): def setUp(self): super(ExportEntityTestCase, self).setUp() self.entity = entities.ExportEntity(safe_key='foo') def test_constructor_requires_safe_key(self): self.assertRaises(AssertionError, entities.ExportEntity) def test_put_raises_not_implemented_error(self): self.assertRaises(NotImplementedError, self.entity.put) class TestEntity(entities.BaseEntity): prop_int = db.IntegerProperty() prop_float = db.FloatProperty(required=True) prop_bool = db.BooleanProperty() prop_string = db.StringProperty() prop_text = db.TextProperty() prop_date = db.DateProperty() prop_datetime = db.DateTimeProperty() prop_intlist = db.ListProperty(int) prop_stringlist = db.StringListProperty() prop_ref = db.SelfReferenceProperty() class DefaultConstructableEntity(entities.BaseEntity): prop_int = db.IntegerProperty() prop_float = db.FloatProperty() prop_bool = db.BooleanProperty() prop_string = db.StringProperty() prop_text = db.TextProperty() prop_date = db.DateProperty() prop_datetime = db.DateTimeProperty() prop_intlist = db.ListProperty(int) prop_stringlist = db.StringListProperty() prop_ref = db.SelfReferenceProperty() class EntityTransformsTest(actions.TestBase): def test_class_schema(self): registry = entity_transforms.get_schema_for_entity(TestEntity) schema = registry.get_json_schema_dict() self.assertEquals(schema['type'], 'object') self.assertEquals(schema['id'], 'TestEntity') props = schema['properties'] self.assertTrue(props['prop_int']['optional']) self.assertEquals(props['prop_int']['type'], 'integer') self.assertNotIn('optional', props['prop_float']) self.assertEquals(props['prop_float']['type'], 'number') self.assertTrue(props['prop_bool']['optional']) self.assertEquals(props['prop_bool']['type'], 'boolean') self.assertTrue(props['prop_string']['optional']) self.assertEquals(props['prop_string']['type'], 'string') self.assertTrue(props['prop_text']['optional']) self.assertEquals(props['prop_text']['type'], 'text') self.assertTrue(props['prop_date']['optional']) self.assertEquals(props['prop_date']['type'], 'date') self.assertTrue(props['prop_datetime']['optional']) self.assertEquals(props['prop_datetime']['type'], 'datetime') self.assertEquals(props['prop_intlist']['type'], 'array') self.assertTrue(props['prop_intlist']['items']['optional']) self.assertEquals(props['prop_intlist']['items']['type'], 'integer') self.assertEquals(props['prop_stringlist']['type'], 'array') self.assertTrue(props['prop_stringlist']['items']['optional']) self.assertEquals(props['prop_stringlist']['items']['type'], 'string') self.assertTrue(props['prop_ref']['optional']) self.assertEquals(props['prop_ref']['type'], 'string') def _verify_contents_equal(self, recovered_entity, test_entity): self.assertEquals(recovered_entity.prop_int, test_entity.prop_int) self.assertEquals(recovered_entity.prop_float, test_entity.prop_float) self.assertEquals(recovered_entity.prop_bool, test_entity.prop_bool) self.assertEquals(recovered_entity.prop_string, test_entity.prop_string) self.assertEquals(recovered_entity.prop_text, test_entity.prop_text) self.assertEquals(recovered_entity.prop_date, test_entity.prop_date) self.assertEquals(recovered_entity.prop_datetime, test_entity.prop_datetime) self.assertEquals(recovered_entity.prop_intlist, test_entity.prop_intlist) self.assertEquals(recovered_entity.prop_stringlist, test_entity.prop_stringlist) if test_entity.prop_ref is None: self.assertIsNone(recovered_entity.prop_ref) else: self.assertEquals(recovered_entity.prop_ref.key(), test_entity.prop_ref.key()) def test_roundtrip_conversion_all_members_set(self): referent = TestEntity(key_name='that_one_over_there', prop_float=2.71) referent.put() test_entity = TestEntity( prop_int=123, prop_float=3.14, prop_bool=True, prop_string='Mary had a little lamb', prop_text='She fed it beans and buns', prop_date=datetime.date.today(), prop_datetime=datetime.datetime.now(), prop_intlist=[4, 3, 2, 1], prop_stringlist=['Flopsy', 'Mopsy', 'Cottontail'], prop_ref=referent ) test_entity.put() converted = entity_transforms.entity_to_dict(test_entity) init_dict = entity_transforms.json_dict_to_entity_initialization_dict( TestEntity, converted) recovered_entity = TestEntity(**init_dict) self._verify_contents_equal(recovered_entity, test_entity) def test_roundtrip_conversion_optional_members_none(self): test_entity = TestEntity( prop_int=None, prop_float=2.31, prop_bool=None, prop_string=None, prop_text=None, prop_date=None, prop_datetime=None, prop_intlist=[], prop_stringlist=[], prop_ref=None ) test_entity.put() converted = entity_transforms.entity_to_dict(test_entity) init_dict = entity_transforms.json_dict_to_entity_initialization_dict( TestEntity, converted) recovered_entity = TestEntity(**init_dict) self._verify_contents_equal(recovered_entity, test_entity) def test_roundtrip_conversion_default_constructable(self): referent = DefaultConstructableEntity(key_name='that_one_over_there') referent.put() test_entity = DefaultConstructableEntity( prop_int=123, prop_float=3.14, prop_bool=True, prop_string='Mary had a little lamb', prop_text='She fed it beans and buns', prop_date=datetime.date.today(), prop_datetime=datetime.datetime.now(), prop_intlist=[4, 3, 2, 1], prop_stringlist=['Flopsy', 'Mopsy', 'Cottontail'], prop_ref=referent ) test_entity.put() converted = entity_transforms.entity_to_dict(test_entity) recovered_entity = DefaultConstructableEntity() entity_transforms.dict_to_entity(recovered_entity, converted) self._verify_contents_equal(recovered_entity, test_entity)
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Verify operation of student setting to remember last page visited.""" from common import utils as common_utils from controllers import sites from models import config from models import courses from models import models from tests.functional import actions COURSE_NAME = 'test_course' COURSE_TITLE = 'Test Course' NAMESPACE = 'ns_%s' % COURSE_NAME ADMIN_EMAIL = 'admin@foo.com' BASE_URL = '/%s' % COURSE_NAME COURSE_URL = '/%s/course' % COURSE_NAME REGISTERED_STUDENT_EMAIL = 'foo@bar.com' REGISTERED_STUDENT_NAME = 'John Smith' UNREGISTERED_STUDENT_EMAIL = 'bar@bar.com' class StudentRedirectTestBase(actions.TestBase): def setUp(self): super(StudentRedirectTestBase, self).setUp() context = actions.simple_add_course(COURSE_NAME, ADMIN_EMAIL, COURSE_TITLE) course = courses.Course(None, context) self.unit = course.add_unit() self.unit.title = 'The Unit' self.unit.now_available = True self.lesson_one = course.add_lesson(self.unit) self.lesson_one.title = 'Lesson One' self.lesson_one.now_available = True self.lesson_two = course.add_lesson(self.unit) self.lesson_two.title = 'Lesson Two' self.lesson_two.now_available = True self.assessment = course.add_assessment() self.assessment.title = 'The Assessment' self.assessment.now_available = True course.save() actions.login(REGISTERED_STUDENT_EMAIL) actions.register(self, REGISTERED_STUDENT_NAME, COURSE_NAME) # Actions.register views the student's profile page; clear this out. with common_utils.Namespace(NAMESPACE): prefs = models.StudentPreferencesDAO.load_or_create() prefs.last_location = None models.StudentPreferencesDAO.save(prefs) class NonRootCourse(StudentRedirectTestBase): def test_load_base_with_no_pref_gives_no_redirect(self): response = self.get(BASE_URL) self.assertEquals(200, response.status_int) def test_unregistered_student_does_not_use_prefs(self): actions.login(UNREGISTERED_STUDENT_EMAIL) response = self.get(BASE_URL) response = response.click('Unit 1 - The Unit') response = self.get(BASE_URL) self.assertEquals(200, response.status_int) def test_logged_out_does_not_use_prefs(self): actions.logout() response = self.get(BASE_URL) response = response.click('Unit 1 - The Unit') response = self.get(BASE_URL) self.assertEquals(200, response.status_int) def _test_redirects(self, saved_path): response = self.get(BASE_URL) self.assertEquals(302, response.status_int) self.assertEquals(saved_path, response.location) response = self.get(BASE_URL + '/') self.assertEquals(302, response.status_int) self.assertEquals(saved_path, response.location) def test_redirects_to_unit(self): response = self.get(BASE_URL) response = self.click(response, 'Unit 1 - The Unit') self._test_redirects(response.request.url) def test_redirects_to_lesson(self): response = self.get(BASE_URL) response = self.click(response, 'Unit 1 - The Unit') response = self.click(response, 'Next Page') self._test_redirects(response.request.url) def test_redirects_to_assessment(self): response = self.get(BASE_URL) response = self.click(response, 'The Assessment') self._test_redirects(response.request.url) def test_redirects_to_profile(self): response = self.get(BASE_URL) response = self.click(response, 'Progress') self._test_redirects(response.request.url) def test_redirects_to_course(self): response = self.get(COURSE_URL) self._test_redirects(response.request.url) def test_course_does_not_redirect(self): response = self.get(COURSE_URL) response = response.click('Unit 1 - The Unit') response = self.get(COURSE_URL) self.assertEquals(200, response.status_int) class RootCourse(StudentRedirectTestBase): def setUp(self): super(RootCourse, self).setUp() config.Registry.test_overrides[sites.GCB_COURSES_CONFIG.name] = ( 'course:/default:/, course:/::ns_test_course') def tearDown(self): super(RootCourse, self).tearDown() config.Registry.test_overrides.clear() def test_root_redirects(self): response = self.get('/') self.assertEquals(302, response.status_int) self.assertEquals('http://localhost/course?use_last_location=true', response.location) def test_root_with_no_pref_does_not_redirect_beyond_course(self): response = self.get('/').follow() self.assertEquals(200, response.status_int) self.assertIn('The Unit', response.body) def test_root_with_pref_redirects(self): response = self.get('/').follow() response = self.click(response, 'Unit 1 - The Unit') saved_path = response.request.url response = self.get('/').follow() self.assertEquals(302, response.status_int) self.assertEquals(saved_path, response.location)
Python
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Functional tests for modules/review/peer.py.""" __author__ = [ 'johncox@google.com (John Cox)', ] from models import models from models import student_work from modules.review import domain from modules.review import peer from tests.functional import actions from google.appengine.ext import db class ReviewStepTest(actions.ExportTestBase): def setUp(self): super(ReviewStepTest, self).setUp() self.reviewee_email = 'reviewee@example.com' self.reviewee_key = models.Student(key_name=self.reviewee_email).put() self.reviewer_email = 'reviewer@example.com' self.reviewer_key = models.Student(key_name=self.reviewer_email).put() self.unit_id = 'unit_id' self.submission_key = student_work.Submission( reviewee_key=self.reviewee_key, unit_id=self.unit_id).put() self.review_key = student_work.Review( reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, unit_id=self.unit_id).put() self.review_summary_key = peer.ReviewSummary( reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id).put() self.step = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, review_key=self.review_key, review_summary_key=self.review_summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, state=domain.REVIEW_STATE_ASSIGNED, submission_key=self.submission_key, unit_id=self.unit_id) self.step_key = self.step.put() def test_constructor_sets_key_name(self): """Tests construction of key_name, put of entity with key_name set.""" self.assertEqual( peer.ReviewStep.key_name(self.submission_key, self.reviewer_key), self.step_key.name()) def test_for_export_transforms_correctly(self): exported = self.step.for_export(self.transform) self.assert_blacklisted_properties_removed(self.step, exported) self.assertEqual( student_work.Review.safe_key(self.review_key, self.transform), exported.review_key) self.assertEqual( peer.ReviewSummary.safe_key( self.review_summary_key, self.transform), exported.review_summary_key) self.assertEqual( models.Student.safe_key(self.reviewee_key, self.transform), exported.reviewee_key) self.assertEqual( models.Student.safe_key(self.reviewer_key, self.transform), exported.reviewer_key) self.assertEqual( student_work.Submission.safe_key( self.submission_key, self.transform), exported.submission_key) def test_safe_key_transforms_or_retains_sensitive_data(self): original_key = peer.ReviewStep.safe_key(self.step_key, lambda x: x) transformed_key = peer.ReviewStep.safe_key( self.step_key, self.transform) get_reviewee_key_name = ( lambda x: x.split('%s:' % self.unit_id)[-1].split(')')[0]) get_reviewer_key_name = lambda x: x.rsplit(':')[-1].strip(')') self.assertEqual( self.reviewee_email, get_reviewee_key_name(original_key.name())) self.assertEqual( self.reviewer_email, get_reviewer_key_name(original_key.name())) self.assertEqual( 'transformed_' + self.reviewee_email, get_reviewee_key_name(transformed_key.name())) self.assertEqual( 'transformed_' + self.reviewer_email, get_reviewer_key_name(transformed_key.name())) class ReviewSummaryTest(actions.ExportTestBase): def setUp(self): super(ReviewSummaryTest, self).setUp() self.unit_id = 'unit_id' self.reviewee_email = 'reviewee@example.com' self.reviewee_key = models.Student( key_name='reviewee@example.com').put() self.submission_key = student_work.Submission( reviewee_key=self.reviewee_key, unit_id=self.unit_id).put() self.summary = peer.ReviewSummary( reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id) self.summary_key = self.summary.put() def test_constructor_sets_key_name(self): summary_key = peer.ReviewSummary( reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id).put() self.assertEqual( peer.ReviewSummary.key_name(self.submission_key), summary_key.name()) def test_decrement_count(self): """Tests decrement_count.""" summary = peer.ReviewSummary( assigned_count=1, completed_count=1, expired_count=1, reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id) self.assertEqual(1, summary.assigned_count) summary.decrement_count(domain.REVIEW_STATE_ASSIGNED) self.assertEqual(0, summary.assigned_count) self.assertEqual(1, summary.completed_count) summary.decrement_count(domain.REVIEW_STATE_COMPLETED) self.assertEqual(0, summary.completed_count) self.assertEqual(1, summary.expired_count) summary.decrement_count(domain.REVIEW_STATE_EXPIRED) self.assertEqual(0, summary.expired_count) self.assertRaises(ValueError, summary.decrement_count, 'bad_state') def test_increment_count(self): """Tests increment_count.""" summary = peer.ReviewSummary( reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id) self.assertRaises(ValueError, summary.increment_count, 'bad_state') self.assertEqual(0, summary.assigned_count) summary.increment_count(domain.REVIEW_STATE_ASSIGNED) self.assertEqual(1, summary.assigned_count) self.assertEqual(0, summary.completed_count) summary.increment_count(domain.REVIEW_STATE_COMPLETED) self.assertEqual(1, summary.completed_count) self.assertEqual(0, summary.expired_count) summary.increment_count(domain.REVIEW_STATE_EXPIRED) self.assertEqual(1, summary.expired_count) check_overflow = peer.ReviewSummary( assigned_count=domain.MAX_UNREMOVED_REVIEW_STEPS - 1, reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id) # Increment to the limit succeeds... check_overflow.increment_count(domain.REVIEW_STATE_ASSIGNED) # ...but not beyond. self.assertRaises( db.BadValueError, check_overflow.increment_count, domain.REVIEW_STATE_ASSIGNED) def test_for_export_transforms_correctly(self): exported = self.summary.for_export(self.transform) self.assert_blacklisted_properties_removed(self.summary, exported) self.assertEqual( models.Student.safe_key(self.reviewee_key, self.transform), exported.reviewee_key) self.assertEqual( student_work.Submission.safe_key( self.submission_key, self.transform), exported.submission_key) def test_safe_key_transforms_or_retains_sensitive_data(self): original_key = peer.ReviewSummary.safe_key( self.summary_key, lambda x: x) transformed_key = peer.ReviewSummary.safe_key( self.summary_key, self.transform) get_reviewee_key_name = lambda x: x.rsplit(':', 1)[-1].strip(')') self.assertEqual( self.reviewee_email, get_reviewee_key_name(original_key.name())) self.assertEqual( 'transformed_' + self.reviewee_email, get_reviewee_key_name(transformed_key.name()))
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Functional tests for the oeditor module.""" __author__ = [ 'John Cox (johncox@google.com)', ] from models import config from models import courses from tests.functional import actions class ObjectEditorTest(actions.TestBase): def tearDown(self): config.Registry.test_overrides = {} super(ObjectEditorTest, self).tearDown() def get_oeditor_dom(self): actions.login('test@example.com', is_admin=True) response = self.get( '/admin?action=config_edit&name=gcb_admin_user_emails') return self.parse_html_string(response.body) def get_script_tag_by_src(self, src): return self.get_oeditor_dom().find('.//script[@src="%s"]' % src) def test_get_drive_tag_parent_frame_script_src_empty_if_apis_disabled(self): self.assertIsNone(self.get_script_tag_by_src( '/modules/core_tags/resources/drive_tag_parent_frame.js')) def test_get_drive_tag_parent_frame_script_src_set_if_apis_enabled(self): config.Registry.test_overrides[ courses.COURSES_CAN_USE_GOOGLE_APIS.name] = True self.assertIsNotNone(self.get_script_tag_by_src( '/modules/core_tags/resources/drive_tag_parent_frame.js')) def test_get_drive_tag_script_manager_script_src_empty_if_apis_disabled( self): self.assertIsNone(self.get_script_tag_by_src( '/modules/core_tags/resources/drive_tag_script_manager.js')) def test_get_drive_tag_script_manager_script_src_set_if_apis_enabled( self): config.Registry.test_overrides[ courses.COURSES_CAN_USE_GOOGLE_APIS.name] = True self.assertIsNotNone(self.get_script_tag_by_src( '/modules/core_tags/resources/drive_tag_script_manager.js'))
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test module configuration script.""" __author__ = 'Mike Gainer (mgainer@google.com)' import cStringIO import logging import os import shutil import sys import tempfile import traceback import unittest import appengine_config from common import yaml_files from scripts import modules as module_config class TestWithTempDir(unittest.TestCase): def setUp(self): super(TestWithTempDir, self).setUp() self._tmpdir = tempfile.mkdtemp() def tearDown(self): super(TestWithTempDir, self).tearDown() shutil.rmtree(self._tmpdir, ignore_errors=True) def _dump_dir(self, _, dirname, names): for name in names: path = os.path.join(dirname, name) if not os.path.isdir(path): print '-------------------------', path with open(path) as fp: print fp.read() def _dump_tree(self): os.path.walk(self._tmpdir, self._dump_dir, None) def _write_content(self, path, content): with open(path, 'w') as fp: for line in content: fp.write(line) def _assert_content_equals(self, path, expected_lines): with open(path) as fp: actual_lines = fp.readlines() self.assertEquals(expected_lines, actual_lines) class ManipulateAppYamlFileTest(TestWithTempDir): def setUp(self): super(ManipulateAppYamlFileTest, self).setUp() self._yaml_path = os.path.join(self._tmpdir, 'app.yaml') self._minimal_content = [ '\n', '\n', 'libraries:\n', '- name: jinja2\n', ' version: "2.6"\n', '\n', 'env_variables:\n', ' FOO: bar\n', ' BAR: bleep\n', ] def test_read_write_unchanged(self): parsed_content = ( '\n' '\n' 'libraries:\n' '- name: jinja2\n' ' version: "2.6"\n' '\n' 'env_variables:\n' ' FOO: bar\n' 'scalar_str: "string"\n' 'scalar_int: 123\n' 'scalar_bool: true\n' 'dict:\n' ' foo1: bar\n' ' foo2: 123\n' ' foo3: true\n' 'list:\n' '- name: blah\n' ' value: 123\n' '- name: blahblah\n' '- value: 999\n' ) with open(self._yaml_path, 'w') as fp: fp.write(parsed_content) app_yaml = yaml_files.AppYamlFile(self._yaml_path) app_yaml.write() with open(self._yaml_path) as fp: written_content = fp.read() self.assertEquals(parsed_content, written_content) def test_get_env_var(self): self._write_content(self._yaml_path, self._minimal_content) app_yaml = yaml_files.AppYamlFile(self._yaml_path) self.assertEquals('bar', app_yaml.get_env('FOO')) self.assertEquals('bleep', app_yaml.get_env('BAR')) def test_add_env_var(self): self._write_content(self._yaml_path, self._minimal_content) app_yaml = yaml_files.AppYamlFile(self._yaml_path) app_yaml.set_env('BAZ', 'bar') self.assertEquals('bar', app_yaml.get_env('BAZ')) app_yaml.write() expected = self._minimal_content + [' BAZ: bar\n'] self._assert_content_equals(self._yaml_path, expected) def test_overwrite_env_var(self): self._write_content(self._yaml_path, self._minimal_content) app_yaml = yaml_files.AppYamlFile(self._yaml_path) app_yaml.set_env('FOO', 'foo') self.assertEquals('foo', app_yaml.get_env('FOO')) app_yaml.write() expected = ( self._minimal_content[:7] + [' FOO: foo\n'] + self._minimal_content[8:]) self._assert_content_equals(self._yaml_path, expected) def test_clear_env_var(self): self._write_content(self._yaml_path, self._minimal_content) app_yaml = yaml_files.AppYamlFile(self._yaml_path) app_yaml.set_env('BAR', '') self.assertIsNone(app_yaml.get_env('BAR')) app_yaml.write() expected = self._minimal_content[:-1] self._assert_content_equals(self._yaml_path, expected) def test_require_existing_library(self): self._write_content(self._yaml_path, self._minimal_content) app_yaml = yaml_files.AppYamlFile(self._yaml_path) app_yaml.require_library('jinja2', '2.6') app_yaml.write() expected = self._minimal_content self._assert_content_equals(self._yaml_path, expected) def test_require_new_library(self): self._write_content(self._yaml_path, self._minimal_content) app_yaml = yaml_files.AppYamlFile(self._yaml_path) app_yaml.require_library('frammis', '1.2') app_yaml.write() expected = ( self._minimal_content[:3] + ['- name: frammis\n', ' version: "1.2"\n'] + self._minimal_content[3:]) self._assert_content_equals(self._yaml_path, expected) def test_require_different_version_of_library(self): self._write_content(self._yaml_path, self._minimal_content) app_yaml = yaml_files.AppYamlFile(self._yaml_path) with self.assertRaises(ValueError): app_yaml.require_library('jinja2', '2.1') class ModuleManifestTest(TestWithTempDir): def setUp(self): super(ModuleManifestTest, self).setUp() self._manifest_path = os.path.join(self._tmpdir, module_config._MANIFEST_NAME) def test_manifest_must_contain_module(self): with open(self._manifest_path, 'w') as fp: fp.write('foo: bar\n') with self.assertRaises(KeyError): # pylint: disable=expression-not-assigned yaml_files.ModuleManifest(self._manifest_path).module_name def test_module_name_must_name_full_python_module(self): with open(self._manifest_path, 'w') as fp: fp.write('module_name: bar\n') with self.assertRaises(ValueError): # pylint: disable=expression-not-assigned yaml_files.ModuleManifest(self._manifest_path).module_name def test_module_name_must_start_with_modules(self): with open(self._manifest_path, 'w') as fp: fp.write('module_name: bar.baz\n') with self.assertRaises(ValueError): # pylint: disable=expression-not-assigned yaml_files.ModuleManifest(self._manifest_path).module_name def test_manifest_must_have_container_version(self): with open(self._manifest_path, 'w') as fp: fp.write('module_name: modules.bar.bar_module\n') with self.assertRaises(KeyError): # pylint: disable=expression-not-assigned yaml_files.ModuleManifest(self._manifest_path).module_name def test_manifest_must_have_tests(self): with open(self._manifest_path, 'w') as fp: fp.write( 'module_name: modules.bar.bar_module\n' 'container_version: 1.3\n' ) with self.assertRaises(KeyError): # pylint: disable=expression-not-assigned yaml_files.ModuleManifest(self._manifest_path).module_name def test_minimal_manifest(self): with open(self._manifest_path, 'w') as fp: fp.write( 'module_name: modules.foo.foo_module\n' 'container_version: 1.2.3\n' 'tests:\n' ' this: 1\n' ' that: 2\n') manifest = yaml_files.ModuleManifest(self._manifest_path) self.assertEquals(manifest.module_name, 'foo') self.assertEquals(manifest.main_module, 'modules.foo.foo_module') self.assertEquals(manifest.third_party_libraries, {}) self.assertEquals(manifest.appengine_libraries, {}) self.assertEquals(manifest.tests, {'this': 1, 'that': 2}) def test_version_compatibility(self): with open(self._manifest_path, 'w') as fp: fp.write( 'module_name: modules.foo.foo_module\n' 'container_version: 1.2.3\n' 'tests:\n' ' this: 1\n' ' that: 2\n') manifest = yaml_files.ModuleManifest(self._manifest_path) manifest.assert_version_compatibility('1.2.3') manifest.assert_version_compatibility('1.2.4') manifest.assert_version_compatibility('1.3.0') manifest.assert_version_compatibility('2.0.0') with self.assertRaises(ValueError): manifest.assert_version_compatibility('1.2.2') with self.assertRaises(ValueError): manifest.assert_version_compatibility('1.1.9') with self.assertRaises(ValueError): manifest.assert_version_compatibility('0.9.9') class ModuleIncorporationTest(TestWithTempDir): def _make_module(self, module_dir, module_name): with open(os.path.join(module_dir, '__init__.py'), 'w'): pass with open(os.path.join(module_dir, module_name), 'w') as fp: fp.write( 'from models import custom_modules\n' 'def register_module():\n' ' return custom_modules.Module("x", "x", [], [])' ) def setUp(self): super(ModuleIncorporationTest, self).setUp() self.foo_dir = os.path.join(self._tmpdir, 'foo') self.foo_src_dir = os.path.join(self.foo_dir, 'src') self.foo_scripts_dir = os.path.join(self.foo_dir, 'scripts') self.bar_dir = os.path.join(self._tmpdir, 'bar') self.bar_src_dir = os.path.join(self.bar_dir, 'src') self.bar_scripts_dir = os.path.join(self.bar_dir, 'scripts') self.cb_dir = os.path.join(self._tmpdir, 'coursebuilder') self.cb_modules_dir = os.path.join(self.cb_dir, 'modules') self.scripts_dir = os.path.join(self.cb_dir, 'scripts') self.lib_dir = os.path.join(self.cb_dir, 'lib') self.modules_dir = os.path.join(self._tmpdir, 'coursebuilder_resources', 'modules') for dirname in (self.foo_dir, self.foo_src_dir, self.foo_scripts_dir, self.bar_dir, self.bar_src_dir, self.bar_scripts_dir, self.cb_dir, self.scripts_dir, self.lib_dir, self.cb_modules_dir, self.modules_dir): os.makedirs(dirname) foo_manifest_path = os.path.join(self.foo_dir, module_config._MANIFEST_NAME) with open(foo_manifest_path, 'w') as fp: fp.write( 'module_name: modules.foo.foo_module\n' 'container_version: 1.6.0\n' 'tests:\n' ' tests.ext.foo.foo_tests.FooTest: 1\n' 'third_party_libraries:\n' '- name: foo_stuff.zip\n') self._make_module(self.foo_src_dir, 'foo_module.py') foo_installer_path = os.path.join(self.foo_dir, 'scripts', 'setup.sh') with open(foo_installer_path, 'w') as fp: fp.write( '#!/bin/bash\n' 'ln -s $(pwd)/src $2/modules/foo\n' 'touch $2/lib/foo_stuff.zip\n' ) bar_manifest_path = os.path.join(self.bar_dir, module_config._MANIFEST_NAME) with open(bar_manifest_path, 'w') as fp: fp.write( 'module_name: modules.bar.bar_module\n' 'container_version: 1.6.0\n' 'tests:\n' ' tests.ext.bar.bar_tests.BarTest: 1\n' 'appengine_libraries:\n' '- name: endpoints\n' ' version: "1.0"\n') self._make_module(self.bar_src_dir, 'bar_module.py') bar_installer_path = os.path.join(self.bar_dir, 'scripts', 'setup.sh') with open(bar_installer_path, 'w') as fp: fp.write( '#!/bin/bash\n' 'ln -s $(pwd)/src $2/modules/bar\n' ) self.initial_app_yaml = [ 'application: mycourse\n', 'runtime: python27\n', 'api_version: 1\n', 'threadsafe: false\n', '\n', 'env_variables:\n', ' GCB_PRODUCT_VERSION: "1.6.0"\n', '\n', 'libraries:\n', '- name: jinja2\n', ' version: "2.6"\n', ] self.app_yaml_path = os.path.join(self.cb_dir, 'app.yaml') self._write_content(self.app_yaml_path, self.initial_app_yaml) self.third_party_tests_path = os.path.join( self.scripts_dir, 'third_party_tests.yaml') with open(os.path.join(self.cb_modules_dir, '__init__.py'), 'w'): pass self.log_stream = cStringIO.StringIO() self.old_log_handlers = list(module_config._LOG.handlers) module_config._LOG.handlers = [logging.StreamHandler(self.log_stream)] self.save_bundle_root = appengine_config.BUNDLE_ROOT appengine_config.BUNDLE_ROOT = self.cb_dir self.save_sys_path = sys.path sys.path.insert(0, self.cb_dir) self.save_modules = sys.modules.pop('modules') def tearDown(self): module_config._LOG.handlers = self.old_log_handlers appengine_config.BUNDLE_ROOT = self.save_bundle_root sys.path = self.save_sys_path sys.modules['modules'] = self.save_modules super(ModuleIncorporationTest, self).tearDown() def _install(self, modules_arg): if modules_arg: args = module_config.PARSER.parse_args([modules_arg]) else: args = module_config.PARSER.parse_args([]) try: module_config.main(args, self.cb_dir, self.modules_dir) except Exception, ex: self._dump_tree() traceback.print_exc() raise ex def _get_log(self): self.log_stream.flush() ret = self.log_stream.getvalue() self.log_stream.reset() return ret def _expect_logs(self, expected_lines): actual_lines = self._get_log().split('\n') for expected, actual in zip(expected_lines, actual_lines): self.assertIn(expected, actual) def test_install_foo(self): self._install('--targets=foo@%s' % self.foo_dir) expected = ( self.initial_app_yaml[:7] + [' GCB_THIRD_PARTY_LIBRARIES: foo_stuff.zip\n', ' GCB_THIRD_PARTY_MODULES: modules.foo.foo_module\n'] + self.initial_app_yaml[7:] ) self._assert_content_equals(self.app_yaml_path, expected) expected = [ 'tests:\n', ' tests.ext.foo.foo_tests.FooTest: 1\n', ] self._assert_content_equals(self.third_party_tests_path, expected) expected = [ 'Downloading module foo', 'Installing module foo', 'Updating scripts/third_party_tests.yaml', 'Updating app.yaml', 'You should change this from its default', ] self._expect_logs(expected) def test_install_both(self): self._install('--targets=foo@%s,bar@%s' % (self.foo_dir, self.bar_dir)) expected = ( self.initial_app_yaml[:7] + [' GCB_THIRD_PARTY_LIBRARIES: foo_stuff.zip\n', ' GCB_THIRD_PARTY_MODULES:\n', ' modules.foo.foo_module\n', ' modules.bar.bar_module\n'] + self.initial_app_yaml[7:9] + ['- name: endpoints\n', ' version: "1.0"\n',] + self.initial_app_yaml[9:] ) self._assert_content_equals(self.app_yaml_path, expected) expected = [ 'tests:\n', ' tests.ext.bar.bar_tests.BarTest: 1\n', ' tests.ext.foo.foo_tests.FooTest: 1\n', ] self._assert_content_equals(self.third_party_tests_path, expected) expected = [ 'Downloading module foo', 'Installing module foo', 'Downloading module bar', 'Installing module bar', 'Updating scripts/third_party_tests.yaml', 'Updating app.yaml', 'You should change this from its default', ] self._expect_logs(expected) def test_reinstall_both(self): self._install('--targets=foo@%s,bar@%s' % (self.foo_dir, self.bar_dir)) self._get_log() self._install('--targets=foo@%s,bar@%s' % (self.foo_dir, self.bar_dir)) expected = ( self.initial_app_yaml[:7] + [' GCB_THIRD_PARTY_LIBRARIES: foo_stuff.zip\n', ' GCB_THIRD_PARTY_MODULES:\n', ' modules.foo.foo_module\n', ' modules.bar.bar_module\n'] + self.initial_app_yaml[7:9] + ['- name: endpoints\n', ' version: "1.0"\n',] + self.initial_app_yaml[9:] ) self._assert_content_equals(self.app_yaml_path, expected) expected = [ 'tests:\n', ' tests.ext.bar.bar_tests.BarTest: 1\n', ' tests.ext.foo.foo_tests.FooTest: 1\n', ] self._assert_content_equals(self.third_party_tests_path, expected) expected = [ 'Updating scripts/third_party_tests.yaml', 'Updating app.yaml', 'You should change this from its default', ] self._expect_logs(expected) def test_reinstall_both_after_manual_removal(self): self._install('--targets=foo@%s,bar@%s' % (self.foo_dir, self.bar_dir)) self._get_log() os.unlink(os.path.join(self.cb_dir, 'modules', 'foo')) os.unlink(os.path.join(self.cb_dir, 'modules', 'bar')) self._install('--targets=foo@%s,bar@%s' % (self.foo_dir, self.bar_dir)) expected = ( self.initial_app_yaml[:7] + [' GCB_THIRD_PARTY_LIBRARIES: foo_stuff.zip\n', ' GCB_THIRD_PARTY_MODULES:\n', ' modules.foo.foo_module\n', ' modules.bar.bar_module\n'] + self.initial_app_yaml[7:9] + ['- name: endpoints\n', ' version: "1.0"\n',] + self.initial_app_yaml[9:] ) self._assert_content_equals(self.app_yaml_path, expected) expected = [ 'tests:\n', ' tests.ext.bar.bar_tests.BarTest: 1\n', ' tests.ext.foo.foo_tests.FooTest: 1\n', ] self._assert_content_equals(self.third_party_tests_path, expected) expected = [ 'Installing module foo', 'Installing module bar', 'Updating scripts/third_party_tests.yaml', 'Updating app.yaml', 'You should change this from its default', ] self._expect_logs(expected) def test_install_both_then_reinstall_foo(self): self._install('--targets=foo@%s,bar@%s' % (self.foo_dir, self.bar_dir)) self._get_log() self._install('--targets=foo@%s' % self.foo_dir) expected = ( self.initial_app_yaml[:7] + [' GCB_THIRD_PARTY_LIBRARIES: foo_stuff.zip\n', ' GCB_THIRD_PARTY_MODULES: modules.foo.foo_module\n'] + self.initial_app_yaml[7:9] + ['- name: endpoints\n', # Note that AE lib requirement stays. ' version: "1.0"\n',] + self.initial_app_yaml[9:] ) self._assert_content_equals(self.app_yaml_path, expected) expected = [ 'tests:\n', ' tests.ext.foo.foo_tests.FooTest: 1\n', ] self._assert_content_equals(self.third_party_tests_path, expected) expected = [ 'Updating scripts/third_party_tests.yaml', 'Updating app.yaml', 'You should change this from its default', ] self._expect_logs(expected) def test_install_both_then_reinstall_bar(self): self._install('--targets=foo@%s,bar@%s' % (self.foo_dir, self.bar_dir)) self._get_log() self._install('--targets=bar@%s' % self.bar_dir) expected = ( self.initial_app_yaml[:7] + [' GCB_THIRD_PARTY_MODULES: modules.bar.bar_module\n'] + self.initial_app_yaml[7:9] + ['- name: endpoints\n', ' version: "1.0"\n',] + self.initial_app_yaml[9:] ) self._assert_content_equals(self.app_yaml_path, expected) expected = [ 'tests:\n', ' tests.ext.bar.bar_tests.BarTest: 1\n', ] self._assert_content_equals(self.third_party_tests_path, expected) expected = [ 'Updating scripts/third_party_tests.yaml', 'Updating app.yaml', 'You should change this from its default', ] self._expect_logs(expected) def test_install_both_then_reinstall_none(self): self._install('--targets=foo@%s,bar@%s' % (self.foo_dir, self.bar_dir)) self._get_log() self._install(None) expected = ( self.initial_app_yaml[:9] + ['- name: endpoints\n', # Note that AE lib requirement stays. ' version: "1.0"\n',] + self.initial_app_yaml[9:] ) self._assert_content_equals(self.app_yaml_path, expected) self.assertFalse(os.path.exists(self.third_party_tests_path)) expected = [ 'Updating app.yaml', 'You should change this from its default', ] self._expect_logs(expected) def test_appengine_config(self): self._install('--targets=foo@%s,bar@%s' % (self.foo_dir, self.bar_dir)) yaml = yaml_files.AppYamlFile(self.app_yaml_path) os.environ.update(yaml.get_all_env()) # Touch into place the hard-coded expected set of libs so we don't # get spurious errors. for lib in appengine_config.THIRD_PARTY_LIBS: with open(lib.file_path, 'w'): pass # Just looking for no crash. appengine_config._import_and_enable_modules('GCB_THIRD_PARTY_MODULES', reraise=True) appengine_config.gcb_init_third_party()
Python
# coding: utf-8 # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for modules/review/stats.py.""" __author__ = 'Sean Lip' import actions from actions import assert_contains from controllers_review import get_review_payload from controllers_review import get_review_step_key from controllers_review import LEGACY_REVIEW_UNIT_ID class PeerReviewAnalyticsTest(actions.TestBase): """Tests the peer review analytics page on the Course Author dashboard.""" # pylint: disable=too-many-statements def test_peer_review_analytics(self): """Test analytics page on course dashboard.""" student1 = 'student1@google.com' name1 = 'Test Student 1' student2 = 'student2@google.com' name2 = 'Test Student 2' peer = {'assessment_type': 'ReviewAssessmentExample'} # Student 1 submits a peer review assessment. actions.login(student1) actions.register(self, name1) actions.submit_assessment(self, 'ReviewAssessmentExample', peer) actions.logout() # Student 2 submits the same peer review assessment. actions.login(student2) actions.register(self, name2) actions.submit_assessment(self, 'ReviewAssessmentExample', peer) actions.logout() email = 'admin@google.com' # The admin looks at the analytics page on the dashboard. actions.login(email, is_admin=True) response = self.get('dashboard?action=analytics&tab=peer_review') assert_contains( 'Google &gt; Dashboard &gt; Analytics &gt; Peer Review', response.body) assert_contains('have not been calculated yet', response.body) response = response.forms[ 'gcb-generate-analytics-data'].submit().follow() assert len(self.taskq.GetTasks('default')) == 1 assert_contains('is running', response.body) self.execute_all_deferred_tasks() response = self.get(response.request.url) assert_contains('were last updated at', response.body) assert_contains('Peer Review', response.body) assert_contains('Sample peer review assignment', response.body) # JSON code for the completion statistics. assert_contains('"[{\\"stats\\": [2]', response.body) actions.logout() # Student2 requests a review. actions.login(student2) response = actions.request_new_review(self, LEGACY_REVIEW_UNIT_ID) review_step_key_2_for_1 = get_review_step_key(response) assert_contains('Assignment to review', response.body) # Student2 submits the review. response = actions.submit_review( self, LEGACY_REVIEW_UNIT_ID, review_step_key_2_for_1, get_review_payload('R2for1')) assert_contains( 'Your review has been submitted successfully', response.body) actions.logout() actions.login(email, is_admin=True) response = self.get('dashboard?action=analytics&tab=peer_review') assert_contains( 'Google &gt; Dashboard &gt; Analytics &gt; Peer Review', response.body) response = response.forms[ 'gcb-generate-analytics-data'].submit().follow() self.execute_all_deferred_tasks() response = self.get(response.request.url) assert_contains('Peer Review', response.body) # JSON code for the completion statistics. assert_contains('"[{\\"stats\\": [1, 1]', response.body) actions.logout()
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the code_tags module.""" __author__ = 'Gun Pinyo (gunpinyo@google.com)' from models import config from models import courses from modules.oeditor import oeditor from tests.functional import actions class CodeTagTests(actions.TestBase): """Tests for the code example tags.""" COURSE_NAME = 'code_tags_test_course' ADMIN_EMAIL = 'user@test.com' CODE_TYPE = 'javascript' CODE_EXAMPLE = ( 'function main() {' ' alert("hi");' '}' 'main();') CODE_TAG_TEMPLATE = ( '<gcb-code mode="%s" instanceid="my-instance">%s</gcb-code>') CODE_MIRROR_URL = '/modules/code_tags/codemirror/lib/codemirror.js' def setUp(self): super(CodeTagTests, self).setUp() actions.login(self.ADMIN_EMAIL, is_admin=True) self.base = '/' + self.COURSE_NAME app_context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'Test Course') self.course = courses.Course(None, app_context=app_context) self.code_tag_unit = self.course.add_unit() self.code_tag_unit.title = 'code_tag_test_unit' self.code_tag_unit.unit_header = self.CODE_TAG_TEMPLATE % ( self.CODE_TYPE, self.CODE_EXAMPLE) self.no_code_tag_unit = self.course.add_unit() self.no_code_tag_unit.title = 'no_code_tag_test_unit' self.no_code_tag_unit.unit_header = 'Unit without code example tags.' self.course.save() def _get_unit_page(self, unit): return self.parse_html_string( self.get('unit?unit=%s' % unit.unit_id).body) def _get_script_element(self, unit): return self._get_unit_page(unit).find( './/script[@src="%s"]' % self.CODE_MIRROR_URL) def test_code_tag_rendered(self): code_elt = self._get_unit_page(self.code_tag_unit).find( './/code[@class="codemirror-container-readonly"]') self.assertEquals(self.CODE_TYPE, code_elt.attrib['data-mode']) self.assertEquals(self.CODE_EXAMPLE, code_elt.text) def test_codemirror_not_loaded_when_no_code_tags_present(self): self.assertIsNone(self._get_script_element(self.no_code_tag_unit)) def test_codemirror_loaded_when_enabled_and_code_tags_present(self): self.assertIsNotNone(self._get_script_element(self.code_tag_unit)) def test_codemirror_not_loaded_when_disabled_and_code_tags_present(self): config.Registry.test_overrides[oeditor.CAN_HIGHLIGHT_CODE.name] = False self.assertIsNone(self._get_script_element(self.code_tag_unit))
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for modules/dashboard/.""" __author__ = 'Glenn De Jonghe (gdejonghe@google.com)' import cgi import time import actions from common import crypto from common.utils import Namespace from models import courses from models import models from models import transforms from models.custom_modules import Module from models.roles import Permission from models.roles import Roles from modules.dashboard import dashboard from modules.dashboard import tabs from modules.dashboard.dashboard import DashboardHandler from modules.dashboard.question_group_editor import QuestionGroupRESTHandler from modules.dashboard.role_editor import RoleRESTHandler from google.appengine.api import namespace_manager class QuestionDashboardTestCase(actions.TestBase): """Tests Assets > Questions.""" COURSE_NAME = 'question_dashboard' ADMIN_EMAIL = 'admin@foo.com' URL = 'dashboard?action=assets&tab=questions' def setUp(self): super(QuestionDashboardTestCase, self).setUp() actions.login(self.ADMIN_EMAIL, is_admin=True) self.base = '/' + self.COURSE_NAME context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'Questions Dashboard') self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME) self.course = courses.Course(None, context) def tearDown(self): namespace_manager.set_namespace(self.old_namespace) super(QuestionDashboardTestCase, self).tearDown() def test_table_entries(self): # Create a question mc_question_description = 'Test MC Question' mc_question_dto = models.QuestionDTO(None, { 'description': mc_question_description, 'type': 0 # MC }) mc_question_id = models.QuestionDAO.save(mc_question_dto) # Create an assessment and add the question to the content. # Also include a broken question ref to the assessment (and expect this # doesn't break anything). assessment_one = self.course.add_assessment() assessment_one.title = 'Test Assessment One' assessment_one.html_content = """ <question quid="%s" weight="1" instanceid="1"></question> <question quid="broken" weight="1" instanceid="broken"></question> """ % mc_question_id # Create a second question sa_question_description = 'Test SA Question' sa_question_dto = models.QuestionDTO(None, { 'description': sa_question_description, 'type': 1 # SA }) sa_question_id = models.QuestionDAO.save(sa_question_dto) # Create a question group and add the second question qg_description = 'Question Group' qg_dto = models.QuestionGroupDTO(None, { 'description': qg_description, 'items': [{'question': str(sa_question_id)}] }) qg_id = models.QuestionGroupDAO.save(qg_dto) # Create a second assessment and add the question group to the content assessment_two = self.course.add_assessment() assessment_two.title = 'Test Assessment' assessment_two.html_content = """ <question-group qgid="%s" instanceid="QG"></question-group> """ % qg_id self.course.save() # Get the Assets > Question tab dom = self.parse_html_string(self.get(self.URL).body) asset_tables = dom.findall('.//table[@class="assets-table"]') self.assertEquals(len(asset_tables), 2) # First check Question Bank table questions_table = asset_tables[0] question_rows = questions_table.findall('./tbody/tr[@data-filter]') self.assertEquals(len(question_rows), 2) # Check edit link and description of the first question first_row = list(question_rows[0]) first_cell = first_row[0] self.assertEquals(first_cell.findall('a')[1].tail, mc_question_description) self.assertEquals(first_cell.find('a').get('href'), ( 'dashboard?action=edit_question&key=%s' % mc_question_id)) # Check if the assessment is listed location_link = first_row[2].find('ul/li/a') self.assertEquals(location_link.get('href'), ( 'assessment?name=%s' % assessment_one.unit_id)) self.assertEquals(location_link.text, assessment_one.title) # Check second question (=row) second_row = list(question_rows[1]) self.assertEquals( second_row[0].findall('a')[1].tail, sa_question_description) # Check whether the containing Question Group is listed self.assertEquals(second_row[1].find('ul/li').text, qg_description) # Now check Question Group table question_groups_table = asset_tables[1] row = question_groups_table.find('./tbody/tr') # Check edit link and description edit_link = row[0].find('a') self.assertEquals(edit_link.tail, qg_description) self.assertEquals(edit_link.get('href'), ( 'dashboard?action=edit_question_group&key=%s' % qg_id)) # The question that is part of this group, should be listed self.assertEquals(row[1].find('ul/li').text, sa_question_description) # Assessment where this Question Group is located, should be linked location_link = row[2].find('ul/li/a') self.assertEquals(location_link.get('href'), ( 'assessment?name=%s' % assessment_two.unit_id)) self.assertEquals(location_link.text, assessment_two.title) def _load_tables(self): asset_tables = self.parse_html_string(self.get(self.URL).body).findall( './/table[@class="assets-table"]') self.assertEquals(len(asset_tables), 2) return asset_tables def test_no_questions_and_question_groups(self): asset_tables = self._load_tables() self.assertEquals( asset_tables[0].find('./tfoot/tr/td').text, 'No questions available' ) self.assertEquals( asset_tables[1].find('./tfoot/tr/td').text, 'No question groups available' ) def test_no_question_groups(self): description = 'Question description' models.QuestionDAO.save(models.QuestionDTO(None, { 'description': description })) asset_tables = self._load_tables() self.assertEquals( asset_tables[0].findall('./tbody/tr/td/a')[1].tail, description ) self.assertEquals( asset_tables[1].find('./tfoot/tr/td').text, 'No question groups available' ) def test_no_questions(self): description = 'Group description' models.QuestionGroupDAO.save(models.QuestionGroupDTO(None, { 'description': description })) asset_tables = self._load_tables() self.assertEquals( asset_tables[0].find('./tfoot/tr/td').text, 'No questions available' ) self.assertEquals( asset_tables[1].find('./tbody/tr/td/a').tail, description ) def test_if_buttons_are_present(self): """Tests if all buttons are present. In the past it wasn't allowed to add a question group when there were no questions yet. """ body = self.get(self.URL).body self.assertIn('Add Short Answer', body) self.assertIn('Add Multiple Choice', body) self.assertIn('Add Question Group', body) def test_adding_empty_question_group(self): QG_URL = '/%s%s' % (self.COURSE_NAME, QuestionGroupRESTHandler.URI) xsrf_token = crypto.XsrfTokenManager.create_xsrf_token( QuestionGroupRESTHandler.XSRF_TOKEN) description = 'Question Group' payload = { 'description': description, 'version': QuestionGroupRESTHandler.SCHEMA_VERSIONS[0], 'introduction': '', 'items': [] } response = self.put(QG_URL, {'request': transforms.dumps({ 'xsrf_token': cgi.escape(xsrf_token), 'payload': transforms.dumps(payload)})}) self.assertEquals(response.status_int, 200) payload = transforms.loads(response.body) self.assertEquals(payload['status'], 200) self.assertEquals(payload['message'], 'Saved.') asset_tables = self._load_tables() self.assertEquals( asset_tables[1].find('./tbody/tr/td/a').tail, description ) def test_last_modified_timestamp(self): begin_time = time.time() question_dto = models.QuestionDTO(None, {}) models.QuestionDAO.save(question_dto) self.assertTrue((begin_time <= question_dto.last_modified) and ( question_dto.last_modified <= time.time())) qg_dto = models.QuestionGroupDTO(None, {}) models.QuestionGroupDAO.save(qg_dto) self.assertTrue((begin_time <= qg_dto.last_modified) and ( question_dto.last_modified <= time.time())) asset_tables = self._load_tables() self.assertEquals( asset_tables[0].find('./tbody/tr/td[@data-timestamp]').get( 'data-timestamp', ''), str(question_dto.last_modified) ) self.assertEquals( asset_tables[1].find('./tbody/tr/td[@data-timestamp]').get( 'data-timestamp', ''), str(qg_dto.last_modified) ) def test_question_clone(self): # Add a question by just nailing it in to the datastore. mc_question_description = 'Test MC Question' mc_question_dto = models.QuestionDTO(None, { 'description': mc_question_description, 'type': 0 # MC }) models.QuestionDAO.save(mc_question_dto) # On the assets -> questions page, clone the question. response = self.get(self.URL) dom = self.parse_html_string(self.get(self.URL).body) clone_link = dom.find('.//a[@class="icon md md-content-copy"]') question_key = clone_link.get('data-key') xsrf_token = dom.find('.//table[@id="question-table"]' ).get('data-clone-question-token') self.post( 'dashboard?action=clone_question', { 'key': question_key, 'xsrf_token': xsrf_token }) response = self.get(self.URL) self.assertIn(mc_question_description + ' (clone)', response.body) def _call_add_to_question_group(self, qu_id, qg_id, weight, xsrf_token): return self.post('dashboard', { 'action': 'add_to_question_group', 'question_id': qu_id, 'group_id': qg_id, 'weight': weight, 'xsrf_token': xsrf_token, }, True) def test_add_to_question_group(self): # Create a question question_description = 'Question' question_dto = models.QuestionDTO(None, { 'description': question_description, 'type': 0 # MC }) question_id = models.QuestionDAO.save(question_dto) # No groups are present so no add_to_group icon should be present self.assertIsNone(self._load_tables()[0].find('./tbody/tr/td[ul]div')) # Create a group qg_description = 'Question Group' qg_dto = models.QuestionGroupDTO(None, { 'description': qg_description, 'items': [] }) qg_id = models.QuestionGroupDAO.save(qg_dto) # Since we now have a group, the add_to_group icon should be visible self.assertIsNotNone( self._load_tables()[0].find('./tbody/tr/td[ul]/div')) # Add Question to Question Group via post_add_to_question_group asset_tables = self._load_tables() xsrf_token = asset_tables[0].get('data-qg-xsrf-token', '') response = self._call_add_to_question_group( question_id, qg_id, 1, xsrf_token) # Check if operation was successful self.assertEquals(response.status_int, 200) asset_tables = self._load_tables() self.assertEquals( asset_tables[0].find('./tbody/tr/td/ul/li').text, qg_description ) self.assertEquals( asset_tables[1].find('./tbody/tr/td/ul/li').text, question_description ) # Check a bunch of calls that should fail response = self._call_add_to_question_group(question_id, qg_id, 1, 'a') self.assertEquals(response.status_int, 403) response = transforms.loads(self._call_add_to_question_group( -1, qg_id, 1, xsrf_token).body) self.assertEquals(response['status'], 500) response = transforms.loads(self._call_add_to_question_group( question_id, -1, 1, xsrf_token).body) self.assertEquals(response['status'], 500) response = transforms.loads(self._call_add_to_question_group( 'a', qg_id, 1, xsrf_token).body) self.assertEquals(response['status'], 500) response = transforms.loads(self._call_add_to_question_group( question_id, qg_id, 'a', xsrf_token).body) self.assertEquals(response['status'], 500) class CourseOutlineTestCase(actions.TestBase): """Tests the Course Outline.""" COURSE_NAME = 'outline' ADMIN_EMAIL = 'admin@foo.com' URL = 'dashboard' def setUp(self): super(CourseOutlineTestCase, self).setUp() actions.login(self.ADMIN_EMAIL, is_admin=True) self.base = '/' + self.COURSE_NAME context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'Outline Testing') self.course = courses.Course(None, context) def _set_draft_status(self, key, component_type, xsrf_token, set_draft): return self.post(self.URL, { 'action': 'set_draft_status', 'key': key, 'type': component_type, 'xsrf_token': xsrf_token, 'set_draft': set_draft }, True) def _check_list_item(self, li, href, title, ctype, key, lock_class): a = li.find('./div/div/div[@class="name"]/a') self.assertEquals(a.get('href', ''), href) self.assertEquals(a.text, title) padlock = li.find('./div/div/div[3]') self.assertEquals(padlock.get('data-component-type', ''), ctype) self.assertEquals(padlock.get('data-key', ''), str(key)) self.assertIn(lock_class, padlock.get('class', '')) def test_action_icons(self): assessment = self.course.add_assessment() assessment.title = 'Test Assessment' assessment.now_available = True link = self.course.add_link() link.title = 'Test Link' link.now_available = False unit = self.course.add_unit() unit.title = 'Test Unit' unit.now_available = True lesson = self.course.add_lesson(unit) lesson.title = 'Test Lesson' lesson.now_available = False self.course.save() dom = self.parse_html_string(self.get(self.URL).body) course_outline = dom.find('.//div[@class="course-outline editable"]') xsrf_token = course_outline.get('data-status-xsrf-token', '') lis = course_outline.findall('.//ol[@class="course"]/li') self.assertEquals(len(lis), 3) # Test Assessment self._check_list_item( lis[0], 'assessment?name=%s' % assessment.unit_id, assessment.title, 'unit', assessment.unit_id, 'md-lock-open' ) # Test Link self._check_list_item( lis[1], '', link.title, 'unit', link.unit_id, 'md-lock') # Test Unit unit_li = lis[2] self._check_list_item( unit_li, 'unit?unit=%s' % unit.unit_id, 'Test Unit', 'unit', unit.unit_id, 'md-lock-open' ) # Test Lesson self._check_list_item( unit_li.find('ol/li'), 'unit?unit=%s&lesson=%s' % (unit.unit_id, lesson.lesson_id), lesson.title, 'lesson', lesson.lesson_id, 'md-lock' ) # Send POST without xsrf token, should give 403 response = self._set_draft_status( assessment.unit_id, 'unit', 'xyz', '1') self.assertEquals(response.status_int, 403) # Set assessment to private response = self._set_draft_status( assessment.unit_id, 'unit', xsrf_token, '1') self.assertEquals(response.status_int, 200) payload = transforms.loads(transforms.loads(response.body)['payload']) self.assertEquals(payload['is_draft'], True) # Set lesson to public response = self._set_draft_status( lesson.lesson_id, 'lesson', xsrf_token, '0') self.assertEquals(response.status_int, 200) payload = transforms.loads(transforms.loads(response.body)['payload']) self.assertEquals(payload['is_draft'], False) # Refresh page, check results lis = self.parse_html_string( self.get(self.URL).body).findall('.//ol[@class="course"]/li') self.assertIn( 'md-lock', lis[0].find('./div/div/div[3]').get('class', '')) self.assertIn( 'md-lock-open', lis[2].find('ol/li/div/div/div[3]').get('class', '')) # Repeat but set assessment to public and lesson to private response = self._set_draft_status( assessment.unit_id, 'unit', xsrf_token, '0') response = self._set_draft_status( lesson.lesson_id, 'lesson', xsrf_token, '1') # Refresh page, check results lis = self.parse_html_string( self.get(self.URL).body).findall('.//ol[@class="course"]/li') self.assertIn( 'md-lock-open', lis[0].find('./div/div/div[3]').get('class', '')) self.assertIn( 'md-lock', lis[2].find('ol/li/div/div/div[3]').get('class', '')) class RoleEditorTestCase(actions.TestBase): """Tests the Roles tab and Role Editor.""" COURSE_NAME = 'role_editor' ADMIN_EMAIL = 'admin@foo.com' URL = 'dashboard?action=roles' def setUp(self): super(RoleEditorTestCase, self).setUp() actions.login(self.ADMIN_EMAIL, is_admin=True) self.base = '/' + self.COURSE_NAME context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'Roles Testing') self.course = courses.Course(None, context) self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME) self.old_registered_permission = Roles._REGISTERED_PERMISSIONS Roles._REGISTERED_PERMISSIONS = {} def tearDown(self): Roles._REGISTERED_PERMISSIONS = self.old_registered_permission namespace_manager.set_namespace(self.old_namespace) super(RoleEditorTestCase, self).tearDown() def _create_role(self, role): role_dto = models.RoleDTO(None, { 'name': role, }) return models.RoleDAO.save(role_dto) def test_roles_tab(self): role_name = 'Test Role' role_id = self._create_role(role_name) li = self.parse_html_string(self.get(self.URL).body).find('.//ul/li') self.assertEquals(li.text, role_name) self.assertEquals(li.find('a').get('href'), ( 'dashboard?action=edit_role&key=%s' % role_id)) def test_editor_hooks(self): module1 = Module('module1', '', [], []) module2 = Module('module2', '', [], []) module3 = Module('module3', '', [], []) module4 = Module('module4', '', [], []) Roles.register_permissions(module1, lambda unused: [ Permission('permissiona', 'a'), Permission('permissionb', 'b')]) Roles.register_permissions(module2, lambda unused: [ Permission('permissionc', 'c'), Permission('permissiond', 'd')]) Roles.register_permissions(module4, lambda unused: [ Permission('permissiong', 'g'), Permission('permissiond', 'h')]) handler = RoleRESTHandler() handler.course = self.course datastore_permissions = { module1.name: ['permission', 'permissiona', 'permissionb'], module2.name: ['permissionc', 'permissiond'], module3.name: ['permissione', 'permissionf'] } datastore_dict = { 'name': 'Role Name', 'users': ['test@test.com', 'test2@test.com'], 'permissions': datastore_permissions } editor_dict = handler.transform_for_editor_hook(datastore_dict) self.assertEquals(editor_dict['name'], 'Role Name') self.assertEquals(editor_dict['users'], 'test@test.com, test2@test.com') modules = editor_dict['modules'] # Test registered assigned permission permissionc = modules[module2.name][0] self.assertEquals(permissionc['assigned'], True) self.assertEquals(permissionc['name'], 'permissionc') self.assertEquals(permissionc['description'], 'c') # Test unregistered module with assigned permission permissionsf = modules[RoleRESTHandler.INACTIVE_MODULES][1] self.assertEquals(permissionsf['assigned'], True) self.assertEquals(permissionsf['name'], 'permissionf') self.assertEquals( permissionsf['description'], 'This permission was set by the module "module3" which is ' 'currently not registered.' ) # Test registered module with assigned unregistered permission permission = modules[module1.name][2] self.assertEquals(permission['assigned'], True) self.assertEquals(permission['name'], 'permission') self.assertEquals( permission['description'], 'This permission is currently not registered.' ) # Test registered unassigned permissions permissiong = editor_dict['modules'][module4.name][0] self.assertEquals(permissiong['assigned'], False) self.assertEquals(permissiong['name'], 'permissiong') self.assertEquals(permissiong['description'], 'g') # Call the hook which gets called when saving new_datastore_dict = handler.transform_after_editor_hook(datastore_dict) # If original dict matches new dict then both hooks work correctly self.assertEquals(datastore_dict, new_datastore_dict) def test_not_unique_role_name(self): role_name = 'Test Role' role_id = self._create_role(role_name) handler = RoleRESTHandler() handler.course = self.course editor_dict = { 'name': role_name } errors = [] handler.validate(editor_dict, role_id + 1, None, errors) self.assertEquals( errors[0], 'The role must have a unique non-empty name.') class DashboardAccessTestCase(actions.TestBase): ACCESS_COURSE_NAME = 'dashboard_access_yes' NO_ACCESS_COURSE_NAME = 'dashboard_access_no' ADMIN_EMAIL = 'admin@foo.com' USER_EMAIL = 'user@foo.com' ROLE = 'test_role' ACTION = 'outline' PERMISSION = 'can_access_dashboard' PERMISSION_DESCRIPTION = 'Can Access Dashboard.' def setUp(self): super(DashboardAccessTestCase, self).setUp() actions.login(self.ADMIN_EMAIL, is_admin=True) context = actions.simple_add_course( self.ACCESS_COURSE_NAME, self.ADMIN_EMAIL, 'Course with access') self.course_with_access = courses.Course(None, context) with Namespace(self.course_with_access.app_context.namespace): role_dto = models.RoleDTO(None, { 'name': self.ROLE, 'users': [self.USER_EMAIL], 'permissions': {dashboard.custom_module.name: [self.PERMISSION]} }) models.RoleDAO.save(role_dto) context = actions.simple_add_course( self.NO_ACCESS_COURSE_NAME, self.ADMIN_EMAIL, 'Course with no access' ) self.course_without_access = courses.Course(None, context) # pylint: disable=W0212 self.old_nav_mappings = DashboardHandler._nav_mappings # pylint: disable=W0212 DashboardHandler._nav_mappings = {self.ACTION: 'outline'} DashboardHandler.map_action_to_permission( 'get_%s' % self.ACTION, self.PERMISSION) actions.logout() def tearDown(self): # pylint: disable=W0212 DashboardHandler._nav_mappings = self.old_nav_mappings super(DashboardAccessTestCase, self).tearDown() def test_dashboard_access_method(self): with Namespace(self.course_with_access.app_context.namespace): self.assertFalse(DashboardHandler.current_user_has_access( self.course_with_access.app_context)) with Namespace(self.course_without_access.app_context.namespace): self.assertFalse(DashboardHandler.current_user_has_access( self.course_without_access.app_context)) actions.login(self.USER_EMAIL, is_admin=False) with Namespace(self.course_with_access.app_context.namespace): self.assertTrue(DashboardHandler.current_user_has_access( self.course_with_access.app_context)) with Namespace(self.course_without_access.app_context.namespace): self.assertFalse(DashboardHandler.current_user_has_access( self.course_without_access.app_context)) actions.logout() def _get_all_picker_options(self): return self.parse_html_string( self.get('/%s/dashboard' % self.ACCESS_COURSE_NAME).body ).findall( './/ol[@id="gcb-course-picker-menu"]/li/a') def test_course_picker(self): actions.login(self.USER_EMAIL, is_admin=False) picker_options = self._get_all_picker_options() self.assertEquals(len(list(picker_options)), 1) self.assertEquals(picker_options[0].get( 'href'), '/%s/dashboard?action=outline' % self.ACCESS_COURSE_NAME) actions.logout() actions.login(self.ADMIN_EMAIL, is_admin=True) picker_options = self._get_all_picker_options() # Expect 3 courses, as the default one is also considered for the picker self.assertEquals(len(picker_options), 3) actions.logout() def _get_right_nav_links(self): return self.parse_html_string( self.get('/%s/' % self.ACCESS_COURSE_NAME).body ).findall( './/div[@id="gcb-nav-x"]/div/ul/li[@class="gcb-pull-right"]') def test_dashboard_link(self): # Not signed in => no dashboard or admin link visible self.assertEquals(len(self._get_right_nav_links()), 0) # Sign in user with dashboard permissions => dashboard link visible actions.login(self.USER_EMAIL, is_admin=False) links = self._get_right_nav_links() self.assertEquals(len(links), 1) self.assertEquals(links[0].find('a').get('href'), 'dashboard') self.assertEquals(links[0].find('a').text, 'Dashboard') # Sign in course admin => dashboard link visible actions.login(self.ADMIN_EMAIL, is_admin=False) links = self._get_right_nav_links() self.assertEquals(len(links), 1) self.assertEquals(links[0].find('a').get('href'), 'dashboard') self.assertEquals(links[0].find('a').text, 'Dashboard') class DashboardCustomNavTestCase(actions.TestBase): """Tests Assets > Questions.""" COURSE_NAME = 'custom_dashboard' ADMIN_EMAIL = 'admin@foo.com' URL = 'dashboard?action=custom_mod' ACTION = 'custom_mod' CONTENT_PATH = './/div[@id="gcb-main-area"]/div[@id="gcb-main-content"]' def setUp(self): super(DashboardCustomNavTestCase, self).setUp() actions.login(self.ADMIN_EMAIL, is_admin=True) self.base = '/' + self.COURSE_NAME context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'Custom Dashboard') self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME) self.course = courses.Course(None, context) def tearDown(self): namespace_manager.set_namespace(self.old_namespace) super(DashboardCustomNavTestCase, self).tearDown() def test_custom_top_nav(self): # Add a new top level navigation action DashboardHandler.add_nav_mapping(self.ACTION, 'CUSTOM_MOD') class CustomNavHandler(object): @classmethod def show_page(cls, dashboard_handler): dashboard_handler.render_page({ 'page_title': dashboard_handler.format_title('CustomNav'), 'main_content': 'MainContent'}) DashboardHandler.add_custom_get_action( self.ACTION, CustomNavHandler.show_page) dom = self.parse_html_string(self.get('dashboard').body) selected_nav_path = ('.//tr[@class="gcb-nav-bar-level-1"]' '//a[@class="selected"]') self.assertEquals('Outline', dom.find(selected_nav_path).text) dom = self.parse_html_string(self.get(self.URL).body) self.assertEquals('CUSTOM_MOD', dom.find(selected_nav_path).text) self.assertEquals( 'MainContent', dom.find(self.CONTENT_PATH).text.strip()) DashboardHandler.remove_custom_get_action(self.ACTION) # Add a new tab under the new navigation action class CustomTabHandler(object): @classmethod def display_html(cls, unused_dashboard_handler): return 'MainTabContent' tabs.Registry.register( self.ACTION, 'cu_tab', 'CustomTab', CustomTabHandler) DashboardHandler.add_custom_get_action(self.ACTION, None) dom = self.parse_html_string(self.get(self.URL).body) self.assertEquals('CUSTOM_MOD', dom.find(selected_nav_path).text) self.assertEquals( 'MainTabContent', dom.find(self.CONTENT_PATH).text.strip()) selected_tab_path = ('.//*[@class="gcb-nav-bar-level-2"]' '//a[@class="selected"]') self.assertEquals('CustomTab', dom.find(selected_tab_path).text) def test_first_tab(self): url = 'dashboard?action=analytics' dom = self.parse_html_string(self.get(url).body) selected_tab_path = ('.//*[@class="gcb-nav-bar-level-2"]' '//a[@class="selected"]') self.assertEquals('Students', dom.find(selected_tab_path).text)
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests the capability for registered students to invite others.""" __author__ = 'John Orr (jorr@google.com)' import urlparse from common import crypto from models import courses from models import models from models import transforms from modules.invitation import invitation from modules.notifications import notifications from modules.unsubscribe import unsubscribe from tests.functional import actions from google.appengine.api import namespace_manager class BaseInvitationTests(actions.TestBase): ADMIN_EMAIL = 'admin@foo.com' COURSE_NAME = 'invitation_course' SENDER_EMAIL = 'sender@foo.com' STUDENT_EMAIL = 'student@foo.com' STUDENT_NAME = 'A. Student' EMAIL_ENV = { 'course': { 'invitation_email': { 'enabled': True, 'sender_email': SENDER_EMAIL, 'subject_template': 'Email from {{sender_name}}', 'body_template': 'From {{sender_name}}. Unsubscribe: {{unsubscribe_url}}'}}} def setUp(self): super(BaseInvitationTests, self).setUp() self.base = '/' + self.COURSE_NAME context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'Invitation Course') self.course = courses.Course(None, context) self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME) self._is_registered = False def tearDown(self): namespace_manager.set_namespace(self.old_namespace) super(BaseInvitationTests, self).tearDown() def register(self): if not self._is_registered: actions.login(self.STUDENT_EMAIL, is_admin=False) actions.register(self, self.STUDENT_NAME) self._is_registered = True class InvitationHandlerTests(BaseInvitationTests): INVITATION_INTENT = 'course_invitation' URL = 'modules/invitation' REST_URL = 'rest/modules/invitation' def setUp(self): super(InvitationHandlerTests, self).setUp() self.old_send_async = notifications.Manager.send_async notifications.Manager.send_async = self._send_async_spy self.send_async_count = 0 self.send_async_call_log = [] def tearDown(self): notifications.Manager.send_async = self.old_send_async super(InvitationHandlerTests, self).tearDown() def _send_async_spy(self, *args, **kwargs): self.send_async_count += 1 self.send_async_call_log.append({'args': args, 'kwargs': kwargs}) def test_invitation_panel_unavailable_when_email_is_not_fully_set_up(self): self.register() for sender_email in ['', 'foo@bar.com']: for subject_template in ['', 'the subject']: for body_template in ['', 'the body']: email_env = { 'course': { 'invitation_email': { 'sender_email': sender_email, 'subject_template': subject_template, 'body_template': body_template}}} with actions.OverriddenEnvironment(email_env): response = self.get(self.URL) if sender_email and subject_template and body_template: self.assertEquals(200, response.status_code) else: self.assertEquals(302, response.status_code) self.assertEquals( 'http://localhost/invitation_course/course', response.headers['Location']) def test_invitation_panel_available_only_for_registered_student(self): with actions.OverriddenEnvironment(self.EMAIL_ENV): response = self.get(self.URL) self.assertEquals(302, response.status_code) self.assertEquals( 'http://localhost/invitation_course/course', response.headers['Location']) actions.login(self.STUDENT_EMAIL, is_admin=False) response = self.get(self.URL) self.assertEquals(302, response.status_code) self.assertEquals( 'http://localhost/invitation_course/course', response.headers['Location']) actions.register(self, self.STUDENT_NAME) response = self.get(self.URL) self.assertEquals(200, response.status_code) def test_invitation_page_content(self): self.register() with actions.OverriddenEnvironment(self.EMAIL_ENV): response = self.get(self.URL) self.assertEquals(200, response.status_code) dom = self.parse_html_string(response.body) # A sample email is displayed self.assertIn( 'Email from A. Student', ''.join(dom.find('.//div[@class="subject-line"]').itertext())) self.assertIn( 'From A. Student. Unsubscribe: ' 'http://localhost/invitation_course/modules/unsubscribe', dom.find('.//div[@class="email-body"]').text) def _post_to_rest_handler(self, request_dict): return transforms.loads(self.post( self.REST_URL, {'request': transforms.dumps(request_dict)}).body) def _get_rest_request(self, payload_dict): xsrf_token = crypto.XsrfTokenManager.create_xsrf_token( 'invitation') return { 'xsrf_token': xsrf_token, 'payload': payload_dict } def test_rest_handler_requires_xsrf(self): response = self._post_to_rest_handler({'xsrf_token': 'BAD TOKEN'}) self.assertEquals(403, response['status']) def test_rest_handler_requires_enrolled_user_in_session(self): response = self._post_to_rest_handler(self._get_rest_request({})) self.assertEquals(401, response['status']) actions.login(self.STUDENT_EMAIL, is_admin=False) response = self._post_to_rest_handler(self._get_rest_request({})) self.assertEquals(401, response['status']) def test_rest_handler_requires_email_available(self): self.register() response = self._post_to_rest_handler(self._get_rest_request({})) self.assertEquals(500, response['status']) def _do_valid_email_list_post(self, email_list): self.register() with actions.OverriddenEnvironment(self.EMAIL_ENV): return self._post_to_rest_handler( self._get_rest_request({'emailList': ','.join(email_list)})) def test_rest_handler_requires_non_empty_email_list(self): response = self._do_valid_email_list_post(['']) self.assertEquals(400, response['status']) self.assertEquals('Error: Empty email list', response['message']) def test_rest_handler_rejects_bad_email_address(self): response = self._do_valid_email_list_post(['bad email']) self.assertEquals(400, response['status']) self.assertIn('Invalid email "bad email"', response['message']) def test_rest_handler_rejects_sending_repeat_invitations(self): spammed_email = 'spammed@foo.com' response = self._do_valid_email_list_post([spammed_email]) self.assertEquals(200, response['status']) response = self._do_valid_email_list_post([spammed_email]) self.assertEquals(400, response['status']) self.assertIn( 'You have already sent an invitation email to "spammed@foo.com"', response['message']) def test_rest_handler_sends_only_one_invitation_to_repeated_addresses(self): spammed_email = 'spammed@foo.com' response = self._do_valid_email_list_post( [spammed_email, spammed_email]) self.assertEquals(200, response['status']) self.assertEquals('OK, 1 messages sent', response['message']) self.assertEqual(1, self.send_async_count) def test_rest_handler_discretely_does_not_mail_unsubscribed_users(self): # For privacy reasons the service should NOT email unsubscribed users, # but should report to the requestor that it did. unsubscribed_email = 'unsubscribed@foo.com' unsubscribe.set_subscribed(unsubscribed_email, False) response = self._do_valid_email_list_post([unsubscribed_email]) self.assertEquals(200, response['status']) self.assertEquals('OK, 1 messages sent', response['message']) self.assertEqual(0, self.send_async_count) def test_rest_handler_discretely_does_not_mail_registered_users(self): # To reduce spam the service should NOT email registered users, but for # privacy reasons should report to the requestor that it did. registered_student = 'some_other_student@foo.com' models.Student(key_name=registered_student, is_enrolled=True).put() response = self._do_valid_email_list_post([registered_student]) self.assertEquals(200, response['status']) self.assertEquals('OK, 1 messages sent', response['message']) self.assertEqual(0, self.send_async_count) def test_rest_handler_can_send_invitation(self): recipient = 'recipient@foo.com' response = self._do_valid_email_list_post([recipient]) self.assertEquals(200, response['status']) self.assertEqual(1, self.send_async_count) self.assertEquals(1, len(self.send_async_call_log)) args = self.send_async_call_log[0]['args'] kwargs = self.send_async_call_log[0]['kwargs'] self.assertEquals(5, len(args)) self.assertEquals(recipient, args[0]) self.assertEquals(self.SENDER_EMAIL, args[1]) self.assertEquals(self.INVITATION_INTENT, args[2]) self.assertIn( 'From A. Student. Unsubscribe: ' 'http://localhost/invitation_course/modules/unsubscribe', args[3]) self.assertEquals('Email from A. Student', args[4]) audit_trail = kwargs['audit_trail'] self.assertEquals('A. Student', audit_trail['sender_name']) unsubscribe_url = urlparse.urlparse(audit_trail['unsubscribe_url']) self.assertEquals( '/invitation_course/modules/unsubscribe', unsubscribe_url.path) query = urlparse.parse_qs(unsubscribe_url.query) self.assertEquals('recipient@foo.com', query['email'][0]) def test_rest_handler_can_send_multiple_invitations(self): email_list = ['a@foo.com', 'b@foo.com', 'c@foo.com'] response = self._do_valid_email_list_post(email_list) self.assertEquals(200, response['status']) self.assertEquals('OK, 3 messages sent', response['message']) self.assertEqual(3, self.send_async_count) self.assertEquals( set(email_list), {log['args'][0] for log in self.send_async_call_log}) def test_rest_handler_can_send_some_invitations_but_not_others(self): spammed_email = 'spammed@foo.com' response = self._do_valid_email_list_post([spammed_email]) self.assertEquals(200, response['status']) self.assertEqual(1, self.send_async_count) self.send_async_count = 0 unsubscribed_email = 'unsubscribed@foo.com' unsubscribe.set_subscribed(unsubscribed_email, False) response = self._do_valid_email_list_post( ['a@foo.com', unsubscribed_email, 'b@foo.com', spammed_email]) self.assertEquals(400, response['status']) self.assertIn('Not all messages were sent (3 / 4)', response['message']) self.assertIn( 'You have already sent an invitation email to "spammed@foo.com"', response['message']) self.assertEqual(2, self.send_async_count) def test_rest_handler_limits_number_of_invitations(self): old_max_emails = invitation.MAX_EMAILS invitation.MAX_EMAILS = 2 try: email_list = ['a@foo.com', 'b@foo.com', 'c@foo.com'] response = self._do_valid_email_list_post(email_list) self.assertEquals(200, response['status']) self.assertEquals( 'This exceeds your email cap. ' 'Number of remaining invitations: 2. ' 'No messages sent.', response['message']) self.assertEqual(0, self.send_async_count) finally: invitation.MAX_EMAILS = old_max_emails class ProfileViewInvitationTests(BaseInvitationTests): URL = 'student/home' def _find_row(self, dom, title): for row in dom.findall('.//table[@class="gcb-student-data-table"]//tr'): if row.find('th').text == title: return row return None def test_invitation_row_supressed_if_invitations_disabled(self): email_env = {'course': {'invitation_email': {'enabled': False}}} with actions.OverriddenEnvironment(email_env): self.register() dom = self.parse_html_string(self.get(self.URL).body) self.assertIsNone(self._find_row(dom, 'Invite Friends')) self.assertIsNotNone(self._find_row(dom, 'Subscribe/Unsubscribe')) def test_invitation_link_supressed_if_email_not_configured(self): email_env = {'course': {'invitation_email': {'enabled': True}}} with actions.OverriddenEnvironment(email_env): self.register() dom = self.parse_html_string(self.get(self.URL).body) invite_friends_row = self._find_row(dom, 'Invite Friends') td = invite_friends_row.find('td') self.assertEquals('Invitations not currently available', td.text) def test_invitation_link_shown(self): self.register() with actions.OverriddenEnvironment(self.EMAIL_ENV): dom = self.parse_html_string(self.get(self.URL).body) invite_friends_row = self._find_row(dom, 'Invite Friends') link = invite_friends_row.find('td/a') self.assertEquals( 'Click to send invitations to family and friends', link.text) self.assertEquals(InvitationHandlerTests.URL, link.attrib['href']) def test_unsubscribe_link_shown_to_subscribed_user(self): self.register() dom = self.parse_html_string(self.get(self.URL).body) subscribe_row = self._find_row(dom, 'Subscribe/Unsubscribe') td = subscribe_row.find('td') self.assertEquals( 'You are currently receiving course-related emails. ', td.text) link = td[0] self.assertEquals( 'Click here to unsubscribe.', link.text) unsubscribe_url = urlparse.urlparse(link.attrib['href']) self.assertEquals( '/invitation_course/modules/unsubscribe', unsubscribe_url.path) query = urlparse.parse_qs(unsubscribe_url.query) self.assertEquals(self.STUDENT_EMAIL, query['email'][0]) self.assertFalse('action' in query) def test_subscribe_link_shown_to_unsubscribed_user(self): self.register() unsubscribe.set_subscribed(self.STUDENT_EMAIL, False) dom = self.parse_html_string(self.get(self.URL).body) subscribe_row = self._find_row(dom, 'Subscribe/Unsubscribe') td = subscribe_row.find('td') self.assertEquals( 'You are currently unsubscribed from course-related emails.', td.text) link = td[0] self.assertEquals( 'Click here to re-subscribe.', link.text) unsubscribe_url = urlparse.urlparse(link.attrib['href']) self.assertEquals( '/invitation_course/modules/unsubscribe', unsubscribe_url.path) query = urlparse.parse_qs(unsubscribe_url.query) self.assertEquals(self.STUDENT_EMAIL, query['email'][0]) self.assertEquals('resubscribe', query['action'][0]) class SantitationTests(BaseInvitationTests): def transform(self, x): return 'tr_' + x def test_for_export_transforms_value_for_invitation_student_property(self): orig_model = invitation.InvitationStudentProperty.load_or_create( models.Student()) orig_model.append_to_invited_list(['a@foo.com']) safe_model = orig_model.for_export(self.transform) self.assertEquals('{"email_list": ["tr_a@foo.com"]}', safe_model.value)
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Analytics for extracting facts based on StudentAnswerEntity entries.""" __author__ = 'Mike Gainer (mgainer@google.com)' import collections from common import crypto from common import utils as common_utils from models import courses from models import models from models import transforms from models.data_sources import utils as data_sources_utils from tests.functional import actions from google.appengine.ext import db COURSE_NAME = 'test_course' COURSE_TITLE = 'Test Course' ADMIN_EMAIL = 'test@example.com' AssessmentDef = collections.namedtuple('AssessmentDef', ['unit_id', 'title', 'html_content']) EntityDef = collections.namedtuple('EntityDef', ['entity_class', 'entity_id', 'entity_key_name', 'data']) ASSESSMENTS = [ AssessmentDef( 1, 'One Question', '<question quid="4785074604081152" weight="1" ' 'instanceid="8TvGgbrrbZ49"></question><br>'), AssessmentDef( 2, 'Groups And Questions', '<question quid="5066549580791808" weight="1" ' 'instanceid="zsgZ8dUMvJjz"></question><br>' '<question quid="5629499534213120" weight="1" ' 'instanceid="YlGaKQ2mnOPG"></question><br>' '<question-group qgid="5348024557502464" ' 'instanceid="YpoECeTunEpj"></question-group><br>' '<question-group qgid="5910974510923776" ' 'instanceid="FcIh3jyWOTbP"></question-group><br>'), AssessmentDef( 3, 'All Questions', '<question quid="6192449487634432" weight="1" ' 'instanceid="E5P0a0bFB0EH"></question><br>' '<question quid="5629499534213120" weight="1" ' 'instanceid="DlfLRsko2QHb"></question><br>' '<question quid="5066549580791808" weight="1" ' 'instanceid="hGrEjnP13pMA"></question><br>' '<question quid="4785074604081152" weight="1" ' 'instanceid="knWukHJApaQh"></question><br>'), ] ENTITIES = [ # Questions ----------------------------------------------------------- EntityDef( models.QuestionEntity, 4785074604081152, None, '{"question": "To produce maximum generosity, what should be the ' 'overall shape of the final protrusion?", "rows": 1, "columns": 1' '00, "defaultFeedback": "", "graders": [{"matcher": "case_insensi' 'tive", "feedback": "", "score": "0.7", "response": "oblong"}, {"' 'matcher": "case_insensitive", "feedback": "", "score": "0.3", "r' 'esponse": "extended"}], "type": 1, "description": "Maximum gener' 'osity protrusion shape", "version": "1.5", "hint": ""}'), EntityDef( models.QuestionEntity, 5066549580791808, None, '{"question": "Describe the shape of a standard trepanning hammer' '", "multiple_selections": false, "choices": [{"feedback": "", "s' 'core": 0.0, "text": "Round"}, {"feedback": "", "score": 0.0, "te' 'xt": "Square"}, {"feedback": "", "score": 1.0, "text": "Diamond"' '}, {"feedback": "", "score": 0.0, "text": "Pyramid"}], "type": 0' ', "description": "Trepanning hammer shape", "version": "1.5"}'), EntityDef( models.QuestionEntity, 5629499534213120, None, '{"question": "Describe an appropriate bedside manner for post-tr' 'eatment patient interaction", "rows": 1, "columns": 100, "defaul' 'tFeedback": "", "graders": [{"matcher": "case_insensitive", "fee' 'dback": "", "score": "1.0", "response": "gentle"}, {"matcher": "' 'case_insensitive", "feedback": "", "score": "0.8", "response": "' 'caring"}], "type": 1, "description": "Post-treatement interactio' 'n", "version": "1.5", "hint": ""}'), EntityDef( models.QuestionEntity, 6192449487634432, None, '{"question": "When making a personality shift, how hard should t' 'he strike be?", "multiple_selections": true, "choices": [{"feedb' 'ack": "", "score": -1.0, "text": "Light"}, {"feedback": "", "sco' 're": 0.7, "text": "Medium"}, {"feedback": "", "score": 0.3, "tex' 't": "Heavy"}, {"feedback": "", "score": -1.0, "text": "Crushing"' '}], "type": 0, "description": "Personality shift strike strength' '", "version": "1.5"}'), # Question Groups ----------------------------------------------------- EntityDef( models.QuestionGroupEntity, 5348024557502464, None, '{"description": "One MC, one SA", "introduction": "", "version":' '"1.5", "items": [{"question": 5066549580791808, "weight": "1"}, ' '{"question": 6192449487634432, "weight": "1"}]}'), EntityDef( models.QuestionGroupEntity, 5910974510923776, None, '{"description": "All Questions", "introduction": "All questions"' ', "version": "1.5", "items": [{"question": 4785074604081152, "we' 'ight": "0.25"}, {"question": 5066549580791808, "weight": "0.25"}' ', {"question": 5629499534213120, "weight": "0.25"}, {"question":' '6192449487634432, "weight": "0.25"}]}'), # Student Answers ----------------------------------------------------- EntityDef( models.StudentAnswersEntity, None, '115715231223232197316', '{"3": {"version": "1.5", "containedTypes": {"DlfLRsko2QHb": "SaQ' 'uestion", "E5P0a0bFB0EH": "McQuestion", "hGrEjnP13pMA": "McQuest' 'ion", "knWukHJApaQh": "SaQuestion"}, "hGrEjnP13pMA": [true, fals' 'e, false, false], "knWukHJApaQh": {"response": "fronk"}, "DlfLRs' 'ko2QHb": {"response": "phleem"}, "answers": {"DlfLRsko2QHb": "ph' 'leem", "E5P0a0bFB0EH": [1], "hGrEjnP13pMA": [0], "knWukHJApaQh":' '"fronk"}, "E5P0a0bFB0EH": [false, true, false, false], "individu' 'alScores": {"DlfLRsko2QHb": 0, "E5P0a0bFB0EH": 0.7, "hGrEjnP13pM' 'A": 0, "knWukHJApaQh": 0}}, "2": {"version": "1.5", "containedTy' 'pes": {"zsgZ8dUMvJjz": "McQuestion", "FcIh3jyWOTbP": ["SaQuestio' 'n", "McQuestion", "SaQuestion", "McQuestion"], "YlGaKQ2mnOPG": "' 'SaQuestion", "YpoECeTunEpj": ["McQuestion", "McQuestion"]}, "ans' 'wers": {"zsgZ8dUMvJjz": [1], "FcIh3jyWOTbP": ["round", [1], "col' 'd", [3]], "YlGaKQ2mnOPG": "gentle", "YpoECeTunEpj": [[2], [1]]},' '"FcIh3jyWOTbP": {"FcIh3jyWOTbP.2.5629499534213120": {"response":' '"cold"}, "FcIh3jyWOTbP.1.5066549580791808": [false, true, false,' 'false], "FcIh3jyWOTbP.3.6192449487634432": [false, false, false,' 'true], "FcIh3jyWOTbP.0.4785074604081152": {"response": "round"}}' ', "YlGaKQ2mnOPG": {"response": "gentle"}, "zsgZ8dUMvJjz": [false' ',true, false, false], "individualScores": {"zsgZ8dUMvJjz": 0, "F' 'cIh3jyWOTbP": [0, 0, 0, 0], "YlGaKQ2mnOPG": 1, "YpoECeTunEpj": [' '1, 0.7]}, "YpoECeTunEpj": {"YpoECeTunEpj.0.5066549580791808": [f' 'alse, false, true, false], "YpoECeTunEpj.1.6192449487634432": [f' 'alse, true, false, false]}}, "1": {"containedTypes": {"8TvGgbrrb' 'Z49": "SaQuestion"}, "version": "1.5", "answers": {"8TvGgbrrbZ49' '": "oblong"}, "individualScores": {"8TvGgbrrbZ49": 0.7}, "8TvGgb' 'rrbZ49": {"response": "oblong"}}}'), EntityDef( models.StudentAnswersEntity, None, '187186200184131193542', '{"3": {"version": "1.5", "containedTypes": {"DlfLRsko2QHb": "SaQ' 'uestion", "E5P0a0bFB0EH": "McQuestion", "hGrEjnP13pMA": "McQuest' 'ion", "knWukHJApaQh": "SaQuestion"}, "hGrEjnP13pMA": [false, tru' 'e, false, false], "knWukHJApaQh": {"response": "square"}, "DlfLR' 'sko2QHb": {"response": "caring"}, "answers": {"DlfLRsko2QHb": "c' 'aring", "E5P0a0bFB0EH": [1], "hGrEjnP13pMA": [1], "knWukHJApaQh"' ': "square"}, "E5P0a0bFB0EH": [false, true, false, false], "indiv' 'idualScores": {"DlfLRsko2QHb": 0.8, "E5P0a0bFB0EH": 0.7, "hGrEjn' 'P13pMA": 0, "knWukHJApaQh": 0}}, "2": {"version": "1.5", "contai' 'nedTypes": {"zsgZ8dUMvJjz": "McQuestion", "FcIh3jyWOTbP": ["SaQu' 'estion", "McQuestion", "SaQuestion", "McQuestion"], "YlGaKQ2mnOP' 'G": "SaQuestion", "YpoECeTunEpj": ["McQuestion", "McQuestion"]},' ' "answers": {"zsgZ8dUMvJjz": [3], "FcIh3jyWOTbP": ["spazzle", [3' '], "gloonk", [3]], "YlGaKQ2mnOPG": "frink", "YpoECeTunEpj": [[0]' ', [0]]}, "FcIh3jyWOTbP": {"FcIh3jyWOTbP.2.5629499534213120": {"r' 'esponse": "gloonk"}, "FcIh3jyWOTbP.1.5066549580791808": [false, ' 'false, false, true], "FcIh3jyWOTbP.3.6192449487634432": [false, ' 'false, false, true], "FcIh3jyWOTbP.0.4785074604081152": {"respon' 'se": "spazzle"}}, "YlGaKQ2mnOPG": {"response": "frink"}, "zsgZ8d' 'UMvJjz": [false, false, false, true], "individualScores": {"zsgZ' '8dUMvJjz": 0, "FcIh3jyWOTbP": [0, 0, 0, 0], "YlGaKQ2mnOPG": 0, "' 'YpoECeTunEpj": [0, 0]}, "YpoECeTunEpj": {"YpoECeTunEpj.0.5066549' '580791808": [true, false, false, false], "YpoECeTunEpj.1.6192449' '487634432": [true, false, false, false]}}, "1": {"containedTypes' '": {"8TvGgbrrbZ49": "SaQuestion"}, "version": "1.5", "answers": ' '{"8TvGgbrrbZ49": "spalpeen"}, "individualScores": {"8TvGgbrrbZ49' '": 0}, "8TvGgbrrbZ49": {"response": "spalpeen"}}}'), ] EXPECTED_COURSE_UNITS = [ { 'title': 'One Question', 'unit_id': '1', 'now_available': True, 'type': 'A', }, { 'title': 'Groups And Questions', 'unit_id': '2', 'now_available': True, 'type': 'A', }, { 'title': 'All Questions', 'unit_id': '3', 'now_available': True, 'type': 'A', } ] EXPECTED_QUESTIONS = [ { 'question_id': '4785074604081152', 'description': 'Maximum generosity protrusion shape', 'choices': [] }, { 'question_id': '5066549580791808', 'description': 'Trepanning hammer shape', 'choices': ['Round', 'Square', 'Diamond', 'Pyramid'] }, { 'question_id': '5629499534213120', 'description': 'Post-treatement interaction', 'choices': [] }, { 'question_id': '6192449487634432', 'description': 'Personality shift strike strength', 'choices': ['Light', 'Medium', 'Heavy', 'Crushing'] } ] EXPECTED_ANSWERS = [ {'unit_id': '1', 'sequence': 0, 'count': 1, 'is_valid': True, 'answer': 'oblong', 'question_id': '4785074604081152'}, {'unit_id': '1', 'sequence': 0, 'count': 1, 'is_valid': False, 'answer': 'spalpeen', 'question_id': '4785074604081152'}, {'unit_id': '2', 'sequence': 0, 'count': 1, 'is_valid': True, 'answer': '1', 'question_id': '5066549580791808'}, {'unit_id': '2', 'sequence': 0, 'count': 1, 'is_valid': True, 'answer': '3', 'question_id': '5066549580791808'}, {'unit_id': '2', 'sequence': 1, 'count': 1, 'is_valid': True, 'answer': 'gentle', 'question_id': '5629499534213120'}, {'unit_id': '2', 'sequence': 1, 'count': 1, 'is_valid': False, 'answer': 'frink', 'question_id': '5629499534213120'}, {'unit_id': '2', 'sequence': 2, 'count': 1, 'is_valid': True, 'answer': '0', 'question_id': '5066549580791808'}, {'unit_id': '2', 'sequence': 2, 'count': 1, 'is_valid': True, 'answer': '2', 'question_id': '5066549580791808'}, {'unit_id': '2', 'sequence': 3, 'count': 1, 'is_valid': True, 'answer': '0', 'question_id': '6192449487634432'}, {'unit_id': '2', 'sequence': 3, 'count': 1, 'is_valid': True, 'answer': '1', 'question_id': '6192449487634432'}, {'unit_id': '2', 'sequence': 4, 'count': 1, 'is_valid': False, 'answer': 'round', 'question_id': '4785074604081152'}, {'unit_id': '2', 'sequence': 4, 'count': 1, 'is_valid': False, 'answer': 'spazzle', 'question_id': '4785074604081152'}, {'unit_id': '2', 'sequence': 5, 'count': 1, 'is_valid': True, 'answer': '1', 'question_id': '5066549580791808'}, {'unit_id': '2', 'sequence': 5, 'count': 1, 'is_valid': True, 'answer': '3', 'question_id': '5066549580791808'}, {'unit_id': '2', 'sequence': 6, 'count': 1, 'is_valid': False, 'answer': 'cold', 'question_id': '5629499534213120'}, {'unit_id': '2', 'sequence': 6, 'count': 1, 'is_valid': False, 'answer': 'gloonk', 'question_id': '5629499534213120'}, {'unit_id': '2', 'sequence': 7, 'count': 2, 'is_valid': True, 'answer': '3', 'question_id': '6192449487634432'}, {'unit_id': '3', 'sequence': 0, 'count': 2, 'is_valid': True, 'answer': '1', 'question_id': '6192449487634432'}, {'unit_id': '3', 'sequence': 1, 'count': 1, 'is_valid': True, 'answer': 'caring', 'question_id': '5629499534213120'}, {'unit_id': '3', 'sequence': 1, 'count': 1, 'is_valid': False, 'answer': 'phleem', 'question_id': '5629499534213120'}, {'unit_id': '3', 'sequence': 2, 'count': 1, 'is_valid': True, 'answer': '0', 'question_id': '5066549580791808'}, {'unit_id': '3', 'sequence': 2, 'count': 1, 'is_valid': True, 'answer': '1', 'question_id': '5066549580791808'}, {'unit_id': '3', 'sequence': 3, 'count': 1, 'is_valid': False, 'answer': 'fronk', 'question_id': '4785074604081152'}, {'unit_id': '3', 'sequence': 3, 'count': 1, 'is_valid': False, 'answer': 'square', 'question_id': '4785074604081152'}, ] class StudentAnswersAnalyticsTest(actions.TestBase): def setUp(self): super(StudentAnswersAnalyticsTest, self).setUp() self.context = actions.simple_add_course(COURSE_NAME, ADMIN_EMAIL, COURSE_TITLE) self.course = courses.Course(None, self.context) for assessment in ASSESSMENTS: self._add_assessment(self.course, assessment) self.course.save() for entity in ENTITIES: self._add_entity(self.context, entity) def _add_assessment(self, course, assessment_def): assessment = course.add_assessment() assessment.unit_id = assessment_def.unit_id assessment.title = assessment_def.title assessment.now_available = True assessment.html_content = assessment_def.html_content def _add_entity(self, context, entity): with common_utils.Namespace(context.get_namespace_name()): if entity.entity_id: key = db.Key.from_path(entity.entity_class.__name__, entity.entity_id) to_store = entity.entity_class(data=entity.data, key=key) else: to_store = entity.entity_class(key_name=entity.entity_key_name, data=entity.data) to_store.put() def _get_data_source(self, source_name): xsrf_token = crypto.XsrfTokenManager.create_xsrf_token( data_sources_utils.DATA_SOURCE_ACCESS_XSRF_ACTION) url = ('/test_course/rest/data/%s/items?' % source_name + 'data_source_token=%s&page_number=0' % xsrf_token) response = self.get(url) return transforms.loads(response.body)['data'] def _verify_content(self, expected, actual): for expected_item, actual_item in zip(expected, actual): self.assertDictContainsSubset(expected_item, actual_item) def test_end_to_end(self): actions.login(ADMIN_EMAIL, is_admin=True) # Start map/reduce analysis job. response = self.get( '/test_course/dashboard?action=analytics&tab=questions') form = response.forms['gcb-run-visualization-question_answers'] self.submit(form, response) # Wait for map/reduce to run to completion. self.execute_all_deferred_tasks() # Verify output. course_units = self._get_data_source('course_units') self._verify_content(EXPECTED_COURSE_UNITS, course_units) course_questions = self._get_data_source('course_questions') self._verify_content(EXPECTED_QUESTIONS, course_questions) question_answers = self._get_data_source('question_answers') self._verify_content(EXPECTED_ANSWERS, question_answers)
Python
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Functional tests for modules/course_explorer/course_explorer.py.""" __author__ = 'rahulsingal@google.com (Rahul Singal)' import actions from actions import assert_contains from actions import assert_does_not_contain from actions import assert_equals from controllers import sites from models import config from models import models from models import transforms from models.models import PersonalProfile from modules.course_explorer import course_explorer from modules.course_explorer import student class BaseExplorerTest(actions.TestBase): """Base class for testing explorer pages.""" def setUp(self): super(BaseExplorerTest, self).setUp() config.Registry.test_overrides[ models.CAN_SHARE_STUDENT_PROFILE.name] = True config.Registry.test_overrides[ course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.name] = True def tearDown(self): config.Registry.test_overrides = {} super(BaseExplorerTest, self).tearDown() class CourseExplorerTest(BaseExplorerTest): """Tests course_explorer module.""" def test_single_uncompleted_course(self): """Tests for a single available course.""" # This call should redirect to explorer page. response = self.get('/') assert_contains('/explorer', response.location) name = 'Test student courses page' email = 'Student' actions.login(email) # Test the explorer page. response = self.get('/explorer') assert_equals(response.status_int, 200) assert_contains('Register', response.body) # Navbar should not contain profile tab. assert_does_not_contain( '<a href="/explorer/profile">Profile</a>', response.body) # Test 'my courses' page when a student is not enrolled in any course. response = self.get('/explorer/courses') assert_equals(response.status_int, 200) assert_contains('You are not currently enrolled in any course', response.body) # Test 'my courses' page when a student is enrolled in all courses. actions.register(self, name) response = self.get('/explorer/courses') assert_equals(response.status_int, 200) assert_contains('Go to course', response.body) assert_does_not_contain('You are not currently enrolled in any course', response.body) # After the student registers for a course, # profile tab should be visible in navbar. assert_contains( '<a href="/explorer/profile">Profile</a>', response.body) # Test profile page. response = self.get('/explorer/profile') assert_contains('<td>%s</td>' % email, response.body) assert_contains('<td>%s</td>' % name, response.body) assert_contains('Progress', response.body) assert_does_not_contain('View score', response.body) def test_single_completed_course(self): """Tests when a single completed course is present.""" email = 'test_assessments@google.com' name = 'Test Assessments' # Register. actions.login(email) actions.register(self, name) response = self.get('/explorer') # Before a course is not completed, # explorer page should not show 'view score' button. assert_does_not_contain('View score', response.body) # Assign a grade to the course enrolled to mark it complete. profile = PersonalProfile.get_by_key_name(email) info = {'final_grade': 'A'} course_info_dict = {'': info} profile.course_info = transforms.dumps(course_info_dict) profile.put() # Check if 'View score' text is visible on profile page. response = self.get('/explorer/profile') assert_contains('View score', response.body) # Check if 'Go to course' button is not visible on explorer page. response = self.get('/explorer') assert_does_not_contain('Go to course', response.body) # Check if 'View score' button is visible on explorer page. response = self.get('/explorer') assert_contains('View score', response.body) def test_multiple_course(self): """Tests when multiple courses are available.""" sites.setup_courses('course:/test::ns_test, course:/:/') name = 'Test completed course' email = 'Student' # Make the course available. get_environ_old = sites.ApplicationContext.get_environ def get_environ_new(self): environ = get_environ_old(self) environ['course']['now_available'] = True return environ sites.ApplicationContext.get_environ = get_environ_new actions.login(email) actions.register(self, name) response = self.get('/explorer/courses') # Assert if 'View course list' text is shown on my course page. assert_contains('View course list', response.body) # Clean up app_context. sites.ApplicationContext.get_environ = get_environ_old sites.reset_courses() class CourseExplorerDisabledTest(actions.TestBase): """Tests when course explorer is disabled.""" def get_auto_deploy(self): return False def test_anonymous_access(self): """Tests for disabled course explorer page.""" # disable the explorer config.Registry.test_overrides[ course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.name] = False self.assertFalse(course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.value) # check root URL's properly redirect to login response = self.get('/') assert_equals(response.status_int, 302) assert_contains( 'http://localhost/admin/welcome', response.location) response = self.get('/assets/img/your_logo_here.png') assert_equals(response.status_int, 302) assert_contains('accounts/Login', response.location) # check explorer pages are not accessible not_accessibles = [ '/explorer', '/explorer/courses', '/explorer/profile', '/explorer/assets/img/your_logo_here.png'] for not_accessible in not_accessibles: response = self.get(not_accessible, expect_errors=True) assert_equals(response.status_int, 404) # enable course explorer config.Registry.test_overrides[ course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.name] = True self.assertTrue(course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.value) # check explorer pages are accessible accessibles = [ '/explorer', '/explorer/courses', '/explorer/assets/img/your_logo_here.png'] for accessible in accessibles: response = self.get(accessible, expect_errors=True) assert_equals(response.status_int, 200) # check student pages are not accessible response = self.get('/explorer/profile') assert_equals(response.status_int, 302) self.assertEqual('http://localhost/explorer', response.location) def test_student_access(self): # enable course explorer config.Registry.test_overrides[ course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.name] = True self.assertTrue(course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.value) # check not being logged in response = self.get('/explorer') assert_contains('Explore Courses', response.body) assert_does_not_contain('My Courses', response.body) assert_does_not_contain('Admin Site', response.body) # login and check logged in student perspective config.Registry.test_overrides[ sites.GCB_COURSES_CONFIG.name] = 'course:/:/' email = 'student' actions.login(email) response = self.get('/explorer') assert_contains('Explore Courses', response.body) assert_contains('My Courses', response.body) assert_does_not_contain('Admin Site', response.body) def test_admin_access(self): # enable course explorer config.Registry.test_overrides[ course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.name] = True self.assertTrue(course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.value) # check the admin site link actions.login('admin@test.foo', is_admin=True) response = self.get('/explorer') assert_contains('Admin Site', response.body) class GlobalProfileTest(BaseExplorerTest): """Tests course_explorer module.""" def test_change_of_name(self): """Tests for a single available course.""" # This call should redirect to explorer page. response = self.get('/') assert_contains('/explorer', response.location) name = 'Test global profile page' email = 'student_global_profile@example.com' actions.login(email) # Test the explorer page. response = self.get('/explorer') assert_equals(response.status_int, 200) assert_contains('Register', response.body) # Test 'my courses' page when a student is enrolled in all courses. actions.register(self, name) # Test profile page. response = self.get('/explorer/profile') assert_contains('<td>%s</td>' % email, response.body) assert_contains('<td>%s</td>' % name, response.body) # Change the name now new_name = 'New global name' response.form.set('name', new_name) response = self.submit(response.form) assert_equals(response.status_int, 302) response = self.get('/explorer/profile') assert_contains('<td>%s</td>' % email, response.body) assert_contains('<td>%s</td>' % new_name, response.body) # Change name with bad xsrf token. response = self.get('/explorer/profile') assert_equals(response.status_int, 200) new_name = 'New Bad global name' response.form.set('name', new_name) response.form.set('xsrf_token', 'asdfsdf') response = response.form.submit(expect_errors=True) assert_equals(response.status_int, 403) # Change name with empty name shold fail. response = self.get('/explorer/profile') assert_equals(response.status_int, 200) new_name = '' response.form.set('name', new_name) response = response.form.submit(expect_errors=True) assert_equals(response.status_int, 400) # Change name with overlong name should fail for str. response = self.get('/explorer/profile') assert_equals(response.status_int, 200) new_name = 'a' * (student._STRING_PROPERTY_MAX_BYTES + 1) response.form.set('name', new_name) response = response.form.submit(expect_errors=True) assert_equals(response.status_int, 400) # Change name with overlong name should fail for unicode. response = self.get('/explorer/profile') assert_equals(response.status_int, 200) # \u03a3 == Sigma. len == 1 for unicode; 2 for utf-8 encoded str. new_name = u'\u03a3' + ('a' * (student._STRING_PROPERTY_MAX_BYTES - 1)) response.form.set('name', new_name) response = response.form.submit(expect_errors=True) assert_equals(response.status_int, 400)
Python
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Functional tests for models/review.py.""" __author__ = [ 'johncox@google.com (John Cox)', ] from models import entities from models import models from models import student_work from models import transforms from tests.functional import actions from google.appengine.ext import db class ReferencedModel(entities.BaseEntity): pass class UnvalidatedReference(entities.BaseEntity): referenced_model_key = student_work.KeyProperty() class ValidatedReference(entities.BaseEntity): referenced_model_key = student_work.KeyProperty(kind=ReferencedModel.kind()) class KeyPropertyTest(actions.TestBase): """Tests KeyProperty.""" def setUp(self): super(KeyPropertyTest, self).setUp() self.referenced_model_key = ReferencedModel().put() def test_bidirectional_transforms_succeed(self): """Tests that transforms entity<->dict<->json round trips correctly.""" referenced_model_key = ReferencedModel().put() entity = UnvalidatedReference(referenced_model_key=referenced_model_key) entity.put() transformed = transforms.entity_to_dict(entity) self.assertEqual(referenced_model_key, entity.referenced_model_key) self.assertEqual( referenced_model_key, transformed['referenced_model_key']) new_key = ReferencedModel().put() transformed['referenced_model_key'] = new_key restored = transforms.dict_to_entity(entity, transformed) self.assertEqual(new_key, restored.referenced_model_key) json = transforms.dict_to_json(transformed, None) self.assertEqual(str(new_key), json['referenced_model_key']) from_json = transforms.json_to_dict( json, {'properties': {'referenced_model_key': {'type': 'string'}}}) self.assertEqual({'referenced_model_key': str(new_key)}, from_json) def test_type_not_validated_if_kind_not_passed(self): model_key = db.Model().put() unvalidated = UnvalidatedReference(referenced_model_key=model_key) self.assertEqual(model_key, unvalidated.referenced_model_key) def test_validation_and_datastore_round_trip_of_keys_succeeds(self): """Tests happy path for both validation and (de)serialization.""" model_with_reference = ValidatedReference( referenced_model_key=self.referenced_model_key) model_with_reference_key = model_with_reference.put() model_with_reference_from_datastore = db.get(model_with_reference_key) self.assertEqual( self.referenced_model_key, model_with_reference_from_datastore.referenced_model_key) custom_model_from_datastore = db.get( model_with_reference_from_datastore.referenced_model_key) self.assertEqual( self.referenced_model_key, custom_model_from_datastore.key()) self.assertTrue(isinstance( model_with_reference_from_datastore.referenced_model_key, db.Key)) def test_validation_fails(self): model_key = db.Model().put() self.assertRaises( db.BadValueError, ValidatedReference, referenced_model_key='not_a_key') self.assertRaises( db.BadValueError, ValidatedReference, referenced_model_key=model_key) class ReviewTest(actions.ExportTestBase): def setUp(self): super(ReviewTest, self).setUp() self.reviewee_email = 'reviewee@exmaple.com' self.reviewer_email = 'reviewer@example.com' self.unit_id = 'unit_id' self.reviewee = models.Student(key_name=self.reviewee_email) self.reviewee_key = self.reviewee.put() self.reviewer = models.Student(key_name=self.reviewer_email) self.reviewer_key = self.reviewer.put() self.review = student_work.Review( reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, unit_id=self.unit_id) self.review_key = self.review.put() def test_constructor_sets_key_name(self): self.assertEqual( student_work.Review.key_name( self.unit_id, self.reviewee_key, self.reviewer_key), self.review_key.name()) def test_for_export_transforms_correctly(self): exported = self.review.for_export(self.transform) self.assert_blacklisted_properties_removed(self.review, exported) self.assertEqual( 'transformed_' + self.reviewer_key.name(), exported.reviewer_key.name()) def test_safe_key_makes_key_names_safe(self): safe_review_key = student_work.Review.safe_key( self.review_key, self.transform) _, safe_unit_id, safe_reviewee_key_str, safe_reviewer_key_str = ( student_work.Review._split_key(safe_review_key.name())) safe_reviewee_key = db.Key(encoded=safe_reviewee_key_str) safe_reviewer_key = db.Key(encoded=safe_reviewer_key_str) self.assertEqual( 'transformed_' + self.reviewee_email, safe_reviewee_key.name()) self.assertEqual( 'transformed_' + self.reviewer_email, safe_reviewer_key.name()) self.assertEqual(self.unit_id, safe_unit_id) class SubmissionTest(actions.ExportTestBase): def setUp(self): super(SubmissionTest, self).setUp() self.reviewee_email = 'reviewee@example.com' self.unit_id = 'unit_id' self.reviewee = models.Student(key_name=self.reviewee_email) self.reviewee_key = self.reviewee.put() self.submission = student_work.Submission( reviewee_key=self.reviewee_key, unit_id=self.unit_id) self.submission_key = self.submission.put() def test_constructor_sets_key_name(self): self.assertEqual( student_work.Submission.key_name(self.unit_id, self.reviewee_key), self.submission_key.name()) def test_for_export_transforms_correctly(self): exported = self.submission.for_export(self.transform) self.assert_blacklisted_properties_removed(self.submission, exported) self.assertEqual( 'transformed_' + self.reviewee_key.name(), exported.reviewee_key.name()) def test_safe_key_makes_reviewee_key_name_safe(self): safe_submission_key = student_work.Submission.safe_key( self.submission_key, self.transform) _, safe_unit_id, safe_reviewee_key_name = ( student_work.Submission._split_key(safe_submission_key.name())) self.assertEqual( 'transformed_' + self.reviewee_email, safe_reviewee_key_name) self.assertEqual(self.unit_id, safe_unit_id)
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for unit header/footer presence.""" __author__ = 'Mike Gainer (mgainer@google.com)' from models import courses from tests.functional import actions COURSE_NAME = 'unit_header_footer' COURSE_TITLE = 'Unit Header Footer' ADMIN_EMAIL = 'admin@foo.com' BASE_URL = '/' + COURSE_NAME UNIT_HEADER_TEXT = 'This is the unit header.' UNIT_FOOTER_TEXT = 'The unit footer is here.' class UnitHeaderFooterTest(actions.TestBase): def setUp(self): super(UnitHeaderFooterTest, self).setUp() context = actions.simple_add_course( COURSE_NAME, ADMIN_EMAIL, COURSE_TITLE) self.course = courses.Course(None, context) self.unit = self.course.add_unit() self.unit.now_available = True self.unit.unit_header = UNIT_HEADER_TEXT self.unit.unit_footer = UNIT_FOOTER_TEXT self.course.save() self.url = BASE_URL + '/unit?unit=' + str(self.unit.unit_id) actions.login(ADMIN_EMAIL) def _add_assessment(self, title): assessment = self.course.add_assessment() assessment.title = title assessment.html_content = 'assessment content' assessment.now_available = True return assessment def _add_lesson(self, title): lesson = self.course.add_lesson(self.unit) lesson.lesson_title = title lesson.objectives = 'lesson content' lesson.now_available = True return lesson def test_no_lessons_or_assessments_or_header_or_footer(self): self.unit.unit_header = None self.unit.unit_footer = None self.course.save() response = self.get(self.url) self.assertNotIn(UNIT_HEADER_TEXT, response) self.assertNotIn(UNIT_FOOTER_TEXT, response) self.assertIn('This unit has no content', response) def test_no_lessons_or_assessments(self): response = self.get(self.url) self.assertIn(UNIT_HEADER_TEXT, response) self.assertIn(UNIT_FOOTER_TEXT, response) self.assertNotIn('This unit has no content', response) def test_no_lessons_or_assessments_all_on_one_page(self): self.unit.show_contents_on_one_page = True self.course.save() response = self.get(self.url) self.assertIn(UNIT_HEADER_TEXT, response) self.assertIn(UNIT_FOOTER_TEXT, response) self.assertNotIn('This unit has no content', response) def test_only_pre_assessment(self): assessment = self._add_assessment('The Assessment') self.unit.pre_assessment = assessment.unit_id self.course.save() response = self.get(self.url) self.assertIn(UNIT_HEADER_TEXT, response) self.assertIn(UNIT_FOOTER_TEXT, response) def test_only_post_assessment(self): assessment = self._add_assessment('The Assessment') self.unit.post_assessment = assessment.unit_id self.course.save() response = self.get(self.url) self.assertIn(UNIT_HEADER_TEXT, response) self.assertIn(UNIT_FOOTER_TEXT, response) def test_only_lesson(self): self._add_lesson('The Lesson') self.course.save() response = self.get(self.url) self.assertIn(UNIT_HEADER_TEXT, response) self.assertIn(UNIT_FOOTER_TEXT, response) def test_multiple_lessons(self): self._add_lesson('Lesson One') lesson_two = self._add_lesson('Lesson Two') lesson_three = self._add_lesson('Lesson Three') self.course.save() response = self.get(self.url) self.assertIn(UNIT_HEADER_TEXT, response) self.assertNotIn(UNIT_FOOTER_TEXT, response) response = self.get(self.url + '&lesson=' + str(lesson_two.lesson_id)) self.assertNotIn(UNIT_HEADER_TEXT, response) self.assertNotIn(UNIT_FOOTER_TEXT, response) response = self.get(self.url + '&lesson=' + str(lesson_three.lesson_id)) self.assertNotIn(UNIT_HEADER_TEXT, response) self.assertIn(UNIT_FOOTER_TEXT, response) def test_pre_post_assessment_and_lesson(self): pre_assessment = self._add_assessment('Pre Assessment') self.unit.pre_assessment = pre_assessment.unit_id post_assessment = self._add_assessment('Post Assessment') self.unit.post_assessment = post_assessment.unit_id lesson = self._add_lesson('The Lesson') self.course.save() response = self.get(self.url) self.assertIn(UNIT_HEADER_TEXT, response) self.assertNotIn(UNIT_FOOTER_TEXT, response) response = self.get(self.url + '&lesson=' + str(lesson.lesson_id)) self.assertNotIn(UNIT_HEADER_TEXT, response) self.assertNotIn(UNIT_FOOTER_TEXT, response) response = self.get(self.url + '&assessment=' + str(post_assessment.unit_id)) self.assertNotIn(UNIT_HEADER_TEXT, response) self.assertIn(UNIT_FOOTER_TEXT, response) def test_lesson_with_activity(self): lesson = self._add_lesson('The Lesson') lesson.has_activity = True lesson.activity_title = 'The Activity' self.course.save() response = self.get(self.url) self.assertIn(UNIT_HEADER_TEXT, response) self.assertNotIn(UNIT_FOOTER_TEXT, response) response = self.get(self.url + '&activity=true') self.assertNotIn(UNIT_HEADER_TEXT, response) self.assertIn(UNIT_FOOTER_TEXT, response) def test_lesson_with_activity_and_post_assessment(self): lesson = self._add_lesson('The Lesson') lesson.has_activity = True lesson.activity_title = 'The Activity' post_assessment = self._add_assessment('The Assessment') self.unit.post_assessment = post_assessment.unit_id self.course.save() response = self.get(self.url) self.assertIn(UNIT_HEADER_TEXT, response) self.assertNotIn(UNIT_FOOTER_TEXT, response) response = self.get(self.url + '&activity=true') self.assertNotIn(UNIT_HEADER_TEXT, response) self.assertNotIn(UNIT_FOOTER_TEXT, response) response = self.get(self.url + '&assessment=' + str(post_assessment.unit_id)) self.assertNotIn(UNIT_HEADER_TEXT, response) self.assertIn(UNIT_FOOTER_TEXT, response) def test_unit_all_on_one_page(self): pre_assessment = self._add_assessment('Pre Assessment') self.unit.pre_assessment = pre_assessment.unit_id post_assessment = self._add_assessment('Post Assessment') self.unit.post_assessment = post_assessment.unit_id self._add_lesson('The Lesson') self.unit.show_contents_on_one_page = True self.course.save() response = self.get(self.url) self.assertIn(UNIT_HEADER_TEXT, response) self.assertIn(UNIT_FOOTER_TEXT, response)
Python
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Functional tests for the balancer module.""" __author__ = [ 'johncox@google.com (John Cox)', ] import types from models import config from models import transforms from modules.balancer import balancer from tests.functional import actions from google.appengine.api import urlfetch from google.appengine.ext import db # Allow access to protected code under test. pylint: disable=protected-access class _FakeResponse(object): def __init__(self, code, body): self.content = transforms.dumps(body) self.status_code = code class ExternalTaskTest(actions.TestBase): def setUp(self): super(ExternalTaskTest, self).setUp() self.worker_id = 'worker_id' self.external_task = balancer._ExternalTask( status=balancer._ExternalTask.RUNNING, worker_id='worker_id') self.key = self.external_task.put() def test_get_key_by_ticket_raises_value_error(self): self.assertRaises( ValueError, balancer._ExternalTask.get_key_by_ticket, 1) def test_get_key_by_ticket_and_get_ticket_round_trip(self): ticket = self.external_task.get_ticket() saved_external_task = db.get( balancer._ExternalTask.get_key_by_ticket(ticket)) self.assertEqual(self.key, saved_external_task.key()) def test_get_key_by_ticket_and_get_ticket_by_key_round_trip(self): ticket = balancer._ExternalTask.get_ticket_by_key(self.key) saved_external_task = db.get( balancer._ExternalTask.get_key_by_ticket(ticket)) self.assertEqual(self.key, saved_external_task.key()) class ManagerTest(actions.TestBase): def setUp(self): super(ManagerTest, self).setUp() self.user_id = 'user_id' self.worker_id = 'worker_id' def test_create(self): no_user_id_key = balancer.Manager.create() with_user_id_key = balancer.Manager.create(user_id=self.user_id) no_user_id = db.get(no_user_id_key) with_user_id = db.get(with_user_id_key) self.assertEqual(balancer._ExternalTask.CREATED, no_user_id.status) self.assertIsNone(no_user_id.user_id) self.assertEqual(balancer._ExternalTask.CREATED, with_user_id.status) self.assertEqual(self.user_id, with_user_id.user_id) def test_delete_removes_entity(self): ticket = balancer.Manager.create() self.assertTrue(balancer.Manager.get(ticket)) balancer.Manager._delete(ticket) self.assertFalse(balancer.Manager.get(ticket)) def test_get(self): ticket = balancer.Manager.create() self.assertEqual(ticket, balancer.Manager.get(ticket).ticket) balancer.Manager._delete(ticket) self.assertIsNone(balancer.Manager.get(ticket)) def test_list(self): self.assertEqual([], balancer.Manager.list(self.user_id)) missing_ticket = balancer.Manager.create(user_id=self.user_id) first_match_ticket = balancer.Manager.create(user_id=self.user_id) second_match_ticket = balancer.Manager.create(user_id=self.user_id) balancer.Manager._delete(missing_ticket) self.assertEqual( [first_match_ticket, second_match_ticket], [task.ticket for task in balancer.Manager.list(self.user_id)]) def test_mark_deleted(self): ticket = balancer.Manager.create() self.assertEqual( balancer._ExternalTask.CREATED, balancer.Manager.get(ticket).status) balancer.Manager.mark_deleted(ticket) self.assertEqual( balancer._ExternalTask.DELETED, balancer.Manager.get(ticket).status) balancer.Manager._delete(ticket) self.assertRaises( balancer.NotFoundError, balancer.Manager.mark_deleted, ticket) def test_mark_done_updates_result_and_status(self): ticket = balancer.Manager.create() task = balancer.Manager.get(ticket) self.assertIsNone(task.result) self.assertEqual(balancer._ExternalTask.CREATED, task.status) result = 'result' balancer.Manager.mark_done( ticket, balancer._ExternalTask.COMPLETE, result) task = balancer.Manager.get(ticket) self.assertEqual(result, task.result) self.assertEqual(balancer._ExternalTask.COMPLETE, task.status) def test_mark_done_raises_not_found_error_if_no_task_for_ticket(self): ticket = balancer.Manager.create() balancer.Manager._delete(ticket) self.assertRaises( balancer.NotFoundError, balancer.Manager.mark_done, ticket, balancer._ExternalTask.COMPLETE, 'result') def test_mark_done_raises_transition_error_if_status_nonterminal(self): ticket = balancer.Manager.create() self.assertFalse( balancer._ExternalTask.is_status_terminal( balancer._ExternalTask.RUNNING)) self.assertRaises( balancer.TransitionError, balancer.Manager.mark_done, ticket, balancer._ExternalTask.RUNNING, 'result') def test_mark_failed(self): ticket = balancer.Manager.create() self.assertEqual( balancer._ExternalTask.CREATED, balancer.Manager.get(ticket).status) balancer.Manager.mark_failed(ticket) self.assertEqual( balancer._ExternalTask.FAILED, balancer.Manager.get(ticket).status) balancer.Manager._delete(ticket) self.assertRaises( balancer.NotFoundError, balancer.Manager.mark_deleted, ticket) def test_mark_running(self): ticket = balancer.Manager.create() task = balancer.Manager.get(ticket) self.assertEqual(balancer._ExternalTask.CREATED, task.status) self.assertIsNone(task.worker_id) balancer.Manager.mark_running(ticket, self.worker_id) task = balancer.Manager.get(ticket) self.assertEqual(balancer._ExternalTask.RUNNING, task.status) self.assertEqual(self.worker_id, task.worker_id) balancer.Manager._delete(ticket) self.assertRaises( balancer.NotFoundError, balancer.Manager.mark_running, ticket, self.worker_id) class _RestTestBase(actions.TestBase): def setUp(self): super(_RestTestBase, self).setUp() self.worker_url = 'http://worker_url' def tearDown(self): config.Registry.test_overrides = {} super(_RestTestBase, self).tearDown() def assert_bad_request_error(self, response): self.assertEqual(400, response.status_code) self.assertIn('Bad request', response.body) def assert_response_equal(self, expected_code, expected_body, response): self.assertEqual(expected_code, response.status_code) self.assertEqual(expected_body, transforms.loads(response.body)) def assert_rest_enabled_but_url_not_set_error(self, response): self.assertEqual(500, response.status_code) self.assertIn('No worker pool found', response.body) def assert_rest_not_enabled_error(self, response): self.assertEqual(404, response.status_code) self.assertIn('Not found', response.body) def assert_unable_to_dispatch_request_error(self, response): self.assertEqual(500, response.status_code) self.assertIn('Unable to dispatch request', response.body) def configure_registry(self): config.Registry.test_overrides[ balancer.EXTERNAL_TASK_BALANCER_REST_ENABLED.name] = True config.Registry.test_overrides[ balancer.EXTERNAL_TASK_BALANCER_WORKER_URL.name] = self.worker_url class ProjectRestHandlerTest(_RestTestBase): def setUp(self): super(ProjectRestHandlerTest, self).setUp() self.project = 'project' self.params = self.make_request_params(self.project) def make_request_params(self, project): return {'request': transforms.dumps({'project': project})} def test_get_returns_400_if_request_malformed(self): self.configure_registry() self.assert_bad_request_error(self.testapp.get( balancer._REST_URL_PROJECT, expect_errors=True)) def test_get_returns_404_if_config_enabled_false(self): self.assert_rest_not_enabled_error(self.testapp.get( balancer._REST_URL_PROJECT, expect_errors=True)) def test_get_returns_500_if_cannot_dispatch_request_to_pool(self): self.configure_registry() self.assert_unable_to_dispatch_request_error(self.testapp.get( balancer._REST_URL_PROJECT, expect_errors=True, params=self.params)) def test_get_returns_500_if_config_enabled_but_no_url_set(self): config.Registry.test_overrides[ balancer.EXTERNAL_TASK_BALANCER_REST_ENABLED.name] = True self.assert_rest_enabled_but_url_not_set_error(self.testapp.get( balancer._REST_URL_PROJECT, expect_errors=True)) def test_get_returns_worker_response(self): self.configure_registry() expected_code = 200 expected_body = {'payload': 'contents'} def fetch_response( _, deadline=None, headers=None, method=None, payload=None): return _FakeResponse(expected_code, expected_body) self.swap(balancer.urlfetch, 'fetch', fetch_response) response = self.testapp.get( balancer._REST_URL_PROJECT, params=self.params) self.assert_response_equal(expected_code, expected_body, response) class TaskRestHandlerTest(_RestTestBase): def setUp(self): super(TaskRestHandlerTest, self).setUp() self.user_id = 'user_id' self.worker_id = 'http://worker_id' def assert_invalid_status_or_payload_too_big_error(self, response): self.assertEqual(500, response.status_code) self.assertIn('Invalid worker status or payload too big', response.body) def assert_task_found(self, expected_task, response): self.assertEqual(200, response.status_code) self.assertEqual( expected_task.for_json(), transforms.loads(response.body)) def assert_task_not_found_error(self, response): self.assertEqual(404, response.status_code) self.assertIn('Task not found for ticket', response.body) def assert_ticket_mismatch_error(self, response): self.assertEqual(500, response.status_code) self.assertIn('Ticket mismatch', response.body) def assert_unable_to_compose_request_for_worker_error(self, response): self.assertEqual(500, response.status_code) self.assertIn('Unable to compose request for worker', response.body) def assert_worker_failed_error(self, response): self.assertEqual(500, response.status_code) self.assertIn('Worker failed', response.body) def assert_worker_locked_error(self, response): self.assertEqual(500, response.status_code) self.assertIn('Worker locked', response.body) def assert_worker_sent_partial_response_error(self, response): self.assertEqual(500, response.status_code) self.assertIn('Worker sent partial response', response.body) def make_get_request_params(self, ticket, payload=None, worker_id=None): body = {'ticket': ticket} if payload: body['payload'] = payload if worker_id: body['worker_id'] = worker_id return {'request' : transforms.dumps(body)} def make_post_request_params(self, payload): return {'request': transforms.dumps(payload)} def test_get_returns_200_if_task_already_done(self): self.configure_registry() ticket = balancer.Manager.create() balancer.Manager.mark_done( ticket, balancer._ExternalTask.COMPLETE, 'result') task = balancer.Task._from_external_task( db.get(balancer._ExternalTask.get_key_by_ticket(ticket))) params = self.make_get_request_params(ticket) response = self.testapp.get(balancer._REST_URL_TASK, params=params) self.assert_task_found(task, response) def test_get_returns_400_if_request_malformed(self): self.configure_registry() self.assert_bad_request_error(self.testapp.get( balancer._REST_URL_TASK, expect_errors=True)) def test_get_returns_404_if_config_enabled_false(self): self.assert_rest_not_enabled_error(self.testapp.get( balancer._REST_URL_TASK, expect_errors=True)) def test_get_returns_404_if_ticket_has_no_matching_task(self): self.configure_registry() ticket = balancer.Manager.create() balancer.Manager._delete(ticket) params = self.make_get_request_params(ticket) self.assert_task_not_found_error(self.testapp.get( balancer._REST_URL_TASK, expect_errors=True, params=params)) def test_get_returns_404_if_ticket_invalid(self): self.configure_registry() ticket = 1 params = self.make_get_request_params(ticket) self.assert_task_not_found_error(self.testapp.get( balancer._REST_URL_TASK, expect_errors=True, params=params)) def test_get_returns_500_if_config_enabled_but_no_url_set(self): config.Registry.test_overrides[ balancer.EXTERNAL_TASK_BALANCER_REST_ENABLED.name] = True self.assert_rest_enabled_but_url_not_set_error(self.testapp.get( balancer._REST_URL_TASK, expect_errors=True)) def test_get_returns_500_if_task_update_fails(self): self.configure_registry() ticket = balancer.Manager.create() balancer.Manager.mark_running(ticket, self.worker_id) params = self.make_get_request_params(ticket) def worker_response( _, deadline=None, headers=None, method=None, payload=None): return _FakeResponse( 200, {'payload': {'status': balancer._ExternalTask.COMPLETE, 'payload': 'x' * 1024 * 1025}}) # Overflow db. self.swap(balancer.urlfetch, 'fetch', worker_response) self.assert_invalid_status_or_payload_too_big_error(self.testapp.get( balancer._REST_URL_TASK, expect_errors=True, params=params)) def test_get_returns_500_if_unable_to_compose_request_for_worker(self): self.configure_registry() ticket = balancer.Manager.create() params = self.make_get_request_params(ticket) self.assert_unable_to_compose_request_for_worker_error(self.testapp.get( balancer._REST_URL_TASK, expect_errors=True, params=params)) def test_get_returns_500_if_worker_sends_partial_response(self): self.configure_registry() ticket = balancer.Manager.create() balancer.Manager.mark_running(ticket, self.worker_id) params = self.make_get_request_params(ticket) def worker_response( _, deadline=None, headers=None, method=None, payload=None): return _FakeResponse(200, {'payload': {'no_status': None}}) self.swap(balancer.urlfetch, 'fetch', worker_response) self.assert_worker_sent_partial_response_error(self.testapp.get( balancer._REST_URL_TASK, expect_errors=True, params=params)) def test_get_relays_non_200_response_from_worker(self): self.configure_registry() ticket = balancer.Manager.create() balancer.Manager.mark_running(ticket, self.worker_id) params = self.make_get_request_params(ticket) self.assert_unable_to_dispatch_request_error(self.testapp.get( balancer._REST_URL_TASK, expect_errors=True, params=params)) def test_get_relays_worker_response_if_status_nonterminal(self): self.configure_registry() ticket = balancer.Manager.create() balancer.Manager.mark_running(ticket, self.worker_id) params = self.make_get_request_params(ticket) def worker_response( _, deadline=None, headers=None, method=None, payload=None): return _FakeResponse(200, {'payload': {'status': 'nonterminal'}}) self.swap(balancer.urlfetch, 'fetch', worker_response) response = self.testapp.get(balancer._REST_URL_TASK, params=params) self.assertEqual(200, response.status_code) self.assertIn('nonterminal', response.body) def test_get_updates_task_relays_worker_response_if_status_terminal(self): self.configure_registry() ticket = balancer.Manager.create() balancer.Manager.mark_running(ticket, self.worker_id) expected_payload = { 'payload': { 'status': balancer._ExternalTask.COMPLETE, 'payload': 'new_payload', }, } params = self.make_get_request_params(ticket) def worker_response( _, deadline=None, headers=None, method=None, payload=None): return _FakeResponse(200, expected_payload) self.swap(balancer.urlfetch, 'fetch', worker_response) response = self.testapp.get(balancer._REST_URL_TASK, params=params) task = balancer.Manager.get(ticket) self.assert_response_equal(200, expected_payload, response) self.assertEqual('new_payload', task.result) self.assertEqual(balancer._ExternalTask.COMPLETE, task.status) def test_post_returns_400_if_request_malformed(self): self.configure_registry() self.assert_bad_request_error(self.testapp.post( balancer._REST_URL_TASK, expect_errors=True)) def test_post_returns_404_if_config_enabled_false(self): self.assert_rest_not_enabled_error(self.testapp.post( balancer._REST_URL_TASK, expect_errors=True)) def test_post_returns_500_if_config_enabled_but_no_url_set(self): config.Registry.test_overrides[ balancer.EXTERNAL_TASK_BALANCER_REST_ENABLED.name] = True self.assert_rest_enabled_but_url_not_set_error(self.testapp.post( balancer._REST_URL_TASK, expect_errors=True)) # TODO(johncox): figure out a way to test op.ready() false. def test_post_returns_200_and_marks_task_running(self): self.configure_registry() params = self.make_post_request_params({'user_id': self.user_id}) ticket = balancer.Manager.create() worker_response_body = { 'payload': { 'payload': None, 'ticket': ticket, 'status': balancer._ExternalTask.RUNNING, } } def create(*args, **kwargs): return ticket def worker_response( _, deadline=None, headers=None, method=None, payload=None): return _FakeResponse(200, worker_response_body) bound_create = types.MethodType( create, balancer.Manager(), balancer.Manager) self.swap(balancer.Manager, 'create', bound_create) self.swap(balancer.urlfetch, 'fetch', worker_response) response = self.testapp.post(balancer._REST_URL_TASK, params=params) task = balancer.Manager.get(ticket) self.assert_response_equal(200, worker_response_body, response) self.assertEqual(balancer._ExternalTask.RUNNING, task.status) def test_post_returns_200_and_marks_task_running_if_retry_succeeds(self): self.configure_registry() params = self.make_post_request_params({'user_id': self.user_id}) ticket = balancer.Manager.create() def create(*args, **kwargs): return ticket def successful_retry(self, response, op): return 200, {'payload': {'status': 'running', 'ticket': ticket}} def worker_response( _, deadline=None, headers=None, method=None, payload=None): return _FakeResponse(500, {'payload': balancer._WORKER_LOCKED}) bound_create = types.MethodType( create, balancer.Manager(), balancer.Manager) self.swap(balancer.Manager, 'create', bound_create) self.swap( balancer._TaskRestHandler, '_retry_create_task', successful_retry) self.swap(balancer.urlfetch, 'fetch', worker_response) response = self.testapp.post(balancer._REST_URL_TASK, params=params) external_task = balancer._ExternalTask.all().fetch(1)[0] self.assertEqual(200, response.status_code) self.assertEqual(balancer._ExternalTask.RUNNING, external_task.status) def test_post_returns_500_and_marks_task_failed_if_retry_fails(self): self.configure_registry() params = self.make_post_request_params({'user_id': self.user_id}) ticket = balancer.Manager.create() def create(*args, **kwargs): return ticket def worker_response( _, deadline=None, headers=None, method=None, payload=None): return _FakeResponse(500, {'payload': balancer._WORKER_LOCKED}) bound_create = types.MethodType( create, balancer.Manager(), balancer.Manager) self.swap(balancer.Manager, 'create', bound_create) self.swap(balancer.urlfetch, 'fetch', worker_response) response = self.testapp.post( balancer._REST_URL_TASK, expect_errors=True, params=params) external_task = balancer._ExternalTask.all().fetch(1)[0] self.assert_worker_locked_error(response) self.assertEqual(balancer._ExternalTask.FAILED, external_task.status) def test_post_returns_500_and_marks_task_failed_if_ticket_mismatch(self): self.configure_registry() params = self.make_post_request_params({'user_id': self.user_id}) def worker_response( _, deadline=None, headers=None, method=None, payload=None): return _FakeResponse( 200, {'payload': {'status': 'running', 'payload': None}}) self.swap(balancer.urlfetch, 'fetch', worker_response) response = self.testapp.post( balancer._REST_URL_TASK, expect_errors=True, params=params) external_task = balancer._ExternalTask.all().fetch(1)[0] self.assert_ticket_mismatch_error(response) self.assertEqual(balancer._ExternalTask.FAILED, external_task.status) def test_post_returns_500_and_marks_task_failed_if_worker_failed(self): self.configure_registry() params = self.make_post_request_params({'user_id': self.user_id}) ticket = balancer.Manager.create() def create(*args, **kwargs): return ticket def worker_response( _, deadline=None, headers=None, method=None, payload=None): return _FakeResponse(500, {'payload': {'ticket': ticket}}) bound_create = types.MethodType( create, balancer.Manager(), balancer.Manager) self.swap(balancer.Manager, 'create', bound_create) self.swap(balancer.urlfetch, 'fetch', worker_response) response = self.testapp.post( balancer._REST_URL_TASK, expect_errors=True, params=params) external_task = balancer._ExternalTask.all().fetch(1)[0] self.assert_worker_failed_error(response) self.assertEqual(balancer._ExternalTask.FAILED, external_task.status) class WorkerPoolTest(actions.TestBase): def setUp(self): super(WorkerPoolTest, self).setUp() self.op = balancer._GetProjectOperation('payload') def assert_unable_to_dispatch_request_error(self, result): code, body = result self.assertEqual(500, code) self.assertEqual('Unable to dispatch request', body['payload']) def test_do_fetch_returns_code_and_transformed_body_from_worker(self): expected_code = 200 expected_body = {'payload': 'contents'} def fetch_response( _, deadline=None, headers=None, method=None, payload=None): return _FakeResponse(expected_code, expected_body) self.swap(balancer.urlfetch, 'fetch', fetch_response) code, body = balancer._WorkerPool._do_fetch( 'http://url', 'GET', self.op) self.assertEqual(expected_code, code) self.assertEqual(expected_body, body) def test_do_fetch_returns_500_when_urlfetch_raises(self): def fetch_error( _, deadline=None, headers=None, method=None, payload=None): raise urlfetch.DownloadError self.swap(balancer.urlfetch, 'fetch', fetch_error) self.assert_unable_to_dispatch_request_error( balancer._WorkerPool._do_fetch('http://url', 'GET', self.op))
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests that verify asset handling via REST.""" __author__ = 'Mike Gainer (mgainer@google.com)' import cgi import os import urllib from common import crypto from models import transforms from modules.dashboard import filer from tests.functional import actions COURSE_NAME = 'test_course' COURSE_TITLE = 'Test Course' NAMESPACE = 'ns_%s' % COURSE_NAME ADMIN_EMAIL = 'admin@foo.com' TEXT_ASSET_URL = '/%s%s' % (COURSE_NAME, filer.TextAssetRESTHandler.URI) ITEM_ASSET_URL = '/%s%s' % (COURSE_NAME, filer.AssetItemRESTHandler.URI) FILES_HANDLER_URL = '/%s%s' % (COURSE_NAME, filer.FilesItemRESTHandler.URI) def _post_asset(test, base, key_name, file_name, content, locale=None): xsrf_token = crypto.XsrfTokenManager.create_xsrf_token( filer.AssetItemRESTHandler.XSRF_TOKEN_NAME) if key_name: key = os.path.join(base, key_name) else: key = base if locale: key = '/locale/%s/%s' % (locale, key) response = test.post( '/%s%s' % (test.COURSE_NAME, filer.AssetItemRESTHandler.URI), {'request': transforms.dumps({ 'xsrf_token': cgi.escape(xsrf_token), 'payload': transforms.dumps({'key': key, 'base': base})})}, upload_files=[('file', file_name, content)]) return response class AssetsRestTest(actions.TestBase): def setUp(self): super(AssetsRestTest, self).setUp() actions.simple_add_course(COURSE_NAME, ADMIN_EMAIL, COURSE_TITLE) actions.login(ADMIN_EMAIL, is_admin=True) actions.update_course_config(COURSE_NAME, { 'extra_locales': [ {'locale': 'de_DE', 'availability': 'available'}]}) self.COURSE_NAME = COURSE_NAME def test_add_file_in_unsupported_dir(self): # Upload file via REST POST xsrf_token = crypto.XsrfTokenManager.create_xsrf_token( filer.TextAssetRESTHandler.XSRF_TOKEN_NAME) key = 'assets/unsupported/foo.js' contents = 'alert("Hello, world");' response = self.put(TEXT_ASSET_URL, {'request': transforms.dumps({ 'xsrf_token': cgi.escape(xsrf_token), 'key': key, 'payload': transforms.dumps({'contents': contents})})}) payload = transforms.loads(response.body) self.assertEquals(400, payload['status']) def test_add_file_in_subdir(self): # Upload file via REST POST xsrf_token = crypto.XsrfTokenManager.create_xsrf_token( filer.TextAssetRESTHandler.XSRF_TOKEN_NAME) key = 'assets/lib/my_project/foo.js' contents = 'alert("Hello, world");' response = self.put(TEXT_ASSET_URL, {'request': transforms.dumps({ 'xsrf_token': cgi.escape(xsrf_token), 'key': key, 'payload': transforms.dumps({'contents': contents})})}) payload = transforms.loads(response.body) self.assertEquals(200, payload['status']) # Verify that content is available via REST GET. response = self.get(TEXT_ASSET_URL + '?key=%s' % cgi.escape(key)) payload = transforms.loads(response.body) self.assertEquals(200, payload['status']) payload = transforms.loads(payload['payload']) self.assertEquals(contents, payload['contents']) # Verify that file uploaded to subdir is available via HTTP server response = self.get('/%s/%s' % (COURSE_NAME, key)) self.assertEquals(contents, response.body) def test_add_new_asset(self): base = 'assets/lib' name = 'foo.js' content = 'alert("Hello, world");' response = _post_asset(self, base, None, name, content) self.assertIn('<status>200</status>', response) self.assertIn('<message>Saved.</message>', response) # Verify asset available via AssetHandler response = self.get('/%s/%s/%s' % (COURSE_NAME, base, name)) self.assertEquals(content, response.body) def test_add_new_asset_with_key(self): base = 'assets/lib' name = 'foo.js' content = 'alert("Hello, world");' response = _post_asset(self, base, name, name, content) self.assertIn('<status>200</status>', response) self.assertIn('<message>Saved.</message>', response) # Verify asset available via AssetHandler response = self.get('/%s/%s/%s' % (COURSE_NAME, base, name)) self.assertEquals(content, response.body) def test_add_asset_in_subdir(self): base = 'assets/lib' key_name = 'a/b/c/foo.js' file_name = 'foo.js' content = 'alert("Hello, world");' response = _post_asset(self, base, key_name, file_name, content) self.assertIn('<status>200</status>', response.body) self.assertIn('<message>Saved.</message>', response.body) # Verify asset available via AssetHandler response = self.get('/%s/%s/%s' % (COURSE_NAME, base, key_name)) self.assertEquals(content, response.body) def test_add_asset_in_bad_dir(self): base = 'assets/not_a_supported_asset_directory' name = 'foo.js' content = 'alert("Hello, world");' response = _post_asset(self, base, name, name, content) self.assertIn('<status>400</status>', response.body) self.assertIn('<message>Malformed request.</message>', response.body) def test_get_item_asset_url_in_subdir(self): response = self.get(ITEM_ASSET_URL + '?key=assets/lib/my_project') payload = transforms.loads(response.body) self.assertEquals(200, payload['status']) def test_get_asset_directory(self): response = self.get(ITEM_ASSET_URL + '?key=assets/img') payload = transforms.loads(transforms.loads(response.body)['payload']) self.assertEquals('assets/img', payload['key']) self.assertEquals('assets/img', payload['base']) self.assertNotIn('asset_url', payload) def test_get_nonexistent_asset(self): response = self.get(ITEM_ASSET_URL + '?key=assets/img/foo.jpg') payload = transforms.loads(transforms.loads(response.body)['payload']) self.assertEquals('assets/img/foo.jpg', payload['key']) self.assertEquals('assets/img', payload['base']) self.assertNotIn('asset_url', payload) def test_cannot_overwrite_existing_file_without_key(self): def add_asset(): base = 'assets/lib' name = 'foo.js' content = 'alert("Hello, world");' return _post_asset(self, base, None, name, content) response = add_asset() self.assertIn('<message>Saved.</message>', response.body) response = add_asset() self.assertIn('<status>403</status>', response.body) self.assertIn('<message>Cannot overwrite existing file.</message>', response.body) def test_can_overwrite_existing_file_with_key(self): def add_asset(): base = 'assets/lib' name = 'foo.js' content = 'alert("Hello, world");' return _post_asset(self, base, name, name, content) response = add_asset() self.assertIn('<message>Saved.</message>', response.body) response = add_asset() self.assertIn('<message>Saved.</message>', response.body) def test_overwrite_ignores_file_name(self): base = 'assets/lib' key_name = 'foo.js' file_name = 'bar.js' content = 'alert("Hello, world");' _post_asset(self, base, key_name, file_name, content) response = self.get('/%s/%s/%s' % (COURSE_NAME, base, key_name)) self.assertEquals(200, response.status_int) response = self.get('/%s/%s/%s' % (COURSE_NAME, base, file_name), expect_errors=True) self.assertEquals(404, response.status_int) def test_deleting(self): base = 'assets/img' name = 'foo.jpg' en_content = 'xyzzy' _post_asset(self, base, name, name, en_content) xsrf_token = crypto.XsrfTokenManager.create_xsrf_token('delete-asset') key = os.path.join(base, name) delete_url = '%s?%s' % ( FILES_HANDLER_URL, urllib.urlencode({ 'key': key, 'xsrf_token': cgi.escape(xsrf_token) })) self.delete(delete_url) asset_url = '/%s/%s/%s' % (COURSE_NAME, base, name) response = self.get(asset_url, expect_errors=True) self.assertEquals(404, response.status_int)
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests that walk through Course Builder pages.""" __author__ = 'Mike Gainer (mgainer@google.com)' import urllib from common import crypto from controllers import sites from models import config from models import models from models import roles from models import transforms from models.custom_modules import Module from models.models import MemcacheManager from tests.functional import actions COURSE_NAME = 'roles_test' SUPER_ADMIN_EMAIL = 'super@foo.com' SITE_ADMIN_EMAIL = 'site@foo.com' COURSE_ADMIN_EMAIL = 'course@foo.como' STUDENT_EMAIL = 'student@foo.com' DUMMY_EMAIL = 'dummy@foo.com' ROLE = 'test_role' PERMISSION_MODULE = Module('test_module', '', [], []) PERMISSION = 'can_test' PERMISSION_DESCRIPTION = 'Can perform tests.' class RolesTest(actions.TestBase): @classmethod def setUpClass(cls): sites.ApplicationContext.get_environ_old = ( sites.ApplicationContext.get_environ) def get_environ_new(slf): environ = slf.get_environ_old() environ['course']['now_available'] = True environ['course'][roles.KEY_ADMIN_USER_EMAILS] = ( '[%s]' % COURSE_ADMIN_EMAIL) return environ sites.ApplicationContext.get_environ = get_environ_new @classmethod def tearDownClass(cls): sites.ApplicationContext.get_environ = ( sites.ApplicationContext.get_environ_old) def tearDown(self): super(RolesTest, self).tearDown() sites.reset_courses() config.Registry.test_overrides.clear() roles.Roles._REGISTERED_PERMISSIONS = self.old_registered_permission config.Registry.test_overrides[models.CAN_USE_MEMCACHE.name] = False def setUp(self): super(RolesTest, self).setUp() actions.login(COURSE_ADMIN_EMAIL, is_admin=True) payload_dict = { 'name': COURSE_NAME, 'title': 'Roles Test', 'admin_email': COURSE_ADMIN_EMAIL} request = { 'payload': transforms.dumps(payload_dict), 'xsrf_token': crypto.XsrfTokenManager.create_xsrf_token( 'add-course-put')} response = self.testapp.put('/rest/courses/item?%s' % urllib.urlencode( {'request': transforms.dumps(request)}), {}) self.assertEquals(response.status_int, 200) sites.setup_courses('course:/%s::ns_%s, course:/:/' % ( COURSE_NAME, COURSE_NAME)) actions.logout() config.Registry.test_overrides[roles.GCB_ADMIN_LIST.name] = ( '[%s]' % SITE_ADMIN_EMAIL) self.old_registered_permission = roles.Roles._REGISTERED_PERMISSIONS roles.Roles._REGISTERED_PERMISSIONS = {} config.Registry.test_overrides[models.CAN_USE_MEMCACHE.name] = True def _get_course(self): courses = sites.get_all_courses() for course in courses: if course.namespace == 'ns_' + COURSE_NAME: return course return None #----------------------------- Super admin tests def test_super_admin_when_super_admin(self): actions.login(SUPER_ADMIN_EMAIL, is_admin=True) self.assertTrue(roles.Roles.is_direct_super_admin()) def test_super_admin_when_site_admin(self): actions.login(SUPER_ADMIN_EMAIL) self.assertFalse(roles.Roles.is_direct_super_admin()) def test_super_admin_when_course_admin(self): actions.login(COURSE_ADMIN_EMAIL) self.assertFalse(roles.Roles.is_direct_super_admin()) def test_super_admin_when_student(self): actions.login(STUDENT_EMAIL) self.assertFalse(roles.Roles.is_direct_super_admin()) def test_super_admin_when_not_logged_in(self): self.assertFalse(roles.Roles.is_direct_super_admin()) #----------------------------- Site admin tests def test_site_admin_when_super_admin(self): actions.login(SUPER_ADMIN_EMAIL, is_admin=True) self.assertTrue(roles.Roles.is_super_admin()) def test_site_admin_when_site_admin(self): actions.login(SITE_ADMIN_EMAIL) self.assertTrue(roles.Roles.is_super_admin()) def test_site_admin_when_course_admin(self): actions.login(COURSE_ADMIN_EMAIL) self.assertFalse(roles.Roles.is_super_admin()) def test_site_admin_when_student(self): actions.login(STUDENT_EMAIL) self.assertFalse(roles.Roles.is_super_admin()) def test_site_admin_when_not_logged_in(self): self.assertFalse(roles.Roles.is_super_admin()) #----------------------------- Course admin tests def test_course_admin_when_super_admin(self): actions.login(SUPER_ADMIN_EMAIL, is_admin=True) self.assertTrue(roles.Roles.is_course_admin(self._get_course())) def test_course_admin_when_site_admin(self): actions.login(SITE_ADMIN_EMAIL) self.assertTrue(roles.Roles.is_course_admin(self._get_course())) def test_course_admin_when_course_admin(self): actions.login(COURSE_ADMIN_EMAIL) self.assertTrue(roles.Roles.is_course_admin(self._get_course())) def test_course_admin_when_student(self): actions.login(STUDENT_EMAIL) self.assertFalse(roles.Roles.is_course_admin(self._get_course())) def test_course_admin_when_not_logged_in(self): self.assertFalse(roles.Roles.is_course_admin(self._get_course())) def test_is_user_allowed_super_admin(self): actions.login(SUPER_ADMIN_EMAIL, is_admin=True) self.assertTrue(roles.Roles.is_user_allowed( self._get_course(), PERMISSION_MODULE, PERMISSION)) def test_is_user_allowed_site_admin(self): actions.login(SITE_ADMIN_EMAIL) self.assertTrue(roles.Roles.is_user_allowed( self._get_course(), PERMISSION_MODULE, PERMISSION)) def test_is_user_allowed_course_admin(self): actions.login(COURSE_ADMIN_EMAIL) self.assertTrue(roles.Roles.is_user_allowed( self._get_course(), PERMISSION_MODULE, PERMISSION)) def test_is_user_allowed_not_logged_in(self): self.assertFalse(roles.Roles.is_user_allowed( self._get_course(), PERMISSION_MODULE, PERMISSION)) def test_is_user_allowed_logged_in(self): actions.login(STUDENT_EMAIL) self.assertFalse(roles.Roles.is_user_allowed( self._get_course(), PERMISSION_MODULE, PERMISSION)) def _create_role(self): role_dto = models.RoleDTO(None, { 'name': ROLE, 'users': [STUDENT_EMAIL], 'permissions': {PERMISSION_MODULE.name: [PERMISSION]} }) models.RoleDAO.save(role_dto) @classmethod def _permissions_callback(cls): yield roles.Permission(PERMISSION, PERMISSION_DESCRIPTION) def test_is_user_allowed_assigned_permission(self): self.assertFalse(roles.Roles.is_user_allowed( self._get_course(), PERMISSION_MODULE, PERMISSION)) self._create_role() actions.login(STUDENT_EMAIL) self.assertTrue(roles.Roles.is_user_allowed( self._get_course(), PERMISSION_MODULE, PERMISSION)) def test_register_permissions(self): roles.Roles.register_permissions( PERMISSION_MODULE, self._permissions_callback) self.assertIn( (PERMISSION_MODULE, self._permissions_callback), roles.Roles.get_permissions() ) def test_unregister_permission(self): roles.Roles.register_permissions( PERMISSION_MODULE, self._permissions_callback) roles.Roles.unregister_permissions(PERMISSION_MODULE) self.assertNotIn( (PERMISSION_MODULE, self._permissions_callback), roles.Roles.get_permissions() ) def test_memcache(self): self._create_role() actions.login(STUDENT_EMAIL) roles.Roles.is_user_allowed( self._get_course(), PERMISSION_MODULE, PERMISSION) mem_map = MemcacheManager.get(roles.Roles.memcache_key) self.assertIn(STUDENT_EMAIL, mem_map) self.assertIn(PERMISSION_MODULE.name, mem_map[STUDENT_EMAIL]) self.assertIn( PERMISSION, mem_map[STUDENT_EMAIL][PERMISSION_MODULE.name]) # --------------------------- Whitelisting tests: # See tests/functional/whitelist.py, which covers both the actual # role behavior as well as more-abstract can-you-see-the-resource # operations.
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for unit description presence.""" __author__ = 'Mike Gainer (mgainer@google.com)' from models import courses from tests.functional import actions COURSE_NAME = 'unit_descriptions' COURSE_TITLE = 'Unit Descriptions' ADMIN_EMAIL = 'admin@foo.com' BASE_URL = '/' + COURSE_NAME UNIT_DESCRIPTION = 'This is the unit. There are many like it, but...' ASSESSMENT_DESCRIPTION = 'None shall pass.' LINK_DESCRIPTION = 'Over the hills and a great way off' class UnitDescriptionsTest(actions.TestBase): def test_descriptions(self): context = actions.simple_add_course( COURSE_NAME, ADMIN_EMAIL, COURSE_TITLE) course = courses.Course(None, context) unit = course.add_unit() unit.title = 'The Unit' unit.now_available = True unit.description = UNIT_DESCRIPTION assessment = course.add_assessment() assessment.title = 'The Assessment' assessment.now_available = True assessment.description = ASSESSMENT_DESCRIPTION link = course.add_link() link.title = 'The Link' link.now_available = True link.description = LINK_DESCRIPTION course.save() actions.login(ADMIN_EMAIL) response = self.get(BASE_URL) self.assertIn(unit.description, response) self.assertIn(assessment.description, response) self.assertIn(link.description, response)
Python
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Functional tests for VFS features.""" __author__ = [ 'mgainer@google.com (Mike Gainer)', ] from common import utils as common_utils from models import config from models import courses from models import models from models import vfs from tests.functional import actions LOREM_IPSUM = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque nisl libero, interdum vel lectus eget, lacinia vestibulum eros. Maecenas posuere finibus pulvinar. Aenean eu eros mauris. Quisque maximus feugiat sollicitudin. Vestibulum aliquam vulputate nulla vel volutpat. Donec in pharetra enim. Nullam et nunc sed nisi ornare suscipit. Curabitur sit amet enim eu ante tristique tincidunt. Aliquam ac nunc luctus arcu ornare iaculis vitae nec turpis. Vivamus ut justo pellentesque, accumsan dui ut, iaculis elit. Nullam congue nunc odio, sed laoreet nisl iaculis eget. Aenean urna libero, iaculis ac sapien at, condimentum pellentesque tellus. Phasellus dapibus arcu a dolor sollicitudin, non tempus erat dapibus. Pellentesque id pellentesque nunc. Nullam interdum, nulla sit amet convallis scelerisque, ligula tellus placerat risus, sit amet sodales elit diam sed tellus. Pellentesque sollicitudin orci imperdiet fermentum semper. Curabitur id ornare elit. Proin pharetra, diam ac iaculis sed. """ * 10 class CourseCachingTest(actions.TestBase): COURSE_NAME = 'test_course' ADMIN_EMAIL = 'admin@foo.com' NAMESPACE = 'ns_%s' % COURSE_NAME def setUp(self): super(CourseCachingTest, self).setUp() self.app_context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'Test Course') self.course = courses.Course(handler=None, app_context=self.app_context) actions.login(self.ADMIN_EMAIL) config.Registry.test_overrides[models.CAN_USE_MEMCACHE.name] = True def tearDown(self): del config.Registry.test_overrides[models.CAN_USE_MEMCACHE.name] super(CourseCachingTest, self).tearDown() def _add_large_unit(self, num_lessons): unit = self.course.add_unit() for unused in range(num_lessons): lesson = self.course.add_lesson(unit) lesson.objectives = LOREM_IPSUM self.course.save() return unit def test_large_course_is_cached_in_memcache(self): num_lessons = models.MEMCACHE_MAX / len(LOREM_IPSUM) unit = self._add_large_unit(num_lessons) memcache_keys = courses.CachedCourse13._make_keys() # Verify memcache has no contents upon initial save. memcache_values = models.MemcacheManager.get_multi( memcache_keys, self.NAMESPACE) self.assertEquals({}, memcache_values) # Load course. It won't be in memcache, so Course will fetch it # from VFS and save it in memcache. course = courses.Course(handler=None, app_context=self.app_context) # Check that things have gotten into memcache. memcache_values = models.MemcacheManager.get_multi( memcache_keys, self.NAMESPACE) self.assertEquals( memcache_keys[0:2], sorted(memcache_values.keys()), 'Only two keys should be present.') self.assertEquals( models.MEMCACHE_MAX, len(memcache_values[memcache_keys[0]]), 'Shard #0 should be full of data.') self.assertGreater( len(memcache_values[memcache_keys[1]]), 0, 'Shard #1 should have data.') # Destroy the contents of the course from VFS, so that we are # absolutely certain that if the next course load succeeds, it has # come from the memcache version, rather than VFS. file_key_names = vfs.DatastoreBackedFileSystem._generate_file_key_names( '/data/course.json', vfs._MAX_VFS_SHARD_SIZE + 1) with common_utils.Namespace(self.NAMESPACE): shard_0 = vfs.FileDataEntity.get_by_key_name(file_key_names[0]) shard_0.delete() shard_1 = vfs.FileDataEntity.get_by_key_name(file_key_names[1]) shard_1.delete() # Re-load course to force load from memcache. course = courses.Course(handler=None, app_context=self.app_context) # Verify contents. lessons = course.get_lessons(unit.unit_id) self.assertEquals(num_lessons, len(lessons)) for lesson in lessons: self.assertEquals(lesson.objectives, LOREM_IPSUM) # Delete items from memcache, and verify that loading fails. This # re-verifies that the loaded data was, in fact, coming from memcache. courses.CachedCourse13.delete(self.app_context) with self.assertRaises(AttributeError): course = courses.Course(handler=None, app_context=self.app_context) def test_recovery_from_missing_initial_shard(self): self._test_recovery_from_missing_shard(0) def test_recovery_from_missing_trailing_shard(self): self._test_recovery_from_missing_shard(1) def _test_recovery_from_missing_shard(self, shard_index): num_lessons = models.MEMCACHE_MAX / len(LOREM_IPSUM) unit = self._add_large_unit(num_lessons) memcache_keys = courses.CachedCourse13._make_keys() # Load course. It won't be in memcache, so Course will fetch it # from VFS and save it in memcache. course = courses.Course(handler=None, app_context=self.app_context) models.MemcacheManager.delete(memcache_keys[shard_index]) # Re-load course to force load from memcache. This should fail back # to VFS, and still load successfully. course = courses.Course(handler=None, app_context=self.app_context) # Verify contents. lessons = course.get_lessons(unit.unit_id) self.assertEquals(num_lessons, len(lessons)) for lesson in lessons: self.assertEquals(lesson.objectives, LOREM_IPSUM) def test_course_that_is_too_large_to_cache_is_not_cached(self): num_lessons = courses.CachedCourse13._max_size() / len(LOREM_IPSUM) # Fudge factor to get size of course as saved to under the VFS limit # but over the memcache limit. num_lessons -= 18 unit = self._add_large_unit(num_lessons) memcache_keys = courses.CachedCourse13._make_keys() # Load the course, which would normally populate memcache with the # loaded content, but will not have, because the course is too large. # Verify that. course = courses.Course(handler=None, app_context=self.app_context) memcache_values = models.MemcacheManager.get_multi( memcache_keys, self.NAMESPACE) self.assertEquals( {}, memcache_values, 'Memcache for too-large course should be cleared.') def test_small_course_occupies_only_one_shard(self): self._add_large_unit(num_lessons=1) memcache_keys = courses.CachedCourse13._make_keys() # Load course to get shard put into memcache. course = courses.Course(handler=None, app_context=self.app_context) memcache_values = models.MemcacheManager.get_multi( memcache_keys, self.NAMESPACE) self.assertEquals( memcache_keys[0:1], memcache_values.keys(), 'Only shard zero should be present in memcache.')
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests exercising the analytics internals (not individual analytics).""" __author__ = 'Mike Gainer (mgainer@google.com)' import time from webtest import app from common import catch_and_log from common import crypto from common import utils as common_utils from models import data_sources from models import entities from models import transforms from models.data_sources import utils as data_sources_utils from google.appengine.ext import db # Data source must be registered before we import actions; actions imports # 'main', which does all setup and registration in package scope. class Character(entities.BaseEntity): user_id = db.StringProperty(indexed=True) goal = db.StringProperty(indexed=True) name = db.StringProperty(indexed=False) age = db.IntegerProperty(indexed=False) rank = db.IntegerProperty(indexed=True) _PROPERTY_EXPORT_BLACKLIST = [name] def for_export(self, transform_fn): model = super(Character, self).for_export(transform_fn) model.user_id = transform_fn(self.user_id) return model @classmethod def safe_key(cls, db_key, transform_fn): return db.Key.from_path(cls.kind(), transform_fn(db_key.id_or_name())) class CharacterDataSource(data_sources.AbstractDbTableRestDataSource): @classmethod def get_name(cls): return 'character' @classmethod def get_entity_class(cls): return Character data_sources.Registry.register(CharacterDataSource) from tests.functional import actions class DataSourceTest(actions.TestBase): def setUp(self): super(DataSourceTest, self).setUp() with common_utils.Namespace(self.NAMESPACE): self.characters = [ Character( user_id='001', goal='L', rank=4, age=8, name='Charlie'), Character( user_id='002', goal='L', rank=6, age=6, name='Sally'), Character( user_id='003', goal='L', rank=0, age=8, name='Lucy'), Character( user_id='004', goal='G', rank=2, age=7, name='Linus'), Character( user_id='005', goal='G', rank=8, age=8, name='Max'), Character( user_id='006', goal='G', rank=1, age=8, name='Patty'), Character( user_id='007', goal='R', rank=9, age=35, name='Othmar'), Character( user_id='008', goal='R', rank=5, age=2, name='Snoopy'), Character( user_id='009', goal='R', rank=7, age=8, name='Pigpen'), Character( user_id='010', goal='R', rank=3, age=8, name='Violet'), ] for c in self.characters: c.put() def tearDown(self): with common_utils.Namespace(self.NAMESPACE): db.delete(Character.all(keys_only=True).run()) super(DataSourceTest, self).tearDown() class PiiExportTest(DataSourceTest): COURSE_NAME = 'test_course' ADMIN_EMAIL = 'admin@foo.com' NAMESPACE = 'ns_' + COURSE_NAME def setUp(self): super(PiiExportTest, self).setUp() self.app_context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'The Course') self.data_source_context = ( CharacterDataSource.get_context_class().build_blank_default({}, 20)) def test_get_non_pii_data(self): data = self._get_page_data(0) self.assertEquals(10, len(data)) for item in data: self.assertNotIn('name', item) def test_get_non_pii_schema(self): schema = self._get_schema() self.assertNotIn('name', schema) def test_get_pii_data(self): self.data_source_context.send_uncensored_pii_data = True data = self._get_page_data(0) self.assertEquals(10, len(data)) for item in data: self.assertIn('name', item) def test_get_pii_schema(self): self.data_source_context.send_uncensored_pii_data = True schema = self._get_schema() self.assertIn('name', schema) def _get_schema(self): log = catch_and_log.CatchAndLog() schema = CharacterDataSource.get_schema( self.app_context, log, self.data_source_context) return schema def _get_page_data(self, page_number): log = catch_and_log.CatchAndLog() schema = self._get_schema() data, _ = CharacterDataSource.fetch_values( self.app_context, self.data_source_context, schema, log, page_number) return data class PaginatedTableTest(DataSourceTest): """Verify operation of paginated access to AppEngine DB tables.""" NAMESPACE = '' def test_simple_read(self): email = 'admin@google.com' actions.login(email, is_admin=True) response = transforms.loads(self.get('/rest/data/character/items').body) self.assertIn('data', response) self._verify_data(self.characters, response['data']) self.assertIn('schema', response) self.assertIn('user_id', response['schema']) self.assertIn('age', response['schema']) self.assertIn('rank', response['schema']) self.assertNotIn('name', response['schema']) # blacklisted self.assertIn('log', response) self.assertIn('source_context', response) self.assertIn('params', response) self.assertEquals([], response['params']['filters']) self.assertEquals([], response['params']['orderings']) def test_admin_required(self): with self.assertRaisesRegexp(app.AppError, 'Bad response: 403'): self.get('/rest/data/character/items') def test_filtered_read(self): email = 'admin@google.com' actions.login(email, is_admin=True) # Single greater-equal filter response = transforms.loads(self.get( '/rest/data/character/items?filter=rank>=7').body) self.assertEquals(3, len(response['data'])) for character in response['data']: self.assertTrue(character['rank'] >= 7) # Single less-than filter response = transforms.loads(self.get( '/rest/data/character/items?filter=rank<7').body) self.assertEquals(7, len(response['data'])) for character in response['data']: self.assertTrue(character['rank'] < 7) # Multiple filters finding some rows response = transforms.loads(self.get( '/rest/data/character/items?filter=rank<5&filter=goal=L').body) self.assertEquals(2, len(response['data'])) for character in response['data']: self.assertTrue(character['rank'] < 5) self.assertTrue(character['goal'] == 'L') def test_ordered_read(self): email = 'admin@google.com' actions.login(email, is_admin=True) # Single ordering by rank response = transforms.loads(self.get( '/rest/data/character/items?ordering=rank').body) self.assertEquals(10, len(response['data'])) prev_rank = -1 for character in response['data']: self.assertTrue(character['rank'] > prev_rank) prev_rank = character['rank'] # Single ordering by rank, descending response = transforms.loads(self.get( '/rest/data/character/items?ordering=-rank').body) self.assertEquals(10, len(response['data'])) prev_rank = 10 for character in response['data']: self.assertTrue(character['rank'] < prev_rank) prev_rank = character['rank'] # Order by goal then rank response = transforms.loads(self.get( '/rest/data/character/items?ordering=goal&ordering=rank').body) self.assertEquals(10, len(response['data'])) prev_goal = 'A' prev_rank = -1 for character in response['data']: self.assertTrue(character['goal'] >= prev_goal) if character['goal'] != prev_goal: prev_rank = -1 prev_goal = character['goal'] else: self.assertTrue(character['rank'] > prev_rank) prev_rank = character['rank'] def test_filtered_and_ordered(self): email = 'admin@google.com' actions.login(email, is_admin=True) response = transforms.loads(self.get( '/rest/data/character/items?filter=rank<7&ordering=rank').body) self.assertEquals(7, len(response['data'])) prev_rank = -1 for character in response['data']: self.assertTrue(character['rank'] > prev_rank) self.assertTrue(character['rank'] < 7) def test_illegal_filters_and_orderings(self): email = 'admin@google.com' actions.login(email, is_admin=True) response = transforms.loads(self.get( '/rest/data/character/items?filter=foo').body) self._assert_have_critical_error( response, 'Filter specification "foo" is not of the form: <name><op><value>') response = transforms.loads(self.get( '/rest/data/character/items?filter=foo=9').body) self._assert_have_critical_error( response, 'field "foo" which is not in the schema for type "Character"') response = transforms.loads(self.get( '/rest/data/character/items?filter=rank=kitten').body) self._assert_have_critical_error( response, 'invalid literal for int() with base 10: \'kitten\'') response = transforms.loads(self.get( '/rest/data/character/items?filter=rank<<7').body) self._assert_have_critical_error( response, '"rank<<7" uses an unsupported comparison operation "<<"') response = transforms.loads(self.get( '/rest/data/character/items?ordering=foo').body) self._assert_have_critical_error( response, 'Invalid property name \'foo\'') response = transforms.loads(self.get( '/rest/data/character/items?ordering=age').body) self._assert_have_critical_error( response, 'Property \'age\' is not indexed') response = transforms.loads(self.get( '/rest/data/character/items?filter=age>5').body) self._assert_have_critical_error( response, 'Property \'age\' is not indexed') response = transforms.loads(self.get( '/rest/data/character/items?filter=rank<7&ordering=goal').body) self._assert_have_critical_error( response, 'First ordering property must be the same as inequality filter') def _assert_have_critical_error(self, response, expected_message): email = 'admin@google.com' actions.login(email, is_admin=True) for log in response['log']: if (log['level'] == 'critical' and expected_message in log['message']): return self.fail('Expected a critical error containing "%s"' % expected_message) def test_pii_encoding(self): email = 'admin@google.com' actions.login(email, is_admin=True) token = data_sources_utils.generate_data_source_token( crypto.XsrfTokenManager) response = transforms.loads(self.get('/rest/data/character/items').body) for d in response['data']: # Ensure that field marked as needing transformation is cleared # when we don't pass in an XSRF token used for generating a secret # for encrypting. self.assertEquals('None', d['user_id']) self.assertEquals(str(db.Key.from_path(Character.kind(), 'None')), d['key']) # Ensure that field marked for blacklist is suppressed. self.assertFalse('name' in d) response = transforms.loads(self.get( '/rest/data/character/items?data_source_token=' + token).body) for d in response['data']: # Ensure that field marked as needing transformation is cleared # when we don't pass in an XSRF token used for generating a secret # for encrypting. self.assertIsNotNone(d['user_id']) self.assertNotEquals('None', d['key']) # Ensure that field marked for blacklist is still suppressed. self.assertFalse('name' in d) def test_pii_encoding_changes(self): email = 'admin@google.com' actions.login(email, is_admin=True) token1 = data_sources_utils.generate_data_source_token( crypto.XsrfTokenManager) time.sleep(1) # Legit: XSRF token is time-based, so will change. token2 = data_sources_utils.generate_data_source_token( crypto.XsrfTokenManager) self.assertNotEqual(token1, token2) response1 = transforms.loads(self.get( '/rest/data/character/items?data_source_token=' + token1).body) response2 = transforms.loads(self.get( '/rest/data/character/items?data_source_token=' + token2).body) for c1, c2 in zip(response1['data'], response2['data']): self.assertNotEquals(c1['user_id'], c2['user_id']) self.assertNotEquals(c1['key'], c2['key']) def test_sequential_pagination(self): email = 'admin@google.com' actions.login(email, is_admin=True) response = transforms.loads(self.get( '/rest/data/character/items?chunk_size=3&page_number=0').body) source_context = response['source_context'] self.assertEquals(0, response['page_number']) self._verify_data(self.characters[:3], response['data']) self._assert_have_only_logs(response, [ 'Creating new context for given parameters', 'fetch page 0 start cursor missing; end cursor missing', 'fetch page 0 using limit 3', 'fetch page 0 saving end cursor', ]) response = transforms.loads(self.get( '/rest/data/character/items?chunk_size=3&page_number=1' '&source_context=%s' % source_context).body) source_context = response['source_context'] self.assertEquals(1, response['page_number']) self._verify_data(self.characters[3:6], response['data']) self._assert_have_only_logs(response, [ 'Existing context matches parameters; using existing context', 'fetch page 1 start cursor present; end cursor missing', 'fetch page 1 using limit 3', 'fetch page 1 saving end cursor', ]) response = transforms.loads(self.get( '/rest/data/character/items?chunk_size=3&page_number=2' '&source_context=%s' % source_context).body) source_context = response['source_context'] self.assertEquals(2, response['page_number']) self._verify_data(self.characters[6:9], response['data']) self._assert_have_only_logs(response, [ 'Existing context matches parameters; using existing context', 'fetch page 2 start cursor present; end cursor missing', 'fetch page 2 using limit 3', 'fetch page 2 saving end cursor', ]) response = transforms.loads(self.get( '/rest/data/character/items?chunk_size=3&page_number=3' '&source_context=%s' % source_context).body) source_context = response['source_context'] self.assertEquals(3, response['page_number']) self._verify_data(self.characters[9:], response['data']) self._assert_have_only_logs(response, [ 'Existing context matches parameters; using existing context', 'fetch page 3 start cursor present; end cursor missing', 'fetch page 3 using limit 3', 'fetch page 3 is partial; not saving end cursor', ]) def test_non_present_page_request(self): email = 'admin@google.com' actions.login(email, is_admin=True) response = transforms.loads(self.get( '/rest/data/character/items?chunk_size=9&page_number=5').body) self._verify_data(self.characters[9:], response['data']) self.assertEquals(1, response['page_number']) self._assert_have_only_logs(response, [ 'Creating new context for given parameters', 'fetch page 0 start cursor missing; end cursor missing', 'fetch page 0 using limit 9', 'fetch page 0 saving end cursor', 'fetch page 1 start cursor present; end cursor missing', 'fetch page 1 using limit 9', 'fetch page 1 is partial; not saving end cursor', 'Fewer pages available than requested. Stopping at last page 1', ]) def test_empty_last_page_request(self): email = 'admin@google.com' actions.login(email, is_admin=True) response = transforms.loads(self.get( '/rest/data/character/items?chunk_size=10&page_number=3').body) self._verify_data([], response['data']) self.assertEquals(1, response['page_number']) self._assert_have_only_logs(response, [ 'Creating new context for given parameters', 'fetch page 0 start cursor missing; end cursor missing', 'fetch page 0 using limit 10', 'fetch page 0 saving end cursor', 'fetch page 1 start cursor present; end cursor missing', 'fetch page 1 using limit 10', 'fetch page 1 is partial; not saving end cursor', 'Fewer pages available than requested. Stopping at last page 1', ]) def test_nonsequential_pagination(self): email = 'admin@google.com' actions.login(email, is_admin=True) response = transforms.loads(self.get( '/rest/data/character/items?chunk_size=3&page_number=2').body) source_context = response['source_context'] self.assertEquals(2, response['page_number']) self._verify_data(self.characters[6:9], response['data']) self._assert_have_only_logs(response, [ 'Creating new context for given parameters', 'fetch page 0 start cursor missing; end cursor missing', 'fetch page 0 using limit 3', 'fetch page 0 saving end cursor', 'fetch page 1 start cursor present; end cursor missing', 'fetch page 1 using limit 3', 'fetch page 1 saving end cursor', 'fetch page 2 start cursor present; end cursor missing', 'fetch page 2 using limit 3', 'fetch page 2 saving end cursor', ]) response = transforms.loads(self.get( '/rest/data/character/items?chunk_size=3&page_number=1' '&source_context=%s' % source_context).body) source_context = response['source_context'] self._verify_data(self.characters[3:6], response['data']) self._assert_have_only_logs(response, [ 'Existing context matches parameters; using existing context', 'fetch page 1 start cursor present; end cursor present', ]) def test_pagination_filtering_and_ordering(self): email = 'admin@google.com' actions.login(email, is_admin=True) response = transforms.loads(self.get( '/rest/data/character/items?filter=rank>=5&ordering=rank' '&chunk_size=3&page_number=1').body) source_context = response['source_context'] self.assertEquals(1, response['page_number']) self._verify_data([self.characters[4], self.characters[6]], response['data']) self._assert_have_only_logs(response, [ 'Creating new context for given parameters', 'fetch page 0 start cursor missing; end cursor missing', 'fetch page 0 using limit 3', 'fetch page 0 saving end cursor', 'fetch page 1 start cursor present; end cursor missing', 'fetch page 1 using limit 3', 'fetch page 1 is partial; not saving end cursor', ]) response = transforms.loads(self.get( '/rest/data/character/items?filter=rank>=5&ordering=rank' '&chunk_size=3&page_number=0' '&source_context=%s' % source_context).body) source_context = response['source_context'] self.assertEquals(0, response['page_number']) self._verify_data([self.characters[7], self.characters[1], self.characters[8]], response['data']) self._assert_have_only_logs(response, [ 'Existing context matches parameters; using existing context', 'fetch page 0 start cursor missing; end cursor present', ]) def test_parameters_can_be_omitted_if_using_source_context(self): email = 'admin@google.com' actions.login(email, is_admin=True) response = transforms.loads(self.get( '/rest/data/character/items?filter=rank>=5&ordering=rank' '&chunk_size=3&page_number=1').body) source_context = response['source_context'] self._verify_data([self.characters[4], self.characters[6]], response['data']) # This should load identical items, without having to respecify # filters, ordering, chunk_size. response = transforms.loads(self.get( '/rest/data/character/items?page_number=1' '&source_context=%s' % source_context).body) self.assertEquals(1, response['page_number']) self._verify_data([self.characters[4], self.characters[6]], response['data']) self._assert_have_only_logs(response, [ 'Continuing use of existing context', 'fetch page 1 start cursor present; end cursor missing', 'fetch page 1 using limit 3', 'fetch page 1 is partial; not saving end cursor', ]) def test_build_default_context(self): email = 'admin@google.com' actions.login(email, is_admin=True) response = transforms.loads(self.get('/rest/data/character/items').body) self._assert_have_only_logs(response, [ 'Building new default context', 'fetch page 0 start cursor missing; end cursor missing', 'fetch page 0 using limit 10000', 'fetch page 0 is partial; not saving end cursor', ]) def test_change_filtering_invalidates_context(self): email = 'admin@google.com' actions.login(email, is_admin=True) response = transforms.loads(self.get( '/rest/data/character/items?filter=rank>=5' '&chunk_size=3&page_number=0').body) source_context = response['source_context'] response = transforms.loads(self.get( '/rest/data/character/items?filter=rank<5' '&chunk_size=3&page_number=0' '&source_context=%s' % source_context).body) source_context = response['source_context'] self._verify_data([self.characters[2], self.characters[5], self.characters[3]], response['data']) self._assert_have_only_logs(response, [ 'Existing context and parameters mismatch; ' 'discarding existing and creating new context.', 'fetch page 0 start cursor missing; end cursor missing', 'fetch page 0 using limit 3', 'fetch page 0 saving end cursor', ]) def test_change_ordering_invalidates_context(self): email = 'admin@google.com' actions.login(email, is_admin=True) response = transforms.loads(self.get( '/rest/data/character/items?ordering=rank' '&chunk_size=3&page_number=0').body) source_context = response['source_context'] response = transforms.loads(self.get( '/rest/data/character/items?ordering=-rank' '&chunk_size=3&page_number=0' '&source_context=%s' % source_context).body) source_context = response['source_context'] self._verify_data([self.characters[6], self.characters[4], self.characters[8]], response['data']) self._assert_have_only_logs(response, [ 'Existing context and parameters mismatch; ' 'discarding existing and creating new context.', 'fetch page 0 start cursor missing; end cursor missing', 'fetch page 0 using limit 3', 'fetch page 0 saving end cursor', ]) def _assert_have_only_logs(self, response, messages): for message in messages: found_index = -1 for index, log in enumerate(response['log']): if message in log['message']: found_index = index break if found_index < 0: self.fail('Expected to find message "%s" in logs' % message) else: del response['log'][found_index] if response['log']: self.fail('Unexpected message "%s"' % response['log'][0]) def _verify_data(self, characters, data): for c, d in zip(characters, data): self.assertEquals(c.rank, d['rank']) self.assertEquals(c.age, d['age'])
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Functional tests for the notifications module.""" __author__ = [ 'johncox@google.com (John Cox)' ] import datetime import itertools import types from models import config from models import counters from modules.notifications import cron from modules.notifications import notifications from modules.notifications import stats from tests.functional import actions from google.appengine.api import mail_errors from google.appengine.ext import db from google.appengine.ext import deferred class UnregisteredRetentionPolicy(notifications.RetentionPolicy): NAME = 'unregistered' class CronTest(actions.TestBase): """Tests notifications/cron.py.""" def setUp(self): super(CronTest, self).setUp() self.now = datetime.datetime.utcnow() self.old_retention_policies = dict(notifications._RETENTION_POLICIES) self.audit_trail = {'key': 'value'} self.body = 'body' self.intent = 'intent' self.to = 'to@example.com' self.sender = 'sender@example.com' self.stats = cron._Stats('namespace') self.subject = 'subject' def tearDown(self): config.Registry.test_overrides.clear() counters.Registry._clear_all() notifications._RETENTION_POLICIES = self.old_retention_policies super(CronTest, self).tearDown() def assert_task_enqueued(self): self.assertEqual(1, len(self.taskq.GetTasks('default'))) def assert_task_not_enqueued(self): self.assertEqual(0, len(self.taskq.GetTasks('default'))) def test_process_notification_enqueues_task_and_updates_notification(self): later_date = self.now + datetime.timedelta(seconds=1) notification_key, _ = db.put( notifications.Manager._make_unsaved_models( self.audit_trail, self.body, self.now, self.intent, notifications.RetainAuditTrail.NAME, self.sender, self.subject, self.to, ) ) notification = db.get(notification_key) self.assertIsNone(notification._last_enqueue_date) cron.process_notification(db.get(notification_key), later_date, self.stats) notification = db.get(notification_key) self.assertEqual(later_date, notification._last_enqueue_date) self.assert_task_enqueued() self.execute_all_deferred_tasks() notification = db.get(notification_key) self.assertTrue(notification._done_date) self.assertEqual(1, self.stats.started) self.assertEqual(1, self.stats.reenqueued) def test_process_notification_if_fail_date_set_and_policy_found(self): notification_key, payload_key = db.put( notifications.Manager._make_unsaved_models( self.audit_trail, self.body, self.now, self.intent, notifications.RetainAuditTrail.NAME, self.sender, self.subject, self.to, ) ) notification = db.get(notification_key) notification._fail_date = self.now notification.put() cron.process_notification(db.get(notification_key), self.now, self.stats) notification, payload = db.get([notification_key, payload_key]) self.assert_task_not_enqueued() self.assertTrue(notification._done_date) self.assertFalse(payload.body) # RetainAuditTrail applied. self.assertEqual(0, self.stats.missing_policy) self.assertEqual(1, self.stats.policy_run) self.assertEqual(1, self.stats.started) def test_process_notification_if_fail_date_set_and_policy_missing(self): notification_key, payload_key = db.put( notifications.Manager._make_unsaved_models( self.audit_trail, self.body, self.now, self.intent, notifications.RetainAuditTrail.NAME, self.sender, self.subject, self.to, ) ) notification = db.get(notification_key) notification._fail_date = self.now notification.put() notifications._RETENTION_POLICIES.pop( notifications.RetainAuditTrail.NAME) cron.process_notification(db.get(notification_key), self.now, self.stats) notification, payload = db.get([notification_key, payload_key]) self.assert_task_not_enqueued() self.assertTrue(notification._done_date) self.assertTrue(payload.body) # RetainAuditTrail not applied. self.assertEqual(0, self.stats.policy_run) self.assertEqual(0, self.stats.reenqueued) self.assertEqual(1, self.stats.started) def test_process_notification_if_notification_too_old(self): too_old = self.now - datetime.timedelta( days=notifications._MAX_RETRY_DAYS, seconds=1) notification_key, payload_key = db.put( notifications.Manager._make_unsaved_models( self.audit_trail, self.body, too_old, self.intent, notifications.RetainAuditTrail.NAME, self.sender, self.subject, self.to, ) ) cron.process_notification(db.get(notification_key), self.now, self.stats) notification, payload = db.get([notification_key, payload_key]) self.assert_task_not_enqueued() self.assertTrue(notification._done_date) self.assertTrue(notification._fail_date) self.assertIn( 'NotificationTooOldError', notification._last_exception['type']) self.assertIsNone(payload.body) # RetainAuditTrail applied. self.assertEqual(1, self.stats.policy_run) self.assertEqual(1, self.stats.started) self.assertEqual(1, self.stats.too_old) def test_process_notification_if_payload_missing(self): notification_key, payload_key = db.put( notifications.Manager._make_unsaved_models( self.audit_trail, self.body, self.now, self.intent, notifications.RetainAuditTrail.NAME, self.sender, self.subject, self.to, ) ) db.delete(payload_key) cron.process_notification(db.get(notification_key), self.now, self.stats) self.assert_task_not_enqueued() self.assertEqual(1, self.stats.missing_payload) self.assertEqual(1, self.stats.started) def test_process_notification_if_send_date_set_and_policy_missing(self): notification_key, payload_key = db.put( notifications.Manager._make_unsaved_models( self.audit_trail, self.body, self.now, self.intent, notifications.RetainAuditTrail.NAME, self.sender, self.subject, self.to, ) ) notification = db.get(notification_key) notification._send_date = self.now notification.put() notifications._RETENTION_POLICIES.pop( notifications.RetainAuditTrail.NAME) cron.process_notification(db.get(notification_key), self.now, self.stats) notification, payload = db.get([notification_key, payload_key]) self.assert_task_not_enqueued() self.assertTrue(notification._done_date) self.assertTrue(payload.body) # RetainAuditTrail not applied. self.assertEqual(1, self.stats.missing_policy) self.assertEqual(0, self.stats.policy_run) self.assertEqual(1, self.stats.started) def test_process_notification_if_send_date_set_and_policy_found(self): notification_key, payload_key = db.put( notifications.Manager._make_unsaved_models( self.audit_trail, self.body, self.now, self.intent, notifications.RetainAuditTrail.NAME, self.sender, self.subject, self.to, ) ) notification = db.get(notification_key) notification._send_date = self.now notification.put() cron.process_notification(db.get(notification_key), self.now, self.stats) notification, payload = db.get([notification_key, payload_key]) self.assert_task_not_enqueued() self.assertTrue(notification._done_date) self.assertFalse(payload.body) # RetainAuditTrail applied. self.assertEqual(0, self.stats.missing_policy) self.assertEqual(1, self.stats.policy_run) self.assertEqual(1, self.stats.started) def test_process_notification_skips_if_already_done(self): notification_key, _ = db.put( notifications.Manager._make_unsaved_models( self.audit_trail, self.body, self.now, self.intent, notifications.RetainAuditTrail.NAME, self.sender, self.subject, self.to, ) ) notification = db.get(notification_key) notification._done_date = self.now notification.put() cron.process_notification(db.get(notification_key), self.now, self.stats) self.assert_task_not_enqueued() self.assertEqual(1, self.stats.skipped_already_done) self.assertEqual(1, self.stats.started) def test_process_notification_skips_if_still_enqueued(self): notification_key, _ = db.put( notifications.Manager._make_unsaved_models( self.audit_trail, self.body, self.now, self.intent, notifications.RetainAuditTrail.NAME, self.sender, self.subject, self.to, ) ) notification = db.get(notification_key) notification._last_enqueue_date = self.now notification.put() cron.process_notification(notification, self.now, self.stats) self.assert_task_not_enqueued() self.assertEqual(1, self.stats.skipped_still_enqueued) self.assertEqual(1, self.stats.started) class DatetimeConversionTest(actions.TestBase): def test_utc_datetime_round_trips_correctly(self): dt_with_usec = datetime.datetime(2000, 1, 1, 1, 1, 1, 1) self.assertEqual( dt_with_usec, notifications._epoch_usec_to_dt( notifications._dt_to_epoch_usec(dt_with_usec))) class ManagerTest(actions.TestBase): def setUp(self): super(ManagerTest, self).setUp() self.now = datetime.datetime.utcnow() self.old_retention_policies = dict(notifications._RETENTION_POLICIES) self.audit_trail = {'key': 'value'} self.body = 'body' self.intent = 'intent' self.to = 'to@example.com' self.sender = 'sender@example.com' self.subject = 'subject' def tearDown(self): config.Registry.test_overrides.clear() counters.Registry._clear_all() notifications._RETENTION_POLICIES = self.old_retention_policies super(ManagerTest, self).tearDown() def test_get_in_process_notifications_query(self): exact_cutoff = self.now - datetime.timedelta( days=notifications._MAX_RETRY_DAYS) already_done = notifications.Notification( enqueue_date=exact_cutoff, to=self.to, intent=self.intent, _done_date=exact_cutoff, _retention_policy=notifications.RetainAuditTrail.NAME, sender=self.sender, subject=self.subject) oldest_match = notifications.Notification( enqueue_date=exact_cutoff - datetime.timedelta(seconds=1), to=self.to, intent=self.intent, _retention_policy=notifications.RetainAuditTrail.NAME, sender=self.sender, subject=self.subject) newest_match = notifications.Notification( enqueue_date=exact_cutoff, to=self.to, intent=self.intent, _retention_policy=notifications.RetainAuditTrail.NAME, sender=self.sender, subject=self.subject ) db.put([already_done, oldest_match, newest_match]) found = (notifications.Manager ._get_in_process_notifications_query().fetch(10)) self.assertEqual( [newest_match.key(), oldest_match.key()], [match.key() for match in found] ) def test_query_returns_correctly_populated_statuses(self): to2 = 'to2@example.com' date2 = self.now + datetime.timedelta(seconds=1) user1_match1 = notifications.Notification( _done_date=self.now, enqueue_date=self.now, intent=self.intent, _retention_policy=notifications.RetainAuditTrail.NAME, sender=self.sender, subject=self.subject, to=self.to ) user1_match2 = notifications.Notification( # Both done and failed so we can test failed trumps done. _done_date=self.now, enqueue_date=date2, _fail_date=self.now, intent=self.intent, _retention_policy=notifications.RetainAuditTrail.NAME, sender=self.sender, subject=self.subject, to=self.to ) user2_match1 = notifications.Notification( enqueue_date=self.now, intent=self.intent, _retention_policy=notifications.RetainAuditTrail.NAME, sender=self.sender, subject=self.subject, to=to2 ) user2_match2 = notifications.Notification( enqueue_date=date2, intent=self.intent, _retention_policy=notifications.RetainAuditTrail.NAME, sender=self.sender, subject=self.subject, to=to2 ) db.put([user1_match1, user1_match2, user2_match1, user2_match2]) expected = { self.to: [ notifications.Status.from_notification(user1_match2), notifications.Status.from_notification(user1_match1), ], to2: [ notifications.Status.from_notification(user2_match2), notifications.Status.from_notification(user2_match1), ], } results = notifications.Manager.query([self.to, to2], self.intent) self.assertEqual(expected, results) self.assertEqual(notifications.Status.FAILED, results[self.to][0].state) self.assertEqual(notifications.Status.SUCCEEDED, results[self.to][1].state) self.assertEqual(notifications.Status.PENDING, results[to2][0].state) def test_get_query_query_returns_expected_records(self): first_match = notifications.Notification( enqueue_date=self.now, intent=self.intent, _retention_policy=notifications.RetainAuditTrail.NAME, sender=self.sender, subject=self.subject, to=self.to ) second_match = notifications.Notification( enqueue_date=self.now + datetime.timedelta(seconds=1), intent=self.intent, _retention_policy=notifications.RetainAuditTrail.NAME, sender=self.sender, subject=self.subject, to=self.to ) different_to = notifications.Notification( enqueue_date=self.now, intent=self.intent, _retention_policy=notifications.RetainAuditTrail.NAME, sender=self.sender, subject=self.subject, to='not_' + self.to ) different_intent = notifications.Notification( enqueue_date=self.now, intent='not_' + self.intent, _retention_policy=notifications.RetainAuditTrail.NAME, sender=self.sender, subject=self.subject, to=self.to ) keys = db.put( [first_match, second_match, different_to, different_intent]) first_match_key, second_match_key = keys[:2] results = notifications.Manager._get_query_query( self.to, self.intent ).fetch(10) self.assertEqual( [second_match_key, first_match_key], [n.key() for n in results] ) def test_is_too_old_to_reenqueue(self): newer = self.now - datetime.timedelta( days=notifications._MAX_RETRY_DAYS - 1) equal = ( self.now - datetime.timedelta(days=notifications._MAX_RETRY_DAYS)) older = self.now - datetime.timedelta( days=notifications._MAX_RETRY_DAYS + 1) self.assertFalse( notifications.Manager._is_too_old_to_reenqueue(newer, self.now) ) self.assertFalse( notifications.Manager._is_too_old_to_reenqueue(equal, self.now) ) self.assertTrue( notifications.Manager._is_too_old_to_reenqueue(older, self.now) ) def test_is_still_enqueued_false_if_done_date_set(self): notification = notifications.Notification( enqueue_date=self.now, intent=self.intent, _last_enqueue_date=self.now, _retention_policy=notifications.RetainAuditTrail.NAME, sender=self.sender, subject=self.subject, to=self.to, ) self.assertTrue( notifications.Manager._is_still_enqueued(notification, self.now)) notification._done_date = self.now self.assertFalse( notifications.Manager._is_still_enqueued(notification, self.now)) def test_is_still_enqueued_false_if_fail_date_set(self): notification = notifications.Notification( enqueue_date=self.now, intent=self.intent, _last_enqueue_date=self.now, _retention_policy=notifications.RetainAuditTrail.NAME, sender=self.sender, subject=self.subject, to=self.to, ) self.assertTrue( notifications.Manager._is_still_enqueued(notification, self.now)) notification._fail_date = self.now self.assertFalse( notifications.Manager._is_still_enqueued(notification, self.now)) def test_is_still_enqueued_false_if_send_date_set(self): notification = notifications.Notification( enqueue_date=self.now, intent=self.intent, _last_enqueue_date=self.now, _retention_policy=notifications.RetainAuditTrail.NAME, sender=self.sender, subject=self.subject, to=self.to, ) self.assertTrue( notifications.Manager._is_still_enqueued(notification, self.now)) notification._fail_date = self.now self.assertFalse( notifications.Manager._is_still_enqueued(notification, self.now)) def test_is_still_enqueued_false_if_last_enqueue_date_not_set(self): notification = notifications.Notification( enqueue_date=self.now, intent=self.intent, _last_enqueue_date=self.now, _retention_policy=notifications.RetainAuditTrail.NAME, sender=self.sender, subject=self.subject, to=self.to, ) self.assertTrue( notifications.Manager._is_still_enqueued(notification, self.now)) notification._last_enqueue_date = None self.assertFalse( notifications.Manager._is_still_enqueued(notification, self.now)) def test_is_still_enqueued_false_if_last_enqueue_date_equal(self): equal = datetime.timedelta( seconds=notifications.Manager._get_task_age_limit_seconds() / notifications._ENQUEUED_BUFFER_MULTIPLIER ) notification = notifications.Notification( enqueue_date=self.now, intent=self.intent, _last_enqueue_date=self.now - equal, _retention_policy=notifications.RetainAuditTrail.NAME, sender=self.sender, subject=self.subject, to=self.to, ) self.assertFalse( notifications.Manager._is_still_enqueued(notification, self.now)) def test_is_still_enqueued_false_if_last_enqueue_date_too_old(self): equal = datetime.timedelta( seconds=notifications.Manager._get_task_age_limit_seconds() / notifications._ENQUEUED_BUFFER_MULTIPLIER ) too_old = self.now - (equal + datetime.timedelta(seconds=1)) notification = notifications.Notification( enqueue_date=self.now, intent=self.intent, _last_enqueue_date=too_old, _retention_policy=notifications.RetainAuditTrail.NAME, sender=self.sender, subject=self.subject, to=self.to, ) self.assertFalse( notifications.Manager._is_still_enqueued(notification, self.now)) def test_is_still_enqueued_true_if_last_enqueue_date_greater_than_now(self): notification = notifications.Notification( enqueue_date=self.now, intent=self.intent, _last_enqueue_date=self.now + datetime.timedelta(seconds=1), _retention_policy=notifications.RetainAuditTrail.NAME, sender=self.sender, subject=self.subject, to=self.to, ) self.assertTrue( notifications.Manager._is_still_enqueued(notification, self.now)) def test_is_still_enqueued_true_if_last_enqueue_date_within_window(self): equal = datetime.timedelta( seconds=notifications.Manager._get_task_age_limit_seconds() / notifications._ENQUEUED_BUFFER_MULTIPLIER ) inside_window = self.now - (equal - datetime.timedelta(seconds=1)) notification = notifications.Notification( enqueue_date=self.now, intent=self.intent, _last_enqueue_date=inside_window, _retention_policy=notifications.RetainAuditTrail.NAME, sender=self.sender, subject=self.subject, to=self.to, ) self.assertTrue( notifications.Manager._is_still_enqueued(notification, self.now)) def test_send_async_with_defaults_set_initial_state_and_can_run_tasks(self): notification_key, payload_key = notifications.Manager.send_async( self.to, self.sender, self.intent, self.body, self.subject ) notification, payload = db.get([notification_key, payload_key]) self.assertIsNone(notification.audit_trail) self.assertTrue(notification.enqueue_date) self.assertEqual(self.intent, notification.intent) self.assertEqual(self.sender, notification.sender) self.assertEqual(self.subject, notification.subject) self.assertEqual(self.to, notification.to) self.assertTrue(notification._change_date) self.assertIsNone(notification._done_date) self.assertEqual(notification.enqueue_date, notification._last_enqueue_date) self.assertIsNone(notification._fail_date) self.assertIsNone(notification._last_exception) self.assertEqual( notifications.RetainAuditTrail.NAME, notification._retention_policy) self.assertIsNone(notification._send_date) self.assertEqual(notification.enqueue_date, payload.enqueue_date) self.assertEqual(self.intent, payload.intent) self.assertEqual(self.to, payload.to) self.assertEqual(self.body, payload.body) self.assertTrue(payload._change_date) self.assertEqual( notifications.RetainAuditTrail.NAME, payload._retention_policy) self.assertEqual(1, len(self.taskq.GetTasks('default'))) self.execute_all_deferred_tasks() messages = self.get_mail_stub().get_sent_messages() self.assertEqual(1, len(messages)) self.assertIsNone(db.get(payload_key).body) # Ran default policy. self.assertEqual(1, notifications.COUNTER_RETENTION_POLICY_RUN.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_FAILED.value) self.assertEqual( 0, notifications.COUNTER_SEND_MAIL_TASK_FAILED_PERMANENTLY.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_SENT.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_SKIPPED.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_STARTED.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_SUCCESS.value) def test_send_async_with_overrides_sets_init_state_and_can_run_tasks(self): notification_key, payload_key = notifications.Manager.send_async( self.to, self.sender, self.intent, self.body, self.subject, audit_trail=self.audit_trail, retention_policy=notifications.RetainAll, ) notification, payload = db.get([notification_key, payload_key]) self.assertEqual(self.audit_trail, notification.audit_trail) self.assertTrue(notification.enqueue_date) self.assertEqual(self.intent, notification.intent) self.assertEqual(self.sender, notification.sender) self.assertEqual(self.subject, notification.subject) self.assertEqual(self.to, notification.to) self.assertTrue(notification._change_date) self.assertIsNone(notification._done_date) self.assertEqual(notification.enqueue_date, notification._last_enqueue_date) self.assertIsNone(notification._fail_date) self.assertIsNone(notification._last_exception) self.assertEqual( notifications.RetainAll.NAME, notification._retention_policy) self.assertIsNone(notification._send_date) self.assertEqual(notification.enqueue_date, payload.enqueue_date) self.assertEqual(self.intent, payload.intent) self.assertEqual(self.to, payload.to) self.assertEqual(self.body, payload.body) self.assertTrue(payload._change_date) self.assertEqual(notifications.RetainAll.NAME, payload._retention_policy) self.assertEqual(1, len(self.taskq.GetTasks('default'))) self.execute_all_deferred_tasks() messages = self.get_mail_stub().get_sent_messages() self.assertEqual(1, len(messages)) self.assertEqual(self.body, db.get(payload_key).body) # Policy override self.assertEqual(1, notifications.COUNTER_RETENTION_POLICY_RUN.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_FAILED.value) self.assertEqual( 0, notifications.COUNTER_SEND_MAIL_TASK_FAILED_PERMANENTLY.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_SENT.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_SKIPPED.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_STARTED.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_SUCCESS.value) def test_send_async_raises_exception_if_datastore_errors(self): def throw(unused_self, unused_notification, unused_payload): raise db.Error('thrown') bound_throw = types.MethodType( throw, notifications.Manager(), notifications.Manager) self.swap( notifications.Manager, '_save_notification_and_payload', bound_throw ) with self.assertRaisesRegexp(db.Error, 'thrown'): notifications.Manager.send_async( self.to, self.sender, self.intent, self.body, self.subject, ) def test_send_async_raises_exception_if_models_cannot_be_made(self): bad_audit_trail = self.now with self.assertRaisesRegexp(db.BadValueError, 'not JSON-serializable'): notifications.Manager.send_async( self.to, self.sender, self.intent, self.body, self.subject, audit_trail=bad_audit_trail, ) def test_send_async_raises_value_error_if_retention_policy_missing(self): self.assertNotIn( UnregisteredRetentionPolicy.NAME, notifications._RETENTION_POLICIES) with self.assertRaisesRegexp(ValueError, 'Invalid retention policy: '): notifications.Manager.send_async( self.to, self.sender, self.intent, self.body, self.subject, retention_policy=UnregisteredRetentionPolicy, ) def test_send_async_raises_value_error_if_sender_invalid(self): # App Engine's validator is not comprehensive, but blank is bad. invalid_sender = '' with self.assertRaisesRegexp(ValueError, 'Malformed email address: ""'): notifications.Manager.send_async( self.to, invalid_sender, self.intent, self.body, self.subject, ) def test_send_async_raises_value_error_if_to_invalid(self): # App Engine's validator is not comprehensive, but blank is bad. invalid_to = '' with self.assertRaisesRegexp(ValueError, 'Malformed email address: ""'): notifications.Manager.send_async( invalid_to, self.sender, self.intent, self.body, self.subject, ) def test_send_mail_task_fails_permanent_and_marks_entities_if_cap_hit(self): over_cap = notifications._RECOVERABLE_FAILURE_CAP + 1 notification_key, payload_key = db.put( notifications.Manager._make_unsaved_models( self.audit_trail, self.body, self.now, self.intent, notifications.RetainAuditTrail.NAME, self.sender, self.subject, self.to, ) ) notification = db.get(notification_key) notification._recoverable_failure_count = over_cap notification.put() with self.assertRaisesRegexp( deferred.PermanentTaskFailure, 'Recoverable failure cap'): notifications.Manager._send_mail_task(notification_key, payload_key) notification, payload = db.get([notification_key, payload_key]) self.assertIsNotNone(notification._done_date) self.assertEqual(notification._done_date, notification._fail_date) self.assertIn( 'Recoverable failure cap', notification._last_exception['string']) self.assertEqual(over_cap + 1, notification._recoverable_failure_count) self.assertIsNone(payload.body) # Policy applied. self.assertEqual(1, notifications.COUNTER_RETENTION_POLICY_RUN.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_FAILED.value) self.assertEqual( 1, notifications.COUNTER_SEND_MAIL_TASK_FAILED_PERMANENTLY.value) self.assertEqual( 1, notifications.COUNTER_SEND_MAIL_TASK_FAILURE_CAP_EXCEEDED.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_SENT.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_SKIPPED.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_STARTED.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_SUCCESS.value) def test_send_mail_error_promotion_with_record_failure_error(self): over_cap = notifications._RECOVERABLE_FAILURE_CAP + 1 notification_key, payload_key = db.put( notifications.Manager._make_unsaved_models( self.audit_trail, self.body, self.now, self.intent, notifications.RetainAuditTrail.NAME, self.sender, self.subject, self.to, ) ) notification = db.get(notification_key) notification._recoverable_failure_count = over_cap notification.put() def record_failure(unused_notification, unused_payload, unused_exception): raise ValueError('message') bound_record_failure = types.MethodType( record_failure, notifications.Manager(), notifications.Manager) self.swap( notifications.Manager, '_record_failure', bound_record_failure ) with self.assertRaisesRegexp( deferred.PermanentTaskFailure, 'Recoverable failure cap '): notifications.Manager._send_mail_task(notification_key, payload_key) self.assertEqual( 1, notifications.COUNTER_SEND_MAIL_TASK_RECORD_FAILURE_CALLED.value) self.assertEqual( 1, notifications.COUNTER_SEND_MAIL_TASK_RECORD_FAILURE_FAILED.value) self.assertEqual( 0, notifications.COUNTER_SEND_MAIL_TASK_RECORD_FAILURE_SUCCESS.value) def test_send_mail_task_fails_permanently_if_notification_missing(self): notification_key = db.Key.from_path( notifications.Notification.kind(), notifications.Notification.key_name(self.to, self.intent, self.now) ) payload_key = db.Key.from_path( notifications.Notification.kind(), notifications.Notification.key_name(self.to, self.intent, self.now) ) with self.assertRaisesRegexp( deferred.PermanentTaskFailure, 'Notification missing: '): notifications.Manager._send_mail_task(notification_key, payload_key) self.assertEqual(0, notifications.COUNTER_RETENTION_POLICY_RUN.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_FAILED.value) self.assertEqual( 1, notifications.COUNTER_SEND_MAIL_TASK_FAILED_PERMANENTLY.value) self.assertEqual( 0, notifications.COUNTER_SEND_MAIL_TASK_FAILURE_CAP_EXCEEDED.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_SENT.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_SKIPPED.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_STARTED.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_SUCCESS.value) def test_send_mail_task_fails_permanently_if_payload_missing(self): notification_key, payload_key = db.put( notifications.Manager._make_unsaved_models( self.audit_trail, self.body, self.now, self.intent, notifications.RetainAuditTrail.NAME, self.sender, self.subject, self.to, ) ) db.delete(payload_key) with self.assertRaisesRegexp( deferred.PermanentTaskFailure, 'Payload missing: '): notifications.Manager._send_mail_task(notification_key, payload_key) self.assertEqual(0, notifications.COUNTER_RETENTION_POLICY_RUN.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_FAILED.value) self.assertEqual( 0, notifications.COUNTER_SEND_MAIL_TASK_FAILURE_CAP_EXCEEDED.value) self.assertEqual( 1, notifications.COUNTER_SEND_MAIL_TASK_FAILED_PERMANENTLY.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_SENT.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_SKIPPED.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_STARTED.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_SUCCESS.value) def test_send_mail_task_fails_permanently_if_retention_policy_missing(self): notification_key, payload_key = db.put( notifications.Manager._make_unsaved_models( self.audit_trail, self.body, self.now, self.intent, notifications.RetainAuditTrail.NAME, self.sender, self.subject, self.to, ) ) notification = db.get(notification_key) notifications._RETENTION_POLICIES.pop(notification._retention_policy) with self.assertRaisesRegexp( deferred.PermanentTaskFailure, 'Unknown retention policy: '): notifications.Manager._send_mail_task(notification_key, payload_key) self.assertEqual(0, notifications.COUNTER_RETENTION_POLICY_RUN.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_FAILED.value) self.assertEqual( 0, notifications.COUNTER_SEND_MAIL_TASK_FAILURE_CAP_EXCEEDED.value) self.assertEqual( 1, notifications.COUNTER_SEND_MAIL_TASK_FAILED_PERMANENTLY.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_SENT.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_SKIPPED.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_STARTED.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_SUCCESS.value) def test_send_mail_task_throws_if_send_mail_failure_recoverable(self): # Ideally we'd do a full test of the retry mechanism, but the # testbed just throws when your task raises an uncaught error. exception_text = 'thrown' def recoverable_error( unused_sender, unused_to, unused_subject, unused_body): raise ValueError(exception_text) notification_key, payload_key = db.put( notifications.Manager._make_unsaved_models( self.audit_trail, self.body, self.now, self.intent, notifications.RetainAuditTrail.NAME, self.sender, self.subject, self.to, ) ) with self.assertRaisesRegexp(ValueError, 'thrown'): notifications.Manager._send_mail_task( notification_key, payload_key, recoverable_error) notification = db.get(notification_key) self.assertEqual(exception_text, notification._last_exception['string']) self.assertEqual(1, notification._recoverable_failure_count) self.assertEqual(0, notifications.COUNTER_RETENTION_POLICY_RUN.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_FAILED.value) self.assertEqual( 0, notifications.COUNTER_SEND_MAIL_TASK_FAILURE_CAP_EXCEEDED.value) self.assertEqual( 0, notifications.COUNTER_SEND_MAIL_TASK_FAILED_PERMANENTLY.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_SENT.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_SKIPPED.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_STARTED.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_SUCCESS.value) def test_send_mail_task_recoverable_error_record_failure_error(self): exception_text = 'thrown' def recoverable_error(unused_sender, unused_to, unused_subject, unused_body): raise ValueError(exception_text) def record_failure(unused_notification, unused_payload, unused_exception): raise IOError('not_' + exception_text) bound_record_failure = types.MethodType( record_failure, notifications.Manager(), notifications.Manager) self.swap( notifications.Manager, '_record_failure', bound_record_failure ) notification_key, payload_key = db.put( notifications.Manager._make_unsaved_models( self.audit_trail, self.body, self.now, self.intent, notifications.RetainAuditTrail.NAME, self.sender, self.subject, self.to, ) ) with self.assertRaisesRegexp(ValueError, '^thrown$'): notifications.Manager._send_mail_task( notification_key, payload_key, recoverable_error) self.assertEqual( 1, notifications.COUNTER_SEND_MAIL_TASK_RECORD_FAILURE_CALLED.value) self.assertEqual( 1, notifications.COUNTER_SEND_MAIL_TASK_RECORD_FAILURE_FAILED.value) self.assertEqual( 0, notifications.COUNTER_SEND_MAIL_TASK_RECORD_FAILURE_SUCCESS.value) def test_send_mail_task_marks_fatal_failure_of_send_mail_and_succeeds(self): def fatal_error(unused_sender, unused_to, unused_subject, unused_body): raise mail_errors.BadRequestError('thrown') notification_key, payload_key = db.put( notifications.Manager._make_unsaved_models( self.audit_trail, self.body, self.now, self.intent, notifications.RetainAuditTrail.NAME, self.sender, self.subject, self.to, ) ) notifications.Manager._send_mail_task( notification_key, payload_key, fatal_error) notification, payload = db.get([notification_key, payload_key]) expected_last_exception = { 'type': 'google.appengine.api.mail_errors.BadRequestError', 'string': 'thrown' } self.assertEqual(expected_last_exception, notification._last_exception) self.assertGreater(notification._fail_date, notification._enqueue_date) self.assertIsNone(payload.body) # Policy applied. self.assertEqual(1, notifications.COUNTER_RETENTION_POLICY_RUN.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_FAILED.value) self.assertEqual( 0, notifications.COUNTER_SEND_MAIL_TASK_FAILURE_CAP_EXCEEDED.value) self.assertEqual( 1, notifications.COUNTER_SEND_MAIL_TASK_FAILED_PERMANENTLY.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_SENT.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_SKIPPED.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_STARTED.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_SUCCESS.value) def test_send_mail_task_sends_marks_and_applies_default_policy(self): notification_key, payload_key = db.put( notifications.Manager._make_unsaved_models( self.audit_trail, self.body, self.now, self.intent, notifications.RetainAuditTrail.NAME, self.sender, self.subject, self.to, ) ) notifications.Manager._send_mail_task(notification_key, payload_key) notification, payload = db.get([notification_key, payload_key]) messages = self.get_mail_stub().get_sent_messages() message = messages[0] self.assertEqual(1, len(messages)) self.assertEqual(self.body, message.body.decode()) self.assertEqual(self.sender, message.sender) self.assertEqual(self.subject, message.subject) self.assertEqual(self.to, message.to) self.assertGreater(notification._send_date, notification._enqueue_date) self.assertEqual(notification._done_date, notification._send_date) self.assertIsNone(notification._fail_date) self.assertIsNone(notification._last_exception) self.assertIsNotNone(notification.audit_trail) self.assertIsNone(payload.body) self.assertEqual(1, notifications.COUNTER_RETENTION_POLICY_RUN.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_FAILED.value) self.assertEqual( 0, notifications.COUNTER_SEND_MAIL_TASK_FAILURE_CAP_EXCEEDED.value) self.assertEqual( 0, notifications.COUNTER_SEND_MAIL_TASK_FAILED_PERMANENTLY.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_SENT.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_SKIPPED.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_STARTED.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_SUCCESS.value) def test_send_mail_task_skips_if_already_done(self): notification_key, payload_key = db.put( notifications.Manager._make_unsaved_models( self.audit_trail, self.body, self.now, self.intent, notifications.RetainAuditTrail.NAME, self.sender, self.subject, self.to, ) ) notification = db.get(notification_key) notification._done_date = self.now notification.put() notifications.Manager._send_mail_task(notification_key, payload_key) self.assertEqual(0, notifications.COUNTER_RETENTION_POLICY_RUN.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_FAILED.value) self.assertEqual( 0, notifications.COUNTER_SEND_MAIL_TASK_FAILURE_CAP_EXCEEDED.value) self.assertEqual( 0, notifications.COUNTER_SEND_MAIL_TASK_FAILED_PERMANENTLY.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_SENT.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_SKIPPED.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_STARTED.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_SUCCESS.value) def test_send_mail_task_skips_if_already_failed(self): notification_key, payload_key = db.put( notifications.Manager._make_unsaved_models( self.audit_trail, self.body, self.now, self.intent, notifications.RetainAuditTrail.NAME, self.sender, self.subject, self.to, ) ) notification = db.get(notification_key) notification._fail_date = self.now notification.put() notifications.Manager._send_mail_task(notification_key, payload_key) self.assertEqual(0, notifications.COUNTER_RETENTION_POLICY_RUN.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_FAILED.value) self.assertEqual( 0, notifications.COUNTER_SEND_MAIL_TASK_FAILURE_CAP_EXCEEDED.value) self.assertEqual( 0, notifications.COUNTER_SEND_MAIL_TASK_FAILED_PERMANENTLY.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_SENT.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_SKIPPED.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_STARTED.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_SUCCESS.value) def test_send_mail_task_skips_if_already_sent(self): notification_key, payload_key = db.put( notifications.Manager._make_unsaved_models( self.audit_trail, self.body, self.now, self.intent, notifications.RetainAuditTrail.NAME, self.sender, self.subject, self.to, ) ) notification = db.get(notification_key) notification._send_date = self.now notification.put() notifications.Manager._send_mail_task(notification_key, payload_key) self.assertEqual(0, notifications.COUNTER_RETENTION_POLICY_RUN.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_FAILED.value) self.assertEqual( 0, notifications.COUNTER_SEND_MAIL_TASK_FAILURE_CAP_EXCEEDED.value) self.assertEqual( 0, notifications.COUNTER_SEND_MAIL_TASK_FAILED_PERMANENTLY.value) self.assertEqual(0, notifications.COUNTER_SEND_MAIL_TASK_SENT.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_SKIPPED.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_STARTED.value) self.assertEqual(1, notifications.COUNTER_SEND_MAIL_TASK_SUCCESS.value) class SerializedPropertyTest(actions.TestBase): def test_supports_values_longer_than_500_bytes(self): class Model(db.Model): prop = notifications._SerializedProperty() db.put(Model(prop='a' * 501)) def test_indexed_true_raises_value_error(self): with self.assertRaisesRegexp( ValueError, '_SerializedProperty does not support indexing'): # The declaration causes the code under test to run; no need to use. # pylint: disable=unused-variable class Model(db.Model): prop = notifications._SerializedProperty(indexed=True) class ModelTestBase(actions.TestBase): def setUp(self): super(ModelTestBase, self).setUp() self.enqueue_date = datetime.datetime(2000, 1, 1, 1, 1, 1, 1) self.intent = 'intent' self.retention_policy = notifications.RetainAuditTrail.NAME self.transform_fn = lambda x: 'transformed_' + x self.to = 'to@example.com' def assert_constructor_argument_required(self, name): kwargs = self._get_init_kwargs() kwargs.pop(name) with self.assertRaisesRegexp( AssertionError, 'Missing required property: ' + name): self.ENTITY_CLASS(**kwargs) def assert_for_export_removes_blacklisted_fields(self, unsafe_model): safe_model = unsafe_model.for_export(self.transform_fn) for blacklisted_prop in self.ENTITY_CLASS._PROPERTY_EXPORT_BLACKLIST: self.assertTrue(hasattr(unsafe_model, blacklisted_prop.name)) self.assertFalse(hasattr(safe_model, blacklisted_prop.name)) def _get_init_kwargs(self): return {} class ModelTestSpec(object): """Tests to be executed against each child of notifications._Model.""" # Require children replace with a callable. pylint: disable=not-callable ENTITY_CLASS = None def test_constructor_raises_value_error_if_intent_contains_delimiter(self): with self.assertRaisesRegexp(ValueError, 'cannot contain'): kwargs = self._get_init_kwargs() kwargs['intent'] += notifications._KEY_DELIMITER self.ENTITY_CLASS(**kwargs) def test_constructor_requires_args_for_key_name(self): self.assert_constructor_argument_required('enqueue_date') self.assert_constructor_argument_required('intent') self.assert_constructor_argument_required('to') def test_key_name(self): kind, to, intent, usec_str = self.ENTITY_CLASS._split_key_name( self.key.name()) self.assertEqual(self.ENTITY_CLASS.kind().lower(), kind) self.assertEqual(self.to, to) self.assertEqual(self.intent, intent) self.assertEqual( self.enqueue_date, notifications._epoch_usec_to_dt(int(usec_str))) def test_key_name_raises_value_error_if_intent_contains_delimiter(self): with self.assertRaisesRegexp(ValueError, 'cannot contain'): self.ENTITY_CLASS.key_name( self.to, self.intent + notifications._KEY_DELIMITER, self.enqueue_date) def test_safe_key_transforms_to(self): safe_key = self.ENTITY_CLASS.safe_key(self.key, self.transform_fn) kind, to, intent, usec_str = self.ENTITY_CLASS._split_key_name( safe_key.name()) self.assertEqual(self.ENTITY_CLASS.kind().lower(), kind) self.assertEqual(self.transform_fn(self.to), to) self.assertEqual(self.intent, intent) self.assertEqual( self.enqueue_date, notifications._epoch_usec_to_dt(int(usec_str))) class NotificationTest(ModelTestSpec, ModelTestBase): ENTITY_CLASS = notifications.Notification def setUp(self): super(NotificationTest, self).setUp() self.sender = 'sender@example.com' self.subject = 'subject' self.utcnow = datetime.datetime.utcnow() self.test_utcnow_fn = lambda: self.utcnow self.notification = notifications.Notification( enqueue_date=self.enqueue_date, intent=self.intent, _retention_policy=self.retention_policy, sender=self.sender, subject=self.subject, to=self.to, ) self.key = self.notification.put() def _get_init_kwargs(self): return { 'audit_trail': {}, 'enqueue_date': self.enqueue_date, 'intent': self.intent, 'retention_policy': self.retention_policy, 'sender': self.sender, 'subject': self.subject, 'to': self.to, } def test_audit_trail_round_trips_successfully(self): serializable = { 'int': 1, 'bool': True, } notification = notifications.Notification( audit_trail=serializable, enqueue_date=self.enqueue_date, intent=self.intent, _retention_policy=self.retention_policy, sender=self.sender, subject=self.subject, to=self.to, ) notification = db.get(notification.put()) self.assertEqual(serializable, db.get(notification.put()).audit_trail) def test_ctor_raises_bad_value_error_when_not_serializable(self): not_json_serializable = datetime.datetime.utcnow() with self.assertRaisesRegexp(db.BadValueError, 'is not JSON-serializable'): notifications.Notification( audit_trail=not_json_serializable, enqueue_date=self.enqueue_date, intent=self.intent, _retention_policy=self.retention_policy, sender=self.sender, subject=self.subject, to=self.to, ) def test_for_export_transforms_to_and_sender_and_strips_blacklist(self): audit_trail = {'will_be': 'stripped'} last_exception = 'will_be_stripped' subject = 'will be stripped' unsafe = notifications.Notification( audit_trail=audit_trail, enqueue_date=self.enqueue_date, intent=self.intent, last_exception=last_exception, _retention_policy=self.retention_policy, sender=self.sender, subject=subject, to=self.to, ) unsafe.put() safe = unsafe.for_export(self.transform_fn) self.assertEqual('transformed_' + self.sender, safe.sender) self.assertEqual('transformed_' + self.to, safe.to) self.assert_for_export_removes_blacklisted_fields(unsafe) class PayloadTest(ModelTestSpec, ModelTestBase): ENTITY_CLASS = notifications.Payload def setUp(self): super(PayloadTest, self).setUp() self.body = 'body' self.payload = notifications.Payload( body='body', enqueue_date=self.enqueue_date, intent=self.intent, _retention_policy=self.retention_policy, to=self.to) self.key = self.payload.put() def _get_init_kwargs(self): return { 'enqueue_date': self.enqueue_date, 'intent': self.intent, 'retention_policy': self.retention_policy, 'to': self.to, } def test_for_export_blacklists_data(self): self.assert_for_export_removes_blacklisted_fields(self.payload) class StatsTest(actions.TestBase): def setUp(self): self.now = datetime.datetime.utcnow() self.result = stats._Result(self.now) super(StatsTest, self).setUp() def test_result_bins_and_counts_correctly(self): within_hour = self.now - datetime.timedelta(minutes=59) on_hour = self.now - datetime.timedelta(hours=1) within_day = self.now - datetime.timedelta(hours=23) on_day = self.now - datetime.timedelta(days=1) within_week = self.now - datetime.timedelta(days=6) on_week = self.now - datetime.timedelta(days=7) all_state_and_date_permutations = [x for x in itertools.product( notifications.Status._STATES, [self.now, within_hour, on_hour, within_day, on_day, within_week, on_week] )] for status, dt in all_state_and_date_permutations: self.result.add(status, dt) self.assertEqual(21, self.result.total()) self.assertEqual(7, self.result.failed()) self.assertEqual(7, self.result.pending()) self.assertEqual(7, self.result.succeeded()) self.assertEqual(6, self.result.last_hour.total()) self.assertEqual(2, self.result.last_hour.failed()) self.assertEqual(2, self.result.last_hour.pending()) self.assertEqual(2, self.result.last_hour.succeeded()) self.assertEqual(12, self.result.last_day.total()) self.assertEqual(4, self.result.last_day.failed()) self.assertEqual(4, self.result.last_day.pending()) self.assertEqual(4, self.result.last_day.succeeded()) self.assertEqual(18, self.result.last_week.total()) self.assertEqual(6, self.result.last_week.failed()) self.assertEqual(6, self.result.last_week.pending()) self.assertEqual(6, self.result.last_week.succeeded()) def test_result_does_not_count_bad_state(self): bad_state = 'bad' self.result.add(bad_state, self.now) self.assertNotIn(bad_state, notifications.Status._STATES) self.assertEqual(0, self.result.total())
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the questionnaire module.""" __author__ = 'Neema Kotonya (neemak@google.com)' from common import crypto from controllers import sites from models import courses from models import models from models import transforms from models.data_sources import utils as data_sources_utils from modules.questionnaire.questionnaire import QuestionnaireDataSource from modules.questionnaire.questionnaire import StudentFormEntity from tests.functional import actions from google.appengine.api import namespace_manager COURSE_NAME = 'questionnaire_tag_test_course' ADMIN_EMAIL = 'user@test.com' UNIQUE_FORM_ID = 'This-is-the-unique-id-for-this-form' STUDENT_EMAIL = 'student@foo.com' STUDENT_NAME = 'A. Test Student' TEST_FORM_HTML = """ <form id="This-is-the-unique-id-for-this-form"> Course Name: <input name="course_name" type="text" value=""><br> Unit Name: <input name="unit_name" type="text" value=""><br> </form>""" QUESTIONNAIRE_TAG = """ <gcb-questionnaire form-id="This-is-the-unique-id-for-this-form" instanceid="hnWDW6Ld4RdO"> </gcb-questionnaire><br> """ class BaseQuestionnaireTests(actions.TestBase): """Tests for REST endpoint and tag renderer.""" def setUp(self): super(BaseQuestionnaireTests, self).setUp() actions.login(ADMIN_EMAIL, is_admin=True) self.base = '/' + COURSE_NAME test_course = actions.simple_add_course( COURSE_NAME, ADMIN_EMAIL, 'Questionnaire Test Course') self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % COURSE_NAME) self.course = courses.Course(None, test_course) test_unit = self.course.add_unit() test_unit.now_available = True test_lesson = self.course.add_lesson(test_unit) test_lesson.now_available = True test_lesson.title = 'This is a lesson that contains a form.' test_lesson.objectives = '%s\n%s' % (TEST_FORM_HTML, QUESTIONNAIRE_TAG) self.unit_id = test_unit.unit_id self.lesson_id = test_lesson.lesson_id self.course.save() actions.logout() def tearDown(self): del sites.Registry.test_overrides[sites.GCB_COURSES_CONFIG.name] namespace_manager.set_namespace(self.old_namespace) super(BaseQuestionnaireTests, self).tearDown() def get_button(self): dom = self.parse_html_string(self.get('unit?unit=%s&lesson=%s' % ( self.unit_id, self.lesson_id)).body) return dom.find('.//button[@class="gcb-button questionnaire-button"]') def register(self): actions.login(STUDENT_EMAIL, is_admin=False) actions.register(self, STUDENT_NAME) return models.Student.get_enrolled_student_by_email(STUDENT_EMAIL) class QuestionnaireTagTests(BaseQuestionnaireTests): def test_submit_answers_button_out_of_session(self): button = self.get_button() self.assertEquals(UNIQUE_FORM_ID, button.attrib['data-form-id']) self.assertEquals('false', button.attrib['data-registered']) def test_submit_answers_button_in_session_no_student(self): actions.login(STUDENT_EMAIL, is_admin=False) button = self.get_button() self.assertEquals(UNIQUE_FORM_ID, button.attrib['data-form-id']) self.assertEquals('false', button.attrib['data-registered']) def test_submit_answers_button_student_in_session(self): actions.login(STUDENT_EMAIL, is_admin=False) actions.register(self, STUDENT_NAME) button = self.get_button() self.assertEquals(UNIQUE_FORM_ID, button.attrib['data-form-id']) self.assertEquals('true', button.attrib.get('data-registered')) class QuestionnaireRESTHandlerTests(BaseQuestionnaireTests): REST_URL = 'rest/modules/questionnaire' PAYLOAD_DICT = { 'form_data': [ {u'query': u''}, {u'course_name': u'course_name'}, {u'unit_name': u'unit_name'}]} def _post_form_to_rest_handler(self, request_dict): return transforms.loads(self.post( self.REST_URL, {'request': transforms.dumps(request_dict)}).body) def _get_rest_request(self, payload_dict): xsrf_token = crypto.XsrfTokenManager.create_xsrf_token( 'questionnaire') return { 'xsrf_token': xsrf_token, 'payload': payload_dict } def _put_data_in_datastore(self, student): data = StudentFormEntity.load_or_create(student, UNIQUE_FORM_ID) data.value = transforms.dumps(self.PAYLOAD_DICT) data.put() return data.value def test_rest_handler_right_data_retrieved(self): self.register() response = self._post_form_to_rest_handler( self._get_rest_request(self.PAYLOAD_DICT)) self.assertEquals(200, response['status']) def test_rest_handler_requires_xsrf(self): response = self._post_form_to_rest_handler({'xsrf_token': 'BAD TOKEN'}) self.assertEquals(403, response['status']) def test_rest_handler_only_allows_enrolled_user_to_submit(self): response = self._post_form_to_rest_handler(self._get_rest_request({})) self.assertEquals(401, response['status']) self.register() response = self._post_form_to_rest_handler(self._get_rest_request({})) self.assertEquals(200, response['status']) def test_form_data_in_datastore(self): student = self.register() self._put_data_in_datastore(student) response = StudentFormEntity.load_or_create(student, UNIQUE_FORM_ID) self.assertNotEqual(None, response) def test_form_data_can_be_retrieved(self): student = self.register() self._put_data_in_datastore(student) response = self._get_rest_request(self.PAYLOAD_DICT) self.assertEquals(self.PAYLOAD_DICT, response['payload']) class QuestionnaireDataSourceTests(BaseQuestionnaireTests): FORM_0_DATA = [ {u'name': u'title', u'value': u'War and Peace'}, {u'name': u'rating', u'value': u'Long'}] FORM_1_DATA = [ {u'name': u'country', u'value': u'Greece'}, {u'name': u'lang', u'value': u'el_EL'}, {u'name': u'tld', u'value': u'el'}] # Form 2 tests malformed data FORM_2_DATA = [ {u'value': u'value without name'}, # missing 'name' field {u'name': u'name without value'}, # missing 'value' field {u'name': u'numeric', u'value': 3.14}] # non-string value FORM_2_DATA_OUT = [ {u'name': None, u'value': u'value without name'}, {u'name': u'name without value', u'value': None}, {u'name': u'numeric', u'value': u'3.14'}] def test_data_extraction(self): # Register a student and save some form values for that student student = self.register() entity = StudentFormEntity.load_or_create(student, 'form-0') entity.value = transforms.dumps({ u'form_data': self.FORM_0_DATA}) entity.put() entity = StudentFormEntity.load_or_create(student, u'form-1') entity.value = transforms.dumps({ u'form_data': self.FORM_1_DATA}) entity.put() entity = StudentFormEntity.load_or_create(student, u'form-2') entity.value = transforms.dumps({ u'form_data': self.FORM_2_DATA}) entity.put() # Log in as admin for the data query actions.logout() actions.login(ADMIN_EMAIL, is_admin=True) xsrf_token = crypto.XsrfTokenManager.create_xsrf_token( data_sources_utils.DATA_SOURCE_ACCESS_XSRF_ACTION) pii_secret = crypto.generate_transform_secret_from_xsrf_token( xsrf_token, data_sources_utils.DATA_SOURCE_ACCESS_XSRF_ACTION) safe_user_id = crypto.hmac_sha_2_256_transform( pii_secret, student.user_id) response = self.get( 'rest/data/questionnaire_responses/items?' 'data_source_token=%s&page_number=0' % xsrf_token) data = transforms.loads(response.body)['data'] self.assertEqual(3, len(data)) for index in range(3): self.assertIn(safe_user_id, data[index]['user_id']) self.assertEqual('form-%s' % index, data[index]['questionnaire_id']) self.assertEqual(self.FORM_0_DATA, data[0]['form_data']) self.assertEqual(self.FORM_1_DATA, data[1]['form_data']) self.assertEqual(self.FORM_2_DATA_OUT, data[2]['form_data']) def test_exportable(self): self.assertTrue(QuestionnaireDataSource.exportable())
Python
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Functional tests for modules/review/review.py.""" __author__ = [ 'johncox@google.com (John Cox)', ] import types from models import models from models import student_work from modules.review import domain from modules.review import peer from modules.review import review as review_module from tests.functional import actions from google.appengine.ext import db class ManagerTest(actions.TestBase): """Tests for review.Manager.""" def setUp(self): super(ManagerTest, self).setUp() self.reviewee = models.Student(key_name='reviewee@example.com') self.reviewee_key = self.reviewee.put() self.reviewer = models.Student(key_name='reviewer@example.com') self.reviewer_key = self.reviewer.put() self.unit_id = '1' self.submission_key = db.Key.from_path( student_work.Submission.kind(), student_work.Submission.key_name( reviewee_key=self.reviewee_key, unit_id=self.unit_id)) def test_add_reviewer_adds_new_step_and_summary(self): step_key = review_module.Manager.add_reviewer( self.unit_id, self.submission_key, self.reviewee_key, self.reviewer_key) step = db.get(step_key) summary = db.get(step.review_summary_key) self.assertEqual(domain.ASSIGNER_KIND_HUMAN, step.assigner_kind) self.assertEqual(self.reviewee_key, step.reviewee_key) self.assertEqual(self.reviewer_key, step.reviewer_key) self.assertEqual(domain.REVIEW_STATE_ASSIGNED, step.state) self.assertEqual(self.submission_key, step.submission_key) self.assertEqual(self.unit_id, step.unit_id) self.assertEqual(1, summary.assigned_count) self.assertEqual(0, summary.completed_count) self.assertEqual(0, summary.expired_count) self.assertEqual(self.reviewee_key, summary.reviewee_key) self.assertEqual(self.submission_key, summary.submission_key) self.assertEqual(self.unit_id, summary.unit_id) def test_add_reviewer_existing_raises_assertion_when_summary_missing(self): missing_key = db.Key.from_path( peer.ReviewSummary.kind(), 'no_summary_found_for_key') peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=missing_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=self.unit_id ).put() self.assertRaises( AssertionError, review_module.Manager.add_reviewer, self.unit_id, self.submission_key, self.reviewee_key, self.reviewer_key) def test_add_reviewer_existing_raises_transition_error_when_assigned(self): summary_key = peer.ReviewSummary( assigned_count=1, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=self.unit_id ).put() self.assertRaises( domain.TransitionError, review_module.Manager.add_reviewer, self.unit_id, self.submission_key, self.reviewee_key, self.reviewer_key) def test_add_reviewer_existing_raises_transition_error_when_completed(self): summary_key = peer.ReviewSummary( completed_count=1, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_COMPLETED, unit_id=self.unit_id ).put() self.assertRaises( domain.TransitionError, review_module.Manager.add_reviewer, self.unit_id, self.submission_key, self.reviewee_key, self.reviewer_key) def test_add_reviewer_unremoved_existing_changes_expired_to_assigned(self): summary_key = peer.ReviewSummary( expired_count=1, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_EXPIRED, unit_id=self.unit_id ).put() review_module.Manager.add_reviewer( self.unit_id, self.submission_key, self.reviewee_key, self.reviewer_key) step, summary = db.get([step_key, summary_key]) self.assertEqual(domain.ASSIGNER_KIND_HUMAN, step.assigner_kind) self.assertEqual(domain.REVIEW_STATE_ASSIGNED, step.state) self.assertFalse(step.removed) self.assertEqual(1, summary.assigned_count) self.assertEqual(0, summary.expired_count) def test_add_reviewer_removed_unremoves_assigned_step(self): summary_key = peer.ReviewSummary( reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, removed=True, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=self.unit_id ).put() review_module.Manager.add_reviewer( self.unit_id, self.submission_key, self.reviewee_key, self.reviewer_key) step, summary = db.get([step_key, summary_key]) self.assertEqual(domain.ASSIGNER_KIND_HUMAN, step.assigner_kind) self.assertEqual(domain.REVIEW_STATE_ASSIGNED, step.state) self.assertFalse(step.removed) self.assertEqual(1, summary.assigned_count) def test_add_reviewer_removed_unremoves_completed_step(self): summary_key = peer.ReviewSummary( reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, removed=True, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_COMPLETED, unit_id=self.unit_id ).put() review_module.Manager.add_reviewer( self.unit_id, self.submission_key, self.reviewee_key, self.reviewer_key) step, summary = db.get([step_key, summary_key]) self.assertEqual(domain.ASSIGNER_KIND_HUMAN, step.assigner_kind) self.assertEqual(domain.REVIEW_STATE_COMPLETED, step.state) self.assertFalse(step.removed) self.assertEqual(1, summary.completed_count) def test_add_reviewer_removed_unremoves_and_assigns_expired_step(self): summary_key = peer.ReviewSummary( expired_count=1, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, removed=True, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_EXPIRED, unit_id=self.unit_id ).put() review_module.Manager.add_reviewer( self.unit_id, self.submission_key, self.reviewee_key, self.reviewer_key) step, summary = db.get([step_key, summary_key]) self.assertEqual(domain.ASSIGNER_KIND_HUMAN, step.assigner_kind) self.assertEqual(domain.REVIEW_STATE_ASSIGNED, step.state) self.assertFalse(step.removed) self.assertEqual(1, summary.assigned_count) self.assertEqual(0, summary.expired_count) def test_delete_reviewer_marks_step_removed_and_decrements_summary(self): summary_key = peer.ReviewSummary( assigned_count=1, reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=self.unit_id ).put() step, summary = db.get([step_key, summary_key]) self.assertFalse(step.removed) self.assertEqual(1, summary.assigned_count) deleted_key = review_module.Manager.delete_reviewer(step_key) step, summary = db.get([step_key, summary_key]) self.assertEqual(step_key, deleted_key) self.assertTrue(step.removed) self.assertEqual(0, summary.assigned_count) def test_delete_reviewer_raises_key_error_when_step_missing(self): self.assertRaises( KeyError, review_module.Manager.delete_reviewer, db.Key.from_path(peer.ReviewStep.kind(), 'missing_step_key')) def test_delete_reviewer_raises_key_error_when_summary_missing(self): missing_key = db.Key.from_path( peer.ReviewSummary.kind(), 'missing_review_summary_key') step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=missing_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=self.unit_id ).put() self.assertRaises( KeyError, review_module.Manager.delete_reviewer, step_key) def test_delete_reviewer_raises_removed_error_if_already_removed(self): summary_key = peer.ReviewSummary( assigned_count=1, reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, removed=True, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=self.unit_id ).put() self.assertRaises( domain.RemovedError, review_module.Manager.delete_reviewer, step_key) def test_expire_review_raises_key_error_when_step_missing(self): self.assertRaises( KeyError, review_module.Manager.expire_review, db.Key.from_path(peer.ReviewStep.kind(), 'missing_step_key')) def test_expire_review_raises_key_error_when_summary_missing(self): missing_key = db.Key.from_path( peer.ReviewSummary.kind(), 'missing_review_summary_key') step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=missing_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=self.unit_id ).put() self.assertRaises( KeyError, review_module.Manager.expire_review, step_key) def test_expire_review_raises_transition_error_when_state_completed(self): summary_key = peer.ReviewSummary( completed=1, reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_COMPLETED, unit_id=self.unit_id ).put() self.assertRaises( domain.TransitionError, review_module.Manager.expire_review, step_key) def test_expire_review_raises_transition_error_when_state_expired(self): summary_key = peer.ReviewSummary( expired_count=1, reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_EXPIRED, unit_id=self.unit_id ).put() self.assertRaises( domain.TransitionError, review_module.Manager.expire_review, step_key) def test_expire_review_raises_removed_error_when_step_removed(self): summary_key = peer.ReviewSummary( reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, removed=True, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=self.unit_id ).put() self.assertRaises( domain.RemovedError, review_module.Manager.expire_review, step_key) def test_expire_review_transitions_state_and_updates_summary(self): summary_key = peer.ReviewSummary( assigned_count=1, reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=self.unit_id ).put() step, summary = db.get([step_key, summary_key]) self.assertEqual(1, summary.assigned_count) self.assertEqual(0, summary.expired_count) self.assertEqual(domain.REVIEW_STATE_ASSIGNED, step.state) expired_key = review_module.Manager.expire_review(step_key) step, summary = db.get([expired_key, summary_key]) self.assertEqual(0, summary.assigned_count) self.assertEqual(1, summary.expired_count) self.assertEqual(domain.REVIEW_STATE_EXPIRED, step.state) def test_expire_old_reviews_for_unit_expires_found_reviews(self): summary_key = peer.ReviewSummary( assigned_count=2, completed_count=1, reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() first_step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=self.unit_id ).put() second_reviewee_key = models.Student( key_name='reviewee2@example.com').put() second_submission_key = student_work.Submission( reviewee_key=second_reviewee_key, unit_id=self.unit_id).put() second_step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=second_reviewee_key, reviewer_key=self.reviewer_key, submission_key=second_submission_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=self.unit_id ).put() review_module.Manager.expire_old_reviews_for_unit(0, self.unit_id) first_step, second_step, summary = db.get( [first_step_key, second_step_key, summary_key]) self.assertEqual( [domain.REVIEW_STATE_EXPIRED, domain.REVIEW_STATE_EXPIRED], [step.state for step in [first_step, second_step]]) self.assertEqual(0, summary.assigned_count) self.assertEqual(2, summary.expired_count) def test_expire_old_reviews_skips_errors_and_continues_processing(self): # Create and bind a function that we can swap in to generate a query # that will pick up bad results so we can tell that we skip them. query_containing_unprocessable_entities = peer.ReviewStep.all( keys_only=True) query_fn = types.MethodType( lambda x, y, z: query_containing_unprocessable_entities, review_module.Manager(), review_module.Manager) self.swap( review_module.Manager, 'get_expiry_query', query_fn) summary_key = peer.ReviewSummary( assigned_count=1, completed_count=1, reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() processable_step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=self.unit_id ).put() second_reviewee_key = models.Student( key_name='reviewee2@example.com').put() second_submission_key = student_work.Submission( reviewee_key=second_reviewee_key, unit_id=self.unit_id).put() error_step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=second_reviewee_key, reviewer_key=self.reviewer_key, submission_key=second_submission_key, state=domain.REVIEW_STATE_COMPLETED, unit_id=self.unit_id ).put() review_module.Manager.expire_old_reviews_for_unit(0, self.unit_id) processed_step, error_step, summary = db.get( [processable_step_key, error_step_key, summary_key]) self.assertEqual(domain.REVIEW_STATE_COMPLETED, error_step.state) self.assertEqual(domain.REVIEW_STATE_EXPIRED, processed_step.state) self.assertEqual(0, summary.assigned_count) self.assertEqual(1, summary.completed_count) self.assertEqual(1, summary.expired_count) def test_get_assignment_candidates_query_filters_and_orders_correctly(self): unused_wrong_unit_key = peer.ReviewSummary( reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=str(int(self.unit_id) + 1) ).put() second_reviewee_key = models.Student( key_name='reviewee2@example.com').put() second_submission_key = student_work.Submission( reviewee_key=second_reviewee_key, unit_id=self.unit_id).put() older_assigned_and_completed_key = peer.ReviewSummary( assigned_count=1, completed_count=1, reviewee_key=second_reviewee_key, submission_key=second_submission_key, unit_id=self.unit_id ).put() third_reviewee_key = models.Student( key_name='reviewee3@example.com').put() third_submission_key = student_work.Submission( reviewee_key=third_reviewee_key, unit_id=self.unit_id).put() younger_assigned_and_completed_key = peer.ReviewSummary( assigned_count=1, completed_count=1, reviewee_key=third_reviewee_key, submission_key=third_submission_key, unit_id=self.unit_id ).put() fourth_reviewee_key = models.Student( key_name='reviewee4@example.com').put() fourth_submission_key = student_work.Submission( reviewee_key=fourth_reviewee_key, unit_id=self.unit_id).put() completed_but_not_assigned_key = peer.ReviewSummary( assigned_count=0, completed_count=1, reviewee_key=fourth_reviewee_key, submission_key=fourth_submission_key, unit_id=self.unit_id ).put() fifth_reviewee_key = models.Student( key_name='reviewee5@example.com').put() fifth_submission_key = student_work.Submission( reviewee_key=fifth_reviewee_key, unit_id=self.unit_id).put() assigned_but_not_completed_key = peer.ReviewSummary( assigned_count=1, completed_count=0, reviewee_key=fifth_reviewee_key, submission_key=fifth_submission_key, unit_id=self.unit_id ).put() results = review_module.Manager.get_assignment_candidates_query( self.unit_id).fetch(5) self.assertEqual([ assigned_but_not_completed_key, completed_but_not_assigned_key, older_assigned_and_completed_key, younger_assigned_and_completed_key ], [r.key() for r in results]) def test_get_expiry_query_filters_and_orders_correctly(self): summary_key = peer.ReviewSummary( assigned_count=2, completed_count=1, reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() unused_completed_step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_COMPLETED, unit_id=self.unit_id ).put() second_reviewee_key = models.Student( key_name='reviewee2@example.com').put() second_submission_key = student_work.Submission( reviewee_key=second_reviewee_key, unit_id=self.unit_id).put() unused_removed_step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, removed=True, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=second_reviewee_key, reviewer_key=self.reviewer_key, submission_key=second_submission_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=self.unit_id ).put() third_reviewee_key = models.Student( key_name='reviewee3@example.com').put() third_submission_key = student_work.Submission( reviewee_key=third_reviewee_key, unit_id=self.unit_id).put() unused_other_unit_step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=third_reviewee_key, reviewer_key=self.reviewer_key, submission_key=third_submission_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=str(int(self.unit_id) + 1) ).put() fourth_reviewee_key = models.Student( key_name='reviewee4@example.com').put() fourth_submission_key = student_work.Submission( reviewee_key=fourth_reviewee_key, unit_id=self.unit_id).put() first_assigned_step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=fourth_reviewee_key, reviewer_key=self.reviewer_key, submission_key=fourth_submission_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=self.unit_id ).put() fifth_reviewee_key = models.Student( key_name='reviewee5@example.com').put() fifth_submission_key = student_work.Submission( reviewee_key=fifth_reviewee_key, unit_id=self.unit_id).put() second_assigned_step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=fifth_reviewee_key, reviewer_key=self.reviewer_key, submission_key=fifth_submission_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=self.unit_id ).put() zero_review_window_query = review_module.Manager.get_expiry_query( 0, self.unit_id) future_review_window_query = review_module.Manager.get_expiry_query( 1, self.unit_id) self.assertEqual( [first_assigned_step_key, second_assigned_step_key], zero_review_window_query.fetch(3)) # No items are > 1 minute old, so we expect an empty result set. self.assertEqual(None, future_review_window_query.get()) def test_get_new_review_creates_step_and_updates_summary(self): summary_key = peer.ReviewSummary( reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() summary = db.get(summary_key) self.assertEqual(0, summary.assigned_count) step_key = review_module.Manager.get_new_review( self.unit_id, self.reviewer_key) step, summary = db.get([step_key, summary_key]) self.assertEqual(domain.ASSIGNER_KIND_AUTO, step.assigner_kind) self.assertEqual(summary.key(), step.review_summary_key) self.assertEqual(self.reviewee_key, step.reviewee_key) self.assertEqual(self.reviewer_key, step.reviewer_key) self.assertEqual(domain.REVIEW_STATE_ASSIGNED, step.state) self.assertEqual(self.submission_key, step.submission_key) self.assertEqual(self.unit_id, step.unit_id) self.assertEqual(1, summary.assigned_count) def test_get_new_review_raises_key_error_when_summary_missing(self): summary_key = peer.ReviewSummary( reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() # Create and bind a function that we can swap in to pick the review # candidate but as a side effect delete the review summary, causing a # the lookup by key to fail. def pick_and_remove(unused_cls, candidates): db.delete(summary_key) return candidates[0] fn = types.MethodType( pick_and_remove, review_module.Manager(), review_module.Manager) self.swap( review_module.Manager, '_choose_assignment_candidate', fn) self.assertRaises( KeyError, review_module.Manager.get_new_review, self.unit_id, self.reviewer_key) def test_get_new_review_raises_not_assignable_when_already_assigned(self): summary_key = peer.ReviewSummary( assigned_count=1, reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() unused_already_assigned_step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=self.unit_id ).put() self.assertRaises( domain.NotAssignableError, review_module.Manager.get_new_review, self.unit_id, self.reviewer_key) def test_get_new_review_raises_not_assignable_when_already_completed(self): summary_key = peer.ReviewSummary( completed=1, reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() already_completed_unremoved_step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_COMPLETED, unit_id=self.unit_id ).put() self.assertRaises( domain.NotAssignableError, review_module.Manager.get_new_review, self.unit_id, self.reviewer_key) db.delete(already_completed_unremoved_step_key) unused_already_completed_removed_step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, removed=True, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_COMPLETED, unit_id=self.unit_id ).put() self.assertRaises( domain.NotAssignableError, review_module.Manager.get_new_review, self.unit_id, self.reviewer_key) def test_get_new_review_raises_not_assignable_when_review_is_for_self(self): peer.ReviewSummary( assigned_count=1, reviewee_key=self.reviewer_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() self.assertRaises( domain.NotAssignableError, review_module.Manager.get_new_review, self.unit_id, self.reviewer_key) def test_get_new_review_raises_not_assignable_when_no_candidates(self): self.assertRaises( domain.NotAssignableError, review_module.Manager.get_new_review, self.unit_id, self.reviewer_key) def test_get_new_review_raises_not_assignable_when_retry_limit_hit(self): higher_priority_summary = peer.ReviewSummary( reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id) higher_priority_summary_key = higher_priority_summary.put() second_reviewee_key = models.Student( key_name='reviewee2@example.com').put() second_submission_key = student_work.Submission( reviewee_key=second_reviewee_key, unit_id=self.unit_id).put() lower_priority_summary_key = peer.ReviewSummary( completed_count=1, reviewee_key=second_reviewee_key, submission_key=second_submission_key, unit_id=self.unit_id ).put() self.assertEqual( # Ensure we'll process higher priority first. [higher_priority_summary_key, lower_priority_summary_key], [c.key() for c in review_module.Manager.get_assignment_candidates_query( self.unit_id).fetch(2)]) # Create and bind a function that we can swap in to pick the review # candidate but as a side-effect updates the highest priority candidate # so we'll skip it and retry. def pick_and_update(unused_cls, candidates): db.put(higher_priority_summary) return candidates[0] fn = types.MethodType( pick_and_update, review_module.Manager(), review_module.Manager) self.swap( review_module.Manager, '_choose_assignment_candidate', fn) self.assertRaises( domain.NotAssignableError, review_module.Manager.get_new_review, self.unit_id, self.reviewer_key, max_retries=0) def test_get_new_review_raises_not_assignable_when_summary_updated(self): summary = peer.ReviewSummary( reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id) summary.put() # Create and bind a function that we can swap in to pick the review # candidate but as a side-effect updates the summary so we'll reject it # as a candidate. def pick_and_update(unused_cls, candidates): db.put(summary) return candidates[0] fn = types.MethodType( pick_and_update, review_module.Manager(), review_module.Manager) self.swap( review_module.Manager, '_choose_assignment_candidate', fn) self.assertRaises( domain.NotAssignableError, review_module.Manager.get_new_review, self.unit_id, self.reviewer_key) def test_get_new_review_reassigns_removed_assigned_step(self): summary_key = peer.ReviewSummary( reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() unused_already_assigned_removed_step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_HUMAN, removed=True, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=self.unit_id ).put() step_key = review_module.Manager.get_new_review( self.unit_id, self.reviewer_key) step, summary = db.get([step_key, summary_key]) self.assertEqual(domain.ASSIGNER_KIND_AUTO, step.assigner_kind) self.assertFalse(step.removed) self.assertEqual(domain.REVIEW_STATE_ASSIGNED, step.state) self.assertEqual(1, summary.assigned_count) def test_get_new_review_reassigns_removed_expired_step(self): summary_key = peer.ReviewSummary( reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() unused_already_expired_removed_step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_HUMAN, removed=True, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_EXPIRED, unit_id=self.unit_id ).put() step_key = review_module.Manager.get_new_review( self.unit_id, self.reviewer_key) step, summary = db.get([step_key, summary_key]) self.assertEqual(domain.ASSIGNER_KIND_AUTO, step.assigner_kind) self.assertFalse(step.removed) self.assertEqual(domain.REVIEW_STATE_ASSIGNED, step.state) self.assertEqual(1, summary.assigned_count) self.assertEqual(0, summary.expired_count) def test_get_new_review_retries_successfully(self): higher_priority_summary = peer.ReviewSummary( reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id) higher_priority_summary_key = higher_priority_summary.put() second_reviewee_key = models.Student( key_name='reviewee2@example.com').put() second_submission_key = student_work.Submission( reviewee_key=second_reviewee_key, unit_id=self.unit_id).put() lower_priority_summary_key = peer.ReviewSummary( completed_count=1, reviewee_key=second_reviewee_key, submission_key=second_submission_key, unit_id=self.unit_id ).put() self.assertEqual( # Ensure we'll process higher priority first. [higher_priority_summary_key, lower_priority_summary_key], [c.key() for c in review_module.Manager.get_assignment_candidates_query( self.unit_id).fetch(2)]) # Create and bind a function that we can swap in to pick the review # candidate but as a side-effect updates the highest priority candidate # so we'll skip it and retry. def pick_and_update(unused_cls, candidates): db.put(higher_priority_summary) return candidates[0] fn = types.MethodType( pick_and_update, review_module.Manager(), review_module.Manager) self.swap( review_module.Manager, '_choose_assignment_candidate', fn) step_key = review_module.Manager.get_new_review( self.unit_id, self.reviewer_key) step = db.get(step_key) self.assertEqual(lower_priority_summary_key, step.review_summary_key) def test_get_review_step_keys_by_returns_list_of_keys(self): summary_key = peer.ReviewSummary( reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() matching_step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, removed=True, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_EXPIRED, unit_id=self.unit_id ).put() non_matching_reviewer = models.Student(key_name='reviewer2@example.com') non_matching_reviewer_key = non_matching_reviewer.put() unused_non_matching_step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, removed=True, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=non_matching_reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_EXPIRED, unit_id=self.unit_id ).put() self.assertEqual( [matching_step_key], review_module.Manager.get_review_step_keys_by( self.unit_id, self.reviewer_key)) def test_get_review_step_keys_by_returns_keys_in_sorted_order(self): summary_key = peer.ReviewSummary( reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() first_step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, removed=True, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_EXPIRED, unit_id=self.unit_id ).put() second_reviewee_key = models.Student( key_name='reviewee2@example.com').put() second_submission_key = student_work.Submission( reviewee_key=second_reviewee_key, unit_id=self.unit_id).put() second_step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, removed=True, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=second_reviewee_key, reviewer_key=self.reviewer_key, submission_key=second_submission_key, state=domain.REVIEW_STATE_EXPIRED, unit_id=self.unit_id ).put() self.assertEqual( [first_step_key, second_step_key], review_module.Manager.get_review_step_keys_by( self.unit_id, self.reviewer_key)) def test_get_review_step_keys_by_returns_empty_list_when_no_matches(self): summary_key = peer.ReviewSummary( reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() non_matching_reviewer = models.Student(key_name='reviewer2@example.com') non_matching_reviewer_key = non_matching_reviewer.put() unused_non_matching_step_different_reviewer_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, removed=True, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=non_matching_reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_EXPIRED, unit_id=self.unit_id, ).put() unused_non_matching_step_different_unit_id_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, removed=True, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_EXPIRED, unit_id=str(int(self.unit_id) + 1), ).put() self.assertEqual( [], review_module.Manager.get_review_step_keys_by( self.unit_id, self.reviewer_key)) def test_get_review_steps_by_keys(self): summary_key = peer.ReviewSummary( reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_HUMAN, removed=True, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_EXPIRED, unit_id=self.unit_id ).put() second_reviewer_key = models.Student( key_name='reviewer2@example.com').put() missing_step_key = db.Key.from_path( peer.ReviewStep.kind(), peer.ReviewStep.key_name( self.submission_key, second_reviewer_key)) model_objects = db.get([step_key, missing_step_key]) domain_objects = review_module.Manager.get_review_steps_by_keys( [step_key, missing_step_key]) model_step, model_miss = model_objects domain_step, domain_miss = domain_objects self.assertEqual(2, len(model_objects)) self.assertEqual(2, len(domain_objects)) self.assertIsNone(model_miss) self.assertIsNone(domain_miss) self.assertEqual(model_step.assigner_kind, domain_step.assigner_kind) self.assertEqual(model_step.change_date, domain_step.change_date) self.assertEqual(model_step.create_date, domain_step.create_date) self.assertEqual(model_step.key(), domain_step.key) self.assertEqual(model_step.removed, domain_step.removed) self.assertEqual(model_step.review_key, domain_step.review_key) self.assertEqual( model_step.review_summary_key, domain_step.review_summary_key) self.assertEqual(model_step.reviewee_key, domain_step.reviewee_key) self.assertEqual(model_step.reviewer_key, domain_step.reviewer_key) self.assertEqual(model_step.state, domain_step.state) self.assertEqual(model_step.submission_key, domain_step.submission_key) self.assertEqual(model_step.unit_id, domain_step.unit_id) def test_get_reviews_by_keys(self): review_key = student_work.Review( contents='contents', reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, unit_id=self.unit_id ).put() missing_review_key = db.Key.from_path( student_work.Review.kind(), student_work.Review.key_name( str(int(self.unit_id) + 1), self.reviewee_key, self.reviewer_key)) model_objects = db.get([review_key, missing_review_key]) domain_objects = review_module.Manager.get_reviews_by_keys( [review_key, missing_review_key]) model_review, model_miss = model_objects domain_review, domain_miss = domain_objects self.assertEqual(2, len(model_objects)) self.assertEqual(2, len(domain_objects)) self.assertIsNone(model_miss) self.assertIsNone(domain_miss) self.assertEqual(model_review.contents, domain_review.contents) self.assertEqual(model_review.key(), domain_review.key) def test_get_submission_and_review_step_keys_no_steps(self): student_work.Submission( reviewee_key=self.reviewee_key, unit_id=self.unit_id).put() peer.ReviewSummary( reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() self.assertEqual( (self.submission_key, []), review_module.Manager.get_submission_and_review_step_keys( self.unit_id, self.reviewee_key)) def test_get_submission_and_review_step_keys_with_steps(self): student_work.Submission( reviewee_key=self.reviewee_key, unit_id=self.unit_id).put() summary_key = peer.ReviewSummary( reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() matching_step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, removed=True, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_EXPIRED, unit_id=self.unit_id ).put() non_matching_reviewee_key = models.Student( key_name='reviewee2@example.com').put() non_matching_submission_key = student_work.Submission( contents='contents2', reviewee_key=non_matching_reviewee_key, unit_id=self.unit_id).put() unused_non_matching_step_different_submission_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_AUTO, removed=True, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=non_matching_reviewee_key, reviewer_key=self.reviewer_key, submission_key=non_matching_submission_key, state=domain.REVIEW_STATE_EXPIRED, unit_id=self.unit_id ).put() self.assertEqual( (self.submission_key, [matching_step_key]), review_module.Manager.get_submission_and_review_step_keys( self.unit_id, self.reviewee_key)) def test_get_submission_and_review_step_keys_returns_none_on_miss(self): self.assertIsNone( review_module.Manager.get_submission_and_review_step_keys( self.unit_id, self.reviewee_key)) def test_get_submissions_by_keys(self): submission_key = student_work.Submission( contents='contents', reviewee_key=self.reviewee_key, unit_id=self.unit_id).put() missing_submission_key = db.Key.from_path( student_work.Submission.kind(), student_work.Submission.key_name( str(int(self.unit_id) + 1), self.reviewee_key)) domain_models = db.get([submission_key, missing_submission_key]) domain_objects = review_module.Manager.get_submissions_by_keys( [submission_key, missing_submission_key]) model_submission, model_miss = domain_models domain_submission, domain_miss = domain_objects self.assertEqual(2, len(domain_models)) self.assertEqual(2, len(domain_objects)) self.assertIsNone(model_miss) self.assertIsNone(domain_miss) self.assertEqual(model_submission.contents, domain_submission.contents) self.assertEqual(model_submission.key(), domain_submission.key) def test_start_review_process_for_succeeds(self): key = review_module.Manager.start_review_process_for( self.unit_id, self.submission_key, self.reviewee_key) summary = db.get(key) self.assertEqual(self.reviewee_key, summary.reviewee_key) self.assertEqual(self.submission_key, summary.submission_key) self.assertEqual(self.unit_id, summary.unit_id) def test_start_review_process_for_throws_if_already_started(self): collision = peer.ReviewSummary( reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id) collision.put() self.assertRaises( domain.ReviewProcessAlreadyStartedError, review_module.Manager.start_review_process_for, self.unit_id, self.submission_key, self.reviewee_key) def test_write_review_raises_constraint_error_if_key_but_no_review(self): summary_key = peer.ReviewSummary( assigned_count=1, reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_HUMAN, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_EXPIRED, unit_id=self.unit_id ).put() self.assertRaises( domain.ConstraintError, review_module.Manager.write_review, step_key, 'payload') def test_write_review_raises_constraint_error_if_no_summary(self): missing_summary_key = db.Key.from_path( peer.ReviewSummary.kind(), peer.ReviewSummary.key_name(self.submission_key)) review_key = student_work.Review( contents='contents', reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, unit_id=self.unit_id).put() step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_HUMAN, review_key=review_key, review_summary_key=missing_summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_EXPIRED, unit_id=self.unit_id ).put() self.assertRaises( domain.ConstraintError, review_module.Manager.write_review, step_key, 'payload') def test_write_review_raises_key_error_if_no_step(self): bad_step_key = db.Key.from_path(peer.ReviewStep.kind(), 'missing') self.assertRaises( KeyError, review_module.Manager.write_review, bad_step_key, 'payload') def test_write_review_raises_removed_error_if_step_removed(self): summary_key = peer.ReviewSummary( assigned_count=1, reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_HUMAN, removed=True, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_EXPIRED, unit_id=self.unit_id ).put() self.assertRaises( domain.RemovedError, review_module.Manager.write_review, step_key, 'payload') def test_write_review_raises_transition_error_if_step_completed(self): summary_key = peer.ReviewSummary( assigned_count=1, reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_HUMAN, review_key=db.Key.from_path(student_work.Review.kind(), 'review'), review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_COMPLETED, unit_id=self.unit_id ).put() self.assertRaises( domain.TransitionError, review_module.Manager.write_review, step_key, 'payload') def test_write_review_with_mark_completed_false(self): summary_key = peer.ReviewSummary( assigned_count=1, reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() review_key = student_work.Review( contents='old_contents', reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, unit_id=self.unit_id).put() step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_HUMAN, review_key=review_key, review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=self.unit_id ).put() updated_step_key = review_module.Manager.write_review( step_key, 'new_contents', mark_completed=False) self.assertEqual(step_key, updated_step_key) step, summary = db.get([updated_step_key, summary_key]) updated_review = db.get(step.review_key) self.assertEqual(1, summary.assigned_count) self.assertEqual(0, summary.completed_count) self.assertEqual(domain.REVIEW_STATE_ASSIGNED, step.state) self.assertEqual('new_contents', updated_review.contents) def test_write_review_with_no_review_mark_completed_false(self): summary_key = peer.ReviewSummary( assigned_count=1, reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_HUMAN, review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=self.unit_id ).put() self.assertIsNone(db.get(step_key).review_key) updated_step_key = review_module.Manager.write_review( step_key, 'contents', mark_completed=False) self.assertEqual(step_key, updated_step_key) step, summary = db.get([updated_step_key, summary_key]) updated_review = db.get(step.review_key) self.assertEqual(1, summary.assigned_count) self.assertEqual(0, summary.completed_count) self.assertEqual(domain.REVIEW_STATE_ASSIGNED, step.state) self.assertEqual(step.review_key, updated_review.key()) self.assertEqual('contents', updated_review.contents) def test_write_review_with_no_review_mark_completed_true(self): summary_key = peer.ReviewSummary( assigned_count=1, reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_HUMAN, review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=self.unit_id ).put() self.assertIsNone(db.get(step_key).review_key) updated_step_key = review_module.Manager.write_review( step_key, 'contents') self.assertEqual(step_key, updated_step_key) step, summary = db.get([updated_step_key, summary_key]) updated_review = db.get(step.review_key) self.assertEqual(0, summary.assigned_count) self.assertEqual(1, summary.completed_count) self.assertEqual(domain.REVIEW_STATE_COMPLETED, step.state) self.assertEqual(step.review_key, updated_review.key()) self.assertEqual('contents', updated_review.contents) def test_write_review_with_state_assigned_and_mark_completed_true(self): summary_key = peer.ReviewSummary( assigned_count=1, reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() review_key = student_work.Review( contents='old_contents', reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, unit_id=self.unit_id).put() step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_HUMAN, review_key=review_key, review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=self.unit_id ).put() updated_step_key = review_module.Manager.write_review( step_key, 'new_contents') self.assertEqual(step_key, updated_step_key) step, summary = db.get([updated_step_key, summary_key]) updated_review = db.get(step.review_key) self.assertEqual(0, summary.assigned_count) self.assertEqual(1, summary.completed_count) self.assertEqual(domain.REVIEW_STATE_COMPLETED, step.state) self.assertEqual('new_contents', updated_review.contents) def test_write_review_with_state_expired_and_mark_completed_true(self): summary_key = peer.ReviewSummary( expired_count=1, reviewee_key=self.reviewee_key, submission_key=self.submission_key, unit_id=self.unit_id ).put() review_key = student_work.Review( contents='old_contents', reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, unit_id=self.unit_id).put() step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_HUMAN, review_key=review_key, review_summary_key=summary_key, reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key, submission_key=self.submission_key, state=domain.REVIEW_STATE_EXPIRED, unit_id=self.unit_id ).put() updated_step_key = review_module.Manager.write_review( step_key, 'new_contents') self.assertEqual(step_key, updated_step_key) step, summary = db.get([updated_step_key, summary_key]) updated_review = db.get(step.review_key) self.assertEqual(1, summary.completed_count) self.assertEqual(0, summary.expired_count) self.assertEqual(domain.REVIEW_STATE_COMPLETED, step.state) self.assertEqual('new_contents', updated_review.contents) def test_write_review_with_two_students_creates_different_reviews(self): reviewee1 = models.Student(key_name='reviewee1@example.com') reviewee1_key = reviewee1.put() reviewee2 = models.Student(key_name='reviewee2@example.com') reviewee2_key = reviewee2.put() submission1_key = db.Key.from_path( student_work.Submission.kind(), student_work.Submission.key_name( reviewee_key=reviewee1_key, unit_id=self.unit_id)) submission2_key = db.Key.from_path( student_work.Submission.kind(), student_work.Submission.key_name( reviewee_key=reviewee2_key, unit_id=self.unit_id)) summary1_key = peer.ReviewSummary( assigned_count=1, reviewee_key=reviewee1_key, submission_key=submission1_key, unit_id=self.unit_id ).put() step1_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_HUMAN, review_summary_key=summary1_key, reviewee_key=reviewee1_key, reviewer_key=self.reviewer_key, submission_key=submission1_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=self.unit_id ).put() self.assertIsNone(db.get(step1_key).review_key) updated_step1_key = review_module.Manager.write_review( step1_key, 'contents1', mark_completed=False) self.assertEqual(step1_key, updated_step1_key) summary2_key = peer.ReviewSummary( assigned_count=1, reviewee_key=reviewee2_key, submission_key=submission2_key, unit_id=self.unit_id ).put() step2_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_HUMAN, review_summary_key=summary2_key, reviewee_key=reviewee2_key, reviewer_key=self.reviewer_key, submission_key=submission2_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=self.unit_id ).put() self.assertIsNone(db.get(step2_key).review_key) updated_step2_key = review_module.Manager.write_review( step2_key, 'contents2', mark_completed=False) self.assertEqual(step2_key, updated_step2_key) step1, summary1 = db.get([updated_step1_key, summary1_key]) updated_review = db.get(step1.review_key) self.assertEqual(1, summary1.assigned_count) self.assertEqual(0, summary1.completed_count) self.assertEqual(domain.REVIEW_STATE_ASSIGNED, step1.state) self.assertEqual(step1.review_key, updated_review.key()) self.assertEqual('contents1', updated_review.contents) step2, summary2 = db.get([updated_step2_key, summary2_key]) updated_review = db.get(step2.review_key) self.assertEqual(1, summary2.assigned_count) self.assertEqual(0, summary2.completed_count) self.assertEqual(domain.REVIEW_STATE_ASSIGNED, step2.state) self.assertEqual(step2.review_key, updated_review.key()) self.assertEqual('contents2', updated_review.contents)
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests that walk through Course Builder pages.""" __author__ = 'Mike Gainer (mgainer@google.com)' from common import crypto from models import courses from tests.functional import actions COURSE_NAME = 'unit_test' COURSE_TITLE = 'Unit Test' NAMESPACE = 'ns_%s' % COURSE_NAME ADMIN_EMAIL = 'admin@foo.com' STUDENT_EMAIL = 'foo@foo.com' BASE_URL = '/' + COURSE_NAME UNIT_URL_PREFIX = BASE_URL + '/unit?unit=' class UnitOnOnePageTest(actions.TestBase): def setUp(self): super(UnitOnOnePageTest, self).setUp() app_context = actions.simple_add_course(COURSE_NAME, ADMIN_EMAIL, COURSE_TITLE) self.course = courses.Course(None, app_context=app_context) self.unit = self.course.add_unit() self.unit.title = 'One Big Unit' self.unit.now_available = True self.unit.show_contents_on_one_page = True self.top_assessment = self.course.add_assessment() self.top_assessment.title = 'Top Assessment' self.top_assessment.html_content = 'content of top assessment' self.top_assessment.now_available = True self.unit.pre_assessment = self.top_assessment.unit_id self.bottom_assessment = self.course.add_assessment() self.bottom_assessment.title = 'Bottom Assessment' self.bottom_assessment.html_content = 'content of bottom assessment' self.bottom_assessment.now_available = True self.unit.post_assessment = self.bottom_assessment.unit_id self.lesson_one = self.course.add_lesson(self.unit) self.lesson_one.title = 'Lesson One' self.lesson_one.objectives = 'body of lesson one' self.lesson_one.now_available = True self.lesson_two = self.course.add_lesson(self.unit) self.lesson_two.title = 'Lesson Two' self.lesson_two.objectives = 'body of lesson two' self.lesson_two.now_available = True self.course.save() actions.login(STUDENT_EMAIL) actions.register(self, STUDENT_EMAIL, COURSE_NAME) def _assert_contains_in_order(self, response, expected): index = 0 for item in expected: index = response.body.find(item, index) if index == -1: self.fail('Did not find expected content "%s" ' % item) def _post_assessment(self, assessment_id): return self.post(BASE_URL + '/answer', { 'xsrf_token': crypto.XsrfTokenManager.create_xsrf_token( 'assessment-post'), 'assessment_type': assessment_id, 'score': '100'}) def _verify_contents(self, response): self._assert_contains_in_order( response, ['Unit 1 - One Big Unit', 'Top Assessment', 'content of top assessment', 'Submit Answers', 'Lesson One', 'body of lesson one', 'Lesson Two', 'body of lesson two', 'Bottom Assessment', 'content of bottom assessment', 'Submit Answers']) self.assertNotIn('Next Page', response.body) self.assertNotIn('Prev Page', response.body) self.assertNotIn('End', response.body) def test_appearance(self): response = self.get(UNIT_URL_PREFIX + str(self.unit.unit_id)) self._verify_contents(response) def test_content_url_insensitive(self): url = UNIT_URL_PREFIX + str(self.unit.unit_id) response = self.get( url + '&assessment=' + str(self.top_assessment.unit_id)) self._verify_contents(response) response = self.get( url + '&assessment=' + str(self.bottom_assessment.unit_id)) self._verify_contents(response) response = self.get( url + '&lesson=' + str(self.lesson_one.lesson_id)) self._verify_contents(response) response = self.get( url + '&lesson=' + str(self.lesson_two.lesson_id)) self._verify_contents(response) def _test_submit_assessment(self, assessment): response = self.get(UNIT_URL_PREFIX + str(self.unit.unit_id)) response = self._post_assessment(assessment.unit_id).follow() self._assert_contains_in_order( response, ['Thank you for taking the %s' % assessment.title.lower(), 'Return to Unit']) self.assertNotIn('Next Page', response.body) self.assertNotIn('Prev Page', response.body) self.assertNotIn('End', response.body) response = self.click(response, 'Return to Unit') self._verify_contents(response) def test_submit_assessments(self): self._test_submit_assessment(self.top_assessment) self._test_submit_assessment(self.bottom_assessment)
Python
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Functional tests for models.models.""" __author__ = [ 'johncox@google.com (John Cox)', ] import datetime from models import config from models import entities from models import models from models import services from modules.notifications import notifications from tests.functional import actions from google.appengine.ext import db class EventEntityTestCase(actions.ExportTestBase): def test_for_export_transforms_correctly(self): event = models.EventEntity(source='source', user_id='1') key = event.put() exported = event.for_export(self.transform) self.assert_blacklisted_properties_removed(event, exported) self.assertEqual('source', event.source) self.assertEqual('transformed_1', exported.user_id) self.assertEqual(key, models.EventEntity.safe_key(key, self.transform)) class ContentChunkTestCase(actions.ExportTestBase): """Tests ContentChunkEntity|DAO|DTO.""" def setUp(self): super(ContentChunkTestCase, self).setUp() config.Registry.test_overrides[models.CAN_USE_MEMCACHE.name] = True self.content_type = 'content_type' self.contents = 'contents' self.id = 1 self.memcache_key = models.ContentChunkDAO._get_memcache_key(self.id) self.resource_id = 'resource:id' # To check colons are preserved. self.supports_custom_tags = True self.type_id = 'type_id' self.uid = models.ContentChunkDAO.make_uid( self.type_id, self.resource_id) def tearDown(self): config.Registry.test_overrides = {} super(ContentChunkTestCase, self).tearDown() def assert_fuzzy_equal(self, first, second): """Assert doesn't check last_modified, allowing clock skew.""" self.assertTrue(isinstance(first, models.ContentChunkDTO)) self.assertTrue(isinstance(second, models.ContentChunkDTO)) self.assertEqual(first.content_type, second.content_type) self.assertEqual(first.contents, second.contents) self.assertEqual(first.id, second.id) self.assertEqual(first.resource_id, second.resource_id) self.assertEqual( first.supports_custom_tags, second.supports_custom_tags) self.assertEqual(first.type_id, second.type_id) def assert_list_fuzzy_equal(self, first, second): self.assertEqual(len(first), len(second)) for f, s in zip(first, second): self.assert_fuzzy_equal(f, s) def test_dao_delete_deletes_entity_and_cached_dto(self): key = models.ContentChunkDAO.save(models.ContentChunkDTO({ 'content_type': self.content_type, 'contents': self.contents, 'id': self.id, 'resource_id': self.resource_id, 'supports_custom_tags': self.supports_custom_tags, 'type_id': self.type_id, })) entity = db.get(key) dto = models.ContentChunkDAO.get(key.id()) self.assertIsNotNone(entity) self.assertIsNotNone(dto) models.ContentChunkDAO.delete(key.id()) entity = db.get(key) dto = models.ContentChunkDAO.get(key.id()) self.assertIsNone(entity) self.assertIsNone(dto) def test_dao_delete_runs_successfully_when_no_entity_present(self): self.assertIsNone(models.ContentChunkDAO.delete(self.id)) def test_dao_get_returns_cached_entity(self): key = models.ContentChunkDAO.save(models.ContentChunkDTO({ 'content_type': self.content_type, 'contents': self.contents, 'resource_id': self.resource_id, 'supports_custom_tags': self.supports_custom_tags, 'type_id': self.type_id, })) entity = db.get(key) entity.contents = 'patched' patched_dto = models.ContentChunkDAO._make_dto(entity) models.MemcacheManager.set(self.memcache_key, patched_dto) from_datastore = models.ContentChunkEntity.get_by_id(self.id) from_cache = models.MemcacheManager.get(self.memcache_key) self.assert_fuzzy_equal(patched_dto, from_cache) self.assertNotEqual(patched_dto.contents, from_datastore.contents) def test_dao_get_returns_datastore_entity_and_populates_cache(self): self.assertIsNone(models.MemcacheManager.get(self.memcache_key)) key = models.ContentChunkDAO.save(models.ContentChunkDTO({ 'content_type': self.content_type, 'contents': self.contents, 'resource_id': self.resource_id, 'supports_custom_tags': self.supports_custom_tags, 'type_id': self.type_id, })) expected_dto = models.ContentChunkDAO._make_dto(db.get(key)) from_datastore = models.ContentChunkEntity.get_by_id(self.id) from_cache = models.MemcacheManager.get(self.memcache_key) self.assert_fuzzy_equal( expected_dto, models.ContentChunkDAO._make_dto(from_datastore)) self.assert_fuzzy_equal(expected_dto, from_cache) def test_dao_get_returns_none_when_entity_id_none(self): self.assertIsNone(models.ContentChunkDAO.get(None)) def test_dao_get_returns_none_when_no_entity_in_datastore(self): self.assertIsNone(models.MemcacheManager.get(self.memcache_key)) self.assertIsNone(models.ContentChunkDAO.get(self.id)) self.assertEqual( models.NO_OBJECT, models.MemcacheManager.get(self.memcache_key)) def test_dao_get_by_uid_returns_empty_list_if_no_matches(self): self.assertEqual([], models.ContentChunkDAO.get_by_uid(self.uid)) def test_dao_get_by_uid_returns_matching_dtos_sorted_by_id(self): different_uid = models.ContentChunkDAO.make_uid( 'other', self.resource_id) first_key = models.ContentChunkEntity( content_type=self.content_type, contents=self.contents, supports_custom_tags=self.supports_custom_tags, uid=self.uid).put() second_key = models.ContentChunkEntity( content_type=self.content_type, contents=self.contents + '2', supports_custom_tags=self.supports_custom_tags, uid=self.uid).put() unused_different_uid_key = models.ContentChunkEntity( content_type=self.content_type, contents=self.contents, supports_custom_tags=self.supports_custom_tags, uid=different_uid).put() expected_dtos = [ models.ContentChunkDAO.get(first_key.id()), models.ContentChunkDAO.get(second_key.id())] actual_dtos = models.ContentChunkDAO.get_by_uid(self.uid) self.assert_list_fuzzy_equal(expected_dtos, actual_dtos) def test_dao_make_dto(self): key = models.ContentChunkEntity( content_type=self.content_type, contents=self.contents, supports_custom_tags=self.supports_custom_tags, uid=self.uid).put() entity = db.get(key) # Refetch to avoid timestamp skew. dto = models.ContentChunkDAO._make_dto(entity) self.assertEqual(entity.content_type, dto.content_type) self.assertEqual(entity.contents, dto.contents) self.assertEqual(entity.key().id(), dto.id) self.assertEqual(entity.last_modified, dto.last_modified) self.assertEqual(entity.supports_custom_tags, dto.supports_custom_tags) entity_type_id, entity_resource_id = models.ContentChunkDAO._split_uid( entity.uid) self.assertEqual(entity_resource_id, dto.resource_id) self.assertEqual(entity_type_id, dto.type_id) def test_dao_make_uid(self): self.assertEqual(None, models.ContentChunkDAO.make_uid(None, None)) self.assertEqual( 'foo:bar', models.ContentChunkDAO.make_uid('foo', 'bar')) def test_dao_make_uid_requires_both_args_disallows_colons_in_type_id(self): bad_pairs = [ (None, 'foo'), ('foo', None), (':', None), (':', 'foo'), ('', ''), ('', 'foo'), ('foo', ''), (':', ''), (':', 'foo'), ] for bad_pair in bad_pairs: with self.assertRaises(AssertionError): models.ContentChunkDAO.make_uid(*bad_pair) def test_dao_split_uid(self): self.assertEqual( (None, None), models.ContentChunkDAO._split_uid(None)) self.assertEqual( ('foo', 'bar'), models.ContentChunkDAO._split_uid('foo:bar')) self.assertEqual( ('foo', 'http://bar'), models.ContentChunkDAO._split_uid('foo:http://bar')) def test_dao_split_uid_requires_colon_and_both_values_are_truthy(self): with self.assertRaises(AssertionError): models.ContentChunkDAO._split_uid('foo') with self.assertRaises(AssertionError): models.ContentChunkDAO._split_uid(':') with self.assertRaises(AssertionError): models.ContentChunkDAO._split_uid('foo:') with self.assertRaises(AssertionError): models.ContentChunkDAO._split_uid(':foo') def test_dao_save_creates_new_object_and_populates_cache(self): self.assertIsNone(models.MemcacheManager.get(self.memcache_key)) key = models.ContentChunkDAO.save(models.ContentChunkDTO({ 'content_type': self.content_type, 'contents': self.contents, 'id': self.id, 'resource_id': self.resource_id, 'supports_custom_tags': self.supports_custom_tags, 'type_id': self.type_id, })) expected_dto = models.ContentChunkDAO._make_dto(db.get(key)) self.assert_fuzzy_equal( expected_dto, models.MemcacheManager.get(self.memcache_key)) def test_dao_save_updates_existing_object_and_populates_cache(self): key = models.ContentChunkDAO.save(models.ContentChunkDTO({ 'content_type': self.content_type, 'contents': self.contents, 'id': self.id, 'resource_id': self.resource_id, 'supports_custom_tags': self.supports_custom_tags, 'type_id': self.type_id, })) original_dto = models.ContentChunkDAO._make_dto(db.get(key)) self.assert_fuzzy_equal( original_dto, models.MemcacheManager.get(self.memcache_key)) original_dto.content_type = 'new_content_type' original_dto.contents = 'new_contents' original_dto.supports_custom_tags = True original_dto.uid = 'new_system_id:new_resource:id' models.ContentChunkDAO.save(original_dto) expected_dto = models.ContentChunkDAO._make_dto(db.get(key)) self.assert_fuzzy_equal( expected_dto, models.MemcacheManager.get(self.memcache_key)) class PersonalProfileTestCase(actions.ExportTestBase): def test_for_export_transforms_correctly_and_sets_safe_key(self): date_of_birth = datetime.date.today() email = 'test@example.com' legal_name = 'legal_name' nick_name = 'nick_name' user_id = '1' profile = models.PersonalProfile( date_of_birth=date_of_birth, email=email, key_name=user_id, legal_name=legal_name, nick_name=nick_name) profile.put() exported = profile.for_export(self.transform) self.assert_blacklisted_properties_removed(profile, exported) self.assertEqual( self.transform(user_id), exported.safe_key.name()) class MemcacheManagerTestCase(actions.TestBase): def setUp(self): super(MemcacheManagerTestCase, self).setUp() config.Registry.test_overrides = {models.CAN_USE_MEMCACHE.name: True} def tearDown(self): config.Registry.test_overrides = {} super(MemcacheManagerTestCase, self).tearDown() def test_set_multi(self): data = {'a': 'A', 'b': 'B'} models.MemcacheManager.set_multi(data) self.assertEquals('A', models.MemcacheManager.get('a')) self.assertEquals('B', models.MemcacheManager.get('b')) def test_get_multi(self): models.MemcacheManager.set('a', 'A') models.MemcacheManager.set('b', 'B') data = models.MemcacheManager.get_multi(['a', 'b', 'c']) self.assertEquals(2, len(data.keys())) self.assertEquals('A', data['a']) self.assertEquals('B', data['b']) def test_set_multi_no_memcache(self): config.Registry.test_overrides = {} data = {'a': 'A', 'b': 'B'} models.MemcacheManager.set_multi(data) self.assertEquals(None, models.MemcacheManager.get('a')) self.assertEquals(None, models.MemcacheManager.get('b')) def test_get_multi_no_memcache(self): config.Registry.test_overrides = {} models.MemcacheManager.set('a', 'A') models.MemcacheManager.set('b', 'B') data = models.MemcacheManager.get_multi(['a', 'b', 'c']) self.assertEquals(0, len(data.keys())) class TestEntity(entities.BaseEntity): data = db.TextProperty(indexed=False) class TestDto(object): def __init__(self, the_id, the_dict): self.id = the_id self.dict = the_dict class TestDao(models.BaseJsonDao): DTO = TestDto ENTITY = TestEntity ENTITY_KEY_TYPE = models.BaseJsonDao.EntityKeyTypeName class BaseJsonDaoTestCase(actions.TestBase): def setUp(self): super(BaseJsonDaoTestCase, self).setUp() config.Registry.test_overrides = {models.CAN_USE_MEMCACHE.name: True} def tearDown(self): config.Registry.test_overrides = {} super(BaseJsonDaoTestCase, self).tearDown() def test_bulk_load(self): key_0 = 'dto_0' key_1 = 'dto_1' mc_key_0 = '(entity:TestEntity:dto_0)' mc_key_1 = '(entity:TestEntity:dto_1)' dto = TestDto(key_0, {'a': 0}) TestDao.save(dto) dto = TestDto(key_1, {'a': 1}) TestDao.save(dto) def assert_bulk_load_succeeds(): dtos = TestDao.bulk_load([key_0, key_1, 'dto_2']) self.assertEquals(3, len(dtos)) self.assertEquals(key_0, dtos[0].id) self.assertEquals({'a': 0}, dtos[0].dict) self.assertEquals(key_1, dtos[1].id) self.assertEquals({'a': 1}, dtos[1].dict) self.assertIsNone(dtos[2]) # Confirm entities in memcache memcache_entities = models.MemcacheManager.get_multi( [mc_key_0, mc_key_1]) self.assertEquals(2, len(memcache_entities)) self.assertIn(mc_key_0, memcache_entities) self.assertIn(mc_key_1, memcache_entities) assert_bulk_load_succeeds() # Evict one from memcache models.MemcacheManager.delete(mc_key_0) memcache_entities = models.MemcacheManager.get_multi( [mc_key_0, mc_key_1]) self.assertEquals(1, len(memcache_entities)) self.assertIn(mc_key_1, memcache_entities) assert_bulk_load_succeeds() # Evict both from memcache models.MemcacheManager.delete(mc_key_0) models.MemcacheManager.delete(mc_key_1) memcache_entities = models.MemcacheManager.get_multi( [mc_key_0, mc_key_1]) self.assertEquals(0, len(memcache_entities)) assert_bulk_load_succeeds() class QuestionDAOTestCase(actions.TestBase): """Functional tests for QuestionDAO.""" def setUp(self): """Sets up datastore contents.""" super(QuestionDAOTestCase, self).setUp() self.used_twice_question_dto = models.QuestionDTO(None, {}) self.used_twice_question_id = models.QuestionDAO.save( self.used_twice_question_dto) self.used_once_question_dto = models.QuestionDTO(None, {}) self.used_once_question_id = models.QuestionDAO.save( self.used_once_question_dto) self.unused_question_dto = models.QuestionDTO(None, {}) self.unused_question_id = models.QuestionDAO.save( self.unused_question_dto) # Handcoding the dicts. This is dangerous because they're handcoded # elsewhere, the implementations could fall out of sync, and these tests # may then pass erroneously. self.first_question_group_description = 'first_question_group' self.first_question_group_dto = models.QuestionGroupDTO( None, {'description': self.first_question_group_description, 'items': [{'question': str(self.used_once_question_id)}]}) self.first_question_group_id = models.QuestionGroupDAO.save( self.first_question_group_dto) self.second_question_group_description = 'second_question_group' self.second_question_group_dto = models.QuestionGroupDTO( None, {'description': self.second_question_group_description, 'items': [{'question': str(self.used_twice_question_id)}]}) self.second_question_group_id = models.QuestionGroupDAO.save( self.second_question_group_dto) self.third_question_group_description = 'third_question_group' self.third_question_group_dto = models.QuestionGroupDTO( None, {'description': self.third_question_group_description, 'items': [{'question': str(self.used_twice_question_id)}]}) self.third_question_group_id = models.QuestionGroupDAO.save( self.third_question_group_dto) def test_used_by_returns_single_question_group(self): self.assertEqual( long(self.first_question_group_id), models.QuestionDAO.used_by(self.used_once_question_id)[0].id) def test_used_by_returns_multiple_question_groups(self): used_by = models.QuestionDAO.used_by(self.used_twice_question_id) self.assertEqual(long(self.second_question_group_id), used_by[0].id) self.assertEqual(long(self.third_question_group_id), used_by[1].id) def test_used_by_returns_empty_list_for_unused_question(self): not_found_id = 7 self.assertFalse(models.QuestionDAO.load(not_found_id)) self.assertEqual([], models.QuestionDAO.used_by(not_found_id)) class StudentTestCase(actions.ExportTestBase): def test_for_export_transforms_correctly(self): user_id = '1' student = models.Student(key_name='name', user_id='1', is_enrolled=True) key = student.put() exported = student.for_export(self.transform) self.assert_blacklisted_properties_removed(student, exported) self.assertTrue(exported.is_enrolled) self.assertEqual('transformed_1', exported.user_id) self.assertEqual( 'transformed_' + user_id, exported.key_by_user_id.name()) self.assertEqual( models.Student.safe_key(key, self.transform), exported.safe_key) def test_get_key_does_not_transform_by_default(self): user_id = 'user_id' student = models.Student(key_name='name', user_id=user_id) student.put() self.assertEqual(user_id, student.get_key().name()) def test_safe_key_transforms_name(self): key = models.Student(key_name='name').put() self.assertEqual( 'transformed_name', models.Student.safe_key(key, self.transform).name()) class StudentProfileDAOTestCase(actions.ExportTestBase): def test_can_send_welcome_notifications_false_if_config_value_false(self): self.swap(services.notifications, 'enabled', lambda: True) self.swap(services.unsubscribe, 'enabled', lambda: True) handler = actions.MockHandler( app_context=actions.MockAppContext(environ={ 'course': {'send_welcome_notifications': False} })) self.assertFalse( models.StudentProfileDAO._can_send_welcome_notifications(handler)) def test_can_send_welcome_notifications_false_notifications_disabled(self): self.swap(services.notifications, 'enabled', lambda: False) self.swap(services.unsubscribe, 'enabled', lambda: True) handler = actions.MockHandler( app_context=actions.MockAppContext(environ={ 'course': {'send_welcome_notifications': True} })) self.assertFalse( models.StudentProfileDAO._can_send_welcome_notifications(handler)) def test_can_send_welcome_notifications_false_unsubscribe_disabled(self): self.swap(services.notifications, 'enabled', lambda: True) self.swap(services.unsubscribe, 'enabled', lambda: False) handler = actions.MockHandler( app_context=actions.MockAppContext(environ={ 'course': {'send_welcome_notifications': True} })) self.assertFalse( models.StudentProfileDAO._can_send_welcome_notifications(handler)) def test_can_send_welcome_notifications_true_if_all_true(self): self.swap(services.notifications, 'enabled', lambda: True) self.swap(services.unsubscribe, 'enabled', lambda: True) handler = actions.MockHandler( app_context=actions.MockAppContext(environ={ 'course': {'send_welcome_notifications': True} })) self.assertTrue( models.StudentProfileDAO._can_send_welcome_notifications(handler)) def test_get_send_welcome_notifications(self): handler = actions.MockHandler(app_context=actions.MockAppContext()) self.assertFalse( models.StudentProfileDAO._get_send_welcome_notifications(handler)) handler = actions.MockHandler( app_context=actions.MockAppContext(environ={ 'course': {} })) self.assertFalse( models.StudentProfileDAO._get_send_welcome_notifications(handler)) handler = actions.MockHandler( app_context=actions.MockAppContext(environ={ 'course': {'send_welcome_notifications': False} })) self.assertFalse( models.StudentProfileDAO._get_send_welcome_notifications(handler)) handler = actions.MockHandler( app_context=actions.MockAppContext(environ={ 'course': {'send_welcome_notifications': True} })) self.assertTrue( models.StudentProfileDAO._get_send_welcome_notifications(handler)) def test_send_welcome_notification_enqueues_and_sends(self): nick_name = 'No Body' email = 'user@example.com' sender = 'sender@example.com' title = 'title' student = models.Student(key_name=email, name=nick_name) self.swap(services.notifications, 'enabled', lambda: True) self.swap(services.unsubscribe, 'enabled', lambda: True) handler = actions.MockHandler( app_context=actions.MockAppContext(environ={ 'course': { 'send_welcome_notifications': True, 'title': title, 'welcome_notifications_sender': sender, }, })) models.StudentProfileDAO._send_welcome_notification(handler, student) self.execute_all_deferred_tasks() notification = notifications.Notification.all().get() payload = notifications.Payload.all().get() audit_trail = notification.audit_trail self.assertEqual(title, audit_trail['course_title']) self.assertEqual( 'http://mycourse.appspot.com/slug/', audit_trail['course_url']) self.assertTrue(audit_trail['unsubscribe_url'].startswith( 'http://mycourse.appspot.com/slug/modules/unsubscribe')) self.assertTrue(notification._done_date) self.assertEqual(email, notification.to) self.assertEqual(sender, notification.sender) self.assertEqual('Welcome to ' + title, notification.subject) self.assertTrue(payload) class StudentAnswersEntityTestCase(actions.ExportTestBase): def test_safe_key_transforms_name(self): student_key = models.Student(key_name='name').put() answers = models.StudentAnswersEntity(key_name=student_key.name()) answers_key = answers.put() self.assertEqual( 'transformed_name', models.StudentAnswersEntity.safe_key( answers_key, self.transform).name()) class StudentPropertyEntityTestCase(actions.ExportTestBase): def test_safe_key_transforms_user_id_component(self): user_id = 'user_id' student = models.Student(key_name='email@example.com', user_id=user_id) student.put() property_name = 'property-name' student_property_key = models.StudentPropertyEntity.create( student, property_name).put() self.assertEqual( 'transformed_%s-%s' % (user_id, property_name), models.StudentPropertyEntity.safe_key( student_property_key, self.transform).name())
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests that walk through Course Builder pages.""" __author__ = 'Mike Gainer (mgainer@google.com)' from common import utils as common_utils from controllers import sites from models import courses from models import models from tests.functional import actions COURSE_NAME = 'tracks_test' COURSE_TITLE = 'Tracks Test' NAMESPACE = 'ns_%s' % COURSE_NAME ADMIN_EMAIL = 'admin@foo.com' REGISTERED_STUDENT_EMAIL = 'foo@bar.com' REGISTERED_STUDENT_NAME = 'John Smith' UNREGISTERED_STUDENT_EMAIL = 'bar@bar.com' COURSE_OVERVIEW_URL = '/%s/course' % COURSE_NAME STUDENT_LABELS_URL = '/%s/rest/student/labels' % COURSE_NAME STUDENT_SETTINGS_URL = '/%s/student/home' % COURSE_NAME class StudentTracksTest(actions.TestBase): _get_environ_old = None @classmethod def setUpClass(cls): super(StudentTracksTest, cls).setUpClass() sites.ApplicationContext.get_environ_old = ( sites.ApplicationContext.get_environ) def get_environ_new(slf): environ = slf.get_environ_old() environ['course']['now_available'] = True return environ sites.ApplicationContext.get_environ = get_environ_new @classmethod def tearDownClass(cls): sites.ApplicationContext.get_environ = ( sites.ApplicationContext.get_environ_old) def setUp(self): super(StudentTracksTest, self).setUp() # Add a course that will show up. actions.simple_add_course(COURSE_NAME, ADMIN_EMAIL, COURSE_TITLE) # Add labels with common_utils.Namespace(NAMESPACE): self.foo_id = models.LabelDAO.save(models.LabelDTO( None, {'title': 'Foo', 'descripton': 'foo', 'type': models.LabelDTO.LABEL_TYPE_COURSE_TRACK})) self.bar_id = models.LabelDAO.save(models.LabelDTO( None, {'title': 'Bar', 'descripton': 'bar', 'type': models.LabelDTO.LABEL_TYPE_COURSE_TRACK})) self.baz_id = models.LabelDAO.save(models.LabelDTO( None, {'title': 'Baz', 'descripton': 'baz', 'type': models.LabelDTO.LABEL_TYPE_COURSE_TRACK})) self.quux_id = models.LabelDAO.save(models.LabelDTO( None, {'title': 'Quux', 'descripton': 'quux', 'type': models.LabelDTO.LABEL_TYPE_GENERAL})) # Register a student for that course. actions.login(REGISTERED_STUDENT_EMAIL) actions.register(self, REGISTERED_STUDENT_NAME, COURSE_NAME) actions.logout() # Add some units to the course. self._course = courses.Course( None, app_context=sites.get_all_courses()[0]) self._unit_no_labels = self._course.add_unit() self._unit_no_labels.title = 'Unit No Labels' self._unit_no_labels.now_available = True self._unit_labels_foo = self._course.add_unit() self._unit_labels_foo.title = 'Unit Labels: Foo' self._unit_labels_foo.now_available = True self._unit_labels_foo.labels = str(self.foo_id) self._unit_labels_foo_bar = self._course.add_unit() self._unit_labels_foo_bar.title = 'Unit Labels: Bar, Foo' self._unit_labels_foo_bar.now_available = True self._unit_labels_foo_bar.labels = '%s %s' % (self.bar_id, self.foo_id) self._unit_labels_quux = self._course.add_unit() self._unit_labels_quux.title = 'Unit Labels: Quux' self._unit_labels_quux.now_available = True self._unit_labels_quux.labels = str(self.quux_id) self._unit_labels_foo_quux = self._course.add_unit() self._unit_labels_foo_quux.title = 'Unit Labels: Foo Quux' self._unit_labels_foo_quux.now_available = True self._unit_labels_foo_quux.labels = '%s %s' % (str(self.foo_id), str(self.quux_id)) self._course.save() def tearDown(self): super(StudentTracksTest, self).tearDown() sites.reset_courses() def _choose_tracks(self, label_ids): response = self.get(STUDENT_SETTINGS_URL) form = response.forms['student_set_tracks'] labels_by_ids = {} for label_field in form.fields['labels']: labels_by_ids[label_field.id] = label_field for label_id in label_ids: labels_by_ids['label_id_%d' % label_id].checked = True self.submit(form, response) def test_unit_matching_no_labels(self): actions.login(REGISTERED_STUDENT_EMAIL) self._choose_tracks([]) response = self.get(COURSE_OVERVIEW_URL) self.assertIn(self._unit_no_labels.title, response.body) self.assertIn(self._unit_labels_foo.title, response.body) self.assertIn(self._unit_labels_foo_bar.title, response.body) def test_unit_matching_foo(self): actions.login(REGISTERED_STUDENT_EMAIL) self._choose_tracks([self.foo_id]) response = self.get(COURSE_OVERVIEW_URL) self.assertIn(self._unit_no_labels.title, response.body) self.assertIn(self._unit_labels_foo.title, response.body) self.assertIn(self._unit_labels_foo_bar.title, response.body) def test_unit_matching_foo_bar(self): actions.login(REGISTERED_STUDENT_EMAIL) self._choose_tracks([self.foo_id, self.bar_id]) response = self.get(COURSE_OVERVIEW_URL) self.assertIn(self._unit_no_labels.title, response.body) self.assertIn(self._unit_labels_foo.title, response.body) self.assertIn(self._unit_labels_foo_bar.title, response.body) def test_unit_matching_bar(self): actions.login(REGISTERED_STUDENT_EMAIL) self._choose_tracks([self.bar_id]) response = self.get(COURSE_OVERVIEW_URL) self.assertIn(self._unit_no_labels.title, response.body) self.assertNotIn(self._unit_labels_foo.title, response.body) self.assertIn(self._unit_labels_foo_bar.title, response.body) def test_unit_matching_baz(self): actions.login(REGISTERED_STUDENT_EMAIL) self._choose_tracks([self.baz_id]) response = self.get(COURSE_OVERVIEW_URL) self.assertIn(self._unit_no_labels.title, response.body) self.assertNotIn(self._unit_labels_foo.title, response.body) self.assertNotIn(self._unit_labels_foo_bar.title, response.body) def test_unit_with_general_and_tracks_student_with_no_tracks(self): actions.login(REGISTERED_STUDENT_EMAIL) response = self.put(STUDENT_LABELS_URL, {'labels': str(self.quux_id)}) response = self.get(COURSE_OVERVIEW_URL) self.assertIn(self._unit_labels_quux.title, response.body) self.assertIn(self._unit_labels_foo_quux.title, response.body) def test_unit_with_general_and_tracks_student_with_matching_tracks(self): actions.login(REGISTERED_STUDENT_EMAIL) response = self.put(STUDENT_LABELS_URL, {'labels': str(self.foo_id)}) response = self.get(COURSE_OVERVIEW_URL) self.assertIn(self._unit_labels_quux.title, response.body) self.assertIn(self._unit_labels_foo_quux.title, response.body) def test_unit_with_general_and_tracks_student_with_mismatched_tracks(self): actions.login(REGISTERED_STUDENT_EMAIL) response = self.put(STUDENT_LABELS_URL, {'labels': str(self.bar_id)}) response = self.get(COURSE_OVERVIEW_URL) self.assertIn(self._unit_labels_quux.title, response.body) self.assertNotIn(self._unit_labels_foo_quux.title, response.body) def test_load_units_student_no_labels(self): actions.login(REGISTERED_STUDENT_EMAIL) self._choose_tracks([]) response = self.get(COURSE_OVERVIEW_URL) self.assertEquals(200, self.get('unit?unit=%d' % self._unit_no_labels.unit_id, response).status_int) self.assertEquals(200, self.get('unit?unit=%d' % self._unit_labels_foo.unit_id, response).status_int) self.assertEquals(200, self.get('unit?unit=%d' % self._unit_labels_foo_bar.unit_id, response).status_int) self.assertEquals(200, self.get('unit?unit=%d' % self._unit_labels_quux.unit_id, response).status_int) self.assertEquals(200, self.get('unit?unit=%d' % self._unit_labels_foo_quux.unit_id, response).status_int) def test_load_units_student_labeled_foo(self): actions.login(REGISTERED_STUDENT_EMAIL) self._choose_tracks([self.foo_id]) response = self.get(COURSE_OVERVIEW_URL) self.assertEquals(200, self.get('unit?unit=%d' % self._unit_no_labels.unit_id, response).status_int) self.assertEquals(200, self.get('unit?unit=%d' % self._unit_labels_foo.unit_id, response).status_int) self.assertEquals(200, self.get('unit?unit=%d' % self._unit_labels_foo_bar.unit_id, response).status_int) self.assertEquals(200, self.get('unit?unit=%d' % self._unit_labels_quux.unit_id, response).status_int) self.assertEquals(200, self.get('unit?unit=%d' % self._unit_labels_foo_quux.unit_id, response).status_int)
Python
# coding: utf-8 # Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the internationalization (i18n) workflow.""" __author__ = 'John Orr (jorr@google.com)' import cgi import collections import cStringIO import StringIO import traceback import unittest import urllib import zipfile from babel.messages import pofile from common import crypto from common import resource from common import tags from common import utils from common.utils import Namespace from controllers import sites from models import config from models import courses from models import resources_display from models import models from models import roles from models import transforms from modules.announcements import announcements from modules.dashboard import dashboard from modules.i18n_dashboard import i18n_dashboard from modules.i18n_dashboard.i18n_dashboard import I18nProgressDAO from modules.i18n_dashboard.i18n_dashboard import I18nProgressDTO from modules.i18n_dashboard.i18n_dashboard import LazyTranslator from modules.i18n_dashboard.i18n_dashboard import ResourceBundleDAO from modules.i18n_dashboard.i18n_dashboard import ResourceBundleDTO from modules.i18n_dashboard.i18n_dashboard import ResourceBundleKey from modules.i18n_dashboard.i18n_dashboard import ResourceRow from modules.i18n_dashboard.i18n_dashboard import TranslationConsoleRestHandler from modules.i18n_dashboard.i18n_dashboard import TranslationUploadRestHandler from modules.i18n_dashboard.i18n_dashboard import VERB_CHANGED from modules.i18n_dashboard.i18n_dashboard import VERB_CURRENT from modules.i18n_dashboard.i18n_dashboard import VERB_NEW from modules.notifications import notifications from tests.functional import actions from google.appengine.api import memcache from google.appengine.api import namespace_manager from google.appengine.api import users from google.appengine.datastore import datastore_rpc class ResourceBundleKeyTests(unittest.TestCase): def test_roundtrip_data(self): key1 = ResourceBundleKey( resources_display.ResourceAssessment.TYPE, '23', 'el') key2 = ResourceBundleKey.fromstring(str(key1)) self.assertEquals(key1.locale, key2.locale) self.assertEquals(key1.resource_key.type, key2.resource_key.type) self.assertEquals(key1.resource_key.key, key2.resource_key.key) def test_from_resource_key(self): resource_key = resource.Key( resources_display.ResourceAssessment.TYPE, '23') key = ResourceBundleKey.from_resource_key(resource_key, 'el') self.assertEquals(resources_display.ResourceAssessment.TYPE, key.resource_key.type) self.assertEquals('23', key.resource_key.key) self.assertEquals('el', key.locale) class ResourceRowTests(unittest.TestCase): def setUp(self): super(ResourceRowTests, self).setUp() course = object() rsrc = object() self.type_str = resources_display.ResourceAssessment.TYPE self.key = '23' self.i18n_progress_dto = I18nProgressDTO(None, {}) self.resource_row = ResourceRow( course, rsrc, self.type_str, self.key, i18n_progress_dto=self.i18n_progress_dto) def test_class_name(self): self.i18n_progress_dto.is_translatable = True self.assertEquals('', self.resource_row.class_name) self.i18n_progress_dto.is_translatable = False self.assertEquals('not-translatable', self.resource_row.class_name) def test_resource_key(self): key = self.resource_row.resource_key self.assertEquals(self.type_str, key.type) self.assertEquals(self.key, key.key) def test_is_translatable(self): self.i18n_progress_dto.is_translatable = True self.assertTrue(self.resource_row.is_translatable) self.i18n_progress_dto.is_translatable = False self.assertFalse(self.resource_row.is_translatable) def test_status(self): self.i18n_progress_dto.set_progress('fr', I18nProgressDTO.NOT_STARTED) self.i18n_progress_dto.set_progress('el', I18nProgressDTO.IN_PROGRESS) self.i18n_progress_dto.set_progress('ru', I18nProgressDTO.DONE) self.assertEquals('Not started', self.resource_row.status('fr')) self.assertEquals('In progress', self.resource_row.status('el')) self.assertEquals('Done', self.resource_row.status('ru')) def test_status_class(self): self.i18n_progress_dto.set_progress('fr', I18nProgressDTO.NOT_STARTED) self.i18n_progress_dto.set_progress('el', I18nProgressDTO.IN_PROGRESS) self.i18n_progress_dto.set_progress('ru', I18nProgressDTO.DONE) self.assertEquals('not-started', self.resource_row.status_class('fr')) self.assertEquals('in-progress', self.resource_row.status_class('el')) self.assertEquals('done', self.resource_row.status_class('ru')) def test_edit_url(self): self.assertEquals( 'dashboard?action=i18_console&key=assessment%3A23%3Ael', self.resource_row.edit_url('el')) class IsTranslatableRestHandlerTests(actions.TestBase): ADMIN_EMAIL = 'admin@foo.com' COURSE_NAME = 'i18n_course' URL = 'rest/modules/i18n_dashboard/is_translatable' def setUp(self): super(IsTranslatableRestHandlerTests, self).setUp() self.base = '/' + self.COURSE_NAME context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'I18N Course') self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME) self.course = courses.Course(None, context) def tearDown(self): del sites.Registry.test_overrides[sites.GCB_COURSES_CONFIG.name] namespace_manager.set_namespace(self.old_namespace) super(IsTranslatableRestHandlerTests, self).tearDown() def _post_response(self, request_dict): return transforms.loads(self.post( self.URL, {'request': transforms.dumps(request_dict)}).body) def _get_request(self, payload_dict): xsrf_token = crypto.XsrfTokenManager.create_xsrf_token( 'is-translatable') return { 'xsrf_token': xsrf_token, 'payload': payload_dict } def test_require_xsrf_token(self): response = self._post_response({'xsrf_token': 'BAD TOKEN'}) self.assertEquals(403, response['status']) def test_require_course_admin(self): response = self._post_response(self._get_request({})) self.assertEquals(401, response['status']) actions.login(self.ADMIN_EMAIL, is_admin=True) response = self._post_response(self._get_request( {'resource_key': 'assessment:23', 'value': True})) self.assertEquals(200, response['status']) def test_set_data(self): resource_key_str = 'assessment:23' actions.login(self.ADMIN_EMAIL, is_admin=True) self.assertIsNone(I18nProgressDAO.load(resource_key_str)) response = self._post_response(self._get_request( {'resource_key': 'assessment:23', 'value': True})) self.assertEquals(200, response['status']) dto = I18nProgressDAO.load(resource_key_str) self.assertTrue(dto.is_translatable) response = self._post_response(self._get_request( {'resource_key': 'assessment:23', 'value': False})) self.assertEquals(200, response['status']) dto = I18nProgressDAO.load(resource_key_str) self.assertFalse(dto.is_translatable) class I18nDashboardHandlerTests(actions.TestBase): ADMIN_EMAIL = 'admin@foo.com' COURSE_NAME = 'i18n_course' URL = 'dashboard?action=i18n_dashboard' def setUp(self): super(I18nDashboardHandlerTests, self).setUp() self.base = '/' + self.COURSE_NAME context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'I18N Course') self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME) self.course = courses.Course(None, context) self.unit = self.course.add_unit() self.unit.title = 'Test Unit' self.assessment = self.course.add_assessment() self.assessment.title = 'Post Assessment' self.unit.post_assessment = self.assessment.unit_id self.lesson = self.course.add_lesson(self.unit) self.lesson.title = 'Test Lesson' self.course.save() actions.login(self.ADMIN_EMAIL, is_admin=True) def tearDown(self): del sites.Registry.test_overrides[sites.GCB_COURSES_CONFIG.name] namespace_manager.set_namespace(self.old_namespace) super(I18nDashboardHandlerTests, self).tearDown() def test_page_data(self): response = self.get(self.URL) dom = self.parse_html_string(response.body) table = dom.find('.//table[@class="i18n-progress-table"]') rows = table.findall('./tbody/tr') expected_row_data = [ '', 'Course Settings', 'Assessments', 'Course', 'Data Pump', 'Homepage', 'I18N', 'Invitation', 'Registration', 'Units and Lessons', '', 'Course Outline', 'Unit 1 - Test Unit', '1.1 Test Lesson', 'Post Assessment', '', 'Questions', 'Empty section', '', 'Question Groups', 'Empty section', '', 'Skills', 'Empty section', '', 'HTML Hooks', 'base.after_body_tag_begins', 'base.after_main_content_ends', 'base.after_navbar_begins', 'base.after_top_content_ends', 'base.before_body_tag_ends', 'base.before_head_tag_ends', 'base.before_navbar_ends', ] self.assertEquals(len(expected_row_data), len(rows)) for index, expected in enumerate(expected_row_data): td_text = (''.join(rows[index].find('td').itertext())).strip() self.assertEquals(expected, td_text) def test_multiple_locales(self): extra_env = { 'extra_locales': [ {'locale': 'el', 'availability': 'unavailable'}, {'locale': 'ru', 'availability': 'unavailable'}, ]} with actions.OverriddenEnvironment(extra_env): dom = self.parse_html_string(self.get(self.URL).body) table = dom.find('.//table[@class="i18n-progress-table"]') columns = table.findall('./thead/tr/th') expected_col_data = [ 'Asset', 'en_US (Base locale)', 'el', 'ru', ] self.assertEquals(len(expected_col_data), len(columns)) for index, expected in enumerate(expected_col_data): self.assertEquals(expected, columns[index].text) def test_is_translatable(self): dom = self.parse_html_string(self.get(self.URL).body) table = dom.find('.//table[@class="i18n-progress-table"]') rows = table.findall('./tbody/tr[@class="not-translatable"]') self.assertEquals(0, len(rows)) dto_key = resource.Key(resources_display.ResourceLesson.TYPE, self.lesson.lesson_id) dto = I18nProgressDTO(str(dto_key), {}) dto.is_translatable = False I18nProgressDAO.save(dto) dom = self.parse_html_string(self.get(self.URL).body) table = dom.find('.//table[@class="i18n-progress-table"]') rows = table.findall('./tbody/tr[@class="not-translatable"]') self.assertEquals(1, len(rows)) def test_progress(self): def assert_progress(class_name, row, index): td = row.findall('td')[index] self.assertIn(class_name, td.get('class').split()) lesson_row_index = 13 extra_env = { 'extra_locales': [ {'locale': 'el', 'availability': 'unavailable'}, {'locale': 'ru', 'availability': 'unavailable'}, ]} with actions.OverriddenEnvironment(extra_env): dom = self.parse_html_string(self.get(self.URL).body) table = dom.find('.//table[@class="i18n-progress-table"]') lesson_row = table.findall('./tbody/tr')[lesson_row_index] lesson_title = ''.join(lesson_row.find('td[1]').itertext()).strip() self.assertEquals('1.1 Test Lesson', lesson_title) assert_progress('not-started', lesson_row, 2) assert_progress('not-started', lesson_row, 3) dto_key = resource.Key( resources_display.ResourceLesson.TYPE, self.lesson.lesson_id) dto = I18nProgressDTO(str(dto_key), {}) dto.set_progress('el', I18nProgressDTO.DONE) dto.set_progress('ru', I18nProgressDTO.IN_PROGRESS) I18nProgressDAO.save(dto) dom = self.parse_html_string(self.get(self.URL).body) table = dom.find('.//table[@class="i18n-progress-table"]') lesson_row = table.findall('./tbody/tr')[lesson_row_index] assert_progress('done', lesson_row, 2) assert_progress('in-progress', lesson_row, 3) class TranslationConsoleRestHandlerTests(actions.TestBase): ADMIN_EMAIL = 'admin@foo.com' COURSE_NAME = 'i18n_course' URL = 'rest/modules/i18n_dashboard/translation_console' def setUp(self): super(TranslationConsoleRestHandlerTests, self).setUp() self.base = '/' + self.COURSE_NAME context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'I18N Course') self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME) self.course = courses.Course(None, context) self.unit = self.course.add_unit() self.unit.title = 'Test Unit' self.unit.unit_header = '<p>a</p><p>b</p>' self.course.save() actions.login(self.ADMIN_EMAIL, is_admin=True) def tearDown(self): del sites.Registry.test_overrides[sites.GCB_COURSES_CONFIG.name] namespace_manager.set_namespace(self.old_namespace) super(TranslationConsoleRestHandlerTests, self).tearDown() def _get_by_key(self, key): return transforms.loads( self.get('%s?key=%s' % (self.URL, str(key))).body) def _assert_section_values( self, section, name, type_str, data_size, source_value): self.assertEquals(name, section['name']) self.assertEquals(type_str, section['type']) self.assertEquals(data_size, len(section['data'])) self.assertEquals(source_value, section['source_value']) def test_get_requires_admin_role(self): actions.logout() key = ResourceBundleKey( resources_display.ResourceUnit.TYPE, self.unit.unit_id, 'el') response = self._get_by_key(key) self.assertEquals(401, response['status']) def test_get_unit_content_with_no_existing_values(self): key = ResourceBundleKey( resources_display.ResourceUnit.TYPE, self.unit.unit_id, 'el') response = self._get_by_key(key) self.assertEquals(200, response['status']) payload = transforms.loads(response['payload']) self.assertEquals('en_US', payload['source_locale']) self.assertEquals('el', payload['target_locale']) sections = payload['sections'] self.assertEquals( ['title', 'unit_header'], [s['name'] for s in sections]) self.assertEquals( ['Title', 'Unit Header'], [s['label'] for s in sections]) expected_values = [ ('title', 'string', 1, ''), ('unit_header', 'html', 2, '<p>a</p><p>b</p>')] for i, (name, type_str, data_size, source_value) in enumerate( expected_values): self._assert_section_values( sections[i], name, type_str, data_size, source_value) # confirm all the data is new for section in sections: for data in section['data']: self.assertEquals(VERB_NEW, data['verb']) header_data = sections[1]['data'] for item in header_data: self.assertIsNone(item['old_source_value']) self.assertEquals('', item['target_value']) self.assertFalse(item['changed']) self.assertEquals('a', header_data[0]['source_value']) self.assertEquals('b', header_data[1]['source_value']) def test_get_unit_content_with_existing_values(self): key = ResourceBundleKey( resources_display.ResourceUnit.TYPE, self.unit.unit_id, 'el') resource_bundle_dict = { 'title': { 'type': 'string', 'source_value': '', 'data': [ {'source_value': 'Test Unit', 'target_value': 'TEST UNIT'}] }, 'unit_header': { 'type': 'html', 'source_value': '<p>a</p><p>b</p>', 'data': [ {'source_value': 'a', 'target_value': 'A'}] } } dto = ResourceBundleDTO(str(key), resource_bundle_dict) ResourceBundleDAO.save(dto) response = self._get_by_key(key) self.assertEquals(200, response['status']) sections = transforms.loads(response['payload'])['sections'] self.assertEquals(2, len(sections)) # Confirm there is a translation for the title title_section = sections[0] self.assertEquals('title', title_section['name']) self.assertEquals('Title', title_section['label']) self.assertEquals(1, len(title_section['data'])) self.assertEquals(VERB_CURRENT, title_section['data'][0]['verb']) self.assertEquals('TEST UNIT', title_section['data'][0]['target_value']) # Confirm there is a translation for one of the two paragraphs header_section = sections[1] self.assertEquals('unit_header', header_section['name']) self.assertEquals('Unit Header', header_section['label']) self.assertEquals(2, len(header_section['data'])) self.assertEquals(VERB_CURRENT, header_section['data'][0]['verb']) self.assertEquals('a', header_section['data'][0]['source_value']) self.assertEquals('a', header_section['data'][0]['old_source_value']) self.assertEquals('A', header_section['data'][0]['target_value']) self.assertEquals(VERB_NEW, header_section['data'][1]['verb']) def test_get_unit_content_with_changed_values(self): key = ResourceBundleKey( resources_display.ResourceUnit.TYPE, self.unit.unit_id, 'el') resource_bundle_dict = { 'title': { 'type': 'string', 'source_value': '', 'data': [ { 'source_value': 'Old Test Unit', 'target_value': 'OLD TEST UNIT'}] }, 'unit_header': { 'type': 'html', 'source_value': '<p>a</p><p>b</p>', 'data': [ {'source_value': 'aa', 'target_value': 'AA'}] } } dto = ResourceBundleDTO(str(key), resource_bundle_dict) ResourceBundleDAO.save(dto) response = self._get_by_key(key) self.assertEquals(200, response['status']) sections = transforms.loads(response['payload'])['sections'] self.assertEquals(2, len(sections)) # Confirm there is a translation for the title title_section = sections[0] self.assertEquals('title', title_section['name']) self.assertEquals('Title', title_section['label']) self.assertEquals(1, len(title_section['data'])) self.assertEquals(VERB_CHANGED, title_section['data'][0]['verb']) self.assertEquals( 'OLD TEST UNIT', title_section['data'][0]['target_value']) # Confirm there is a translation for one of the two paragraphs header_section = sections[1] self.assertEquals('unit_header', header_section['name']) self.assertEquals('Unit Header', header_section['label']) self.assertEquals(2, len(header_section['data'])) self.assertEquals(VERB_CHANGED, header_section['data'][0]['verb']) self.assertEquals('a', header_section['data'][0]['source_value']) self.assertEquals('aa', header_section['data'][0]['old_source_value']) self.assertEquals('AA', header_section['data'][0]['target_value']) self.assertEquals(VERB_NEW, header_section['data'][1]['verb']) def test_core_tags_handle_none_handler(self): for _, tag_cls in tags.Registry.get_all_tags().items(): self.assertTrue(tag_cls().get_schema(None)) def test_get_unit_content_with_custom_tag(self): unit = self.course.add_unit() unit.title = 'Test Unit with Tag' unit.unit_header = ( 'text' '<gcb-youtube videoid="Kdg2drcUjYI" instanceid="c4CLTDvttJEu">' '</gcb-youtube>') self.course.save() key = ResourceBundleKey( resources_display.ResourceUnit.TYPE, unit.unit_id, 'el') response = self._get_by_key(key) payload = transforms.loads(response['payload']) data = payload['sections'][1]['data'] self.assertEquals(1, len(data)) self.assertEquals( 'text<gcb-youtube#1 videoid="Kdg2drcUjYI" />', data[0]['source_value']) def test_get_unit_content_with_custom_tag_with_body(self): unit = self.course.add_unit() unit.title = 'Test Unit with Tag' unit.unit_header = '<gcb-markdown>*hello*</gcb-markdown>' self.course.save() key = ResourceBundleKey( resources_display.ResourceUnit.TYPE, unit.unit_id, 'el') response = self._get_by_key(key) payload = transforms.loads(response['payload']) data = payload['sections'][1]['data'] self.assertEquals(1, len(data)) self.assertEquals( '<gcb-markdown#1>*hello*</gcb-markdown#1>', data[0]['source_value']) def test_defaults_to_known_translations(self): unit = self.course.add_unit() # Make the unit title be a string which is part of CB's i18n data unit.title = 'Registration' self.course.save() key = ResourceBundleKey( resources_display.ResourceUnit.TYPE, unit.unit_id, 'el') response = self._get_by_key(key) payload = transforms.loads(response['payload']) data = payload['sections'][0]['data'] self.assertEqual(VERB_CHANGED, data[0]['verb']) self.assertEqual(u'Εγγραφή', data[0]['target_value']) class TranslationConsoleValidationTests(actions.TestBase): ADMIN_EMAIL = 'admin@foo.com' COURSE_NAME = 'i18n_course' URL = 'rest/modules/i18n_dashboard/translation_console' INVALID = LazyTranslator.INVALID_TRANSLATION VALID = LazyTranslator.VALID_TRANSLATION def setUp(self): super(TranslationConsoleValidationTests, self).setUp() self.base = '/' + self.COURSE_NAME context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'I18N Course') self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME) self.course = courses.Course(None, context) self.unit = self.course.add_unit() self.unit.title = 'Test Unit' self.unit.unit_header = '<p>a</p><p>b</p>' self.course.save() actions.login(self.ADMIN_EMAIL, is_admin=True) self.key = ResourceBundleKey( resources_display.ResourceUnit.TYPE, self.unit.unit_id, 'el') self.validation_payload = { 'key': str(self.key), 'title': 'Unit 1 - Test Unit', 'source_locale': 'en_US', 'target_locale': 'el', 'sections': [ { 'name': 'title', 'label': 'Title', 'type': 'string', 'source_value': '', 'data': [ { 'source_value': 'Test Unit', 'target_value': 'TEST UNIT', 'verb': 1, # verb NEW 'old_source_value': '', 'changed': True } ] }, { 'name': 'unit_header', 'label': 'Unit Header', 'type': 'html', 'source_value': '<p>a</p><p>b</p>', 'data': [ { 'source_value': 'a', 'target_value': 'A', 'verb': 1, # verb NEW 'old_source_value': 'a', 'changed': True }, { 'source_value': 'b', 'target_value': 'B', 'verb': 1, # verb NEW 'old_source_value': 'b', 'changed': True }, ] }, ]} self.resource_bundle_dict = { 'title': { 'type': 'string', 'source_value': '', 'data': [ {'source_value': 'Test Unit', 'target_value': 'TEST UNIT'}] }, 'unit_header': { 'type': 'html', 'source_value': '<p>a</p><p>b</p>', 'data': [ {'source_value': 'a', 'target_value': 'A'}, {'source_value': 'a', 'target_value': 'B'}] } } def tearDown(self): del sites.Registry.test_overrides[sites.GCB_COURSES_CONFIG.name] namespace_manager.set_namespace(self.old_namespace) super(TranslationConsoleValidationTests, self).tearDown() def _validate(self): request_dict = { 'key': str(self.key), 'xsrf_token': crypto.XsrfTokenManager.create_xsrf_token( 'translation-console'), 'payload': transforms.dumps(self.validation_payload), 'validate': True} response = self.put( self.URL, {'request': transforms.dumps(request_dict)}) response = transforms.loads(response.body) self.assertEquals(200, response['status']) payload = transforms.loads(response['payload']) expected_keys = { section['name'] for section in self.validation_payload['sections']} self.assertEquals(expected_keys, set(payload.keys())) return payload def test_valid_content(self): payload = self._validate() self.assertEquals(self.VALID, payload['title']['status']) self.assertEquals('', payload['title']['errm']) self.assertEquals(self.VALID, payload['unit_header']['status']) self.assertEquals('', payload['unit_header']['errm']) def test_invalid_content(self): self.validation_payload[ 'sections'][1]['data'][0]['target_value'] = '<img#1/>' payload = self._validate() self.assertEquals(self.VALID, payload['title']['status']) self.assertEquals('', payload['title']['errm']) self.assertEquals(self.INVALID, payload['unit_header']['status']) self.assertEquals( 'Error in chunk 1. Unexpected tag: <img#1>.', payload['unit_header']['errm']) def test_with_bundle(self): dto = ResourceBundleDTO(str(self.key), self.resource_bundle_dict) ResourceBundleDAO.save(dto) payload = self._validate() self.assertEquals(self.VALID, payload['title']['status']) self.assertEquals('', payload['title']['errm']) self.assertEquals(self.VALID, payload['unit_header']['status']) self.assertEquals('', payload['unit_header']['errm']) def test_with_bundle_with_extra_fields(self): self.resource_bundle_dict['description'] = { 'type': 'string', 'source_value': '', 'data': [ {'source_value': 'descr', 'target_value': 'DESCR'}] } dto = ResourceBundleDTO(str(self.key), self.resource_bundle_dict) ResourceBundleDAO.save(dto) payload = self._validate() self.assertEquals(self.VALID, payload['title']['status']) self.assertEquals('', payload['title']['errm']) self.assertEquals(self.VALID, payload['unit_header']['status']) self.assertEquals('', payload['unit_header']['errm']) def test_untranslated_section(self): # Add a section to the unit which has no translation in the bundle self.unit.unit_footer = 'footer' self.course.save() self.validation_payload['sections'].append( { 'name': 'unit_footer', 'label': 'Unit Footer', 'type': 'html', 'source_value': 'footer', 'data': [ { 'source_value': 'footer', 'target_value': '', 'verb': 1, # verb NEW 'old_source_value': None, 'changed': False } ] }) payload = self._validate() footer_data = payload['unit_footer'] self.assertEqual( LazyTranslator.NOT_STARTED_TRANSLATION, footer_data['status']) self.assertEqual('No translation saved yet', footer_data['errm']) class I18nProgressDeferredUpdaterTests(actions.TestBase): ADMIN_EMAIL = 'admin@foo.com' COURSE_NAME = 'i18n_course' COURSE_TITLE = 'I18N Course' def setUp(self): super(I18nProgressDeferredUpdaterTests, self).setUp() self.base = '/' + self.COURSE_NAME self.app_context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, self.COURSE_TITLE) self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME) self.course = courses.Course(None, self.app_context) self.unit = self.course.add_unit() self.unit.title = 'Test Unit' self.unit.unit_header = '<p>a</p><p>b</p>' self.unit.now_available = True self.lesson = self.course.add_lesson(self.unit) self.lesson.title = 'Test Lesson' self.lesson.objectives = '<p>c</p><p>d</p>' self.lesson.now_available = True self.course.save() courses.Course.ENVIRON_TEST_OVERRIDES = { 'extra_locales': [ {'locale': 'el', 'availability': 'available'}, {'locale': 'ru', 'availability': 'available'}] } actions.login(self.ADMIN_EMAIL) def tearDown(self): del sites.Registry.test_overrides[sites.GCB_COURSES_CONFIG.name] namespace_manager.set_namespace(self.old_namespace) courses.Course.ENVIRON_TEST_OVERRIDES = {} super(I18nProgressDeferredUpdaterTests, self).tearDown() def _put_payload(self, url, xsrf_name, key, payload): request_dict = { 'key': key, 'xsrf_token': ( crypto.XsrfTokenManager.create_xsrf_token(xsrf_name)), 'payload': transforms.dumps(payload) } response = transforms.loads(self.put( url, {'request': transforms.dumps(request_dict)}).body) self.assertEquals(200, response['status']) self.assertEquals('Saved.', response['message']) return response def _assert_progress(self, key, el_progress=None, ru_progress=None): progress_dto = I18nProgressDAO.load(str(key)) self.assertIsNotNone(progress_dto) self.assertEquals(el_progress, progress_dto.get_progress('el')) self.assertEquals(ru_progress, progress_dto.get_progress('ru')) def test_on_lesson_changed(self): unit = self.course.add_unit() unit.title = 'Test Unit' lesson = self.course.add_lesson(unit) lesson.title = 'Test Lesson' lesson.objectives = '<p>a</p><p>b</p>' lesson.now_available = True self.course.save() lesson_bundle = { 'title': { 'type': 'string', 'source_value': '', 'data': [ { 'source_value': 'Test Lesson', 'target_value': 'TEST LESSON'}] }, 'objectives': { 'type': 'html', 'source_value': '<p>a</p><p>b</p>', 'data': [ {'source_value': 'a', 'target_value': 'A'}, {'source_value': 'b', 'target_value': 'B'}] } } lesson_key = resource.Key( resources_display.ResourceLesson.TYPE, lesson.lesson_id) lesson_key_el = ResourceBundleKey.from_resource_key(lesson_key, 'el') ResourceBundleDAO.save( ResourceBundleDTO(str(lesson_key_el), lesson_bundle)) progress_dto = I18nProgressDAO.load(str(lesson_key)) self.assertIsNone(progress_dto) edit_lesson_payload = { 'key': lesson.lesson_id, 'unit_id': unit.unit_id, 'title': 'Test Lesson', 'objectives': '<p>a</p><p>b</p>', 'auto_index': True, 'is_draft': True, 'video': '', 'scored': 'not_scored', 'notes': '', 'activity_title': '', 'activity_listed': True, 'activity': '', 'manual_progress': False, } self._put_payload( 'rest/course/lesson', 'lesson-edit', lesson.lesson_id, edit_lesson_payload) self.execute_all_deferred_tasks() self._assert_progress( lesson_key, el_progress=I18nProgressDTO.DONE, ru_progress=I18nProgressDTO.NOT_STARTED) edit_lesson_payload['title'] = 'New Title' self._put_payload( 'rest/course/lesson', 'lesson-edit', lesson.lesson_id, edit_lesson_payload) self.execute_all_deferred_tasks() self._assert_progress( lesson_key, el_progress=I18nProgressDTO.IN_PROGRESS, ru_progress=I18nProgressDTO.NOT_STARTED) def test_on_unit_changed(self): unit = self.course.add_unit() unit.title = 'Test Unit' self.course.save() unit_bundle = { 'title': { 'type': 'string', 'source_value': '', 'data': [ {'source_value': 'Test Unit', 'target_value': 'TEST UNIT'}] } } unit_key = resource.Key( resources_display.ResourceUnit.TYPE, unit.unit_id) unit_key_el = ResourceBundleKey.from_resource_key(unit_key, 'el') ResourceBundleDAO.save( ResourceBundleDTO(str(unit_key_el), unit_bundle)) progress_dto = I18nProgressDAO.load(str(unit_key)) self.assertIsNone(progress_dto) edit_unit_payload = { 'key': unit.unit_id, 'type': 'Unit', 'title': 'Test Unit', 'description': '', 'label_groups': [], 'is_draft': True, 'unit_header': '', 'pre_assessment': -1, 'post_assessment': -1, 'show_contents_on_one_page': False, 'manual_progress': False, 'unit_footer': '' } self._put_payload( 'rest/course/unit', 'put-unit', unit.unit_id, edit_unit_payload) self.execute_all_deferred_tasks() self._assert_progress( unit_key, el_progress=I18nProgressDTO.DONE, ru_progress=I18nProgressDTO.NOT_STARTED) edit_unit_payload['title'] = 'New Title' self._put_payload( 'rest/course/unit', 'put-unit', unit.unit_id, edit_unit_payload) self.execute_all_deferred_tasks() self._assert_progress( unit_key, el_progress=I18nProgressDTO.IN_PROGRESS, ru_progress=I18nProgressDTO.NOT_STARTED) def test_on_question_changed(self): qu_payload = { 'version': '1.5', 'question': 'What is a question?', 'description': 'Test Question', 'hint': '', 'defaultFeedback': '', 'rows': '1', 'columns': '100', 'graders': [{ 'score': '1.0', 'matcher': 'case_insensitive', 'response': 'yes', 'feedback': ''}] } response = self._put_payload( 'rest/question/sa', 'sa-question-edit', '', qu_payload) key = transforms.loads(response['payload'])['key'] qu_key = resource.Key(resources_display.ResourceSAQuestion.TYPE, key) qu_bundle = { 'question': { 'type': 'html', 'source_value': 'What is a question?', 'data': [{ 'source_value': 'What is a question?', 'target_value': 'WHAT IS A QUESTION?'}] }, 'description': { 'type': 'string', 'source_value': '', 'data': [{ 'source_value': 'Test Question', 'target_value': 'TEST QUESTION'}] }, 'graders:[0]:response': { 'type': 'string', 'source_value': '', 'data': [{ 'source_value': 'yes', 'target_value': 'YES'}] } } qu_key_el = ResourceBundleKey.from_resource_key(qu_key, 'el') ResourceBundleDAO.save( ResourceBundleDTO(str(qu_key_el), qu_bundle)) self.execute_all_deferred_tasks() self._assert_progress( qu_key, el_progress=I18nProgressDTO.DONE, ru_progress=I18nProgressDTO.NOT_STARTED) qu_payload['description'] = 'New Description' qu_payload['key'] = key response = self._put_payload( 'rest/question/sa', 'sa-question-edit', key, qu_payload) self.execute_all_deferred_tasks() self._assert_progress( qu_key, el_progress=I18nProgressDTO.IN_PROGRESS, ru_progress=I18nProgressDTO.NOT_STARTED) def test_on_question_group_changed(self): qgp_payload = { 'version': '1.5', 'description': 'Test Question Group', 'introduction': 'Test introduction', 'items': [] } response = self._put_payload( 'rest/question_group', 'question-group-edit', '', qgp_payload) key = transforms.loads(response['payload'])['key'] qgp_key = resource.Key( resources_display.ResourceQuestionGroup.TYPE, key) qgp_bundle = { 'description': { 'type': 'string', 'source_value': '', 'data': [{ 'source_value': 'Test Question Group', 'target_value': 'TEST QUESTION GROUP'}] }, 'introduction': { 'type': 'html', 'source_value': 'Test introduction', 'data': [{ 'source_value': 'Test introduction', 'target_value': 'TEST INTRODUCTION'}] } } qgp_key_el = ResourceBundleKey.from_resource_key(qgp_key, 'el') ResourceBundleDAO.save( ResourceBundleDTO(str(qgp_key_el), qgp_bundle)) self.execute_all_deferred_tasks() self._assert_progress( qgp_key, el_progress=I18nProgressDTO.DONE, ru_progress=I18nProgressDTO.NOT_STARTED) qgp_payload['description'] = 'New Description' qgp_payload['key'] = key response = self._put_payload( 'rest/question_group', 'question-group-edit', key, qgp_payload) self.execute_all_deferred_tasks() self._assert_progress( qgp_key, el_progress=I18nProgressDTO.IN_PROGRESS, ru_progress=I18nProgressDTO.NOT_STARTED) def test_on_course_settings_changed(self): homepage_payload = { 'homepage': { 'base:show_gplus_button': True, 'base:nav_header': 'Search Education', 'course:title': 'My New Course', 'course:blurb': 'Awesome course', 'course:instructor_details': '', 'course:main_video:url': '', 'course:main_image:url': '', 'course:main_image:alt_text': '', 'base:privacy_terms_url': 'Privacy Policy'} } homepage_bundle = { 'course:title': { 'type': 'string', 'source_value': '', 'data': [{ 'source_value': 'My New Course', 'target_value': 'MY NEW COURSE'}] }, 'course:blurb': { 'type': 'html', 'source_value': 'Awesome course', 'data': [{ 'source_value': 'Awesome course', 'target_value': 'AWESOME COURSE'}] }, 'base:nav_header': { 'type': 'string', 'source_value': '', 'data': [{ 'source_value': 'Search Education', 'target_value': 'SEARCH EDUCATION'}] }, 'base:privacy_terms_url': { 'type': 'string', 'source_value': '', 'data': [{ 'source_value': 'Privacy Policy', 'target_value': 'PRIVACY_POLICY'}] } } homepage_key = resource.Key( resources_display.ResourceCourseSettings.TYPE, 'homepage') homepage_key_el = ResourceBundleKey.from_resource_key( homepage_key, 'el') ResourceBundleDAO.save( ResourceBundleDTO(str(homepage_key_el), homepage_bundle)) self._put_payload( 'rest/course/settings', 'basic-course-settings-put', '/course.yaml', homepage_payload) self.execute_all_deferred_tasks() self._assert_progress( homepage_key, el_progress=I18nProgressDTO.DONE, ru_progress=I18nProgressDTO.NOT_STARTED) homepage_payload['homepage']['course:title'] = 'New Title' self._put_payload( 'rest/course/settings', 'basic-course-settings-put', '/course.yaml', homepage_payload) self.execute_all_deferred_tasks() self._assert_progress( homepage_key, el_progress=I18nProgressDTO.IN_PROGRESS, ru_progress=I18nProgressDTO.NOT_STARTED) class LazyTranslatorTests(actions.TestBase): ADMIN_EMAIL = 'admin@foo.com' COURSE_NAME = 'i18n_course' COURSE_TITLE = 'I18N Course' def setUp(self): super(LazyTranslatorTests, self).setUp() self.base = '/' + self.COURSE_NAME self.app_context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, self.COURSE_TITLE) def test_lazy_translator_is_json_serializable(self): source_value = 'hello' translation_dict = { 'type': 'string', 'data': [ {'source_value': 'hello', 'target_value': 'HELLO'}]} key = ResourceBundleKey( resources_display.ResourceLesson.TYPE, '23', 'el') lazy_translator = LazyTranslator( self.app_context, key, source_value, translation_dict) self.assertEquals( '{"lt": "HELLO"}', transforms.dumps({'lt': lazy_translator})) def test_lazy_translator_supports_addition(self): source_value = 'hello, ' translation_dict = { 'type': 'string', 'data': [ {'source_value': 'hello, ', 'target_value': 'HELLO, '}]} key = ResourceBundleKey( resources_display.ResourceLesson.TYPE, '23', 'el') lazy_translator = LazyTranslator( self.app_context, key, source_value, translation_dict) self.assertEquals('HELLO, world', lazy_translator + 'world') def test_lazy_translator_supports_interpolation(self): source_value = 'hello, %s' translation_dict = { 'type': 'string', 'data': [ {'source_value': 'hello, %s', 'target_value': 'HELLO, %s'}]} key = ResourceBundleKey( resources_display.ResourceLesson.TYPE, '23', 'el') lazy_translator = LazyTranslator( self.app_context, key, source_value, translation_dict) self.assertEquals('HELLO, world', lazy_translator % 'world') def test_lazy_translator_supports_upper_and_lower(self): source_value = 'Hello' translation_dict = { 'type': 'string', 'data': [ {'source_value': 'Hello', 'target_value': 'Bonjour'}]} key = ResourceBundleKey( resources_display.ResourceLesson.TYPE, '23', 'el') lazy_translator = LazyTranslator( self.app_context, key, source_value, translation_dict) self.assertEquals('BONJOUR', lazy_translator.upper()) self.assertEquals('bonjour', lazy_translator.lower()) def test_lazy_translator_records_status(self): source_value = 'hello' translation_dict = { 'type': 'html', 'source_value': 'hello', 'data': [ {'source_value': 'hello', 'target_value': 'HELLO'}]} key = ResourceBundleKey( resources_display.ResourceLesson.TYPE, '23', 'el') lazy_translator = LazyTranslator( self.app_context, key, source_value, translation_dict) self.assertEquals( LazyTranslator.NOT_STARTED_TRANSLATION, lazy_translator.status) str(lazy_translator) self.assertEquals( LazyTranslator.VALID_TRANSLATION, lazy_translator.status) # Monkey patch get_template_environ because the app_context is not # fully setn up def mock_get_template_environ(unused_locale, dirs): return self.app_context.fs.get_jinja_environ(dirs) self.app_context.get_template_environ = mock_get_template_environ lazy_translator = LazyTranslator( self.app_context, key, 'changed', translation_dict) str(lazy_translator) self.assertEquals( LazyTranslator.INVALID_TRANSLATION, lazy_translator.status) self.assertEquals( 'The content has changed and 1 part ' 'of the translation is out of date.', lazy_translator.errm) class CourseContentTranslationTests(actions.TestBase): ADMIN_EMAIL = 'admin@foo.com' COURSE_NAME = 'i18n_course' COURSE_TITLE = 'I18N Course' STUDENT_EMAIL = 'student@foo.com' def setUp(self): super(CourseContentTranslationTests, self).setUp() self.base = '/' + self.COURSE_NAME app_context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, self.COURSE_TITLE) self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME) self.course = courses.Course(None, app_context) self.unit = self.course.add_unit() self.unit.title = 'Test Unit' self.unit.unit_header = '<p>a</p><p>b</p>' self.unit.now_available = True self.lesson = self.course.add_lesson(self.unit) self.lesson.title = 'Test Lesson' self.lesson.objectives = '<p>c</p><p>d</p>' self.lesson.now_available = True self.course.save() self.unit_bundle = { 'title': { 'type': 'string', 'source_value': '', 'data': [ {'source_value': 'Test Unit', 'target_value': 'TEST UNIT'}] }, 'unit_header': { 'type': 'html', 'source_value': '<p>a</p><p>b</p>', 'data': [ {'source_value': 'a', 'target_value': 'A'}, {'source_value': 'b', 'target_value': 'B'}] } } self.lesson_bundle = { 'title': { 'type': 'string', 'source_value': '', 'data': [ { 'source_value': 'Test Lesson', 'target_value': 'TEST LESSON'}] }, 'objectives': { 'type': 'html', 'source_value': '<p>c</p><p>d</p>', 'data': [ {'source_value': 'c', 'target_value': 'C'}, {'source_value': 'd', 'target_value': 'D'}] } } self.unit_key_el = ResourceBundleKey( resources_display.ResourceUnit.TYPE, self.unit.unit_id, 'el') self.lesson_key_el = ResourceBundleKey( resources_display.ResourceLesson.TYPE, self.lesson.lesson_id, 'el') actions.login(self.ADMIN_EMAIL, is_admin=True) prefs = models.StudentPreferencesDAO.load_or_create() prefs.locale = 'el' models.StudentPreferencesDAO.save(prefs) def tearDown(self): del sites.Registry.test_overrides[sites.GCB_COURSES_CONFIG.name] namespace_manager.set_namespace(self.old_namespace) super(CourseContentTranslationTests, self).tearDown() def _store_resource_bundle(self): ResourceBundleDAO.save_all([ ResourceBundleDTO(str(self.unit_key_el), self.unit_bundle), ResourceBundleDTO(str(self.lesson_key_el), self.lesson_bundle)]) def test_lesson_and_unit_translated(self): self._store_resource_bundle() page_html = self.get('unit?unit=1').body self.assertIn('TEST UNIT', page_html) self.assertIn('<p>A</p><p>B</p>', page_html) self.assertIn('TEST LESSON', page_html) self.assertIn('<p>C</p><p>D</p>', page_html) def test_links_are_translated(self): link = self.course.add_link() link.title = 'Test Link' link.description = 'Test Description' link.href = 'http://www.foo.com' self.course.save() link_bundle = { 'title': { 'type': 'string', 'source_value': '', 'data': [ { 'source_value': 'Test Link', 'target_value': 'TEST LINK'}] }, 'description': { 'type': 'string', 'source_value': '', 'data': [ { 'source_value': 'Test description', 'target_value': 'TEST DESCRIPTION'}] }, 'url': { 'type': 'string', 'source_value': '', 'data': [ { 'source_value': 'http://www.foo.com', 'target_value': 'http://www.foo.gr'}] } } link_key = ResourceBundleKey( resources_display.ResourceLink.TYPE, link.unit_id, 'el') ResourceBundleDAO.save( ResourceBundleDTO(str(link_key), link_bundle)) page_html = self.get('course').body self.assertIn('TEST LINK', page_html) self.assertIn('TEST DESCRIPTION', page_html) self.assertIn('http://www.foo.gr', page_html) def test_assessments_are_translated(self): assessment = self.course.add_assessment() assessment.title = 'Test Assessment' assessment.html_content = '<p>a</p><p>b</p>' self.course.save() assessment_bundle = { 'assessment:title': { 'type': 'string', 'source_value': '', 'data': [ { 'source_value': 'Test Assessment', 'target_value': 'TEST ASSESSMENT'}] }, 'assessment:html_content': { 'type': 'html', 'source_value': '<p>a</p><p>b</p>', 'data': [ {'source_value': 'a', 'target_value': 'A'}, {'source_value': 'b', 'target_value': 'B'}] } } assessment_key = ResourceBundleKey( resources_display.ResourceAssessment.TYPE, assessment.unit_id, 'el') ResourceBundleDAO.save( ResourceBundleDTO(str(assessment_key), assessment_bundle)) page_html = self.get('assessment?name=%s' % assessment.unit_id).body self.assertIn('TEST ASSESSMENT', page_html) self.assertIn('<p>A</p><p>B</p>', page_html) def test_bad_translations_are_flagged_for_admin(self): self.unit_bundle['unit_header']['data'][1] = { 'source_value': 'b', 'target_value': '<b#1>b</b#1>'} self._store_resource_bundle() dom = self.parse_html_string(self.get('unit?unit=1').body) self.assertEquals( 'Error in chunk 2. Unexpected tag: <b#1>.', dom.find('.//div[@class="gcb-translation-error-body"]/p[1]').text) edit_link = dom.find( './/div[@class="gcb-translation-error-body"]/p[2]a') self.assertEquals('Edit the resource', edit_link.text) self.assertEquals( 'dashboard?action=i18_console&key=unit%%3A%s%%3Ael' % ( self.unit.unit_id), edit_link.attrib['href']) def test_bad_translations_are_not_flagged_for_student(self): self.unit_bundle['unit_header']['data'][1] = { 'source_value': 'b', 'target_value': '<b#1>b</b#1>'} self._store_resource_bundle() actions.logout() actions.login(self.STUDENT_EMAIL, is_admin=False) self.assertIn('<p>a</p><p>b</p>', self.get('unit?unit=1').body) def test_fallback_to_default_when_translation_missing(self): del self.lesson_bundle['objectives'] self._store_resource_bundle() page_html = self.get('unit?unit=1').body self.assertIn('TEST UNIT', page_html) self.assertIn('<p>A</p><p>B</p>', page_html) self.assertIn('TEST LESSON', page_html) self.assertNotIn('<p>C</p><p>D</p>', page_html) self.assertIn('<p>c</p><p>d</p>', page_html) def test_partial_translations(self): def update_lesson_objectives(objectives): self.lesson = self.course.find_lesson_by_id( self.unit.unit_id, self.lesson.lesson_id) self.lesson.objectives = objectives self.course.save() def assert_p_tags(dom, expected_content_list, expected_error_msg): # Ensure that the lesson body is a list of <p>..</p> tags with the # expected content. All should be inside an error warning div. p_tag_content_list = [ p_tag.text for p_tag in dom.findall( './/div[@class="gcb-lesson-content"]' '//div[@class="gcb-translation-error-alt"]/p')] self.assertEquals(expected_content_list, p_tag_content_list) error_msg = dom.find( './/div[@class="gcb-lesson-content"]' '//div[@class="gcb-translation-error-body"]/p[1]') self.assertIn('content has changed', error_msg.text) if expected_error_msg: self.assertIn(expected_error_msg, error_msg.text) self._store_resource_bundle() # Delete first para from lesson update_lesson_objectives('<p>d</p>') dom = self.parse_html_string(self.get('unit?unit=1').body) assert_p_tags( dom, ['C', 'D'], '1 part of the translation is out of date') # Delete second para from lesson update_lesson_objectives('<p>c</p>') dom = self.parse_html_string(self.get('unit?unit=1').body) assert_p_tags( dom, ['C', 'D'], '1 part of the translation is out of date') # Add para to lesson update_lesson_objectives('<p>c</p><p>d</p><p>e</p>') dom = self.parse_html_string(self.get('unit?unit=1').body) assert_p_tags( dom, ['C', 'D'], '1 part of the translation is out of date') # Change para in lesson update_lesson_objectives('<p>cc</p><p>d</p>') dom = self.parse_html_string(self.get('unit?unit=1').body) assert_p_tags( dom, ['C', 'D'], '1 part of the translation is out of date') # Change two paras update_lesson_objectives('<p>cc</p><p>dd</p>') dom = self.parse_html_string(self.get('unit?unit=1').body) assert_p_tags( dom, ['C', 'D'], '2 parts of the translation are out of date') # A student should see the partial translation but no error message actions.logout() actions.login(self.STUDENT_EMAIL, is_admin=False) prefs = models.StudentPreferencesDAO.load_or_create() prefs.locale = 'el' models.StudentPreferencesDAO.save(prefs) dom = self.parse_html_string(self.get('unit?unit=1').body) self.assertEquals( ['C', 'D'], [p_tag.text for p_tag in dom.findall( './/div[@class="gcb-lesson-content"]/p')]) self.assertIsNone(dom.find('.//div[@class="gcb-translation-error"]')) def test_custom_tag_expanded(self): source_video_id = 'Kdg2drcUjYI' target_video_id = 'jUfccP5Rl5M' unit_header = ( 'text' '<gcb-youtube videoid="%s" instanceid="c4CLTDvttJEu">' '</gcb-youtube>') % source_video_id unit = self.course.add_unit() unit.title = 'Tag Unit' unit.unit_header = unit_header self.course.save() unit_bundle = { 'title': { 'type': 'string', 'source_value': '', 'data': [ {'source_value': 'Tag Unit', 'target_value': 'TAG UNIT'}] }, 'unit_header': { 'type': 'html', 'source_value': unit_header, 'data': [ { 'source_value': ( 'text<gcb-youtube#1 videoid="%s" />' ) % source_video_id, 'target_value': ( 'TEXT<gcb-youtube#1 videoid="%s" />' ) % target_video_id}] } } unit_key_el = ResourceBundleKey( resources_display.ResourceUnit.TYPE, unit.unit_id, 'el') ResourceBundleDAO.save( ResourceBundleDTO(str(unit_key_el), unit_bundle)) page_html = self.get('unit?unit=%s' % unit.unit_id).body dom = self.parse_html_string(page_html) main = dom.find('.//div[@id="gcb-main-article"]/div[2]') self.assertEquals('TEXT', main.text.strip()) self.assertEquals('div', main[0].tag) self.assertEquals('gcb-video-container', main[0].attrib['class']) self.assertEquals(1, len(main[0])) self.assertEquals('iframe', main[0][0].tag) self.assertIn(target_video_id, main[0][0].attrib['src']) def test_custom_tag_with_body_is_translated(self): tag_string = ( '<gcb-markdown instanceid="c4CLTDvttJEu">' '*hello*' '</gcb-markdown>') unit = self.course.add_unit() unit.title = 'Tag Unit' unit.unit_header = tag_string self.course.save() unit_bundle = { 'unit_header': { 'type': 'html', 'source_value': tag_string, 'data': [ { 'source_value': ( '<gcb-markdown#1>*hello*</gcb-markdown#1>'), 'target_value': ( '<gcb-markdown#1>*HELLO*</gcb-markdown#1>')} ] } } unit_key_el = ResourceBundleKey( resources_display.ResourceUnit.TYPE, unit.unit_id, 'el') ResourceBundleDAO.save( ResourceBundleDTO(str(unit_key_el), unit_bundle)) page_html = self.get('unit?unit=%s' % unit.unit_id).body dom = self.parse_html_string(page_html) main = dom.find('.//div[@id="gcb-main-article"]/div[2]') markdown = main.find('.//div[@class="gcb-markdown"]/p') self.assertEquals('HELLO', markdown.find('./em').text) def _add_question(self): # Create a question qu_dict = { 'type': 0, 'question': 'question text', 'description': 'description text', 'choices': [ {'text': 'choice 1', 'score': 0.0, 'feedback': ''}, {'text': 'choice 2', 'score': 1.0, 'feedback': ''}], 'multiple_selections': False, 'last_modified': 1410451682.042784, 'version': '1.5' } qu_dto = models.QuestionDTO(None, qu_dict) qu_id = models.QuestionDAO.save(qu_dto) # Store translation data for the question qu_bundle = { 'question': { 'type': 'html', 'source_value': 'question text', 'data': [ { 'source_value': 'question text', 'target_value': 'QUESTION TEXT' }] }, 'description': { 'source_value': None, 'type': 'string', 'data': [ { 'source_value': 'description text', 'target_value': 'DESCRIPTION TEXT' }] }, 'choices:[0]:text': { 'type': 'html', 'source_value': 'choice 1', 'data': [ { 'source_value': 'choice 1', 'target_value': 'CHOICE 1' } ] }, 'choices:[1]:text': { 'source_value': 'choice 2', 'type': 'html', 'data': [ { 'source_value': 'choice 2', 'target_value': 'CHOICE 2' } ] }} key_el = ResourceBundleKey( resources_display.ResourceMCQuestion.TYPE, qu_id, 'el') ResourceBundleDAO.save( ResourceBundleDTO(str(key_el), qu_bundle)) return qu_id def test_questions_are_translated(self): # Create an assessment and add the question to the content assessment = self.course.add_assessment() assessment.title = 'Test Assessment' assessment.html_content = """ <question quid="%s" weight="1" instanceid="test_question"></question> """ % self._add_question() self.course.save() page_html = self.get('assessment?name=%s' % assessment.unit_id).body self.assertIn('QUESTION TEXT', page_html) self.assertIn('CHOICE 1', page_html) self.assertIn('CHOICE 2', page_html) def test_legacy_questions_with_null_body(self): # Create a question qu_dict = { 'type': 0, 'question': None, 'description': 'description text', 'choices': [ {'text': 'choice 1', 'score': 0.0, 'feedback': ''}, {'text': 'choice 2', 'score': 1.0, 'feedback': ''}], 'multiple_selections': False, 'last_modified': 1410451682.042784, 'version': '1.5' } qu_dto = models.QuestionDTO(None, qu_dict) qu_id = models.QuestionDAO.save(qu_dto) assessment = self.course.add_assessment() assessment.title = 'Test Assessment' assessment.html_content = """ <question quid="%s" weight="1" instanceid="test_question"></question> """ % qu_id self.course.save() # Store translation data for the question qu_bundle = { 'question': { 'type': 'html', 'source_value': 'None', 'data': [ { 'source_value': 'None', 'target_value': 'NONE' }] } } key_el = ResourceBundleKey( resources_display.ResourceMCQuestion.TYPE, qu_id, 'el') ResourceBundleDAO.save( ResourceBundleDTO(str(key_el), qu_bundle)) dom = self.parse_html_string( self.get('assessment?name=%s' % assessment.unit_id).body) self.assertIsNone(dom.find('.//div[@class="qt-question"]').text) def test_question_groups_are_translated(self): # Create a question group with one question qgp_dict = { 'description': 'description text', 'introduction': '<p>a</p><p>b</p>', 'items': [{'question': self._add_question(), 'weight': '1'}], 'last_modified': 1410451682.042784, 'version': '1.5' } qgp_dto = models.QuestionGroupDTO(None, qgp_dict) qgp_id = models.QuestionGroupDAO.save(qgp_dto) # Create an assessment and add the question group to the content assessment = self.course.add_assessment() assessment.title = 'Test Assessment' assessment.html_content = """ <question-group qgid="%s" instanceid="test-qgp"> </question-group><br> """ % qgp_id self.course.save() # Store translation data for the question qgp_bundle = { 'description': { 'source_value': None, 'type': 'string', 'data': [ { 'source_value': 'description text', 'target_value': 'DESCRIPTION TEXT' }] }, 'introduction': { 'type': 'html', 'source_value': '<p>a</p><p>b</p>', 'data': [ { 'source_value': 'a', 'target_value': 'A' }, { 'source_value': 'b', 'target_value': 'B' } ] }} key_el = ResourceBundleKey( resources_display.ResourceQuestionGroup.TYPE, qgp_id, 'el') ResourceBundleDAO.save( ResourceBundleDTO(str(key_el), qgp_bundle)) page_html = self.get('assessment?name=%s' % assessment.unit_id).body dom = self.parse_html_string(page_html) main = dom.find('.//div[@id="test-qgp"]') self.assertEquals( 'A', main.find('.//div[@class="qt-introduction"]/p[1]').text) self.assertEquals( 'B', main.find('.//div[@class="qt-introduction"]/p[2]').text) self.assertEquals( 'QUESTION TEXT', main.find('.//div[@class="qt-question"]').text) self.assertEquals( 'CHOICE 1', main.findall('.//div[@class="qt-choices"]//label')[0].text.strip()) self.assertEquals( 'CHOICE 2', main.findall('.//div[@class="qt-choices"]//label')[1].text.strip()) def test_course_settings_are_translated(self): course_bundle = { 'course:title': { 'source_value': None, 'type': 'string', 'data': [ { 'source_value': self.COURSE_TITLE, 'target_value': 'TRANSLATED TITLE' }] }} key_el = ResourceBundleKey( resources_display.ResourceCourseSettings.TYPE, 'homepage', 'el') ResourceBundleDAO.save( ResourceBundleDTO(str(key_el), course_bundle)) page_html = self.get('course').body dom = self.parse_html_string(page_html) self.assertEquals( 'TRANSLATED TITLE', dom.find('.//h1[@class="gcb-product-headers-large"]').text.strip()) def test_course_settings_load_with_default_locale(self): # NOTE: This is to test the protections against a vulnerability # to infinite recursion in the course settings translation. The issue # is that when no locale is set, then sites.get_current_locale needs # to refer to the course settings to find the default locale. However # if this call to get_current_locale takes place inside the translation # callback from loading the course settings, there will be infinite # recursion. This test checks that this case is defended. prefs = models.StudentPreferencesDAO.load_or_create() models.StudentPreferencesDAO.delete(prefs) page_html = self.get('course').body dom = self.parse_html_string(page_html) self.assertEquals( self.COURSE_TITLE, dom.find('.//h1[@class="gcb-product-headers-large"]').text.strip()) def test_invitations_are_translated(self): student_name = 'A. Student' sender_email = 'sender@foo.com' recipient_email = 'recipient@foo.com' translated_subject = 'EMAIL_FROM A. Student' # The invitation email email_env = { 'course': { 'invitation_email': { 'enabled': True, 'sender_email': sender_email, 'subject_template': 'Email from {{sender_name}}', 'body_template': 'From {{sender_name}}. Unsubscribe: {{unsubscribe_url}}'}}} # Translate the subject line of the email invitation_bundle = { 'course:invitation_email:subject_template': { 'type': 'string', 'source_value': None, 'data': [{ 'source_value': 'Email from {{sender_name}}', 'target_value': 'EMAIL_FROM {{sender_name}}'}]}} key_el = ResourceBundleKey( resources_display.ResourceCourseSettings.TYPE, 'invitation', 'el') ResourceBundleDAO.save( ResourceBundleDTO(str(key_el), invitation_bundle)) # Set up a spy to capture mails sent send_async_call_log = [] def send_async_spy(unused_cls, *args, **kwargs): send_async_call_log.append({'args': args, 'kwargs': kwargs}) # Patch the course env and the notifications sender courses.Course.ENVIRON_TEST_OVERRIDES = email_env old_send_async = notifications.Manager.send_async notifications.Manager.send_async = classmethod(send_async_spy) try: # register a student actions.login(self.STUDENT_EMAIL, is_admin=False) actions.register(self, student_name) # Set locale prefs prefs = models.StudentPreferencesDAO.load_or_create() prefs.locale = 'el' models.StudentPreferencesDAO.save(prefs) # Read the sample email displayed to the student self.assertIn( translated_subject, self.get('modules/invitation').body) # Post a request to the REST handler request_dict = { 'xsrf_token': ( crypto.XsrfTokenManager.create_xsrf_token('invitation')), 'payload': {'emailList': recipient_email} } response = transforms.loads(self.post( 'rest/modules/invitation', {'request': transforms.dumps(request_dict)}).body) self.assertEquals(200, response['status']) self.assertEquals('OK, 1 messages sent', response['message']) self.assertEquals( translated_subject, send_async_call_log[0]['args'][4]) finally: courses.Course.ENVIRON_TEST_OVERRIDES = [] notifications.Manager.send_async = old_send_async class TranslationImportExportTests(actions.TestBase): ADMIN_EMAIL = 'admin@foo.com' COURSE_NAME = 'i18n_course' COURSE_TITLE = 'I18N Course' STUDENT_EMAIL = 'student@foo.com' URL = 'dashboard?action=i18n_dashboard' def setUp(self): super(TranslationImportExportTests, self).setUp() self.base = '/' + self.COURSE_NAME app_context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, self.COURSE_TITLE) self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME) self.course = courses.Course(None, app_context) self.unit = self.course.add_unit() self.unit.title = 'Unit Title' self.unit.description = 'unit description' self.unit.unit_header = 'unit header' self.unit.unit_footer = 'unit footer' self.unit.now_available = True self.assessment = self.course.add_assessment() self.assessment.title = 'Assessment Title' self.assessment.description = 'assessment description' self.assessment.html_content = 'assessment html content' self.assessment.html_review_form = 'assessment html review form' self.assessment.now_available = True self.link = self.course.add_link() self.link.title = 'Link Title' self.link.description = 'link description' self.link.url = 'link url' self.lesson = self.course.add_lesson(self.unit) self.lesson.unit_id = self.unit.unit_id self.lesson.title = 'Lesson Title' self.lesson.objectives = 'lesson objectives' self.lesson.video_id = 'lesson video' self.lesson.notes = 'lesson notes' self.lesson.now_available = True self.course.save() foo_content = StringIO.StringIO('content of foo.jpg') fs = app_context.fs.impl fs.put(fs.physical_to_logical('/assets/img/foo.jpg'), foo_content) mc_qid = models.QuestionDAO.save(models.QuestionDTO( None, { 'question': 'mc question', 'description': 'mc description', 'type': 0, 'choices': [ {'score': 1.0, 'feedback': 'mc feedback one', 'text': 'mc answer one'}, {'score': 0.0, 'feedback': 'mc feedback two', 'text': 'mc answer two'} ], 'multiple_selections': False, 'version': '1.5', })) sa_qid = models.QuestionDAO.save(models.QuestionDTO( None, { 'question': 'sa question', 'description': 'sa description', 'type': 1, 'columns': 100, 'hint': 'sa hint', 'graders': [ {'score': '1.0', 'response': 'sa response', 'feedback': 'sa feedback', 'matcher': 'case_insensitive'} ], 'version': '1.5', 'defaultFeedback': 'sa default feedback', 'rows': 1})) models.QuestionGroupDAO.save(models.QuestionGroupDTO( None, {'items': [ {'weight': '1', 'question': mc_qid}, {'weight': '1', 'question': sa_qid}], 'version': '1.5', 'introduction': 'question group introduction', 'description': 'question group description'})) actions.login(self.ADMIN_EMAIL, is_admin=True) prefs = models.StudentPreferencesDAO.load_or_create() prefs.locale = 'el' models.StudentPreferencesDAO.save(prefs) def tearDown(self): namespace_manager.set_namespace(self.old_namespace) super(TranslationImportExportTests, self).tearDown() def _do_download(self, payload, method='put'): request = { 'xsrf_token': crypto.XsrfTokenManager.create_xsrf_token( i18n_dashboard.TranslationDownloadRestHandler.XSRF_TOKEN_NAME), 'payload': transforms.dumps(payload), } if method == 'put': fp = self.put else: fp = self.post response = fp( '/%s%s' % (self.COURSE_NAME, i18n_dashboard.TranslationDownloadRestHandler.URL), {'request': transforms.dumps(request)}) return response def _do_deletion(self, payload): request = { 'xsrf_token': crypto.XsrfTokenManager.create_xsrf_token( i18n_dashboard.TranslationDeletionRestHandler.XSRF_TOKEN_NAME), 'payload': transforms.dumps(payload), } response = self.put( '/%s%s' % (self.COURSE_NAME, i18n_dashboard.TranslationDeletionRestHandler.URL), params={'request': transforms.dumps(request)}) return response def _do_upload(self, contents): xsrf_token = crypto.XsrfTokenManager.create_xsrf_token( i18n_dashboard.TranslationUploadRestHandler.XSRF_TOKEN_NAME) response = self.post( '/%s%s' % (self.COURSE_NAME, i18n_dashboard.TranslationUploadRestHandler.URL), {'request': transforms.dumps({'xsrf_token': xsrf_token})}, upload_files=[('file', 'doesntmatter', contents)]) return response def test_deletion_ui_no_request(self): response = self.put( '/%s%s' % (self.COURSE_NAME, i18n_dashboard.TranslationDeletionRestHandler.URL), {}) rsp = transforms.loads(response.body) self.assertEquals(rsp['status'], 400) self.assertEquals( rsp['message'], 'Malformed or missing "request" parameter.') def test_deletion_ui_no_payload(self): response = self.put( '/%s%s' % (self.COURSE_NAME, i18n_dashboard.TranslationDeletionRestHandler.URL), {'request': transforms.dumps({'foo': 'bar'})}) rsp = transforms.loads(response.body) self.assertEquals(rsp['status'], 400) self.assertEquals( rsp['message'], 'Malformed or missing "payload" parameter.') def test_deletion_ui_no_xsrf(self): response = self.put( '/%s%s' % (self.COURSE_NAME, i18n_dashboard.TranslationDeletionRestHandler.URL), {'request': transforms.dumps({'payload': '{}'})}) rsp = transforms.loads(response.body) self.assertEquals(rsp['status'], 403) self.assertEquals( rsp['message'], 'Bad XSRF token. Please reload the page and try again') def test_deletion_ui_no_locales(self): rsp = transforms.loads(self._do_deletion({'locales': []}).body) self.assertEquals(rsp['status'], 400) self.assertEquals(rsp['message'], 'Please select at least one language to delete.') def test_deletion_ui_malformed_locales(self): actions.login('foo@bar.com', is_admin=False) rsp = transforms.loads(self._do_deletion( {'locales': [{'checked': True}]}).body) self.assertEquals(rsp['status'], 400) self.assertEquals('Locales specification not as expected.', rsp['message']) def test_deletion_ui_no_selected_locales(self): actions.login('foo@bar.com', is_admin=False) rsp = transforms.loads(self._do_deletion( {'locales': [{'locale': 'de'}]}).body) self.assertEquals(rsp['status'], 400) self.assertEquals('Please select at least one language to delete.', rsp['message']) def test_deletion_ui_no_permissions(self): actions.login('foo@bar.com', is_admin=False) rsp = transforms.loads(self._do_deletion( {'locales': [{'locale': 'de', 'checked': True}]}).body) self.assertEquals(401, rsp['status']) self.assertEquals('Access denied.', rsp['message']) def test_deletion(self): self.get('dashboard?action=i18n_reverse_case') # Verify that there are translation bundle rows for 'ln', # and progress items with settings for 'ln'. bundles = ResourceBundleDAO.get_all_for_locale('ln') self.assertGreater(len(bundles), 0) progress = I18nProgressDAO.get_all() self.assertGreater(len(progress), 0) for p in progress: self.assertEquals(I18nProgressDTO.DONE, p.get_progress('ln')) rsp = transforms.loads(self._do_deletion( {'locales': [{'locale': 'ln', 'checked': True}]}).body) self.assertEquals(200, rsp['status']) self.assertEquals('Success.', rsp['message']) # Verify that there are no translation bundle rows for 'ln', # and no progress items with settings for 'ln'. bundles = ResourceBundleDAO.get_all_for_locale('ln') self.assertEquals(len(bundles), 0) progress = I18nProgressDAO.get_all() self.assertGreater(len(progress), 0) for p in progress: self.assertEquals(I18nProgressDTO.NOT_STARTED, p.get_progress('ln')) def test_upload_ui_no_request(self): response = self.post( '/%s%s' % (self.COURSE_NAME, i18n_dashboard.TranslationUploadRestHandler.URL), {}) self.assertEquals( '<response><status>400</status><message>' 'Malformed or missing "request" parameter.</message></response>', response.body) def test_upload_ui_no_xsrf(self): response = self.post( '/%s%s' % (self.COURSE_NAME, i18n_dashboard.TranslationUploadRestHandler.URL), {'request': transforms.dumps({})}) self.assertEquals( '<response><status>403</status><message>' 'Missing or invalid XSRF token.</message></response>', response.body) def test_upload_ui_no_file(self): xsrf_token = crypto.XsrfTokenManager.create_xsrf_token( i18n_dashboard.TranslationUploadRestHandler.XSRF_TOKEN_NAME) response = self.post( '/%s%s' % (self.COURSE_NAME, i18n_dashboard.TranslationUploadRestHandler.URL), {'request': transforms.dumps({'xsrf_token': xsrf_token})}) self.assertEquals( '<response><status>400</status><message>' 'Must select a .zip or .po file to upload.</message></response>', response.body) def test_upload_ui_bad_file_param(self): xsrf_token = crypto.XsrfTokenManager.create_xsrf_token( i18n_dashboard.TranslationUploadRestHandler.XSRF_TOKEN_NAME) response = self.post( '/%s%s' % (self.COURSE_NAME, i18n_dashboard.TranslationUploadRestHandler.URL), { 'request': transforms.dumps({'xsrf_token': xsrf_token}), 'file': '' }) self.assertEquals( '<response><status>400</status><message>' 'Must select a .zip or .po file to upload</message></response>', response.body) def test_upload_ui_empty_file(self): response = self._do_upload('') self.assertEquals( '<response><status>400</status><message>' 'The .zip or .po file must not be empty.</message></response>', response.body) def test_upload_ui_bad_content(self): response = self._do_upload('23 skidoo') self.assertEquals( '<response><status>400</status><message>' 'No translations found in provided file.</message></response>', response.body) def test_upload_ui_no_permissions(self): actions.login('foo@bar.com', is_admin=False) response = self._do_upload( '# <span class="">1.1 Lesson Title</span>\n' '#: GCB-1|title|string|lesson:4:de:0\n' '#| msgid ""\n' 'msgid "Lesson Title"\n' 'msgstr "Lektion Titel"\n') self.assertEquals( '<response><status>401</status><message>' 'Access denied.</message></response>', response.body) def test_upload_ui_bad_protocol(self): actions.login('foo@bar.com', is_admin=False) response = self._do_upload( '# <span class="">1.1 Lesson Title</span>\n' '#: GCB-2|title|string|lesson:4:de:0\n' '#| msgid ""\n' 'msgid "Lesson Title"\n' 'msgstr "Lektion Titel"\n') self.assertEquals( '<response><status>400</status><message>' 'Expected location format GCB-1, but had GCB-2' '</message></response>', response.body) def test_upload_ui_multiple_languages(self): actions.login('foo@bar.com', is_admin=False) response = self._do_upload( '# <span class="">1.1 Lesson Title</span>\n' '#: GCB-1|title|string|lesson:4:de:0\n' '#: GCB-1|title|string|lesson:4:fr:0\n' '#| msgid ""\n' 'msgid "Lesson Title"\n' 'msgstr "Lektion Titel"\n') self.assertEquals( '<response><status>400</status><message>' 'File has translations for both "de" and "fr"' '</message></response>', response.body) def test_upload_ui_one_item(self): # Do export to force creation of progress, bundle entities self._do_download({'locales': [{'locale': 'de', 'checked': True}], 'export_what': 'all'}, method='post') # Upload one translation. response = self._do_upload( '# <span class="">1.1 Lesson Title</span>\n' '#: GCB-1|title|string|lesson:4:de:0\n' '#| msgid ""\n' 'msgid "Lesson Title"\n' 'msgstr "Lektion Titel"\n') self.assertIn( '<response><status>200</status><message>Success.</message>', response.body) self.assertIn('made 1 total replacements', response.body) # Verify uploaded translation makes it to lesson page when # viewed with appropriate language preference. prefs = models.StudentPreferencesDAO.load_or_create() prefs.locale = 'de' models.StudentPreferencesDAO.save(prefs) response = self.get( '/%s/unit?unit=%s&lesson=%s' % ( self.COURSE_NAME, self.unit.unit_id, self.lesson.lesson_id)) self.assertIn('Lektion Titel', response.body) def _parse_messages(self, response): dom = self.parse_html_string(response.body) payload = dom.find('.//payload') return transforms.loads(payload.text)['messages'] def test_upload_ui_no_bundles_created(self): # Upload one translation. response = self._do_upload( '# <span class="">1.1 Lesson Title</span>\n' '#: GCB-1|title|string|lesson:4:de:0\n' '#| msgid ""\n' 'msgid "Lesson Title"\n' 'msgstr "Lektion Titel"\n') messages = self._parse_messages(response) # Expect no messages other than the expected missing translations and # the summary line indicating that we did something. for message in messages: self.assertTrue( message.startswith('Did not find translation for') or message.startswith('For Deutsch (de), made 1 total replacem')) def test_upload_ui_with_bundles_created(self): # Do export to force creation of progress, bundle entities self._do_download({'locales': [{'locale': 'de', 'checked': True}], 'export_what': 'all'}, method='post') # Upload one translation. response = self._do_upload( '# <span class="">1.1 Lesson Title</span>\n' '#: GCB-1|title|string|lesson:4:de:0\n' '#| msgid ""\n' 'msgid "Lesson Title"\n' 'msgstr "Lektion Titel"\n') messages = self._parse_messages(response) # Expect no messages other than the expected missing translations and # the summary line indicating that we did something. for message in messages: self.assertTrue( message.startswith('Did not find translation for') or message.startswith('For Deutsch (de), made 1 total replacem')) def test_upload_ui_with_unexpected_resource(self): # Do export to force creation of progress, bundle entities self._do_download({'locales': [{'locale': 'de', 'checked': True}], 'export_what': 'all'}, method='post') # Upload one translation. response = self._do_upload( '# <span class="">1.1 Lesson Title</span>\n' '#: GCB-1|title|string|lesson:999:de:0\n' '#| msgid ""\n' 'msgid "Lesson Title"\n' 'msgstr "Lektion Titel"\n') messages = self._parse_messages(response) self.assertIn('Translation file had 1 items for resource ' '"lesson:999:de", but course had no such resource.', messages) def test_upload_ui_with_unexpected_translation(self): # Do export to force creation of progress, bundle entities self._do_download({'locales': [{'locale': 'de', 'checked': True}], 'export_what': 'all'}, method='post') # Upload one translation. response = self._do_upload( '# <span class="">1.1 Lesson Title</span>\n' '#: GCB-1|title|string|lesson:4:de:0\n' '#| msgid ""\n' 'msgid "FizzBuzz"\n' 'msgstr "Lektion Titel"\n') messages = self._parse_messages(response) self.assertIn('Translation for "FizzBuzz" present but not used.', messages) def test_upload_ui_with_missing_translation(self): # Do export to force creation of progress, bundle entities self._do_download({'locales': [{'locale': 'de', 'checked': True}], 'export_what': 'all'}, method='post') # Upload one translation. response = self._do_upload( '# <span class="">1.1 Lesson Title</span>\n' '#: GCB-1|title|string|lesson:4:de:0\n' '#| msgid ""\n' 'msgid "FizzBuzz"\n' 'msgstr "Lektion Titel"\n') messages = self._parse_messages(response) self.assertIn('Did not find translation for "Lesson Title"', messages) def test_upload_ui_with_blank_translation(self): # Do export to force creation of progress, bundle entities self._do_download({'locales': [{'locale': 'de', 'checked': True}], 'export_what': 'all'}, method='post') # Upload one translation. response = self._do_upload( '# <span class="">1.1 Lesson Title</span>\n' '#: GCB-1|title|string|lesson:4:de:0\n' '#| msgid ""\n' 'msgid "Lesson Title"\n' 'msgstr ""\n') messages = self._parse_messages(response) self.assertIn( 'For Deutsch (de), made 0 total replacements in 22 resources. ' '1 items in the uploaded file did not have translations.', messages) def test_download_ui_no_request(self): response = self.put( '/%s%s' % (self.COURSE_NAME, i18n_dashboard.TranslationDownloadRestHandler.URL), {}) rsp = transforms.loads(response.body) self.assertEquals(rsp['status'], 400) self.assertEquals( rsp['message'], 'Malformed or missing "request" parameter.') def test_download_ui_no_payload(self): response = self.put( '/%s%s' % (self.COURSE_NAME, i18n_dashboard.TranslationDownloadRestHandler.URL), {'request': transforms.dumps({'foo': 'bar'})}) rsp = transforms.loads(response.body) self.assertEquals(rsp['status'], 400) self.assertEquals( rsp['message'], 'Malformed or missing "payload" parameter.') def test_download_ui_no_xsrf(self): response = self.put( '/%s%s' % (self.COURSE_NAME, i18n_dashboard.TranslationDownloadRestHandler.URL), {'request': transforms.dumps({'payload': '{}'})}) rsp = transforms.loads(response.body) self.assertEquals(rsp['status'], 403) self.assertEquals( rsp['message'], 'Bad XSRF token. Please reload the page and try again') def test_download_ui_no_locales(self): rsp = transforms.loads(self._do_download({'locales': []}).body) self.assertEquals(rsp['status'], 400) self.assertEquals(rsp['message'], 'Please select at least one language to export.') def test_download_ui_malformed_locales(self): actions.login('foo@bar.com', is_admin=False) rsp = transforms.loads(self._do_download( {'locales': [{'checked': True}]}).body) self.assertEquals(rsp['status'], 400) self.assertEquals('Locales specification not as expected.', rsp['message']) def test_download_ui_no_selected_locales(self): actions.login('foo@bar.com', is_admin=False) rsp = transforms.loads(self._do_download( {'locales': [{'locale': 'de'}]}).body) self.assertEquals(rsp['status'], 400) self.assertEquals('Please select at least one language to export.', rsp['message']) def test_download_ui_no_permissions(self): actions.login('foo@bar.com', is_admin=False) rsp = transforms.loads(self._do_download( {'locales': [{'locale': 'de', 'checked': True}]}).body) self.assertEquals(401, rsp['status']) self.assertEquals('Access denied.', rsp['message']) def test_download_ui_file_name_default(self): extra_env = { 'extra_locales': [{'locale': 'de', 'availability': 'available'}] } with actions.OverriddenEnvironment(extra_env): rsp = self._do_download( {'locales': [{'locale': 'de', 'checked': True}]}, method='post') self.assertEquals('application/octet-stream', rsp.content_type) self.assertEquals('attachment; filename="i18n_course.zip"', rsp.content_disposition) def test_download_ui_file_name_set(self): extra_env = { 'extra_locales': [{'locale': 'de', 'availability': 'available'}] } with actions.OverriddenEnvironment(extra_env): rsp = self._do_download({ 'locales': [{'locale': 'de', 'checked': True}], 'file_name': 'xyzzy.zip', }, method='post') self.assertEquals('application/octet-stream', rsp.content_type) self.assertEquals('attachment; filename="xyzzy.zip"', rsp.content_disposition) def _translated_value_swapcase(self, key, section_name): get_response = self.get( '/%s%s?%s' % ( self.COURSE_NAME, i18n_dashboard.TranslationConsoleRestHandler.URL, urllib.urlencode({'key': str(key)}))) response = transforms.loads(get_response.body) payload = transforms.loads(response['payload']) s = next(s for s in payload['sections'] if s['name'] == section_name) s['data'][0]['changed'] = True s['data'][0]['target_value'] = s['data'][0]['source_value'].swapcase() response['payload'] = transforms.dumps(payload) response['key'] = payload['key'] response = self.put( '/%s%s' % (self.COURSE_NAME, i18n_dashboard.TranslationConsoleRestHandler.URL), {'request': transforms.dumps(response)}) def _make_current_and_stale_translation(self): # Provide translations for lesson title and assessment title. self._translated_value_swapcase( ResourceBundleKey(resources_display.ResourceLesson.TYPE, self.lesson.lesson_id, 'de'), 'title') self._translated_value_swapcase( ResourceBundleKey(resources_display.ResourceAssessment.TYPE, self.assessment.unit_id, 'de'), 'assessment:title') # Make assessment out-of-date by changing the assessment title # via the course interface. assessment = self.course.find_unit_by_id(self.assessment.unit_id) assessment.title = 'Edited Assessment Title' self.course.save() def _parse_zip_response(self, response): download_zf = zipfile.ZipFile(cStringIO.StringIO(response.body), 'r') out_stream = StringIO.StringIO() out_stream.fp = out_stream for item in download_zf.infolist(): file_data = download_zf.read(item) catalog = pofile.read_po(cStringIO.StringIO(file_data)) yield catalog def test_export_only_selected_languages(self): extra_env = { 'extra_locales': [ {'locale': 'de', 'availability': 'available'}, {'locale': 'fr', 'availability': 'available'}, {'locale': 'es', 'availability': 'available'}, ] } with actions.OverriddenEnvironment(extra_env): payload = { 'locales': [ {'locale': 'de', 'checked': True}, {'locale': 'fr', 'checked': True}, {'locale': 'es'}, ], 'export_what': 'all'} response = self._do_download(payload, method='post') zf = zipfile.ZipFile(cStringIO.StringIO(response.body), 'r') contents = [item.filename for item in zf.infolist()] self.assertIn('locale/de/LC_MESSAGES/messages.po', contents) self.assertIn('locale/fr/LC_MESSAGES/messages.po', contents) self.assertNotIn('locale/es/LC_MESSAGES/messages.po', contents) def _test_export(self, export_what, expect_lesson): def find_message(catalog, the_id): for message in catalog: if message.id == the_id: return message return None extra_env = { 'extra_locales': [{'locale': 'de', 'availability': 'available'}] } with actions.OverriddenEnvironment(extra_env): self._make_current_and_stale_translation() payload = { 'locales': [{'locale': 'de', 'checked': True}], 'export_what': export_what, } response = self._do_download(payload) rsp = transforms.loads(response.body) self.assertEquals(200, rsp['status']) self.assertEquals('Success.', rsp['message']) response = self._do_download(payload, method='post') for catalog in self._parse_zip_response(response): unit = find_message(catalog, 'Unit Title') self.assertEquals(1, len(unit.locations)) self.assertEquals('GCB-1|title|string|unit:1:de', unit.locations[0][0]) self.assertEquals('', unit.string) assessment = find_message(catalog, 'Edited Assessment Title') self.assertEquals(1, len(assessment.locations)) self.assertEquals( 'GCB-1|assessment:title|string|assessment:2:de', assessment.locations[0][0]) self.assertEquals('', assessment.string) lesson = find_message(catalog, 'Lesson Title') if expect_lesson: self.assertEquals(1, len(lesson.locations)) self.assertEquals('GCB-1|title|string|lesson:4:de', lesson.locations[0][0]) self.assertEquals('lESSON tITLE', lesson.string) self.assertEquals([], lesson.previous_id) else: self.assertIsNone(lesson) def test_export_only_new(self): self._test_export('new', False) def test_export_all(self): self._test_export('all', True) def test_added_items_appear_on_dashboard(self): """Ensure that all items added in setUp are present on dashboard. Do this so that we can trust in other tests that when we don't see something that we don't expect to see it's not because we failed to add the item, but instead it really is getting actively suppressed. """ response = self.get(self.URL) self.assertIn('Unit Title', response.body) self.assertIn('Assessment Title', response.body) self.assertIn('Link Title', response.body) self.assertIn('Lesson Title', response.body) self.assertIn('mc description', response.body) self.assertIn('sa description', response.body) self.assertIn('question group description', response.body) def test_download_exports_all_expected_fields(self): extra_env = { 'extra_locales': [{'locale': 'de', 'availability': 'available'}] } with actions.OverriddenEnvironment(extra_env): response = self._do_download( {'locales': [{'locale': 'de', 'checked': True}], 'export_what': 'all'}, method='post') for catalog in self._parse_zip_response(response): messages = [msg.id for msg in catalog] self.assertIn('Unit Title', messages) self.assertIn('unit description', messages) self.assertIn('unit header', messages) self.assertIn('unit footer', messages) self.assertIn('Assessment Title', messages) self.assertIn('assessment description', messages) self.assertIn('assessment html content', messages) self.assertIn('assessment html review form', messages) self.assertIn('Link Title', messages) self.assertIn('link description', messages) self.assertIn('Lesson Title', messages) self.assertIn('lesson objectives', messages) self.assertIn('lesson notes', messages) self.assertIn('mc question', messages) self.assertIn('mc description', messages) self.assertIn('mc feedback one', messages) self.assertIn('mc answer one', messages) self.assertIn('mc feedback two', messages) self.assertIn('mc answer two', messages) self.assertIn('sa question', messages) self.assertIn('sa description', messages) self.assertIn('sa hint', messages) self.assertIn('sa response', messages) self.assertIn('sa feedback', messages) self.assertIn('sa default feedback', messages) self.assertIn('question group introduction', messages) self.assertIn('question group description', messages) # Non-translatable items; will require manual attention from # someone who understands the course material. self.assertNotIn('link url', messages) self.assertNotIn('lesson video', messages) self.assertNotIn('foo.jpg', messages) def test_upload_translations(self): actions.update_course_config( self.COURSE_NAME, {'extra_locales': [{'locale': 'el', 'availability': 'available'}]}) # Download the course translations, and build a catalog containing # all the translations repeated. response = self._do_download( {'locales': [{'locale': 'el', 'checked': True}], 'export_what': 'all'}, method='post') download_zf = zipfile.ZipFile(cStringIO.StringIO(response.body), 'r') out_stream = StringIO.StringIO() out_stream.fp = out_stream upload_zf = zipfile.ZipFile(out_stream, 'w') num_translations = 0 for item in download_zf.infolist(): catalog = pofile.read_po(cStringIO.StringIO(download_zf.read(item))) for msg in catalog: if msg.locations: msg.string = msg.id.upper() * 2 content = cStringIO.StringIO() pofile.write_po(content, catalog) upload_zf.writestr(item.filename, content.getvalue()) content.close() upload_zf.close() # Upload the modified translations. upload_contents = out_stream.getvalue() xsrf_token = crypto.XsrfTokenManager.create_xsrf_token( TranslationUploadRestHandler.XSRF_TOKEN_NAME) self.post('/%s%s' % (self.COURSE_NAME, TranslationUploadRestHandler.URL), {'request': transforms.dumps({ 'xsrf_token': cgi.escape(xsrf_token), 'payload': transforms.dumps({'key', ''})})}, upload_files=[('file', 'doesntmatter', upload_contents)]) # Download the translations; verify the doubling. response = self._do_download( {'locales': [{'locale': 'el', 'checked': True}], 'export_what': 'all'}, method='post') for catalog in self._parse_zip_response(response): num_translations = 0 for msg in catalog: if msg.locations: # Skip header pseudo-message entry num_translations += 1 self.assertNotEquals(msg.id, msg.string) self.assertEquals(msg.id.upper() * 2, msg.string) self.assertEquals(31, num_translations) # And verify the presence of the translated versions on actual # course pages. response = self.get('unit?unit=%s' % self.unit.unit_id) self.assertIn(self.unit.title.upper() * 2, response.body) self.assertIn(self.lesson.title.upper() * 2, response.body) def test_reverse_case(self): response = self.get('dashboard?action=i18n_reverse_case') prefs = models.StudentPreferencesDAO.load_or_create() prefs.locale = 'ln' models.StudentPreferencesDAO.save(prefs) response = self.get('unit?unit=%s' % self.unit.unit_id) self.assertIn('uNIT tITLE', response.body) self.assertIn('lESSON tITLE', response.body) def _test_progress_calculation(self, sections, expected_status): key = i18n_dashboard.ResourceBundleKey.fromstring('assessment:1:de') i18n_progress_dto = i18n_dashboard.I18nProgressDAO.create_blank(key) for section in sections: section['name'] = 'fred' section['type'] = 'string' TranslationConsoleRestHandler.update_dtos_with_section_data( key, sections, None, i18n_progress_dto) self.assertEquals(expected_status, i18n_progress_dto.get_progress(key.locale)) def test_progress_no_sections_is_done(self): self._test_progress_calculation([], i18n_dashboard.I18nProgressDTO.DONE) def test_progress_one_section_current_and_not_changed_is_done(self): self._test_progress_calculation( [{'data': [{'verb': i18n_dashboard.VERB_CURRENT, 'changed': False, 'source_value': 'yes', 'target_value': 'ja'}]}], i18n_dashboard.I18nProgressDTO.DONE) def test_progress_one_section_current_and_changed_is_done(self): self._test_progress_calculation( [{'data': [{'verb': i18n_dashboard.VERB_CURRENT, 'changed': True, 'source_value': 'yes', 'target_value': 'yup'}]}], i18n_dashboard.I18nProgressDTO.DONE) def test_progress_one_section_stale_and_not_changed_is_in_progress(self): self._test_progress_calculation( [{'data': [{'verb': i18n_dashboard.VERB_CHANGED, 'changed': False, 'old_source_value': 'yse', 'source_value': 'yes', 'target_value': 'ja'}]}], i18n_dashboard.I18nProgressDTO.IN_PROGRESS) def test_progress_one_section_stale_but_changed_is_done(self): self._test_progress_calculation( [{'data': [{'verb': i18n_dashboard.VERB_CHANGED, 'changed': True, 'old_source_value': 'yse', 'source_value': 'yes', 'target_value': 'ja'}]}], i18n_dashboard.I18nProgressDTO.DONE) def test_progress_one_section_new_and_not_translated_is_not_started(self): self._test_progress_calculation( [{'data': [{'verb': i18n_dashboard.VERB_NEW, 'changed': False, 'source_value': 'yes', 'target_value': ''}]}], i18n_dashboard.I18nProgressDTO.NOT_STARTED) def test_progress_one_section_new_and_translated_is_done(self): self._test_progress_calculation( [{'data': [{'verb': i18n_dashboard.VERB_NEW, 'changed': False, 'source_value': 'yes', 'target_value': 'ja'}]}], i18n_dashboard.I18nProgressDTO.NOT_STARTED) def test_progress_one_section_current_but_changed_to_blank_unstarted(self): self._test_progress_calculation( [{'data': [{'verb': i18n_dashboard.VERB_CURRENT, 'changed': True, 'source_value': 'yes', 'target_value': ''}]}], i18n_dashboard.I18nProgressDTO.NOT_STARTED) def test_progress_one_section_changed_but_changed_to_blank_unstarted(self): self._test_progress_calculation( [{'data': [{'verb': i18n_dashboard.VERB_CHANGED, 'changed': True, 'source_value': 'yes', 'target_value': ''}]}], i18n_dashboard.I18nProgressDTO.NOT_STARTED) def test_progress_one_section_new_but_changed_to_blank_is_unstarted(self): self._test_progress_calculation( [{'data': [{'verb': i18n_dashboard.VERB_NEW, 'changed': True, 'source_value': 'yes', 'target_value': ''}]}], i18n_dashboard.I18nProgressDTO.NOT_STARTED) def test_progress_one_not_started_and_one_done_is_in_progress(self): self._test_progress_calculation( [{'data': [{'verb': i18n_dashboard.VERB_NEW, 'changed': False, 'source_value': 'yes', 'target_value': ''}, {'verb': i18n_dashboard.VERB_CURRENT, 'changed': False, 'source_value': 'yes', 'target_value': 'ja'}]}], i18n_dashboard.I18nProgressDTO.IN_PROGRESS) def test_progress_one_stale_and_one_done_is_in_progress(self): self._test_progress_calculation( [{'data': [{'verb': i18n_dashboard.VERB_CHANGED, 'changed': False, 'old_source_value': 'yse', 'source_value': 'yes', 'target_value': 'ja'}, {'verb': i18n_dashboard.VERB_CURRENT, 'changed': False, 'source_value': 'yes', 'target_value': 'ja'}]}], i18n_dashboard.I18nProgressDTO.IN_PROGRESS) def test_progress_one_stale_and_one_not_started_is_in_progress(self): self._test_progress_calculation( [{'data': [{'verb': i18n_dashboard.VERB_CHANGED, 'changed': False, 'old_source_value': 'yse', 'source_value': 'yes', 'target_value': 'ja'}, {'verb': i18n_dashboard.VERB_NEW, 'changed': False, 'source_value': 'yes', 'target_value': ''}]}], i18n_dashboard.I18nProgressDTO.IN_PROGRESS) class TranslatorRoleTests(actions.TestBase): ADMIN_EMAIL = 'admin@foo.com' USER_EMAIL = 'user@foo.com' COURSE_NAME = 'i18n_course' DASHBOARD_URL = 'dashboard?action=i18n_dashboard' CONSOLE_REST_URL = 'rest/modules/i18n_dashboard/translation_console' ENVIRON = { 'extra_locales': [ {'locale': 'el', 'availability': 'unavailable'}, {'locale': 'ru', 'availability': 'unavailable'}, ]} def setUp(self): super(TranslatorRoleTests, self).setUp() self.base = '/' + self.COURSE_NAME actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'I18N Course') self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME) self.old_registered_permission = roles.Roles._REGISTERED_PERMISSIONS roles.Roles.REGISTERED_PERMISSIONS = {} def tearDown(self): del sites.Registry.test_overrides[sites.GCB_COURSES_CONFIG.name] roles.Roles.REGISTERED_PERMISSIONS = self.old_registered_permission namespace_manager.set_namespace(self.old_namespace) super(TranslatorRoleTests, self).tearDown() def _createTranslatorRole(self, name, locales): permissions = { dashboard.custom_module.name: [i18n_dashboard.ACCESS_PERMISSION], i18n_dashboard.custom_module.name: [ i18n_dashboard.locale_to_permission(loc) for loc in locales] } role_dto = models.RoleDTO(None, { 'name': name, 'users': [self.USER_EMAIL], 'permissions': permissions }) models.RoleDAO.save(role_dto) def test_no_permission_redirect(self): with actions.OverriddenEnvironment(self.ENVIRON): actions.login(self.USER_EMAIL, is_admin=False) self.assertEquals(self.get(self.DASHBOARD_URL).status_int, 302) def test_restricted_access(self): with actions.OverriddenEnvironment(self.ENVIRON): self._createTranslatorRole('ElTranslator', ['el']) actions.login(self.USER_EMAIL, is_admin=False) dom = self.parse_html_string(self.get(self.DASHBOARD_URL).body) table = dom.find('.//table[@class="i18n-progress-table"]') columns = table.findall('./thead/tr/th') expected_col_data = [ 'Asset', 'el' ] self.assertEquals(len(expected_col_data), len(columns)) for index, expected in enumerate(expected_col_data): self.assertEquals(expected, columns[index].text) response = self.get('%s?key=%s' % ( self.CONSOLE_REST_URL, 'course_settings%3Acourse%3Aru')) self.assertEquals(transforms.loads(response.body)['status'], 401) response = self.get('%s?key=%s' % ( self.CONSOLE_REST_URL, 'course_settings%3Acourse%3Ael')) self.assertEquals(transforms.loads(response.body)['status'], 200) class CourseLocalizationTestBase(actions.TestBase): def setUp(self): super(CourseLocalizationTestBase, self).setUp() if sites.GCB_COURSES_CONFIG.name in sites.Registry.test_overrides: del sites.Registry.test_overrides[sites.GCB_COURSES_CONFIG.name] self.auto_deploy = sites.ApplicationContext.AUTO_DEPLOY_DEFAULT_COURSE sites.ApplicationContext.AUTO_DEPLOY_DEFAULT_COURSE = False self._import_course() self._locale_to_label = {} def tearDown(self): del sites.Registry.test_overrides[sites.GCB_COURSES_CONFIG.name] sites.ApplicationContext.AUTO_DEPLOY_DEFAULT_COURSE = self.auto_deploy super(CourseLocalizationTestBase, self).tearDown() def _import_course(self): email = 'test_course_localization@google.com' actions.login(email, is_admin=True) response = self.get('/admin/welcome') self.assertEquals(response.status_int, 200) response = self.post( '/admin/welcome?action=add_first_course', params={'xsrf_token': crypto.XsrfTokenManager.create_xsrf_token( 'add_first_course')}) self.assertEquals(response.status_int, 302) sites.setup_courses('course:/first::ns_first') response = self.get('first/dashboard') self.assertIn('My First Course', response.body) self.assertEquals(response.status_int, 200) class SampleCourseLocalizationTest(CourseLocalizationTestBase): def _import_sample_course(self): email = 'test_course_localization@google.com' actions.login(email, is_admin=True) response = self.get('/admin/welcome') self.assertEquals(response.status_int, 200) response = self.post( '/admin/welcome?action=explore_sample', params={'xsrf_token': crypto.XsrfTokenManager.create_xsrf_token( 'explore_sample')}) self.assertEquals(response.status_int, 302) sites.setup_courses('course:/sample::ns_sample') response = self.get('sample/dashboard') self.assertIn('Power Searching with Google', response.body) self.assertEquals(response.status_int, 200) def _setup_locales(self, availability='available', course='first'): request = { 'key': '/course.yaml', 'payload': ( '{\"i18n\":{\"course:locale\":\"en_US\",\"extra_locales\":[' '{\"locale\":\"ru_RU\",\"availability\":\"%s\"}, ' '{\"locale\":\"es_ES\",\"availability\":\"%s\"}' ']}}' % (availability, availability)), 'xsrf_token': crypto.XsrfTokenManager.create_xsrf_token( 'basic-course-settings-put')} response = self.put( '%s/rest/course/settings' % course, params={ 'request': transforms.dumps(request)}) self.assertEquals(response.status_int, 200) # check labels exist with Namespace('ns_%s' % course): labels = models.LabelDAO.get_all_of_type( models.LabelDTO.LABEL_TYPE_LOCALE) self.assertEqual(3, len(labels)) for label in labels: self._locale_to_label[label.title] = label def _add_announcement(self, title, locales): with Namespace('ns_first'): labels = models.LabelDAO.get_all_of_type( models.LabelDTO.LABEL_TYPE_LOCALE) label_ids = [] for label in labels: for locale in locales: if label.title == locale: label_ids.append(label.id) annon = announcements.AnnouncementEntity() annon.title = title annon.labels = utils.list_to_text(label_ids) annon.is_draft = False annon.put() def _add_announcements(self): self._add_announcement('Test announcement EN', ['en_US']) self._add_announcement('Test announcement RU', ['ru_RU']) self._add_announcement('Test announcement ES', ['es_ES']) self._add_announcement( 'Test announcement ALL', ['en_US', 'ru_RU', 'es_ES']) self._add_announcement('Test announcement NONE', []) with Namespace('ns_first'): items = announcements.AnnouncementEntity.get_announcements() self.assertEqual(5, len(items)) def _add_units(self, locale_labels=False): with Namespace('ns_first'): course = courses.Course(None, sites.get_all_courses()[0]) _en = course.add_unit() _en.type = 'U' _en.now_available = True _en.title = 'Unit en_US' _ru = course.add_unit() _ru.type = 'U' _ru.now_available = True _ru.title = 'Unit ru_RU' _es = course.add_unit() _es.type = 'U' _es.now_available = True _es.title = 'Unit es_ES' _all = course.add_unit() _all.type = 'U' _all.now_available = True _all.title = 'Unit all_ALL' _none = course.add_unit() _none.type = 'U' _none.now_available = True _none.title = 'Unit none_NONE' if locale_labels: _en.labels = utils.list_to_text( [self._locale_to_label['en_US'].id]) _ru.labels = utils.list_to_text( [self._locale_to_label['ru_RU'].id]) _es.labels = utils.list_to_text( [self._locale_to_label['es_ES'].id]) _all.labels = utils.list_to_text([ self._locale_to_label['es_ES'].id, self._locale_to_label['ru_RU'].id]) _none.labels = utils.list_to_text([]) course.save() self._locale_to_unit = {} self._locale_to_unit['en_US'] = _en self._locale_to_unit['ru_RU'] = _ru self._locale_to_unit['es_ES'] = _es def _set_labels_on_current_student(self, labels, ids=None): with Namespace('ns_first'): user = users.get_current_user() if ids is None: ids = [label.id for label in labels] labels = utils.list_to_text(ids) models.StudentProfileDAO.update( user.user_id(), user.email(), labels=labels) def _set_prefs_locale(self, locale, course='first'): with Namespace('ns_%s' % course): prefs = models.StudentPreferencesDAO.load_or_create() if prefs: prefs.locale = locale models.StudentPreferencesDAO.save(prefs) def _assert_picker(self, is_present, has_locales=None, is_admin=False): actions.login('_assert_picker_visible@example.com', is_admin=is_admin) response = self.get('first/course') self.assertEquals(response.status_int, 200) dom = self.parse_html_string(response.body) if is_present: self.assertTrue(dom.find('.//select[@id="locale-select"]')) for has_locale in has_locales: option = dom.find( './/select[@id="locale-select"]' '/option[@value="%s"]' % has_locale) self.assertIsNotNone(option) else: self.assertFalse(dom.find('.//select[@id="locale-select"]')) actions.logout() def _assert_en_ru_es_all_none(self, en, ru, es, _all, _none, lang): response = self.get('first/announcements') self.assertEquals(response.status_int, 200) if en: self.assertIn('Test announcement EN', response.body) else: self.assertNotIn('Test announcement EN', response.body) if ru: self.assertIn('Test announcement RU', response.body) else: self.assertNotIn('Test announcement RU', response.body) if es: self.assertIn('Test announcement ES', response.body) else: self.assertNotIn('Test announcement ES', response.body) if _all: self.assertIn('Test announcement ALL', response.body) else: self.assertNotIn('Test announcement ALL', response.body) if _none: self.assertIn('Test announcement NONE', response.body) else: self.assertNotIn('Test announcement NONE', response.body) self.assertEquals(self.parse_html_string( response.body).get('lang'), lang) return response def _course_en_ru_es_all_none(self, en, ru, es, _all, _none, lang): response = self.get('first/course') self.assertEquals(response.status_int, 200) if en: self.assertIn('Unit en_US', response.body) else: self.assertNotIn('Unit en_US', response.body) if ru: self.assertIn('Unit ru_RU', response.body) else: self.assertNotIn('Unit ru_RU', response.body) if es: self.assertIn('Unit es_ES', response.body) else: self.assertNotIn('Unit es_ES', response.body) if _all: self.assertIn('Unit all_ALL', response.body) else: self.assertNotIn('Unit all_ALL', response.body) if _none: self.assertIn('Unit none_NONE', response.body) else: self.assertNotIn('Unit none_NONE', response.body) self.assertEquals(self.parse_html_string( response.body).get('lang'), lang) return response def test_locale_picker_visibility_for_available_locales_as_student(self): self._setup_locales() with actions.OverriddenEnvironment( {'course': { 'now_available': True, 'can_student_change_locale': True}}): self._assert_picker(True, ['en_US', 'ru_RU', 'es_ES']) with actions.OverriddenEnvironment( {'course': { 'now_available': True, 'can_student_change_locale': False}}): self._assert_picker(False) def test_locale_picker_visibility_for_unavailable_locales_as_student(self): self._setup_locales(availability='unavailable') with actions.OverriddenEnvironment( {'course': { 'now_available': True, 'can_student_change_locale': True}}): self._assert_picker(True, ['en_US']) with actions.OverriddenEnvironment( {'course': { 'now_available': True, 'can_student_change_locale': False}}): self._assert_picker(False) def test_locale_picker_visibility_for_unavailable_locales_as_admin(self): self._setup_locales(availability='unavailable') with actions.OverriddenEnvironment( {'course': { 'now_available': True, 'can_student_change_locale': True}}): self._assert_picker( True, ['en_US', 'ru_RU', 'es_ES'], is_admin=True) with actions.OverriddenEnvironment( {'course': { 'now_available': True, 'can_student_change_locale': False}}): self._assert_picker( True, ['en_US', 'ru_RU', 'es_ES'], is_admin=True) def test_view_announcement_via_locale_picker(self): self._setup_locales() self._add_announcements() actions.logout() actions.login('test_view_announcement_via_locale_picker@example.com') with actions.OverriddenEnvironment( {'course': { 'now_available': True, 'can_student_change_locale': True}}): actions.register( self, 'test_view_announcement_via_locale_picker', course='first') self._set_prefs_locale(None) response = self._assert_en_ru_es_all_none( True, False, False, True, True, 'en_US') self.assertIn('Announcements', response.body) self._set_prefs_locale('ru_RU') response = self._assert_en_ru_es_all_none( False, True, False, True, True, 'ru_RU') self.assertIn('Сообщения', response.body) self._set_prefs_locale('es_ES') response = self._assert_en_ru_es_all_none( False, False, True, True, True, 'es_ES') self.assertIn('Avisos', response.body) # when locale labels are combined with prefs, labels win self._set_prefs_locale(None) self._set_labels_on_current_student( [self._locale_to_label['ru_RU']]) self._assert_en_ru_es_all_none( False, True, False, True, True, 'ru_RU') self._set_prefs_locale('es_ES') self._set_labels_on_current_student( [self._locale_to_label['ru_RU']]) self._assert_en_ru_es_all_none( False, True, False, True, True, 'ru_RU') def test_announcements_via_locale_labels(self): self._setup_locales() self._add_announcements() actions.logout() actions.login('test_announcements_via_locale_labels@example.com') with actions.OverriddenEnvironment( {'course': { 'now_available': True, 'can_student_change_locale': False}}): actions.register( self, 'test_announcements_via_locale_labels', course='first') self._set_prefs_locale(None) self._set_labels_on_current_student([]) self._assert_en_ru_es_all_none( True, True, True, True, True, 'en_US') self._set_labels_on_current_student( [self._locale_to_label['en_US']]) self._assert_en_ru_es_all_none( True, False, False, True, True, 'en_US') self._set_labels_on_current_student( [self._locale_to_label['ru_RU']]) self._assert_en_ru_es_all_none( False, True, False, True, True, 'ru_RU') self._set_labels_on_current_student( [self._locale_to_label['es_ES']]) self._assert_en_ru_es_all_none( False, False, True, True, True, 'es_ES') self._set_prefs_locale('ru_RU') self._set_labels_on_current_student([]) response = self._assert_en_ru_es_all_none( True, True, True, True, True, 'ru_RU') self.assertIn('Сообщения', response.body) self._set_prefs_locale('ru_RU') self._set_labels_on_current_student( [self._locale_to_label['es_ES']]) response = self._assert_en_ru_es_all_none( False, False, True, True, True, 'es_ES') self.assertIn('Avisos', response.body) def test_course_track_via_locale_picker(self): self._setup_locales() self._add_units(locale_labels=True) actions.logout() actions.login('test_course_track_via_locale_picker@example.com') with actions.OverriddenEnvironment( {'course': { 'now_available': True, 'can_student_change_locale': True}}): actions.register( self, 'test_course_track_via_locale_picker', course='first') self._set_prefs_locale(None) self._course_en_ru_es_all_none( True, False, False, False, True, 'en_US') self._set_prefs_locale('en_US') response = self._course_en_ru_es_all_none( True, False, False, False, True, 'en_US') self.assertIn('Announcements', response.body) self._set_prefs_locale('ru_RU') response = self._course_en_ru_es_all_none( False, True, False, True, True, 'ru_RU') self.assertIn('Сообщения', response.body) self._set_prefs_locale('es_ES') response = self._course_en_ru_es_all_none( False, False, True, True, True, 'es_ES') self.assertIn('Avisos', response.body) def test_button_captions(self): self._import_sample_course() self._setup_locales(course='sample') self._set_prefs_locale('ru', course='sample') response = self.get('/sample/course') # TODO(psimakov): 'Search' button caption must be localized; but it's # in the hook and we don't curently support gettext() inside hook :( self.assertIn('type="submit" value="Search"', response.body) response = self.get('/sample/unit?unit=14&lesson=20') self.assertIn('Проверить ответ', response.body) self.assertIn('Подсказка', response.body) self.assertIn('Баллов: 1', response.body) self.assertIn('Предыдущая страница', response.body) self.assertIn('Следующая страница', response.body) response = self.get('/sample/assessment?name=1') self.assertIn('Отправить ответы', response.body) for url in [ '/sample/assessment?name=35', '/sample/assessment?name=65']: response = self.get(url) self.assertIn('Баллов: 1', response.body) self.assertIn('Проверить ответы', response.body) self.assertIn('Отправить ответы', response.body) def test_course_track_via_locale_labels(self): self._setup_locales() self._add_units(locale_labels=True) actions.logout() actions.login('test_course_track_via_locale_picker@example.com') with actions.OverriddenEnvironment( {'course': { 'now_available': True, 'can_student_change_locale': True}}): actions.register( self, 'test_course_track_via_locale_picker', course='first') self._set_labels_on_current_student([]) self._course_en_ru_es_all_none( True, False, False, False, True, 'en_US') self._set_labels_on_current_student( [self._locale_to_label['en_US']]) self._course_en_ru_es_all_none( True, False, False, False, True, 'en_US') self._set_labels_on_current_student( [self._locale_to_label['ru_RU']]) self._course_en_ru_es_all_none( False, True, False, True, True, 'ru_RU') self._set_labels_on_current_student( [self._locale_to_label['es_ES']]) self._course_en_ru_es_all_none( False, False, True, True, True, 'es_ES') def test_track_and_locale_labels_do_work_together(self): self._setup_locales() with Namespace('ns_first'): track_a_id = models.LabelDAO.save(models.LabelDTO( None, {'title': 'Track A', 'version': '1.0', 'description': 'Track A', 'type': models.LabelDTO.LABEL_TYPE_COURSE_TRACK})) track_b_id = models.LabelDAO.save(models.LabelDTO( None, {'title': 'Track B', 'version': '1.0', 'description': 'Track B', 'type': models.LabelDTO.LABEL_TYPE_COURSE_TRACK})) locale_ru_id = self._locale_to_label['ru_RU'].id locale_es_id = self._locale_to_label['es_ES'].id course = courses.Course(None, sites.get_all_courses()[0]) unit_1 = course.add_unit() unit_1.type = 'U' unit_1.now_available = True unit_1.title = 'Unit for Track A and Locale ru_RU' unit_1.labels = utils.list_to_text( [track_a_id, locale_ru_id]) unit_2 = course.add_unit() unit_2.type = 'U' unit_2.now_available = True unit_2.title = 'Unit for Track B and Locale es_ES' unit_2.labels = utils.list_to_text( [track_b_id, locale_es_id]) course.save() def _assert_course( locale, label_ids, is_unit_1_visible, is_unit_2_visible): self._set_prefs_locale(locale) self._set_labels_on_current_student(None, ids=label_ids) response = self.get('first/course') if is_unit_1_visible: self.assertIn(unit_1.title, response.body) else: self.assertNotIn(unit_1.title, response.body) if is_unit_2_visible: self.assertIn(unit_2.title, response.body) else: self.assertNotIn(unit_2.title, response.body) actions.logout() with actions.OverriddenEnvironment( {'course': {'now_available': True}}): actions.login( 'test_track_and_locale_labels_dont_interfere@example.com') actions.register( self, 'test_track_and_locale_labels_dont_interfere', course='first') with actions.OverriddenEnvironment( {'course': { 'now_available': True, 'can_student_change_locale': True}}): _assert_course(None, [], False, False) _assert_course('ru_RU', [], True, False) _assert_course('es_ES', [], False, True) _assert_course(None, [track_a_id], False, False) _assert_course('ru_RU', [track_a_id], True, False) _assert_course('ru_RU', [track_b_id], False, False) _assert_course('es_ES', [track_a_id], False, False) _assert_course('es_ES', [track_b_id], False, True) _assert_course(None, [locale_ru_id], True, False) _assert_course('ru_RU', [locale_ru_id], True, False) _assert_course('ru_RU', [locale_es_id], False, True) _assert_course('es_ES', [locale_ru_id], True, False) _assert_course('es_ES', [locale_es_id], False, True) _assert_course(None, [track_a_id, track_b_id], False, False) _assert_course('ru_RU', [track_a_id, track_b_id], True, False) _assert_course('es_ES', [track_a_id, track_b_id], False, True) _assert_course( None, [track_a_id, locale_ru_id], True, False) _assert_course('ru_RU', [track_a_id, locale_ru_id], True, False) _assert_course( 'ru_RU', [track_a_id, locale_es_id], False, False) _assert_course('ru_RU', [track_b_id, locale_es_id], False, True) _assert_course('ru_RU', [track_b_id, locale_ru_id], False, False) _assert_course( None, [track_a_id, track_b_id, locale_ru_id], True, False) _assert_course( None, [track_a_id, track_b_id, locale_es_id], False, True) _assert_course( 'ru_RU', [track_a_id, track_b_id, locale_ru_id], True, False) _assert_course( 'ru_RU', [track_a_id, track_b_id, locale_es_id], False, True) _assert_course( 'es_ES', [track_a_id, track_b_id, locale_ru_id], True, False) _assert_course( 'es_ES', [track_a_id, track_b_id, locale_es_id], False, True) with actions.OverriddenEnvironment( {'course': { 'now_available': True, 'can_student_change_locale': False}}): _assert_course(None, [], True, True) _assert_course('ru_RU', [], True, True) _assert_course('es_ES', [], True, True) _assert_course(None, [locale_ru_id], True, False) _assert_course('ru_RU', [locale_ru_id], True, False) _assert_course('ru_RU', [locale_es_id], False, True) _assert_course('es_ES', [locale_ru_id], True, False) _assert_course('es_ES', [locale_es_id], False, True) _assert_course(None, [track_a_id], True, False) _assert_course('ru_RU', [track_a_id], True, False) _assert_course('ru_RU', [track_b_id], False, True) _assert_course('es_ES', [track_a_id], True, False) _assert_course('es_ES', [track_b_id], False, True) _assert_course(None, [track_a_id, track_b_id], True, True) # the one below is not an error; the empty locale label set on # student is a match for unit labeled with any locale or none _assert_course('ru_RU', [track_a_id, track_b_id], True, True) _assert_course('es_ES', [track_a_id, track_b_id], True, True) _assert_course(None, [track_a_id, locale_ru_id], True, False) _assert_course('ru_RU', [track_a_id, locale_ru_id], True, False) _assert_course('ru_RU', [track_a_id, locale_es_id], False, False) _assert_course('ru_RU', [track_b_id, locale_es_id], False, True) _assert_course('ru_RU', [track_b_id, locale_ru_id], False, False) _assert_course( None, [track_a_id, track_b_id, locale_ru_id], True, False) _assert_course( None, [track_a_id, track_b_id, locale_es_id], False, True) _assert_course( 'ru_RU', [track_a_id, track_b_id, locale_ru_id], True, False) _assert_course( 'ru_RU', [track_a_id, track_b_id, locale_es_id], False, True) _assert_course( 'es_ES', [track_a_id, track_b_id, locale_ru_id], True, False) _assert_course( 'es_ES', [track_a_id, track_b_id, locale_es_id], False, True) def test_localized_course_with_images(self): self._import_sample_course() self._setup_locales(course='sample') with actions.OverriddenEnvironment( {'course': {'now_available': True}}): actions.logout() actions.login( 'test_track_and_locale_labels_dont_interfere@example.com') actions.register( self, 'test_track_and_locale_labels_dont_interfere', course='sample') def _assert_image(): response = self.get('sample/assets/img/Image2.2.1.png') self.assertEquals(200, response.status_int) self.assertEquals(215086, len(response.body)) with actions.OverriddenEnvironment( {'course': { 'now_available': True, 'can_student_change_locale': True}}): self._set_prefs_locale('en_US', course='sample') response = self.get('sample/unit?unit=14&lesson=18') self.assertIn( 'You are a cosmetologist and business owner', response.body) self.assertIn('Announcements', response.body) _assert_image() self._set_prefs_locale('ru_RU', course='sample') response = self.get('sample/unit?unit=14&lesson=18') self.assertIn( 'You are a cosmetologist and business owner', response.body) self.assertIn('Сообщения', response.body) _assert_image() def test_set_current_locale_reloads_environ(self): app_context = sites.get_all_courses()[0] self._setup_locales() course = courses.Course(None, app_context) course_bundle = { 'course:title': { 'source_value': None, 'type': 'string', 'data': [ { 'source_value': app_context.get_title(), 'target_value': 'TRANSLATED TITLE' }] }} with Namespace('ns_first'): key_el = ResourceBundleKey( resources_display.ResourceCourseSettings.TYPE, 'homepage', 'es_ES') ResourceBundleDAO.save( ResourceBundleDTO(str(key_el), course_bundle)) sites.set_path_info('/first') app_context.set_current_locale('ru_RU') ru_env = course.get_environ(app_context) app_context.set_current_locale('es_ES') es_env = course.get_environ(app_context) sites.unset_path_info() self.assertNotEquals(ru_env, es_env) def test_swapcase(self): source = '12345' target = u'12345λ' self.assertEquals(target, i18n_dashboard.swapcase(source)) source = '<img alt="Hello!">W0rld</img>' target = u'<img alt="Hello!">w0RLDλ</img>' self.assertEquals(target, i18n_dashboard.swapcase(source)) source = 'Hello W0rld!' target = u'hELLO w0RLD!λ' self.assertEquals(target, i18n_dashboard.swapcase(source)) source = 'Hello&apos;W0rld!' target = u'hELLO\'w0RLD!λ' self.assertEquals(target, i18n_dashboard.swapcase(source)) # content inside tags must be preserved source = ( 'Hello<img src="http://a.b.com/' 'foo?bar=baz&amp;cookie=sweet"/>W0rld') target = ( u'hELLOλ<img src="http://a.b.com/' u'foo?bar=baz&amp;cookie=sweet"/>w0RLDλ') self.assertEquals(target, i18n_dashboard.swapcase(source)) # %s and other formatting must be preserved source = 'Hello%sW0rld!' target = u'hELLO%sw0RLD!λ' self.assertEquals(target, i18n_dashboard.swapcase(source)) source = 'Hello%(foo)sW0rld!' target = u'hELLO%(foo)sw0RLD!λ' self.assertEquals(target, i18n_dashboard.swapcase(source)) # we dont support {foo} type formatting source = 'Hello{s}W0rld!' target = u'hELLO{S}w0RLD!λ' self.assertEquals(target, i18n_dashboard.swapcase(source)) def test_reverse_case(self): self._import_sample_course() actions.login('test_reverse_case@example.com', is_admin=True) self.get('sample/dashboard?action=i18n_reverse_case') self._set_prefs_locale('ln', course='sample') def check_all_in(response, texts): self.assertEquals(200, response.status_int) for text in texts: self.assertIn(text, response.body) # check selected pages check_all_in(self.get('sample/course'), [ 'dANIEL rUSSELL', 'pRE-COURSE ASSESSMENT', 'iNTRODUCTION', 'hANG oUT WITH']) check_all_in(self.get('sample/assessment?name=1'), [ 'tHANK YOU, AND HAVE FUN!', 'wHEN SEARCHING gOOGLE iMAGES', 'a AND c', 'iF YOU DO NOT KNOW']) check_all_in(self.get('sample/unit?unit=14'), [ 'Unit 2 - iNTERPRETING RESULTS', 'wHEN SEARCH RESULTS SUGGEST', 'lESSON 2.3 aCTIVITY']) check_all_in(self.get('sample/unit?unit=2&lesson=9'), [ 'lESSON 1.4 aCTIVITY']) check_all_in(self.get('sample/unit?unit=14&lesson=16'), [ 'hAVE YOU EVER PLAYED THE']) check_all_in(self.get('sample/unit?unit=47&lesson=53'), [ 'dID dARWIN, HIMSELF, USE', 'aDVENTURES IN wONDERLAND']) check_all_in(self.get('sample/assessment?name=64'), [ 'sOLVE THE PROBLEM BELOW', 'hOW MANY pOWER sEARCH CONCEPTS', 'lIST THE pOWER sEARCH CONCEPTS']) # check assesment submition; it has fragile %s type complex formatting # functions that we need to check actions.register(self, 'test_reverse_case', course='sample') response = self.post('sample/answer', { 'xsrf_token': crypto.XsrfTokenManager.create_xsrf_token( 'assessment-post'), 'score': 0, 'assessment_type': 65, 'answers': {}}) self.assertEquals(200, response.status_int) for text in ['for taking the pOST-COURSE', 'cERTIFICATE OR NOT, WE']: self.assertIn(text, response.body) # check invalid_question = 0 translation_error = 0 course = courses.Course(None, sites.get_all_courses()[0]) for unit in course.get_units(): for lesson in course.get_lessons(unit.unit_id): response = self.get('sample/unit?unit=%s&lesson=%s' % ( unit.unit_id, lesson.lesson_id)) self.assertEquals(200, response.status_int) self.assertIn( unit.title.swapcase(), response.body.decode('utf-8')) self.assertIn( lesson.title.swapcase(), response.body.decode('utf-8')) # check standard multibyte character is present self.assertIn(u'λ', response.body.decode('utf-8')) try: self.assertNotIn('[Invalid question]', response.body) except AssertionError: invalid_question += 1 try: self.assertNotIn('gcb-translation-error', response.body) except AssertionError: translation_error += 1 self.assertEquals((invalid_question, translation_error), (0, 0)) def test_course_with_one_common_unit_and_two_per_locale_units(self): # TODO(psimakov): incomplete pass def test_readonly(self): self._import_sample_course() self._setup_locales(course='sample') actions.login('test_readonly@example.com', is_admin=True) response = self.get('sample/dashboard?action=i18n_dashboard') self.assertNotIn('(readonly)', response.body) self.assertNotIn('input disabled', response.body) self.assertIn('action=i18n_download', response.body) self.assertIn('action=i18n_upload', response.body) self.assertIn('action=i18n_reverse_case', response.body) self.assertIn('action=i18_console', response.body) with actions.OverriddenEnvironment( {'course': {'prevent_translation_edits': True}}): response = self.get('sample/dashboard?action=i18n_dashboard') self.assertIn('(readonly)', response.body) self.assertIn('input disabled', response.body) self.assertNotIn('action=i18n_download', response.body) self.assertNotIn('action=i18n_upload', response.body) self.assertNotIn('action=i18n_reverse_case', response.body) self.assertNotIn('action=i18_console', response.body) def test_rpc_performance(self): """Tests various common actions for the number of memcache/db rpc.""" self._import_sample_course() # add fake 'ln' locale and fake translations response = self.get('sample/dashboard?action=i18n_reverse_case') self.assertEquals(302, response.status_int) response = self.get('sample/dashboard?action=i18n_dashboard') self.assertEquals(200, response.status_int) self.assertIn('<th>ln</th>', response.body) config.Registry.test_overrides[models.CAN_USE_MEMCACHE.name] = True old_memcache_make_async_call = memcache._CLIENT._make_async_call old_db_make_rpc_call = datastore_rpc.BaseConnection._make_rpc_call try: lines = [] over_quota = [False] def _profile(url, hint, quota=(128, 32)): """Fetches a URL while counting a number of RPC calls. Args: url: URL to fetch hint: hint about this operation to put in the report quota: tuple of max counts of (memcache, db) RPC calls allowed during this request """ counters = [0, 0] memcache_stacks = collections.defaultdict(int) db_stacks = collections.defaultdict(int) def reset(): counters[0] = 0 counters[1] = 0 def _memcache_make_async_call(*args, **kwds): memcache_stacks[tuple(traceback.extract_stack())] += 1 counters[0] += 1 return old_memcache_make_async_call(*args, **kwds) def _db_make_rpc_call(*args, **kwds): db_stacks[tuple(traceback.extract_stack())] += 1 counters[1] += 1 return old_db_make_rpc_call(*args, **kwds) def _assert_quota(quota, actual, lines): memcache_quota, db_quota = quota memcache_actual, db_actual = actual respects_quota = True if memcache_quota is not None and ( memcache_quota < memcache_actual): respects_quota = False if db_quota is not None and (db_quota < db_actual): respects_quota = False if not respects_quota: over_quota[0] = True lines.append( 'Request metrics %s exceed RPC quota ' '[memcache:%s, db:%s]: %s (%s)' % ( actual, memcache_quota, db_quota, hint, url)) for stacktrace, count in memcache_stacks.iteritems(): lines.append('Memcache: %d calls to:' % count) lines += [l.rstrip() for l in traceback.format_list(stacktrace)] for stacktrace, count in db_stacks.iteritems(): lines.append('DB: %d calls to:' % count) lines += [l.rstrip() for l in traceback.format_list(stacktrace)] counters_list = [] memcache._CLIENT._make_async_call = _memcache_make_async_call datastore_rpc.BaseConnection._make_rpc_call = _db_make_rpc_call for locale in ['en_US', 'ln']: self._set_prefs_locale(locale, course='sample') memcache.flush_all() app_context = sites.get_all_courses()[0] app_context.clear_per_process_cache() app_context.clear_per_request_cache() for attempt in [0, 1]: reset() response = self.get(url) self.assertEquals(200, response.status_int) actual = [] + counters counters_list.append((actual)) if quota is not None and attempt == 1: _assert_quota(quota, actual, lines) stats = ' '.join([ '[% 4d|% 4d]' % (_memcache, _db) for _memcache, _db in counters_list]) lines.append('\t{ %s }\t%s (%s)' % (stats, hint, url)) header = ( '[memcache|db] for {first load, second load, ' 'first locale load, second locale load}') with actions.OverriddenEnvironment( {'course': { 'now_available': True, 'can_student_change_locale': True}}): actions.logout() lines.append('RPC Profile, anonymous user %s' % header) _profile( '/modules/oeditor/resources/butterbar.js', 'Butterbar', quota=(0, 0)) _profile('sample/assets/css/main.css', 'main.css', quota=(6, 0)) _profile('sample/course', 'Home page', quota=(None, 1)) _profile( 'sample/announcements', 'Announcements', quota=(None, 1)) actions.login('test_rpc_performance@example.com') actions.register(self, 'test_rpc_performance', course='sample') lines.append('RPC Profile, registered user %s' % header) _profile( '/modules/oeditor/resources/butterbar.js', 'Butterbar', quota=(0, 0)) _profile( 'sample/assets/css/main.css', 'main.css', quota=(3, 1)) _profile('sample/course', 'Home page') _profile('sample/announcements', 'Announcements') _profile('sample/unit?unit=14&lesson=17', 'Lesson 2.2') _profile('sample/assessment?name=35', 'Mid-term exam') actions.logout() actions.login('test_rpc_performance@example.com', is_admin=True) lines.append('RPC Profile, admin user %s' % header) _profile( '/modules/oeditor/resources/butterbar.js', 'Butterbar', quota=(0, 0)) _profile( 'sample/assets/css/main.css', 'main.css', quota=(3, 1)) _profile('sample/course', 'Home page') _profile('sample/announcements', 'Announcements') _profile('sample/unit?unit=14&lesson=17', 'Lesson 2.2') _profile('sample/assessment?name=35', 'Mid-term exam') _profile('sample/admin', 'Admin home') _profile('sample/admin?action=settings', 'Settings') _profile('sample/dashboard', 'Dashboard', quota=(150, 60)) _profile('sample/dashboard?action=assets', 'Questions') _profile( 'sample/dashboard?action=i18n_dashboard', 'I18N Dashboard') _profile('sample/dashboard?action=i18n_download', 'I18N Export') print '\n', '\n'.join(lines) self.assertFalse(over_quota[0], msg='Some items exceed quota.') finally: memcache._CLIENT._make_async_call = old_memcache_make_async_call datastore_rpc.BaseConnection._make_rpc_call = old_db_make_rpc_call del config.Registry.test_overrides[models.CAN_USE_MEMCACHE.name]
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for crypto and hashing.""" __author__ = 'Mike Gainer (mgainer@google.com)' import re import actions from common import crypto URLSAFE_B64_ALPHABET = re.compile('^[a-zA-Z0-9-_=]+$') class EncryptionManagerTests(actions.TestBase): def test_hmac_is_consistent(self): message = 'Mary had a little lamb. Her doctors were astounded' h1 = crypto.EncryptionManager.hmac([message]) h2 = crypto.EncryptionManager.hmac([message]) self.assertEquals(h1, h2) self.assertNotEquals(h1, message) def test_encrypt_is_consistent(self): message = 'Mary had a little lamb. Her doctors were astounded' e1 = crypto.EncryptionManager.encrypt(message) e2 = crypto.EncryptionManager.encrypt(message) self.assertEquals(e1, e2) self.assertNotEquals(e1, message) def test_encrypt_urlsafe_is_urlsafe(self): message = 'Mary had a little lamb. Her doctors were astounded' e1 = crypto.EncryptionManager.encrypt(message) self.assertIsNone(URLSAFE_B64_ALPHABET.match(e1)) # some illegal chars e2 = crypto.EncryptionManager.encrypt_to_urlsafe_ciphertext(message) self.assertIsNotNone(URLSAFE_B64_ALPHABET.match(e2)) self.assertNotEquals(message, e2) def test_encrypt_decrypt(self): message = 'Mary had a little lamb. Her doctors were astounded' e = crypto.EncryptionManager.encrypt(message) d = crypto.EncryptionManager.decrypt(e) self.assertEquals(d, message) self.assertNotEquals(e, d) def test_encrypt_decrypt_urlsafe(self): message = 'Mary had a little lamb. Her doctors were astounded' e = crypto.EncryptionManager.encrypt_to_urlsafe_ciphertext(message) d = crypto.EncryptionManager.decrypt_from_urlsafe_ciphertext(e) self.assertEquals(d, message) self.assertNotEquals(e, d) class GetExternalUserIdTests(actions.TestBase): def setUp(self): super(GetExternalUserIdTests, self).setUp() self.app_id = 'app_id' self.namespace = 'namespace' self.email = 'email' self.id = crypto.get_external_user_id( self.app_id, self.namespace, self.email) def test_consistent(self): self.assertEqual( self.id, crypto.get_external_user_id( self.app_id, self.namespace, self.email)) def test_change_app_id_changes_hmac(self): self.assertNotEqual( self.id, crypto.get_external_user_id( 'not' + self.app_id, self.namespace, self.email)) def test_change_namespace_changes_hmac(self): self.assertNotEqual( self.id, crypto.get_external_user_id( self.app_id, 'not' + self.namespace, self.email)) def test_change_email_changes_hmac(self): self.assertNotEqual( self.id, crypto.get_external_user_id( self.app_id, self.namespace, 'not' + self.email)) class XsrfTokenManagerTests(actions.TestBase): def test_valid_token(self): action = 'lob_cheese' t = crypto.XsrfTokenManager.create_xsrf_token(action) self.assertTrue(crypto.XsrfTokenManager.is_xsrf_token_valid( t, action)) def test_token_for_different_action(self): action1 = 'lob_cheese' action2 = 'eat_cheese' t1 = crypto.XsrfTokenManager.create_xsrf_token(action1) self.assertFalse(crypto.XsrfTokenManager.is_xsrf_token_valid( t1, action2)) def test_token_for_mangled_string(self): action = 'lob_cheese' t = crypto.XsrfTokenManager.create_xsrf_token(action) self.assertFalse(crypto.XsrfTokenManager.is_xsrf_token_valid( t, action + '.')) class PiiObfuscationHmac(actions.TestBase): def test_consistent(self): message = 'Mary had a little lamb. Her doctors were astounded' secret = 'skoodlydoodah' h1 = crypto.hmac_sha_2_256_transform(secret, message) h2 = crypto.hmac_sha_2_256_transform(secret, message) self.assertEquals(h1, h2) self.assertNotEquals(h1, message) def test_change_secret_changes_hmac(self): message = 'Mary had a little lamb. Her doctors were astounded' secret = 'skoodlydoodah' h1 = crypto.hmac_sha_2_256_transform(secret, message) h2 = crypto.hmac_sha_2_256_transform(secret + '.', message) self.assertNotEquals(h1, h2) self.assertNotEquals(h1, message) class GenCryptoKeyFromHmac(actions.TestBase): def test_gen_crypto_key(self): message = 'Mary had a little lamb. Her doctors were astounded' action = 'lob_cheese' t = crypto.XsrfTokenManager.create_xsrf_token(message) secret = crypto.generate_transform_secret_from_xsrf_token(t, action) self.assertNotEqual(secret, message) self.assertNotEqual(secret, action) self.assertNotEqual(secret, t) def test_use_crypto_key(self): action = 'lob_cheese' t = crypto.XsrfTokenManager.create_xsrf_token(action) secret = crypto.generate_transform_secret_from_xsrf_token(t, action) message = 'Mary had a little lamb. Her doctors were astounded' e = crypto.EncryptionManager.encrypt(message, secret) d = crypto.EncryptionManager.decrypt(e, secret) self.assertEquals(d, message) self.assertNotEquals(e, d) self.assertNotEquals(e, secret)
Python
# coding: utf-8 # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for controllers pertaining to peer review assessments.""" __author__ = 'Sean Lip' import actions from actions import assert_contains from actions import assert_does_not_contain from actions import assert_equals from controllers import sites from controllers import utils from models import config from models import courses from models import transforms # The unit id for the peer review assignment in the default course. LEGACY_REVIEW_UNIT_ID = 'ReviewAssessmentExample' def get_review_step_key(response): """Returns the review step key in a request query parameter.""" request_query_string = response.request.environ['QUERY_STRING'] return request_query_string[request_query_string.find('key=') + 4:] def get_review_payload(identifier, is_draft=False): """Returns a sample review payload.""" review = transforms.dumps([ {'index': 0, 'type': 'choices', 'value': '0', 'correct': False}, {'index': 1, 'type': 'regex', 'value': identifier, 'correct': True} ]) return { 'answers': review, 'is_draft': 'true' if is_draft else 'false', } class PeerReviewControllerTest(actions.TestBase): """Test peer review from the Student perspective.""" def test_submit_assignment(self): """Test submission of peer-reviewed assignments.""" # Override course.yaml settings by patching app_context. get_environ_old = sites.ApplicationContext.get_environ def get_environ_new(self): environ = get_environ_old(self) environ['course']['browsable'] = False return environ sites.ApplicationContext.get_environ = get_environ_new email = 'test_peer_reviewed_assignment_submission@google.com' name = 'Test Peer Reviewed Assignment Submission' submission = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'First answer to Q1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'First answer to Q3', 'correct': True}, ]) second_submission = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'Second answer to Q1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'Second answer to Q3', 'correct': True}, ]) # Check that the sample peer-review assignment shows up in the preview # page. response = actions.view_preview(self) assert_contains('Sample peer review assignment', response.body) assert_does_not_contain('Review peer assignments', response.body) actions.login(email) actions.register(self, name) # Check that the sample peer-review assignment shows up in the course # page and that it can be visited. response = actions.view_course(self) assert_contains('Sample peer review assignment', response.body) assert_contains('Review peer assignments', response.body) assert_contains( '<a href="assessment?name=%s">' % LEGACY_REVIEW_UNIT_ID, response.body) assert_contains('<span> Review peer assignments </span>', response.body, collapse_whitespace=True) assert_does_not_contain('<a href="reviewdashboard', response.body, collapse_whitespace=True) # Check that the progress circle for this assignment is unfilled. assert_contains( 'progress-notstarted-%s' % LEGACY_REVIEW_UNIT_ID, response.body) assert_does_not_contain( 'progress-completed-%s' % LEGACY_REVIEW_UNIT_ID, response.body) # Try to access an invalid assignment. response = self.get( 'assessment?name=FakeAssessment', expect_errors=True) assert_equals(response.status_int, 404) # The student should not be able to see others' reviews because he/she # has not submitted an assignment yet. response = self.get('assessment?name=%s' % LEGACY_REVIEW_UNIT_ID) assert_does_not_contain('Submitted assignment', response.body) assert_contains('Due date for this assignment', response.body) assert_does_not_contain('Reviews received', response.body) # The student should not be able to access the review dashboard because # he/she has not submitted the assignment yet. response = self.get( 'reviewdashboard?unit=%s' % LEGACY_REVIEW_UNIT_ID, expect_errors=True) assert_contains('You must submit the assignment for', response.body) # The student submits the assignment. response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, {'answers': submission, 'assessment_type': LEGACY_REVIEW_UNIT_ID} ) assert_contains( 'Thank you for completing this assignment', response.body) assert_contains('Review peer assignments', response.body) # The student views the submitted assignment, which has become readonly. response = self.get('assessment?name=%s' % LEGACY_REVIEW_UNIT_ID) assert_contains('First answer to Q1', response.body) assert_contains('Submitted assignment', response.body) # The student tries to re-submit the same assignment. This should fail. response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, {'answers': second_submission, 'assessment_type': LEGACY_REVIEW_UNIT_ID}, presubmit_checks=False ) assert_contains( 'You have already submitted this assignment.', response.body) assert_contains('Review peer assignments', response.body) # The student views the submitted assignment. The new answers have not # been saved. response = self.get('assessment?name=%s' % LEGACY_REVIEW_UNIT_ID) assert_contains('First answer to Q1', response.body) assert_does_not_contain('Second answer to Q1', response.body) # The student checks the course page and sees that the progress # circle for this assignment has been filled, and that the 'Review # peer assignments' link is now available. response = actions.view_course(self) assert_contains( 'progress-completed-%s' % LEGACY_REVIEW_UNIT_ID, response.body) assert_does_not_contain( '<span> Review peer assignments </span>', response.body, collapse_whitespace=True) assert_contains( '<a href="reviewdashboard?unit=%s">' % LEGACY_REVIEW_UNIT_ID, response.body, collapse_whitespace=True) # The student should also be able to now view the review dashboard. response = self.get('reviewdashboard?unit=%s' % LEGACY_REVIEW_UNIT_ID) assert_contains('Assignments for your review', response.body) assert_contains('Review a new assignment', response.body) actions.logout() # Clean up app_context. sites.ApplicationContext.get_environ = get_environ_old def test_handling_of_fake_review_step_key(self): """Test that bad keys result in the appropriate responses.""" email = 'student1@google.com' name = 'Student 1' submission = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S1-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'is-S1', 'correct': True}, ]) payload = { 'answers': submission, 'assessment_type': LEGACY_REVIEW_UNIT_ID} actions.login(email) actions.register(self, name) actions.submit_assessment(self, LEGACY_REVIEW_UNIT_ID, payload) actions.view_review( self, LEGACY_REVIEW_UNIT_ID, 'Fake key', expected_status_code=404) actions.logout() def test_not_enough_assignments_to_allocate(self): """Test for the case when there are too few assignments in the pool.""" email = 'student1@google.com' name = 'Student 1' submission = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S1-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'is-S1', 'correct': True}, ]) payload = { 'answers': submission, 'assessment_type': LEGACY_REVIEW_UNIT_ID} actions.login(email) actions.register(self, name) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload) # The student goes to the review dashboard and requests an assignment # to review -- but there is nothing to review. response = actions.request_new_review( self, LEGACY_REVIEW_UNIT_ID, expected_status_code=200) assert_does_not_contain('Assignment to review', response.body) assert_contains('Sorry, there are no new submissions ', response.body) assert_contains('disabled="true"', response.body) actions.logout() def test_reviewer_cannot_impersonate_another_reviewer(self): """Test that one reviewer cannot use another's review step key.""" email1 = 'student1@google.com' name1 = 'Student 1' submission1 = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S1-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'is-S1', 'correct': True}, ]) payload1 = { 'answers': submission1, 'assessment_type': LEGACY_REVIEW_UNIT_ID} email2 = 'student2@google.com' name2 = 'Student 2' submission2 = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S2-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'not-S1', 'correct': True}, ]) payload2 = { 'answers': submission2, 'assessment_type': LEGACY_REVIEW_UNIT_ID} email3 = 'student3@google.com' name3 = 'Student 3' submission3 = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S3-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'not-S1', 'correct': True}, ]) payload3 = { 'answers': submission3, 'assessment_type': LEGACY_REVIEW_UNIT_ID} # Student 1 submits the assignment. actions.login(email1) actions.register(self, name1) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload1) actions.logout() # Student 2 logs in and submits the assignment. actions.login(email2) actions.register(self, name2) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload2) # Student 2 requests a review, and is given Student 1's assignment. response = actions.request_new_review(self, LEGACY_REVIEW_UNIT_ID) review_step_key_2_for_1 = get_review_step_key(response) assert_contains('S1-1', response.body) actions.logout() # Student 3 logs in, and submits the assignment. actions.login(email3) actions.register(self, name3) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload3) # Student 3 tries to view Student 1's assignment using Student 2's # review step key, but is not allowed to. response = actions.view_review( self, LEGACY_REVIEW_UNIT_ID, review_step_key_2_for_1, expected_status_code=404) # Student 3 logs out. actions.logout() def test_student_cannot_see_reviews_prematurely(self): """Test that students cannot see others' reviews prematurely.""" email = 'student1@google.com' name = 'Student 1' submission = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S1-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'is-S1', 'correct': True}, ]) payload = { 'answers': submission, 'assessment_type': LEGACY_REVIEW_UNIT_ID} actions.login(email) actions.register(self, name) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload) # Student 1 cannot see the reviews for his assignment yet, because he # has not submitted the two required reviews. response = self.get('assessment?name=%s' % LEGACY_REVIEW_UNIT_ID) assert_equals(response.status_int, 200) assert_contains('Due date for this assignment', response.body) assert_contains( 'After you have completed the required number of peer reviews', response.body) actions.logout() # pylint: disable=too-many-statements def test_draft_review_behaviour(self): """Test correctness of draft review visibility.""" email1 = 'student1@google.com' name1 = 'Student 1' submission1 = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S1-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'is-S1', 'correct': True}, ]) payload1 = { 'answers': submission1, 'assessment_type': LEGACY_REVIEW_UNIT_ID} email2 = 'student2@google.com' name2 = 'Student 2' submission2 = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S2-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'not-S1', 'correct': True}, ]) payload2 = { 'answers': submission2, 'assessment_type': LEGACY_REVIEW_UNIT_ID} email3 = 'student3@google.com' name3 = 'Student 3' submission3 = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S3-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'not-S1', 'correct': True}, ]) payload3 = { 'answers': submission3, 'assessment_type': LEGACY_REVIEW_UNIT_ID} # Student 1 submits the assignment. actions.login(email1) actions.register(self, name1) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload1) actions.logout() # Student 2 logs in and submits the assignment. actions.login(email2) actions.register(self, name2) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload2) # Student 2 requests a review, and is given Student 1's assignment. response = actions.request_new_review(self, LEGACY_REVIEW_UNIT_ID) review_step_key_2_for_1 = get_review_step_key(response) assert_contains('S1-1', response.body) # Student 2 saves her review as a draft. review_2_for_1_payload = get_review_payload( 'R2for1', is_draft=True) response = actions.submit_review( self, LEGACY_REVIEW_UNIT_ID, review_step_key_2_for_1, review_2_for_1_payload) assert_contains('Your review has been saved.', response.body) response = self.get('reviewdashboard?unit=%s' % LEGACY_REVIEW_UNIT_ID) assert_equals(response.status_int, 200) assert_contains('(Draft)', response.body) # Student 2's draft is still changeable. response = actions.view_review( self, LEGACY_REVIEW_UNIT_ID, review_step_key_2_for_1) assert_contains('Submit Review', response.body) response = actions.submit_review( self, LEGACY_REVIEW_UNIT_ID, review_step_key_2_for_1, review_2_for_1_payload) assert_contains('Your review has been saved.', response.body) # Student 2 logs out. actions.logout() # Student 3 submits the assignment. actions.login(email3) actions.register(self, name3) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload3) actions.logout() # Student 1 logs in and requests two assignments to review. actions.login(email1) response = self.get('/reviewdashboard?unit=%s' % LEGACY_REVIEW_UNIT_ID) response = actions.request_new_review(self, LEGACY_REVIEW_UNIT_ID) assert_contains('Assignment to review', response.body) assert_contains('not-S1', response.body) review_step_key_1_for_someone = get_review_step_key(response) response = actions.request_new_review(self, LEGACY_REVIEW_UNIT_ID) assert_contains('Assignment to review', response.body) assert_contains('not-S1', response.body) review_step_key_1_for_someone_else = get_review_step_key(response) response = self.get('reviewdashboard?unit=%s' % LEGACY_REVIEW_UNIT_ID) assert_equals(response.status_int, 200) assert_contains('disabled="true"', response.body) # Student 1 submits both reviews, fulfilling his quota. review_1_for_other_payload = get_review_payload('R1for') response = actions.submit_review( self, LEGACY_REVIEW_UNIT_ID, review_step_key_1_for_someone, review_1_for_other_payload) assert_contains( 'Your review has been submitted successfully', response.body) response = actions.submit_review( self, LEGACY_REVIEW_UNIT_ID, review_step_key_1_for_someone_else, review_1_for_other_payload) assert_contains( 'Your review has been submitted successfully', response.body) response = self.get('/reviewdashboard?unit=%s' % LEGACY_REVIEW_UNIT_ID) assert_contains('(Completed)', response.body) assert_does_not_contain('(Draft)', response.body) # Although Student 1 has submitted 2 reviews, he cannot view Student # 2's review because it is still in Draft status. response = self.get('assessment?name=%s' % LEGACY_REVIEW_UNIT_ID) assert_equals(response.status_int, 200) assert_contains( 'You have not received any peer reviews yet.', response.body) assert_does_not_contain('R2for1', response.body) # Student 1 logs out. actions.logout() # Student 2 submits her review for Student 1's assignment. actions.login(email2) response = self.get('review?unit=%s&key=%s' % ( LEGACY_REVIEW_UNIT_ID, review_step_key_2_for_1)) assert_does_not_contain('Submitted review', response.body) response = actions.submit_review( self, LEGACY_REVIEW_UNIT_ID, review_step_key_2_for_1, get_review_payload('R2for1')) assert_contains( 'Your review has been submitted successfully', response.body) # Her review is now read-only. response = self.get('review?unit=%s&key=%s' % ( LEGACY_REVIEW_UNIT_ID, review_step_key_2_for_1)) assert_contains('Submitted review', response.body) assert_contains('R2for1', response.body) # Student 2 logs out. actions.logout() # Now Student 1 can see the review he has received from Student 2. actions.login(email1) response = self.get('assessment?name=%s' % LEGACY_REVIEW_UNIT_ID) assert_equals(response.status_int, 200) assert_contains('R2for1', response.body) def test_independence_of_draft_reviews(self): """Test that draft reviews do not interfere with each other.""" email1 = 'student1@google.com' name1 = 'Student 1' submission1 = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S1-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'is-S1', 'correct': True}, ]) payload1 = { 'answers': submission1, 'assessment_type': LEGACY_REVIEW_UNIT_ID} email2 = 'student2@google.com' name2 = 'Student 2' submission2 = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S2-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'not-S1', 'correct': True}, ]) payload2 = { 'answers': submission2, 'assessment_type': LEGACY_REVIEW_UNIT_ID} email3 = 'student3@google.com' name3 = 'Student 3' submission3 = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S3-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'not-S1', 'correct': True}, ]) payload3 = { 'answers': submission3, 'assessment_type': LEGACY_REVIEW_UNIT_ID} # Student 1 submits the assignment. actions.login(email1) actions.register(self, name1) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload1) actions.logout() # Student 2 logs in and submits the assignment. actions.login(email2) actions.register(self, name2) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload2) actions.logout() # Student 3 logs in and submits the assignment. actions.login(email3) actions.register(self, name3) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload3) actions.logout() # Student 1 logs in and requests two assignments to review. actions.login(email1) response = self.get('/reviewdashboard?unit=%s' % LEGACY_REVIEW_UNIT_ID) response = actions.request_new_review(self, LEGACY_REVIEW_UNIT_ID) assert_equals(response.status_int, 200) assert_contains('Assignment to review', response.body) assert_contains('not-S1', response.body) review_step_key_1_for_someone = get_review_step_key(response) response = actions.request_new_review(self, LEGACY_REVIEW_UNIT_ID) assert_equals(response.status_int, 200) assert_contains('Assignment to review', response.body) assert_contains('not-S1', response.body) review_step_key_1_for_someone_else = get_review_step_key(response) self.assertNotEqual( review_step_key_1_for_someone, review_step_key_1_for_someone_else) # Student 1 submits two draft reviews. response = actions.submit_review( self, LEGACY_REVIEW_UNIT_ID, review_step_key_1_for_someone, get_review_payload('R1forFirst', is_draft=True)) assert_contains('Your review has been saved.', response.body) response = actions.submit_review( self, LEGACY_REVIEW_UNIT_ID, review_step_key_1_for_someone_else, get_review_payload('R1forSecond', is_draft=True)) assert_contains('Your review has been saved.', response.body) # The two draft reviews should still be different when subsequently # accessed. response = self.get('review?unit=%s&key=%s' % ( LEGACY_REVIEW_UNIT_ID, review_step_key_1_for_someone)) assert_contains('R1forFirst', response.body) response = self.get('review?unit=%s&key=%s' % ( LEGACY_REVIEW_UNIT_ID, review_step_key_1_for_someone_else)) assert_contains('R1forSecond', response.body) # Student 1 logs out. actions.logout() class PeerReviewDashboardAdminTest(actions.TestBase): """Test peer review dashboard from the Admin perspective.""" def test_add_reviewer(self): """Test that admin can add a reviewer, and cannot re-add reviewers.""" email = 'test_add_reviewer@google.com' name = 'Test Add Reviewer' submission = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'First answer to Q1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'First answer to Q3', 'correct': True}, ]) payload = { 'answers': submission, 'assessment_type': LEGACY_REVIEW_UNIT_ID} actions.login(email) actions.register(self, name) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload) # There is nothing to review on the review dashboard. response = actions.request_new_review( self, LEGACY_REVIEW_UNIT_ID, expected_status_code=200) assert_does_not_contain('Assignment to review', response.body) assert_contains('Sorry, there are no new submissions ', response.body) actions.logout() # The admin assigns the student to review his own work. actions.login(email, is_admin=True) response = actions.add_reviewer( self, LEGACY_REVIEW_UNIT_ID, email, email) assert_equals(response.status_int, 302) response = self.get(response.location) assert_does_not_contain( 'Error 412: The reviewer is already assigned', response.body) assert_contains('First answer to Q1', response.body) assert_contains( 'Review 1 from test_add_reviewer@google.com', response.body) # The admin repeats the 'add reviewer' action. This should fail. response = actions.add_reviewer( self, LEGACY_REVIEW_UNIT_ID, email, email) assert_equals(response.status_int, 302) response = self.get(response.location) assert_contains( 'Error 412: The reviewer is already assigned', response.body) class PeerReviewDashboardStudentTest(actions.TestBase): """Test peer review dashboard from the Student perspective.""" COURSE_NAME = 'back_button_top_level' STUDENT_EMAIL = 'foo@foo.com' def setUp(self): super(PeerReviewDashboardStudentTest, self).setUp() self.base = '/' + self.COURSE_NAME context = actions.simple_add_course( self.COURSE_NAME, 'admin@foo.com', 'Peer Back Button Child') self.course = courses.Course(None, context) self.assessment = self.course.add_assessment() self.assessment.title = 'Assessment' self.assessment.html_content = 'assessment content' self.assessment.workflow_yaml = ( '{grader: human,' 'matcher: peer,' 'review_due_date: \'2034-07-01 12:00\',' 'review_min_count: 1,' 'review_window_mins: 20,' 'submission_due_date: \'2034-07-01 12:00\'}') self.assessment.now_available = True self.course.save() actions.login(self.STUDENT_EMAIL) actions.register(self, self.STUDENT_EMAIL) config.Registry.test_overrides[ utils.CAN_PERSIST_ACTIVITY_EVENTS.name] = True actions.submit_assessment( self, self.assessment.unit_id, {'answers': '', 'score': 0, 'assessment_type': self.assessment.unit_id}, presubmit_checks=False ) def test_back_button_top_level_assessment(self): response = self.get('reviewdashboard?unit=%s' % str( self.assessment.unit_id)) back_button = self.parse_html_string(response.body).find( './/*[@href="assessment?name=%s"]' % self.assessment.unit_id) self.assertIsNotNone(back_button) self.assertEquals(back_button.text, 'Back to assignment') def test_back_button_child_assessment(self): parent_unit = self.course.add_unit() parent_unit.title = 'No Lessons' parent_unit.now_available = True parent_unit.pre_assessment = self.assessment.unit_id self.course.save() response = self.get('reviewdashboard?unit=%s' % str( self.assessment.unit_id)) back_button = self.parse_html_string(response.body).find( './/*[@href="unit?unit=%s&assessment=%s"]' % ( parent_unit.unit_id, self.assessment.unit_id)) self.assertIsNotNone(back_button) self.assertEquals(back_button.text, 'Back to assignment')
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests that walk through Course Builder pages.""" __author__ = 'Mike Gainer (mgainer@google.com)' import cgi import os import re import urllib from common import crypto from common import utils as common_utils from controllers import sites from controllers import utils from models import courses from models import models from models import transforms from modules.dashboard import course_settings from modules.dashboard import filer from modules.i18n_dashboard import i18n_dashboard from tests.functional import actions from tests.functional.actions import assert_contains from tests.functional.actions import assert_does_not_contain COURSE_NAME = 'admin_settings' COURSE_TITLE = 'Admin Settings' ADMIN_EMAIL = 'admin@foo.com' NAMESPACE = 'ns_%s' % COURSE_NAME BASE_URL = '/' + COURSE_NAME ADMIN_SETTINGS_URL = '/%s%s' % ( COURSE_NAME, course_settings.HtmlHookRESTHandler.URI) TEXT_ASSET_URL = '/%s%s' % ( COURSE_NAME, filer.TextAssetRESTHandler.URI) STUDENT_EMAIL = 'student@foo.com' SETTINGS_URL = '/%s/dashboard?action=settings&tab=admin_prefs' % COURSE_NAME class AdminSettingsTests(actions.TestBase): def setUp(self): super(AdminSettingsTests, self).setUp() actions.simple_add_course(COURSE_NAME, ADMIN_EMAIL, COURSE_TITLE) actions.login(ADMIN_EMAIL) def test_defaults(self): prefs = models.StudentPreferencesDAO.load_or_create() self.assertEquals(False, prefs.show_hooks) class WelcomePageTests(actions.TestBase): def setUp(self): super(WelcomePageTests, self).setUp() self.auto_deploy = sites.ApplicationContext.AUTO_DEPLOY_DEFAULT_COURSE sites.ApplicationContext.AUTO_DEPLOY_DEFAULT_COURSE = False def tearDown(self): sites.ApplicationContext.AUTO_DEPLOY_DEFAULT_COURSE = self.auto_deploy super(WelcomePageTests, self).tearDown() def test_welcome_page(self): actions.login(ADMIN_EMAIL, is_admin=True) response = self.get('/') self.assertEqual(response.status_int, 302) self.assertEqual( response.headers['location'], 'http://localhost/admin/welcome') response = self.get('/admin/welcome?action=welcome') assert_contains('Welcome to Course Builder', response.body) assert_contains('action="/admin/welcome"', response.body) assert_contains('Create Empty Course', response.body) assert_contains('Explore Sample Course', response.body) assert_contains('Configure Settings', response.body) def test_explore_sample_course(self): actions.login(ADMIN_EMAIL, is_admin=True) response = self.post( '/admin/welcome?action=explore_sample', params={'xsrf_token': crypto.XsrfTokenManager.create_xsrf_token( 'explore_sample')}) self.assertEqual(response.status_int, 302) assert_contains('/dashboard', response.headers['location']) response = self.get(response.headers['location']) assert_contains('Power Searching with Google', response.body) assert_does_not_contain('explore_sample', response.body) def test_create_new_course(self): actions.login(ADMIN_EMAIL, is_admin=True) response = self.post( '/admin/welcome?action=add_first_course', params={'xsrf_token': crypto.XsrfTokenManager.create_xsrf_token( 'add_first_course')}) self.assertEqual(response.status_int, 302) self.assertEqual( response.headers['location'], 'http://localhost/first/dashboard') response = self.get('/first/dashboard') assert_contains('My First Course', response.body) response = self.get('/admin/welcome?action=welcome') assert_does_not_contain('Create Empty Course', response.body) def test_configure_settings(self): actions.login(ADMIN_EMAIL, is_admin=True) response = self.post( '/admin/welcome?action=configure_settings', params={'xsrf_token': crypto.XsrfTokenManager.create_xsrf_token( 'configure_settings')}) self.assertEqual(302, response.status_int) self.assertEqual( response.headers['location'], 'http://localhost/admin/global') def test_explore_sample_course_not_idempotent(self): for uid in ['sample', 'sample_%s' % os.environ[ 'GCB_PRODUCT_VERSION'].replace('.', '_')]: self.test_explore_sample_course() response = self.get('/') self.assertEqual(response.status_int, 302) self.assertEqual( response.headers['location'], 'http://localhost/%s/course?use_last_location=true' % uid) self.test_create_new_course() def test_create_new_course_idempotent(self): self.test_create_new_course() self.test_create_new_course() self.test_explore_sample_course() response = self.get('/') self.assertEqual(response.status_int, 302) self.assertEqual( response.headers['location'], 'http://localhost/first/course?use_last_location=true') class HtmlHookTest(actions.TestBase): def setUp(self): super(HtmlHookTest, self).setUp() self.app_context = actions.simple_add_course(COURSE_NAME, ADMIN_EMAIL, COURSE_TITLE) self.course = courses.Course(None, self.app_context) actions.login(ADMIN_EMAIL, is_admin=True) self.xsrf_token = crypto.XsrfTokenManager.create_xsrf_token( course_settings.HtmlHookRESTHandler.XSRF_ACTION) def tearDown(self): settings = self.course.get_environ(self.app_context) settings.pop('foo', None) settings['html_hooks'].pop('foo', None) self.course.save_settings(settings) super(HtmlHookTest, self).tearDown() def test_hook_edit_button_presence(self): # Turn preference on; expect to see hook editor button with common_utils.Namespace(NAMESPACE): prefs = models.StudentPreferencesDAO.load_or_create() prefs.show_hooks = True models.StudentPreferencesDAO.save(prefs) response = self.get(BASE_URL) self.assertIn('gcb-html-hook-edit', response.body) # Turn preference off; expect editor button not present. with common_utils.Namespace(NAMESPACE): prefs = models.StudentPreferencesDAO.load_or_create() prefs.show_hooks = False models.StudentPreferencesDAO.save(prefs) response = self.get(BASE_URL) self.assertNotIn('gcb-html-hook-edit', response.body) def test_non_admin_permissions_failures(self): actions.login(STUDENT_EMAIL) student_xsrf_token = crypto.XsrfTokenManager.create_xsrf_token( course_settings.HtmlHookRESTHandler.XSRF_ACTION) response = self.get(ADMIN_SETTINGS_URL) self.assertEquals(200, response.status_int) payload = transforms.loads(response.body) self.assertEquals(401, payload['status']) self.assertEquals('Access denied.', payload['message']) response = self.put(ADMIN_SETTINGS_URL, {'request': transforms.dumps({ 'key': 'base:after_body_tag_begins', 'xsrf_token': cgi.escape(student_xsrf_token), 'payload': '{}'})}) payload = transforms.loads(response.body) self.assertEquals(401, payload['status']) self.assertEquals('Access denied.', payload['message']) response = self.delete(ADMIN_SETTINGS_URL + '?xsrf_token=' + cgi.escape(student_xsrf_token)) self.assertEquals(200, response.status_int) payload = transforms.loads(response.body) self.assertEquals(401, payload['status']) self.assertEquals('Access denied.', payload['message']) def test_malformed_requests(self): response = self.put(ADMIN_SETTINGS_URL, {}) payload = transforms.loads(response.body) self.assertEquals(400, payload['status']) self.assertEquals('Missing "request" parameter.', payload['message']) response = self.put(ADMIN_SETTINGS_URL, {'request': 'asdfasdf'}) payload = transforms.loads(response.body) self.assertEquals(400, payload['status']) self.assertEquals('Malformed "request" parameter.', payload['message']) response = self.put(ADMIN_SETTINGS_URL, {'request': transforms.dumps({ 'xsrf_token': cgi.escape(self.xsrf_token)})}) payload = transforms.loads(response.body) self.assertEquals(400, payload['status']) self.assertEquals('Request missing "key" parameter.', payload['message']) response = self.put(ADMIN_SETTINGS_URL, {'request': transforms.dumps({ 'xsrf_token': cgi.escape(self.xsrf_token), 'key': 'base:after_body_tag_begins'})}) payload = transforms.loads(response.body) self.assertEquals(400, payload['status']) self.assertEquals('Request missing "payload" parameter.', payload['message']) response = self.put(ADMIN_SETTINGS_URL, {'request': transforms.dumps({ 'xsrf_token': cgi.escape(self.xsrf_token), 'key': 'base:after_body_tag_begins', 'payload': 'asdfsdfasdf'})}) payload = transforms.loads(response.body) self.assertEquals(400, payload['status']) self.assertEquals('Malformed "payload" parameter.', payload['message']) response = self.put(ADMIN_SETTINGS_URL, {'request': transforms.dumps({ 'xsrf_token': cgi.escape(self.xsrf_token), 'key': 'base:after_body_tag_begins', 'payload': '{}'})}) payload = transforms.loads(response.body) self.assertEquals(400, payload['status']) self.assertEquals('Payload missing "hook_content" parameter.', payload['message']) def test_get_unknown_hook_content(self): # Should be safe (but unhelpful) to ask for no hook. response = transforms.loads(self.get(ADMIN_SETTINGS_URL).body) payload = transforms.loads(response['payload']) self.assertIsNone(payload['hook_content']) def test_get_defaulted_hook_content(self): url = '%s?key=%s' % ( ADMIN_SETTINGS_URL, cgi.escape('base.after_body_tag_begins')) response = transforms.loads(self.get(url).body) self.assertEquals(200, response['status']) self.assertEquals('Success.', response['message']) payload = transforms.loads(response['payload']) self.assertEquals('<!-- base.after_body_tag_begins -->', payload['hook_content']) def test_page_has_defaulted_hook_content(self): response = self.get(BASE_URL) self.assertIn('<!-- base.after_body_tag_begins -->', response.body) def test_set_hook_content(self): html_text = '<table><tbody><tr><th>;&lt;&gt;</th></tr></tbody></table>' response = self.put(ADMIN_SETTINGS_URL, {'request': transforms.dumps({ 'xsrf_token': cgi.escape(self.xsrf_token), 'key': 'base.after_body_tag_begins', 'payload': transforms.dumps( {'hook_content': html_text})})}) self.assertEquals(200, response.status_int) response = transforms.loads(response.body) self.assertEquals(200, response['status']) self.assertEquals('Saved.', response['message']) # And verify that the changed text appears on course pages. # NOTE that text is as-is; no escaping of special HTML # characters should have been done. response = self.get(BASE_URL) self.assertIn(html_text, response.body) def test_delete_default_content_ineffective(self): response = self.get(BASE_URL) self.assertIn('<!-- base.after_body_tag_begins -->', response.body) url = '%s?key=%s&xsrf_token=%s' % ( ADMIN_SETTINGS_URL, cgi.escape('base.after_body_tag_begins'), cgi.escape(self.xsrf_token)) response = transforms.loads(self.delete(url).body) self.assertEquals(200, response['status']) self.assertEquals('Deleted.', response['message']) response = self.get(BASE_URL) self.assertIn('<!-- base.after_body_tag_begins -->', response.body) def test_manipulate_non_default_item(self): html_text = '<table><tbody><tr><th>;&lt;&gt;</th></tr></tbody></table>' new_hook_name = 'html.some_new_hook' # Verify that content prior to setting is blank. url = '%s?key=%s&xsrf_token=%s' % ( ADMIN_SETTINGS_URL, cgi.escape(new_hook_name), cgi.escape(self.xsrf_token)) response = transforms.loads(self.get(url).body) payload = transforms.loads(response['payload']) self.assertIsNone(payload['hook_content']) # Set the content. response = self.put(ADMIN_SETTINGS_URL, {'request': transforms.dumps({ 'xsrf_token': cgi.escape(self.xsrf_token), 'key': new_hook_name, 'payload': transforms.dumps( {'hook_content': html_text})})}) self.assertEquals(200, response.status_int) response = transforms.loads(response.body) self.assertEquals(200, response['status']) self.assertEquals('Saved.', response['message']) # Verify that content after setting is as expected url = '%s?key=%s&xsrf_token=%s' % ( ADMIN_SETTINGS_URL, cgi.escape(new_hook_name), cgi.escape(self.xsrf_token)) response = transforms.loads(self.get(url).body) payload = transforms.loads(response['payload']) self.assertEquals(html_text, payload['hook_content']) # Delete the content. response = transforms.loads(self.delete(url).body) self.assertEquals(200, response['status']) self.assertEquals('Deleted.', response['message']) # Verify that content after setting is None. url = '%s?key=%s&xsrf_token=%s' % ( ADMIN_SETTINGS_URL, cgi.escape(new_hook_name), cgi.escape(self.xsrf_token)) response = transforms.loads(self.get(url).body) payload = transforms.loads(response['payload']) self.assertIsNone(payload['hook_content']) def test_add_new_hook_to_page(self): hook_name = 'html.my_new_hook' html_text = '<table><tbody><tr><th>;&lt;&gt;</th></tr></tbody></table>' key = 'views/base.html' url = '%s?key=%s' % ( TEXT_ASSET_URL, cgi.escape(key)) # Get base page template. response = transforms.loads(self.get(url).body) xsrf_token = response['xsrf_token'] payload = transforms.loads(response['payload']) contents = payload['contents'] # Add hook specification to page content. contents = contents.replace( '<body data-gcb-page-locale="{{ page_locale }}">', '<body data-gcb-page-locale="{{ page_locale }}">\n' + '{{ html_hooks.insert(\'%s\') | safe }}' % hook_name) self.put(TEXT_ASSET_URL, {'request': transforms.dumps({ 'xsrf_token': cgi.escape(xsrf_token), 'key': key, 'payload': transforms.dumps({'contents': contents})})}) # Verify that new hook appears on page. response = self.get(BASE_URL) self.assertIn('id="%s"' % re.sub('[^a-zA-Z-]', '-', hook_name), response.body) # Verify that modified hook content appears on page response = self.put(ADMIN_SETTINGS_URL, {'request': transforms.dumps({ 'xsrf_token': cgi.escape(self.xsrf_token), 'key': hook_name, 'payload': transforms.dumps( {'hook_content': html_text})})}) response = self.get(BASE_URL) self.assertIn(html_text, response.body) def test_student_admin_hook_visibility(self): actions.login(STUDENT_EMAIL, is_admin=False) with common_utils.Namespace(NAMESPACE): prefs = models.StudentPreferencesDAO.load_or_create() prefs.show_hooks = True models.StudentPreferencesDAO.save(prefs) response = self.get(BASE_URL) self.assertNotIn('gcb-html-hook-edit', response.body) actions.login(ADMIN_EMAIL, is_admin=True) with common_utils.Namespace(NAMESPACE): prefs = models.StudentPreferencesDAO.load_or_create() prefs.show_hooks = True models.StudentPreferencesDAO.save(prefs) response = self.get(BASE_URL) self.assertIn('gcb-html-hook-edit', response.body) def test_hook_i18n(self): actions.update_course_config( COURSE_NAME, { 'html_hooks': {'base': {'after_body_tag_begins': 'foozle'}}, 'extra_locales': [ {'locale': 'de', 'availability': 'available'}, ] }) hook_bundle = { 'content': { 'type': 'html', 'source_value': '', 'data': [{ 'source_value': 'foozle', 'target_value': 'FUZEL', }], } } hook_key = i18n_dashboard.ResourceBundleKey( utils.ResourceHtmlHook.TYPE, 'base.after_body_tag_begins', 'de') with common_utils.Namespace(NAMESPACE): i18n_dashboard.ResourceBundleDAO.save( i18n_dashboard.ResourceBundleDTO(str(hook_key), hook_bundle)) # Verify non-translated version. response = self.get(BASE_URL) dom = self.parse_html_string(response.body) html_hook = dom.find('.//div[@id="base-after-body-tag-begins"]') self.assertEquals('foozle', html_hook.text) # Set preference to translated language, and check that that's there. with common_utils.Namespace(NAMESPACE): prefs = models.StudentPreferencesDAO.load_or_create() prefs.locale = 'de' models.StudentPreferencesDAO.save(prefs) response = self.get(BASE_URL) dom = self.parse_html_string(response.body) html_hook = dom.find('.//div[@id="base-after-body-tag-begins"]') self.assertEquals('FUZEL', html_hook.text) # With no translation present, but preference set to foreign language, # verify that we fall back to the original language. # Remove translation bundle, and clear cache. with common_utils.Namespace(NAMESPACE): i18n_dashboard.ResourceBundleDAO.delete( i18n_dashboard.ResourceBundleDTO(str(hook_key), hook_bundle)) i18n_dashboard.ProcessScopedResourceBundleCache.instance().clear() response = self.get(BASE_URL) dom = self.parse_html_string(response.body) html_hook = dom.find('.//div[@id="base-after-body-tag-begins"]') self.assertEquals('foozle', html_hook.text) def test_hook_content_found_in_old_location(self): actions.update_course_config(COURSE_NAME, {'foo': {'bar': 'baz'}}) self.assertEquals( 'baz', utils.HtmlHooks.get_content(self.course, 'foo.bar')) def test_insert_on_page_and_hook_content_found_using_old_separator(self): settings = self.course.get_environ(self.app_context) settings['html_hooks']['foo'] = {'bar': 'baz'} self.course.save_settings(settings) hooks = utils.HtmlHooks(self.course) content = hooks.insert('foo:bar') self.assertEquals('<div class="gcb-html-hook" id="foo-bar">baz</div>', str(content)) def test_hook_content_new_location_overrides_old_location(self): actions.update_course_config(COURSE_NAME, {'html_hooks': {'foo': {'bar': 'zab'}}}) actions.update_course_config(COURSE_NAME, {'foo': {'bar': 'baz'}}) self.assertEquals( 'zab', utils.HtmlHooks.get_content(self.course, 'foo.bar')) def test_hook_rest_edit_removes_from_old_location(self): actions.update_course_config(COURSE_NAME, {'html_hooks': {'foo': {'bar': 'zab'}}}) actions.update_course_config(COURSE_NAME, {'foo': {'bar': 'baz'}}) response = self.put(ADMIN_SETTINGS_URL, {'request': transforms.dumps({ 'xsrf_token': cgi.escape(self.xsrf_token), 'key': 'foo.bar', 'payload': transforms.dumps({'hook_content': 'BAZ'})})}) env = self.course.get_environ(self.app_context) self.assertNotIn('bar', env['foo']) self.assertEquals('BAZ', env['html_hooks']['foo']['bar']) def test_hook_rest_delete_removes_from_old_and_new_location(self): actions.update_course_config(COURSE_NAME, {'html_hooks': {'foo': {'bar': 'zab'}}}) actions.update_course_config(COURSE_NAME, {'foo': {'bar': 'baz'}}) url = '%s?key=%s&xsrf_token=%s' % ( ADMIN_SETTINGS_URL, cgi.escape('foo.bar'), cgi.escape(self.xsrf_token)) self.delete(url) env = self.course.get_environ(self.app_context) self.assertNotIn('bar', env['foo']) self.assertNotIn('bar', env['html_hooks']['foo']) class JinjaContextTest(actions.TestBase): def setUp(self): super(JinjaContextTest, self).setUp() actions.simple_add_course(COURSE_NAME, ADMIN_EMAIL, COURSE_TITLE) actions.login(ADMIN_EMAIL, is_admin=True) def _get_jinja_context_text(self, response): root = self.parse_html_string(response.text) div = root.find('body/div[last()]') return ''.join(div.itertext()) def test_show_jina_context_presence(self): # Turn preference on; expect to see context dump. with common_utils.Namespace(NAMESPACE): prefs = models.StudentPreferencesDAO.load_or_create() prefs.show_jinja_context = True models.StudentPreferencesDAO.save(prefs) self.assertIn('is_read_write_course:', self._get_jinja_context_text(self.get(BASE_URL))) # Turn preference off; expect context dump not present. with common_utils.Namespace(NAMESPACE): prefs = models.StudentPreferencesDAO.load_or_create() prefs.show_jinja_context = False models.StudentPreferencesDAO.save(prefs) self.assertNotIn('is_read_write_course:', self._get_jinja_context_text(self.get(BASE_URL))) def test_student_jinja_context_visibility(self): actions.login(STUDENT_EMAIL, is_admin=False) with common_utils.Namespace(NAMESPACE): prefs = models.StudentPreferencesDAO.load_or_create() prefs.show_jinja_context = True models.StudentPreferencesDAO.save(prefs) self.assertNotIn('is_read_write_course:', self._get_jinja_context_text(self.get(BASE_URL))) class ExitUrlTest(actions.TestBase): def setUp(self): super(ExitUrlTest, self).setUp() actions.simple_add_course(COURSE_NAME, ADMIN_EMAIL, COURSE_TITLE) actions.login(ADMIN_EMAIL, is_admin=True) def test_exit_url(self): base_url = '/%s/dashboard?action=settings&tab=data_pump' % COURSE_NAME url = base_url + '&' + urllib.urlencode({ 'exit_url': 'dashboard?%s' % urllib.urlencode({ 'action': 'analytics', 'tab': 'data_pump'})}) response = self.get(url) self.assertIn( 'cb_global.exit_url = \'dashboard?action=analytics' '\\u0026tab=data_pump\'', response.body)
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for modules/data_source_providers/.""" __author__ = 'Mike Gainer (mgainer@google.com)' import datetime import actions from common import utils from controllers import sites from models import courses from models import models from models import transforms from tests.functional import actions class CourseElementsTest(actions.TestBase): def setUp(self): super(CourseElementsTest, self).setUp() sites.setup_courses('course:/test::ns_test, course:/:/') self._course = courses.Course( None, app_context=sites.get_all_courses()[0]) actions.login('admin@google.com', is_admin=True) def test_assessments_schema(self): response = transforms.loads(self.get( '/test/rest/data/assessments/items').body) self.assertIn('unit_id', response['schema']) self.assertIn('title', response['schema']) self.assertIn('weight', response['schema']) self.assertIn('html_check_answers', response['schema']) self.assertIn('props', response['schema']) def test_units_schema(self): response = transforms.loads(self.get( '/test/rest/data/units/items').body) self.assertIn('unit_id', response['schema']) self.assertIn('title', response['schema']) self.assertIn('props', response['schema']) def test_lessons_schema(self): response = transforms.loads(self.get( '/test/rest/data/lessons/items').body) self.assertIn('lesson_id', response['schema']) self.assertIn('unit_id', response['schema']) self.assertIn('title', response['schema']) self.assertIn('scored', response['schema']) self.assertIn('has_activity', response['schema']) self.assertIn('activity_title', response['schema']) def test_no_assessments_in_course(self): response = transforms.loads(self.get( '/test/rest/data/assessments/items').body) self.assertListEqual([], response['data']) def test_no_units_in_course(self): response = transforms.loads(self.get( '/test/rest/data/units/items').body) self.assertListEqual([], response['data']) def test_no_lessons_in_course(self): response = transforms.loads(self.get( '/test/rest/data/lessons/items').body) self.assertListEqual([], response['data']) def test_one_assessment_in_course(self): title = 'Plugh' weight = 123 html_check_answers = True properties = {'a': 456, 'b': 789} assessment1 = self._course.add_assessment() assessment1.title = title assessment1.weight = weight assessment1.html_check_answers = html_check_answers assessment1.properties = properties self._course.save() response = transforms.loads(self.get( '/test/rest/data/assessments/items').body) self.assertEquals(1, len(response['data'])) self.assertEquals(title, response['data'][0]['title']) self.assertEquals(weight, response['data'][0]['weight']) self.assertEquals(html_check_answers, response['data'][0]['html_check_answers']) self.assertEquals(transforms.dumps(properties), response['data'][0]['props']) def test_one_unit_in_course(self): title = 'Plugh' properties = {'a': 456, 'b': 789} unit1 = self._course.add_unit() unit1.title = title unit1.properties = properties self._course.save() response = transforms.loads(self.get( '/test/rest/data/units/items').body) self.assertEquals(1, len(response['data'])) self.assertEquals(title, response['data'][0]['title']) self.assertEquals(properties, response['data'][0]['props']) def test_one_lesson_in_course(self): title = 'Plover' scored = True has_activity = True activity_title = 'Xyzzy' unit1 = self._course.add_unit() lesson1 = self._course.add_lesson(unit1) lesson1.title = title lesson1.scored = scored lesson1.has_activity = has_activity lesson1.activity_title = activity_title self._course.save() response = transforms.loads(self.get( '/test/rest/data/lessons/items').body) self.assertEquals(1, len(response['data'])) self.assertEquals(str(unit1.unit_id), response['data'][0]['unit_id']) self.assertEquals(title, response['data'][0]['title']) self.assertEquals(scored, response['data'][0]['scored']) self.assertEquals(has_activity, response['data'][0]['has_activity']) self.assertEquals(activity_title, response['data'][0]['activity_title']) def test_unit_and_assessment(self): self._course.add_assessment() self._course.add_unit() self._course.save() response = transforms.loads(self.get( '/test/rest/data/units/items').body) self.assertEquals(1, len(response['data'])) self.assertEquals('New Unit', response['data'][0]['title']) response = transforms.loads(self.get( '/test/rest/data/assessments/items').body) self.assertEquals(1, len(response['data'])) self.assertEquals('New Assessment', response['data'][0]['title']) def test_stable_ids(self): self._course.add_assessment() unit2 = self._course.add_unit() self._course.add_assessment() self._course.add_unit() self._course.add_assessment() self._course.add_unit() self._course.add_assessment() self._course.add_unit() self._course.add_assessment() self._course.add_unit() self._course.add_assessment() self._course.add_assessment() self._course.add_assessment() self._course.add_unit() self._course.save() response = transforms.loads(self.get( '/test/rest/data/units/items').body) self.assertListEqual(['2', '4', '6', '8', '10', '14'], [u['unit_id'] for u in response['data']]) self._course.delete_unit(unit2) self._course.save() response = transforms.loads(self.get( '/test/rest/data/units/items').body) self.assertListEqual(['4', '6', '8', '10', '14'], [u['unit_id'] for u in response['data']]) class StudentsTest(actions.TestBase): def setUp(self): super(StudentsTest, self).setUp() sites.setup_courses('course:/test::ns_test, course:/:/') self._course = courses.Course( None, app_context=sites.get_all_courses()[0]) actions.login('admin@google.com', is_admin=True) def test_students_schema(self): response = transforms.loads(self.get( '/test/rest/data/students/items').body) self.assertNotIn('name', response['schema']) self.assertNotIn('additional_fields', response['schema']) self.assertIn('enrolled_on', response['schema']) self.assertIn('user_id', response['schema']) self.assertIn('is_enrolled', response['schema']) def test_no_students(self): response = transforms.loads(self.get( '/test/rest/data/students/items').body) self.assertListEqual([], response['data']) def test_one_student(self): expected_enrolled_on = datetime.datetime.utcnow() user_id = '123456' is_enrolled = True with utils.Namespace('ns_test'): models.Student(user_id=user_id, is_enrolled=is_enrolled).put() response = transforms.loads(self.get( '/test/rest/data/students/items').body) self.assertEquals('None', response['data'][0]['user_id']) self.assertEquals(is_enrolled, response['data'][0]['is_enrolled']) # expected/actual enrolled_on timestamp may be _slightly_ off # since it's automatically set on creation by DB internals. # Allow for this. actual_enrolled_on = datetime.datetime.strptime( response['data'][0]['enrolled_on'], transforms.ISO_8601_DATETIME_FORMAT) self.assertAlmostEqual( 0, abs((expected_enrolled_on - actual_enrolled_on).total_seconds()), 1) def test_modified_blacklist_schema(self): save_blacklist = models.Student._PROPERTY_EXPORT_BLACKLIST models.Student._PROPERTY_EXPORT_BLACKLIST = [ 'name', 'additional_fields.age', 'additional_fields.gender', ] response = transforms.loads(self.get( '/test/rest/data/students/items').body) self.assertNotIn('name', response['schema']) self.assertIn('enrolled_on', response['schema']) self.assertIn('user_id', response['schema']) self.assertIn('is_enrolled', response['schema']) self.assertIn('additional_fields', response['schema']) models.Student._PROPERTY_EXPORT_BLACKLIST = save_blacklist def test_modified_blacklist_contents(self): save_blacklist = models.Student._PROPERTY_EXPORT_BLACKLIST models.Student._PROPERTY_EXPORT_BLACKLIST = [ 'name', 'additional_fields.age', 'additional_fields.gender', ] blacklisted = [ {'name': 'age', 'value': '22'}, {'name': 'gender', 'value': 'female'}, ] permitted = [ {'name': 'goal', 'value': 'complete_course'}, {'name': 'timezone', 'value': 'America/Los_Angeles'}, ] additional_fields = transforms.dumps( [[x['name'], x['value']] for x in blacklisted + permitted]) with utils.Namespace('ns_test'): models.Student( user_id='123456', additional_fields=additional_fields).put() response = transforms.loads(self.get( '/test/rest/data/students/items').body) self.assertEquals(permitted, response['data'][0]['additional_fields']) models.Student._PROPERTY_EXPORT_BLACKLIST = save_blacklist class StudentScoresTest(actions.TestBase): def setUp(self): super(StudentScoresTest, self).setUp() sites.setup_courses('course:/test::ns_test, course:/:/') self._course = courses.Course( None, app_context=sites.get_all_courses()[0]) actions.login('admin@google.com', is_admin=True) def test_students_schema(self): response = transforms.loads(self.get( '/test/rest/data/assessment_scores/items').body) self.assertIn('user_id', response['schema']) self.assertIn('id', response['schema']) self.assertIn('title', response['schema']) self.assertIn('score', response['schema']) self.assertIn('weight', response['schema']) self.assertIn('completed', response['schema']) self.assertIn('human_graded', response['schema']) def test_no_students(self): response = transforms.loads(self.get( '/test/rest/data/assessment_scores/items').body) self.assertListEqual([], response['data']) def test_one_student_no_scores(self): with utils.Namespace('ns_test'): models.Student(user_id='123456').put() response = transforms.loads(self.get( '/test/rest/data/assessment_scores/items').body) self.assertListEqual([], response['data']) def _score_data(self, unit_id, title, weight, score, assessment_rank): return { 'id': unit_id, 'title': title, 'weight': weight, 'score': score, 'user_id': 'None', 'attempted': True, 'completed': False, 'human_graded': False, 'user_rank': 0, 'assessment_rank': assessment_rank, } def test_one_student_one_score(self): scores = '{"1": 20}' with utils.Namespace('ns_test'): self._course.add_assessment() self._course.save() models.Student(user_id='123456', scores=scores).put() response = transforms.loads(self.get( '/test/rest/data/assessment_scores/items').body) self.assertItemsEqual( [self._score_data('1', 'New Assessment', 1, 20, 0)], response['data']) def test_two_students_two_scores_each(self): s1_scores = '{"1": 20, "2": 30}' s2_scores = '{"1": 10, "2": 40}' with utils.Namespace('ns_test'): a1 = self._course.add_assessment() a1.title = 'A1' a1.weight = 1 a2 = self._course.add_assessment() a2.title = 'A2' a2.weight = 2 self._course.save() models.Student(user_id='1', scores=s1_scores).put() models.Student(user_id='2', scores=s2_scores).put() response = transforms.loads(self.get( '/test/rest/data/assessment_scores/items').body) self.assertItemsEqual([self._score_data('1', 'A1', 1, 20, 0), self._score_data('1', 'A1', 1, 10, 0), self._score_data('2', 'A2', 2, 30, 1), self._score_data('2', 'A2', 2, 40, 1)], response['data']) def test_two_students_partial_scores(self): s1_scores = '{"1": 20}' s2_scores = '{"1": 10, "2": 40}' with utils.Namespace('ns_test'): a1 = self._course.add_assessment() a1.title = 'A1' a1.weight = 1 a2 = self._course.add_assessment() a2.title = 'A2' a2.weight = 2 self._course.save() models.Student(user_id='1', scores=s1_scores).put() models.Student(user_id='2', scores=s2_scores).put() response = transforms.loads(self.get( '/test/rest/data/assessment_scores/items').body) self.assertItemsEqual([self._score_data('1', 'A1', 1, 20, 0), self._score_data('1', 'A1', 1, 10, 0), self._score_data('2', 'A2', 2, 40, 1)], response['data'])
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests that walk through Course Builder pages.""" __author__ = 'Mike Gainer (mgainer@google.com)' from common import crypto from common import utils as common_utils from controllers import utils from models import config from models import courses from models import models from models import transforms from modules.manual_progress import manual_progress from tests.functional import actions COURSE_NAME = 'tracks_test' COURSE_TITLE = 'Tracks Test' NAMESPACE = 'ns_%s' % COURSE_NAME ADMIN_EMAIL = 'admin@foo.com' REGISTERED_STUDENT_EMAIL = 'foo@bar.com' REGISTERED_STUDENT_NAME = 'John Smith' UNREGISTERED_STUDENT_EMAIL = 'bar@bar.com' COURSE_OVERVIEW_URL = '/%s/course' % COURSE_NAME STUDENT_LABELS_URL = '/%s/rest/student/labels' % COURSE_NAME STUDENT_SETTINGS_URL = '/%s/student/home' % COURSE_NAME LESSON_PROGRESS_URL = '/%s%s' % (COURSE_NAME, manual_progress.LessonProgressRESTHandler.URI) UNIT_PROGRESS_URL = '/%s%s' % (COURSE_NAME, manual_progress.UnitProgressRESTHandler.URI) COURSE_PROGRESS_URL = '/%s%s' % (COURSE_NAME, manual_progress.CourseProgressRESTHandler.URI) ASSESSMENT_COMPLETION_URL = '/%s/answer' % COURSE_NAME class ManualProgressTest(actions.TestBase): def setUp(self): super(ManualProgressTest, self).setUp() # Add a course that will show up. context = actions.simple_add_course(COURSE_NAME, ADMIN_EMAIL, COURSE_TITLE) # Register a student for that course. actions.login(REGISTERED_STUDENT_EMAIL) actions.register(self, REGISTERED_STUDENT_NAME, COURSE_NAME) # Add content to course self._course = courses.Course(None, context) self._unit_one = self._course.add_unit() self._unit_one.title = 'Unit Labels: Foo' self._unit_one.now_available = True self._lesson_1_1 = self._course.add_lesson(self._unit_one) self._lesson_1_1.title = 'Unit One, Lesson One' self._lesson_1_1.now_available = True self._lesson_1_1.manual_progress = True self._lesson_1_2 = self._course.add_lesson(self._unit_one) self._lesson_1_2.title = 'Unit One, Lesson Two' self._lesson_1_2.now_available = True self._lesson_1_2.manual_progress = True self._unit_two = self._course.add_unit() self._unit_two.title = 'Unit Labels: Foo' self._unit_two.now_available = True self._unit_two.manual_progress = True self._lesson_2_1 = self._course.add_lesson(self._unit_two) self._lesson_2_1.title = 'Unit Two, Lesson One' self._lesson_2_1.now_available = True self._lesson_2_2 = self._course.add_lesson(self._unit_two) self._lesson_2_2.title = 'Unit Two, Lesson Two' self._lesson_2_2.now_available = True self._sub_assessment = self._course.add_assessment() self._sub_assessment.now_available = True self._toplevel_assessment = self._course.add_assessment() self._sub_assessment.now_available = True self._unit_three = self._course.add_unit() self._unit_three.pre_assessment = self._sub_assessment.unit_id self._course.save() with common_utils.Namespace(NAMESPACE): self.foo_id = models.LabelDAO.save(models.LabelDTO( None, {'title': 'Foo', 'descripton': 'foo', 'type': models.LabelDTO.LABEL_TYPE_COURSE_TRACK})) self.bar_id = models.LabelDAO.save(models.LabelDTO( None, {'title': 'Bar', 'descripton': 'bar', 'type': models.LabelDTO.LABEL_TYPE_COURSE_TRACK})) config.Registry.test_overrides[ utils.CAN_PERSIST_ACTIVITY_EVENTS.name] = True def _expect_response(self, response, status, message, html_status=200): content = transforms.loads(response.body) self.assertEquals(html_status, response.status_int) self.assertEquals(status, content['status']) self.assertEquals(message, content['message']) def _expect_payload(self, response, status): content = transforms.loads(response.body) self.assertEquals(200, response.status_int) self.assertEquals(200, content['status']) self.assertEquals('OK.', content['message']) if status: payload = transforms.loads(content['payload']) self.assertEquals(status, payload['status']) def _assert_progress_state(self, expected, lesson_title, response): title_index = response.body.index(lesson_title) alt_marker = 'alt="' state_start = response.body.rfind( alt_marker, 0, title_index) + len(alt_marker) state_end = response.body.find('"', state_start) self.assertEquals(expected, response.body[state_start:state_end]) def _get(self, url, unit_id): return self.get( url + '?xsrf_token=%s' % crypto.XsrfTokenManager.create_xsrf_token( manual_progress.XSRF_ACTION) + '&key=%s' % unit_id) def _get_course(self): return self._get(COURSE_PROGRESS_URL, 'course') def _get_unit(self, unit_id): return self._get(UNIT_PROGRESS_URL, unit_id) def _get_lesson(self, lesson_id): return self._get(LESSON_PROGRESS_URL, lesson_id) def _post(self, url, key): params = { 'xsrf_token': crypto.XsrfTokenManager.create_xsrf_token( manual_progress.XSRF_ACTION), 'key': key, } return self.post(url, params) def _post_course(self): return self._post(COURSE_PROGRESS_URL, 'course') def _post_unit(self, unit_id): return self._post(UNIT_PROGRESS_URL, str(unit_id)) def _post_lesson(self, lesson_id): return self._post(LESSON_PROGRESS_URL, str(lesson_id)) def _post_assessment(self, assessment_id): self.post(ASSESSMENT_COMPLETION_URL, { 'assessment_type': str(assessment_id), 'score': '0', 'xsrf_token': crypto.XsrfTokenManager.create_xsrf_token( 'assessment-post')}) def test_not_logged_in(self): actions.logout() response = self.get(UNIT_PROGRESS_URL + '?key=%s' % self._unit_one.unit_id) self._expect_response( response, 403, 'Bad XSRF token. Please reload the page and try again') def test_not_registered(self): actions.logout() actions.login(UNREGISTERED_STUDENT_EMAIL) xsrf_token = crypto.XsrfTokenManager.create_xsrf_token( manual_progress.XSRF_ACTION) response = self.get(UNIT_PROGRESS_URL + '?key=%s' % self._unit_one.unit_id + '&xsrf_token=%s' % xsrf_token) self._expect_response(response, 401, 'Access Denied.') def test_no_key(self): xsrf_token = crypto.XsrfTokenManager.create_xsrf_token( manual_progress.XSRF_ACTION) response = self.get(UNIT_PROGRESS_URL + '?xsrf_token=%s' % xsrf_token) self._expect_response(response, 400, 'Bad Request.') def test_no_such_course(self): url = '/no_such_course%s?key=%s' % ( manual_progress.UnitProgressRESTHandler.URI, self._unit_one.unit_id) response = self.get(url, expect_errors=True) self.assertEquals(404, response.status_int) def test_no_xsrf_token(self): response = self.get(UNIT_PROGRESS_URL + '?key=monkeyshines') self._expect_response( response, 403, 'Bad XSRF token. Please reload the page and try again') def test_no_such_unit(self): response = self._get_unit('monkeyshines') self._expect_response(response, 400, 'Bad Request.') def test_no_such_lesson(self): response = self._get_lesson('monkeyshines') self._expect_response(response, 400, 'Bad Request.') def test_unit_manual_progress_not_allowed(self): response = self._post_unit(self._unit_one.unit_id) self._expect_response(response, 401, 'Access Denied.') def test_lesson_manual_progress_not_allowed(self): response = self._post_lesson(self._lesson_2_2.lesson_id) self._expect_response(response, 401, 'Access Denied.') def test_uncompleted_unit_status(self): response = self._get_unit(self._unit_one.unit_id) self._expect_payload(response, None) def test_uncompleted_lesson_status(self): response = self._get_lesson(self._lesson_1_1.lesson_id) self._expect_payload(response, None) def test_uncompleted_course_status(self): response = self._get_course() self._expect_payload(response, 0) def test_manual_lesson_progress(self): # Complete 1 of 2 lessons; unit should show as partial. response = self._post_lesson(self._lesson_1_1.lesson_id) self._expect_payload(response, 2) response = self._get_unit(self._unit_one.unit_id) self._expect_payload(response, 1) response = self._get_course() self._expect_payload(response, 1) # Complete 2 of 2 lessons; unit should show as fully successful. response = self._post_lesson(self._lesson_1_2.lesson_id) self._expect_payload(response, 2) response = self._get_unit(self._unit_one.unit_id) self._expect_payload(response, 2) response = self._get_course() self._expect_payload(response, 1) def test_manual_unit_progress(self): response = self._post_unit(self._unit_two.unit_id) self._expect_payload(response, 2) # Component lessons should not show as completed. response = self._get_lesson(self._lesson_2_1.lesson_id) self._expect_payload(response, 0) response = self._get_lesson(self._lesson_2_2.lesson_id) self._expect_payload(response, 0) def test_view_non_manual_lesson_increments_progress(self): url = '/%s/unit?unit=%s&lesson=%s' % ( COURSE_NAME, self._unit_two.unit_id, self._lesson_2_2.lesson_id) response = self.get(url) self._assert_progress_state( 'Not yet started', '2.1 ' + self._lesson_2_1.title, response) self._assert_progress_state( 'Not yet started', '2.2 ' + self._lesson_2_2.title, response) response = self._get_lesson(self._lesson_2_2.lesson_id) self._expect_payload(response, 2) response = self._get_course() self._expect_payload(response, 1) response = self.get(url) self._assert_progress_state( 'Not yet started', '2.1 ' + self._lesson_2_1.title, response) self._assert_progress_state( 'Completed', '2.2 ' + self._lesson_2_2.title, response) def test_view_manual_lesson_does_not_increment_progress(self): url = '/%s/unit?unit=%s&lesson=%s' % ( COURSE_NAME, self._unit_one.unit_id, self._lesson_1_2.lesson_id) response = self.get(url) self._assert_progress_state( 'Not yet started', '1.1 ' + self._lesson_1_1.title, response) self._assert_progress_state( 'Not yet started', '1.2 ' + self._lesson_1_2.title, response) response = self._get_lesson(self._lesson_1_2.lesson_id) self._expect_payload(response, None) response = self.get(url) self._assert_progress_state( 'Not yet started', '1.1 ' + self._lesson_1_1.title, response) self._assert_progress_state( 'Not yet started', '1.2 ' + self._lesson_1_2.title, response) response = self._post_lesson(self._lesson_1_2.lesson_id) response = self.get(url) self._assert_progress_state( 'Not yet started', '1.1 ' + self._lesson_1_1.title, response) self._assert_progress_state( 'Completed', '1.2 ' + self._lesson_1_2.title, response) def test_events_handler_ignores_manually_completed_items(self): url = '/%s/rest/events' % COURSE_NAME payload = transforms.dumps({ 'location': 'http://localhost:8081/%s/unit?unit=%s&lesson=%s' % ( COURSE_NAME, self._unit_one.unit_id, self._lesson_1_2.lesson_id) }) request = transforms.dumps({ 'xsrf_token': crypto.XsrfTokenManager.create_xsrf_token( 'event-post'), 'source': 'attempt-lesson', 'payload': payload }) response = self.post(url, {'request': request}) response = self._get_lesson(self._lesson_1_2.lesson_id) self._expect_payload(response, None) def test_events_handler_processes_normally_completed_items(self): url = '/%s/rest/events' % COURSE_NAME payload = transforms.dumps({ 'location': 'http://localhost:8081/%s/unit?unit=%s&lesson=%s' % ( COURSE_NAME, self._unit_two.unit_id, self._lesson_2_2.lesson_id) }) request = transforms.dumps({ 'xsrf_token': crypto.XsrfTokenManager.create_xsrf_token( 'event-post'), 'source': 'attempt-lesson', 'payload': payload }) response = self.post(url, {'request': request}) response = self._get_lesson(self._lesson_2_2.lesson_id) self._expect_payload(response, 2) def test_manual_complete_course(self): response = self._get_course() self._expect_payload(response, 0) response = self._post_course() self._expect_payload(response, 2) def test_completing_assessment_as_lesson(self): self._post_assessment(self._sub_assessment.unit_id) # Assessment is the only content in the unit, so completing it # should also complete its containing unit. response = self._get_unit(self._unit_three.unit_id) self._expect_payload(response, 2) response = self._get_course() self._expect_payload(response, 1) def test_completing_toplevel_assessment(self): self._post_assessment(self._toplevel_assessment.unit_id) response = self._get_course() self._expect_payload(response, 1) def test_completing_all_units_completes_course(self): self._post_lesson(self._lesson_1_1.lesson_id) self._post_lesson(self._lesson_1_2.lesson_id) self._post_unit(self._unit_two.unit_id) self._post_assessment(self._sub_assessment.unit_id) self._post_assessment(self._toplevel_assessment.unit_id) response = self._get_course() self._expect_payload(response, 2) def test_unit_completion_with_labels_looks_complete(self): # Mark all but self._unit_two as in 'bar' track. Especially note # that here we are *not* marking the sub-assessment in unit 3 # as being in that track; this should be skipped when considering # unit-level completeness. self._unit_one.labels = str(self.bar_id) self._unit_three.labels = str(self.bar_id) self._toplevel_assessment.labels = str(self.bar_id) self._course.save() # Mark student as being in 'foo' track; student only sees # unit two. self.put(STUDENT_LABELS_URL, {'labels': str(self.foo_id)}) # Complete unit two, and verify that the course is now complete. self._post_unit(self._unit_two.unit_id) response = self._get_course() self._expect_payload(response, 2) def test_assessment_completion_with_labels_looks_complete(self): # Mark all but self._unit_two as in 'bar' track. Especially note # that here we are *not* marking the sub-assessment in unit 3 # as being in that track; this should be skipped when considering # unit-level completeness. self._unit_one.labels = str(self.bar_id) self._unit_two.labels = str(self.bar_id) self._unit_three.labels = str(self.bar_id) self._course.save() # Mark student as being in 'foo' track; student only sees # unit two. self.put(STUDENT_LABELS_URL, {'labels': str(self.foo_id)}) # Complete unit two, and verify that the course is now complete. self._post_assessment(self._toplevel_assessment.unit_id) response = self._get_course() self._expect_payload(response, 2)
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests that walk through Course Builder pages.""" __author__ = 'Mike Gainer (mgainer@google.com)' from common import crypto from common import utils as common_utils from models import models from models import transforms from tests.functional import actions COURSE_NAME = 'labels_test' COURSE_TITLE = 'Labels Test' NAMESPACE = 'ns_%s' % COURSE_NAME ADMIN_EMAIL = 'admin@foo.com' REGISTERED_STUDENT_EMAIL = 'foo@bar.com' REGISTERED_STUDENT_NAME = 'John Smith' UNREGISTERED_STUDENT_EMAIL = 'bar@bar.com' STUDENT_LABELS_URL = '/%s/rest/student/labels' % COURSE_NAME STUDENT_SETTRACKS_URL = '/%s/student/settracks' % COURSE_NAME ANALYTICS_URL = '/%s/dashboard?action=analytics&tab=students' % COURSE_NAME LABELS_STUDENT_EMAIL = 'labels@bar.com' class FakeContext(object): def __init__(self, namespace): self._namespace = namespace def get_namespace_name(self): return self._namespace class StudentLabelsTest(actions.TestBase): def setUp(self): super(StudentLabelsTest, self).setUp() actions.simple_add_course(COURSE_NAME, ADMIN_EMAIL, COURSE_TITLE) with common_utils.Namespace(NAMESPACE): self.foo_id = models.LabelDAO.save(models.LabelDTO( None, {'title': 'Foo', 'descripton': 'foo', 'type': models.LabelDTO.LABEL_TYPE_COURSE_TRACK})) self.bar_id = models.LabelDAO.save(models.LabelDTO( None, {'title': 'Bar', 'descripton': 'bar', 'type': models.LabelDTO.LABEL_TYPE_COURSE_TRACK})) self.baz_id = models.LabelDAO.save(models.LabelDTO( None, {'title': 'Baz', 'descripton': 'baz', 'type': models.LabelDTO.LABEL_TYPE_COURSE_TRACK})) self.quux_id = models.LabelDAO.save(models.LabelDTO( None, {'title': 'Quux', 'descripton': 'quux', 'type': models.LabelDTO.LABEL_TYPE_GENERAL})) actions.login(REGISTERED_STUDENT_EMAIL) actions.register(self, REGISTERED_STUDENT_NAME, COURSE_NAME) actions.logout() # ------------------------------- failures when unsupported label subtype def test_bad_url_404(self): actions.login(UNREGISTERED_STUDENT_EMAIL) response = self.get('/rest/student/labels/interests', expect_errors=True) self.assertEquals(404, response.status_int) # ------------------------------- failures when not logged in. def _verify_error(self, response, expected_message, expected_status=None): self.assertEquals(200, response.status_int) content = transforms.loads(response.body) self.assertEquals(expected_message, content['message']) self.assertEquals(expected_status or 403, content['status']) payload = transforms.loads(content['payload']) self.assertItemsEqual([], payload['labels']) def test_get_fails_not_logged_in(self): self._verify_error(self.get(STUDENT_LABELS_URL), 'No logged-in user') def test_post_fails_not_logged_in(self): self._verify_error(self.post(STUDENT_LABELS_URL, {}), 'No logged-in user') def test_put_fails_not_logged_in(self): self._verify_error(self.put(STUDENT_LABELS_URL, {}), 'No logged-in user') def test_delete_fails_not_logged_in(self): self._verify_error(self.delete(STUDENT_LABELS_URL), 'No logged-in user') # ------------------------------- failures when not registered student. def test_get_fails_logged_in_unregistered(self): actions.login(UNREGISTERED_STUDENT_EMAIL) self._verify_error(self.get(STUDENT_LABELS_URL), 'User is not enrolled') def test_post_fails_logged_in_unregistered(self): actions.login(UNREGISTERED_STUDENT_EMAIL) self._verify_error(self.post(STUDENT_LABELS_URL, {}), 'User is not enrolled') def test_put_fails_logged_in_unregistered(self): actions.login(UNREGISTERED_STUDENT_EMAIL) self._verify_error(self.put(STUDENT_LABELS_URL, {}), 'User is not enrolled') def test_delete_fails_logged_in_unregistered(self): actions.login(UNREGISTERED_STUDENT_EMAIL) self._verify_error(self.delete(STUDENT_LABELS_URL), 'User is not enrolled') # ------------------------------- Failure when put/post bad label ID def test_put_invalid_label_id(self): actions.login(REGISTERED_STUDENT_EMAIL) self._verify_error(self.put(STUDENT_LABELS_URL, {'labels': '123'}), 'Unknown label id(s): [\'123\']', 400) def test_post_invalid_label_id(self): actions.login(REGISTERED_STUDENT_EMAIL) self._verify_error(self.post(STUDENT_LABELS_URL, {'labels': '123'}), 'Unknown label id(s): [\'123\']', 400) # ------------------------------- Bad tags parameter def test_put_no_labels_param(self): actions.login(REGISTERED_STUDENT_EMAIL) self._verify_labels(self.put(STUDENT_LABELS_URL, {}), []) def test_post_no_labels_param(self): actions.login(REGISTERED_STUDENT_EMAIL) self._verify_labels(self.post(STUDENT_LABELS_URL, {}), []) def test_put_blank_labels_param(self): actions.login(REGISTERED_STUDENT_EMAIL) self._verify_labels(self.put(STUDENT_LABELS_URL, 'labels'), []) def test_post_blank_labels_param(self): actions.login(REGISTERED_STUDENT_EMAIL) self._verify_labels(self.post(STUDENT_LABELS_URL, 'labels'), []) # ------------------------------- Actual manipulations. def _verify_labels(self, response, expected_labels): self.assertEquals(200, response.status_int) content = transforms.loads(response.body) self.assertEquals('OK', content['message']) self.assertEquals(200, content['status']) payload = transforms.loads(content['payload']) self.assertItemsEqual(expected_labels, payload['labels']) def test_get_labels_empty_on_registration(self): actions.login(REGISTERED_STUDENT_EMAIL) self._verify_labels(self.get(STUDENT_LABELS_URL), []) def test_put_labels_to_blank(self): actions.login(REGISTERED_STUDENT_EMAIL) self._verify_labels( self.put(STUDENT_LABELS_URL, {'labels': '%d,%d,%d' % ( self.foo_id, self.bar_id, self.baz_id)}), [self.foo_id, self.bar_id, self.baz_id]) self._verify_labels(self.get(STUDENT_LABELS_URL), [self.foo_id, self.bar_id, self.baz_id]) def test_post_labels_to_blank(self): actions.login(REGISTERED_STUDENT_EMAIL) self._verify_labels( self.post(STUDENT_LABELS_URL, {'labels': '%d,%d' % ( self.foo_id, self.baz_id)}), [self.foo_id, self.baz_id]) self._verify_labels(self.get(STUDENT_LABELS_URL), [self.foo_id, self.baz_id]) def test_delete_labels_from_blank(self): actions.login(REGISTERED_STUDENT_EMAIL) self._verify_labels(self.delete(STUDENT_LABELS_URL), []) def test_put_labels_replaces(self): actions.login(REGISTERED_STUDENT_EMAIL) self._verify_labels( self.put(STUDENT_LABELS_URL, {'labels': '%d,%d' % ( self.foo_id, self.bar_id)}), [self.foo_id, self.bar_id]) self._verify_labels( self.put(STUDENT_LABELS_URL, {'labels': '%d' % self.baz_id}), [self.baz_id]) def test_post_labels_merges(self): actions.login(REGISTERED_STUDENT_EMAIL) self._verify_labels( self.put(STUDENT_LABELS_URL, {'labels': '%d,%d' % (self.foo_id, self.bar_id)}), [self.foo_id, self.bar_id]) self._verify_labels( self.post(STUDENT_LABELS_URL, {'labels': '%d' % self.baz_id}), [self.foo_id, self.bar_id, self.baz_id]) def test_delete_labels_deletes(self): actions.login(REGISTERED_STUDENT_EMAIL) self._verify_labels( self.put(STUDENT_LABELS_URL, {'labels': '%d,%d' % (self.foo_id, self.bar_id)}), [self.foo_id, self.bar_id]) self._verify_labels(self.delete(STUDENT_LABELS_URL), []) # ------------------------------------- Removal of broken label references def _add_broken_label_references(self): # Add some broken references to student's labels list. actions.login(REGISTERED_STUDENT_EMAIL) student = ( models.StudentProfileDAO.get_enrolled_student_by_email_for( REGISTERED_STUDENT_EMAIL, FakeContext(NAMESPACE))) student.labels = '123123123 456456456 %d' % self.foo_id student.put() def test_get_expired_label_ids(self): self._add_broken_label_references() self._verify_labels(self.get(STUDENT_LABELS_URL), [self.foo_id]) def test_put_expired_label_ids(self): self._add_broken_label_references() self._verify_labels(self.put(STUDENT_LABELS_URL, {'labels': '%d' % (self.bar_id)}), [self.bar_id]) def test_post_expired_label_ids(self): self._add_broken_label_references() self._verify_labels(self.post(STUDENT_LABELS_URL, {'labels': '%d' % (self.bar_id)}), [self.foo_id, self.bar_id]) def test_delete_expired_label_ids(self): self._add_broken_label_references() self._verify_labels(self.delete(STUDENT_LABELS_URL, {'labels': '%d' % (self.bar_id)}), []) # ------------------------------------ POST on student tracks selection def test_post_tracks_replaces(self): actions.login(REGISTERED_STUDENT_EMAIL) xsrf_token = crypto.XsrfTokenManager.create_xsrf_token('student-edit') self.put(STUDENT_LABELS_URL, {'labels': '%d,%d' % ( self.foo_id, self.bar_id)}) self.post(STUDENT_SETTRACKS_URL, {'labels': '%d' % self.baz_id, 'xsrf_token': xsrf_token}) self._verify_labels(self.get(STUDENT_LABELS_URL), [self.baz_id]) def test_post_tracks_clears(self): actions.login(REGISTERED_STUDENT_EMAIL) xsrf_token = crypto.XsrfTokenManager.create_xsrf_token('student-edit') self.put(STUDENT_LABELS_URL, {'labels': '%d,%d' % ( self.foo_id, self.bar_id)}) self.post(STUDENT_SETTRACKS_URL, {'xsrf_token': xsrf_token}) self._verify_labels(self.get(STUDENT_LABELS_URL), []) def test_post_tracks_sets(self): actions.login(REGISTERED_STUDENT_EMAIL) xsrf_token = crypto.XsrfTokenManager.create_xsrf_token('student-edit') self.post(STUDENT_SETTRACKS_URL, {'labels': '%d' % self.foo_id, 'xsrf_token': xsrf_token}) self._verify_labels(self.get(STUDENT_LABELS_URL), [self.foo_id]) def test_post_tracks_does_not_affect_non_tracks_labels(self): actions.login(REGISTERED_STUDENT_EMAIL) xsrf_token = crypto.XsrfTokenManager.create_xsrf_token('student-edit') self.put(STUDENT_LABELS_URL, {'labels': '%d,%d' % ( self.foo_id, self.quux_id)}) self.post(STUDENT_SETTRACKS_URL, {'labels': '%d' % self.baz_id, 'xsrf_token': xsrf_token}) self._verify_labels(self.get(STUDENT_LABELS_URL), [self.baz_id, self.quux_id]) # ---------------------------------- Analytics page. def test_analytics(self): actions.login(REGISTERED_STUDENT_EMAIL) self.put(STUDENT_LABELS_URL, {'labels': '%d,%d' % ( self.foo_id, self.quux_id)}) actions.login(ADMIN_EMAIL) response = self.get(ANALYTICS_URL) self.submit(response.forms['gcb-run-visualization-labels_on_students'], response) self.execute_all_deferred_tasks() rest_url = ( '/%s/rest/data/labels_on_students/items' % COURSE_NAME + '?data_source_token=%s&page_number=0&chunk_size=0' % crypto.XsrfTokenManager.create_xsrf_token('data_source_access')) label_counts = transforms.loads(self.get(rest_url).body) self.assertEquals( [{'title': 'Quux', 'count': 1, 'type': 'General', 'description': ''}, {'title': 'Bar', 'count': 0, 'type': 'Course Track', 'description': ''}, {'title': 'Baz', 'count': 0, 'type': 'Course Track', 'description': ''}, {'title': 'Foo', 'count': 1, 'type': 'Course Track', 'description': ''}], label_counts['data']) # --------------------------------- Registration def test_register_with_labels(self): student_name = 'John Smith from Back East' actions.login(LABELS_STUDENT_EMAIL) response = actions.view_registration(self, COURSE_NAME) register_form = actions.get_form_by_action(response, 'register') self.post('/%s/%s' % (COURSE_NAME, register_form.action), { 'form01': student_name, 'xsrf_token': register_form['xsrf_token'].value, 'labels': common_utils.list_to_text([self.bar_id, self.baz_id])}) self._verify_labels(self.get(STUDENT_LABELS_URL), [self.bar_id, self.baz_id]) with common_utils.Namespace(NAMESPACE): student = models.Student.get_enrolled_student_by_email( LABELS_STUDENT_EMAIL) self.assertEquals(student.name, student_name)
Python
# coding: utf-8 # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for modules/dashboard/analytics.""" __author__ = 'Julia Oh(juliaoh@google.com)' import datetime import os import time import actions from actions import assert_contains from actions import assert_does_not_contain from actions import assert_equals from mapreduce.lib.pipeline import models as pipeline_models from mapreduce.lib.pipeline import pipeline import appengine_config from common import utils as common_utils from controllers import sites from controllers import utils from models import config from models import courses from models import entities from models import jobs from models import models from models import transforms from models.progress import ProgressStats from models.progress import UnitLessonCompletionTracker from modules.data_source_providers import rest_providers from modules.data_source_providers import synchronous_providers from modules.mapreduce import mapreduce_module from google.appengine.api import files from google.appengine.ext import db class AnalyticsTabsWithNoJobs(actions.TestBase): def tearDown(self): config.Registry.test_overrides.clear() def test_blank_students_tab_no_mr(self): email = 'admin@google.com' actions.login(email, is_admin=True) self.get('dashboard?action=analytics&tab=students') def test_blank_questions_tab_no_mr(self): email = 'admin@google.com' actions.login(email, is_admin=True) self.get('dashboard?action=analytics&tab=questions') def test_blank_assessments_tab_no_mr(self): email = 'admin@google.com' actions.login(email, is_admin=True) self.get('dashboard?action=analytics&tab=assessments') def test_blank_peer_review_tab_no_mr(self): email = 'admin@google.com' actions.login(email, is_admin=True) self.get('dashboard?action=analytics&tab=peer_review') def test_blank_students_tab_with_mr(self): config.Registry.test_overrides[ mapreduce_module.GCB_ENABLE_MAPREDUCE_DETAIL_ACCESS.name] = True email = 'admin@google.com' actions.login(email, is_admin=True) self.get('dashboard?action=analytics&tab=students') def test_blank_questions_tab_with_mr(self): config.Registry.test_overrides[ mapreduce_module.GCB_ENABLE_MAPREDUCE_DETAIL_ACCESS.name] = True email = 'admin@google.com' actions.login(email, is_admin=True) self.get('dashboard?action=analytics&tab=questions') def test_blank_assessments_tab_with_mr(self): config.Registry.test_overrides[ mapreduce_module.GCB_ENABLE_MAPREDUCE_DETAIL_ACCESS.name] = True email = 'admin@google.com' actions.login(email, is_admin=True) self.get('dashboard?action=analytics&tab=assessments') def test_blank_peer_review_tab_with_mr(self): config.Registry.test_overrides[ mapreduce_module.GCB_ENABLE_MAPREDUCE_DETAIL_ACCESS.name] = True email = 'admin@google.com' actions.login(email, is_admin=True) self.get('dashboard?action=analytics&tab=peer_review') class ProgressAnalyticsTest(actions.TestBase): """Tests the progress analytics page on the Course Author dashboard.""" EXPECTED_TASK_COUNT = 3 def enable_progress_tracking(self): config.Registry.test_overrides[ utils.CAN_PERSIST_ACTIVITY_EVENTS.name] = True def test_empty_student_progress_stats_analytics_displays_nothing(self): """Test analytics page on course dashboard when no progress stats.""" # The admin looks at the analytics page on the board to check right # message when no progress has been recorded. email = 'admin@google.com' actions.login(email, is_admin=True) response = self.get('dashboard?action=analytics&tab=students') assert_contains( 'Google &gt; Dashboard &gt; Analytics &gt; Students', response.body) assert_contains('have not been calculated yet', response.body) response = response.forms[ 'gcb-generate-analytics-data'].submit().follow() assert len(self.taskq.GetTasks('default')) == ( ProgressAnalyticsTest.EXPECTED_TASK_COUNT) assert_contains('is running', response.body) self.execute_all_deferred_tasks() response = self.get(response.request.url) assert_contains('were last updated at', response.body) assert_contains('currently enrolled: 0', response.body) assert_contains('total: 0', response.body) assert_contains('Student Progress', response.body) assert_contains( 'No student progress has been recorded for this course.', response.body) actions.logout() def test_student_progress_stats_analytics_displays_on_dashboard(self): """Test analytics page on course dashboard.""" self.enable_progress_tracking() student1 = 'student1@google.com' name1 = 'Test Student 1' student2 = 'student2@google.com' name2 = 'Test Student 2' # Student 1 completes a unit. actions.login(student1) actions.register(self, name1) actions.view_unit(self) actions.logout() # Student 2 completes a unit. actions.login(student2) actions.register(self, name2) actions.view_unit(self) actions.logout() # Admin logs back in and checks if progress exists. email = 'admin@google.com' actions.login(email, is_admin=True) response = self.get('dashboard?action=analytics&tab=students') assert_contains( 'Google &gt; Dashboard &gt; Analytics &gt; Students', response.body) assert_contains('have not been calculated yet', response.body) response = response.forms[ 'gcb-generate-analytics-data'].submit().follow() assert len(self.taskq.GetTasks('default')) == ( ProgressAnalyticsTest.EXPECTED_TASK_COUNT) response = self.get('dashboard?action=analytics') assert_contains('is running', response.body) self.execute_all_deferred_tasks() response = self.get('dashboard?action=analytics') assert_contains('were last updated at', response.body) assert_contains('currently enrolled: 2', response.body) assert_contains('total: 2', response.body) assert_contains('Student Progress', response.body) assert_does_not_contain( 'No student progress has been recorded for this course.', response.body) # JSON code for the completion statistics. assert_contains( '\\"u.1.l.1\\": {\\"progress\\": 0, \\"completed\\": 2}', response.body) assert_contains( '\\"u.1\\": {\\"progress\\": 2, \\"completed\\": 0}', response.body) def test_analytics_are_individually_cancelable_and_runnable(self): """Test run/cancel controls for individual analytics jobs.""" # Submit all analytics. email = 'admin@google.com' actions.login(email, is_admin=True) response = self.get('dashboard?action=analytics&tab=peer_review') response = response.forms[ 'gcb-generate-analytics-data'].submit().follow() # Ensure that analytics appear to be running and have cancel buttons. assert_contains('is running', response.body) assert_contains('Cancel Statistic Calculation', response.body) # Now that all analytics are pending, ensure that we do _not_ have # an update-all button. with self.assertRaises(KeyError): response = response.forms['gcb-generate-analytics-data'] # Click the cancel button for one of the slower jobs. response = response.forms[ 'gcb-cancel-visualization-peer_review'].submit().follow() # Verify that page shows job was canceled. assert_contains('error updating peer review statistics', response.body) assert_contains('Canceled by ' + email, response.body) # We should now have our update-statistics button back. self.assertIsNotNone(response.forms['gcb-generate-analytics-data']) # Should also have a button to run the canceled job; click that. response = response.forms[ 'gcb-run-visualization-peer_review'].submit().follow() # All jobs should now again be running, and update-all button gone. with self.assertRaises(KeyError): response = response.forms['gcb-generate-analytics-data'] def test_cancel_map_reduce(self): email = 'admin@google.com' actions.login(email, is_admin=True) response = self.get('dashboard?action=analytics&tab=peer_review') response = response.forms[ 'gcb-run-visualization-peer_review'].submit().follow() # Launch 1st stage of map/reduce job; we must do this in order to # get the pipeline woken up enough to have built a root pipeline # record. Without this, we do not have an ID to use when canceling. self.execute_all_deferred_tasks(iteration_limit=1) # Cancel the job. response = response.forms[ 'gcb-cancel-visualization-peer_review'].submit().follow() assert_contains('Canceled by ' + email, response.body) # Now permit any pending tasks to complete, and expect the job's # status message to remain at "Canceled by ...". # # If the cancel didn't take effect, the map/reduce should have run to # completion and the job's status would change to completed, changing # the message. This is verified in # model_jobs.JobOperationsTest.test_killed_job_can_still_complete self.execute_all_deferred_tasks() response = self.get(response.request.url) assert_contains('Canceled by ' + email, response.body) def test_get_entity_id_wrapper_in_progress_works(self): """Tests get_entity_id wrappers in progress.ProgressStats.""" sites.setup_courses('course:/test::ns_test, course:/:/') course = courses.Course(None, app_context=sites.get_all_courses()[0]) progress_stats = ProgressStats(course) unit1 = course.add_unit() assert_equals( progress_stats._get_unit_ids_of_type_unit(), [unit1.unit_id]) assessment1 = course.add_assessment() assert_equals( progress_stats._get_assessment_ids(), [assessment1.unit_id]) lesson11 = course.add_lesson(unit1) lesson12 = course.add_lesson(unit1) assert_equals( progress_stats._get_lesson_ids(unit1.unit_id), [lesson11.lesson_id, lesson12.lesson_id]) lesson11.has_activity = True course.set_activity_content(lesson11, u'var activity=[]', []) assert_equals( progress_stats._get_activity_ids(unit1.unit_id, lesson11.lesson_id), [0]) assert_equals( progress_stats._get_activity_ids(unit1.unit_id, lesson12.lesson_id), []) def test_get_entity_label_wrapper_in_progress_works(self): """Tests get_entity_label wrappers in progress.ProgressStats.""" sites.setup_courses('course:/test::ns_test, course:/:/') course = courses.Course(None, app_context=sites.get_all_courses()[0]) progress_stats = ProgressStats(course) unit1 = course.add_unit() assert_equals( progress_stats._get_unit_label(unit1.unit_id), 'Unit %s' % unit1.index) assessment1 = course.add_assessment() assert_equals( progress_stats._get_assessment_label(assessment1.unit_id), assessment1.title) lesson11 = course.add_lesson(unit1) lesson12 = course.add_lesson(unit1) assert_equals( progress_stats._get_lesson_label(unit1.unit_id, lesson11.lesson_id), lesson11.index) lesson11.has_activity = True course.set_activity_content(lesson11, u'var activity=[]', []) assert_equals( progress_stats._get_activity_label( unit1.unit_id, lesson11.lesson_id, 0), 'L1.1') assert_equals( progress_stats._get_activity_label( unit1.unit_id, lesson12.lesson_id, 0), 'L1.2') lesson12.objectives = """ <question quid="123" weight="1" instanceid=1></question> random_text <gcb-youtube videoid="Kdg2drcUjYI" instanceid="VD"></gcb-youtube> more_random_text <question-group qgid="456" instanceid=2></question-group> yet_more_random_text """ cpt_ids = progress_stats._get_component_ids( unit1.unit_id, lesson12.lesson_id, 0) self.assertEqual(set([u'1', u'2']), set(cpt_ids)) def test_compute_entity_dict_constructs_dict_correctly(self): sites.setup_courses('course:/test::ns_test, course:/:/') course = courses.Course(None, app_context=sites.get_all_courses()[0]) progress_stats = ProgressStats(course) course_dict = progress_stats.compute_entity_dict('course', []) assert_equals(course_dict, { 'label': 'UNTITLED COURSE', 'u': {}, 's': {}}) def test_compute_entity_dict_constructs_dict_for_empty_course_correctly( self): """Tests correct entity_structure is built.""" sites.setup_courses('course:/test::ns_test, course:/:/') course = courses.Course(None, app_context=sites.get_all_courses()[0]) unit1 = course.add_unit() assessment1 = course.add_assessment() progress_stats = ProgressStats(course) assert_equals( progress_stats.compute_entity_dict('course', []), {'label': 'UNTITLED COURSE', 'u': {unit1.unit_id: { 'label': 'Unit %s' % unit1.index, 'l': {}}}, 's': { assessment1.unit_id: {'label': assessment1.title}}}) lesson11 = course.add_lesson(unit1) assert_equals( progress_stats.compute_entity_dict('course', []), { "s": { assessment1.unit_id: { "label": assessment1.title } }, "u": { unit1.unit_id: { "l": { lesson11.lesson_id: { "a": {}, "h": { 0: { "c": {}, "label": "L1.1" } }, "label": lesson11.index } }, "label": "Unit %s" % unit1.index } }, 'label': 'UNTITLED COURSE' }) lesson11.objectives = """ <question quid="123" weight="1" instanceid="1"></question> random_text <gcb-youtube videoid="Kdg2drcUjYI" instanceid="VD"></gcb-youtube> more_random_text <question-group qgid="456" instanceid="2"></question-group> yet_more_random_text """ assert_equals( progress_stats.compute_entity_dict('course', []), { "s": { assessment1.unit_id: { "label": assessment1.title } }, "u": { unit1.unit_id: { "l": { lesson11.lesson_id: { "a": {}, "h": { 0: { "c": { u'1': { "label": "L1.1.1" }, u'2': { "label": "L1.1.2" } }, "label": "L1.1" } }, "label": lesson11.index } }, "label": "Unit %s" % unit1.index } }, "label": 'UNTITLED COURSE' }) class QuestionAnalyticsTest(actions.TestBase): """Tests the question analytics page from Course Author dashboard.""" def _enable_activity_tracking(self): config.Registry.test_overrides[ utils.CAN_PERSIST_ACTIVITY_EVENTS.name] = True def _get_sample_v15_course(self): """Creates a course with different types of questions and returns it.""" sites.setup_courses('course:/test::ns_test, course:/:/') course = courses.Course(None, app_context=sites.get_all_courses()[0]) unit1 = course.add_unit() lesson1 = course.add_lesson(unit1) assessment_old = course.add_assessment() assessment_old.title = 'Old assessment' assessment_new = course.add_assessment() assessment_new.title = 'New assessment' assessment_peer = course.add_assessment() assessment_peer.title = 'Peer review assessment' # Create a multiple choice question. mcq_new_dict = { 'description': 'mcq_new', 'type': 0, # Multiple choice question. 'choices': [{ 'text': 'answer', 'score': 1.0 }], 'version': '1.5' } mcq_new_dto = models.QuestionDTO(None, mcq_new_dict) mcq_new_id = models.QuestionDAO.save(mcq_new_dto) # Create a short answer question. frq_new_dict = { 'defaultFeedback': '', 'rows': 1, 'description': 'short answer', 'hint': '', 'graders': [{ 'matcher': 'case_insensitive', 'score': '1.0', 'response': 'hi', 'feedback': '' }], 'question': 'short answer question', 'version': '1.5', 'type': 1, # Short answer question. 'columns': 100 } frq_new_dto = models.QuestionDTO(None, frq_new_dict) frq_new_id = models.QuestionDAO.save(frq_new_dto) # Create a question group. question_group_dict = { 'description': 'question_group', 'items': [ {'question': str(mcq_new_id)}, {'question': str(frq_new_id)}, {'question': str(mcq_new_id)} ], 'version': '1.5', 'introduction': '' } question_group_dto = models.QuestionGroupDTO(None, question_group_dict) question_group_id = models.QuestionGroupDAO.save(question_group_dto) # Add a MC question and a question group to leesson1. lesson1.objectives = """ <question quid="%s" weight="1" instanceid="QN"></question> random_text <gcb-youtube videoid="Kdg2drcUjYI" instanceid="VD"></gcb-youtube> more_random_text <question-group qgid="%s" instanceid="QG"></question-group> """ % (mcq_new_id, question_group_id) # Add a MC question, a short answer question, and a question group to # new style assessment. assessment_new.html_content = """ <question quid="%s" weight="1" instanceid="QN2"></question> <question quid="%s" weight="1" instanceid="FRQ2"></question> random_text <gcb-youtube videoid="Kdg2drcUjYI" instanceid="VD"></gcb-youtube> more_random_text <question-group qgid="%s" instanceid="QG2"></question-group> """ % (mcq_new_id, frq_new_id, question_group_id) return course def test_get_summarized_question_list_from_event(self): """Tests the transform functions per event type.""" sites.setup_courses('course:/test::ns_test, course:/:/') course = courses.Course(None, app_context=sites.get_all_courses()[0]) question_aggregator = (synchronous_providers.QuestionStatsGenerator .MultipleChoiceQuestionAggregator(course)) event_payloads = open(os.path.join( appengine_config.BUNDLE_ROOT, 'tests/unit/common/event_payloads.json')).read() event_payload_dict = transforms.loads(event_payloads) for event_info in event_payload_dict.values(): questions = question_aggregator._process_event( event_info['event_source'], event_info['event_data']) assert_equals(questions, event_info['transformed_dict_list']) def test_compute_question_stats_on_empty_course_returns_empty_dicts(self): sites.setup_courses('course:/test::ns_test, course:/:/') app_context = sites.get_all_courses()[0] question_stats_computer = ( synchronous_providers.QuestionStatsGenerator(app_context)) id_to_questions, id_to_assessments = question_stats_computer.run() assert_equals({}, id_to_questions) assert_equals({}, id_to_assessments) def test_id_to_question_dict_constructed_correctly(self): """Tests id_to_question dicts are constructed correctly.""" course = self._get_sample_v15_course() tracker = UnitLessonCompletionTracker(course) assert_equals( tracker.get_id_to_questions_dict(), { 'u.1.l.2.c.QN': { 'answer_counts': [0], 'label': 'Unit 1 Lesson 1, Question mcq_new', 'location': 'unit?unit=1&lesson=2', 'num_attempts': 0, 'score': 0 }, 'u.1.l.2.c.QG.i.0': { 'answer_counts': [0], 'label': ('Unit 1 Lesson 1, Question Group question_group ' 'Question mcq_new'), 'location': 'unit?unit=1&lesson=2', 'num_attempts': 0, 'score': 0 }, 'u.1.l.2.c.QG.i.2': { 'answer_counts': [0], 'label': ('Unit 1 Lesson 1, Question Group question_group ' 'Question mcq_new'), 'location': 'unit?unit=1&lesson=2', 'num_attempts': 0, 'score': 0 } } ) assert_equals( tracker.get_id_to_assessments_dict(), { 's.4.c.QN2': { 'answer_counts': [0], 'label': 'New assessment, Question mcq_new', 'location': 'assessment?name=4', 'num_attempts': 0, 'score': 0 }, 's.4.c.QG2.i.0': { 'answer_counts': [0], 'label': ('New assessment, Question Group question_group ' 'Question mcq_new'), 'location': 'assessment?name=4', 'num_attempts': 0, 'score': 0 }, 's.4.c.QG2.i.2': { 'answer_counts': [0], 'label': ('New assessment, Question Group question_group ' 'Question mcq_new'), 'location': 'assessment?name=4', 'num_attempts': 0, 'score': 0 } } ) COURSE_ONE = 'course_one' COURSE_TWO = 'course_two' class CronCleanupTest(actions.TestBase): def setUp(self): super(CronCleanupTest, self).setUp() admin_email = 'admin@foo.com' self.course_one = actions.simple_add_course( COURSE_ONE, admin_email, 'Course One') self.course_two = actions.simple_add_course( COURSE_TWO, admin_email, 'Course Two') actions.login(admin_email, True) actions.register(self, admin_email, COURSE_ONE) actions.register(self, admin_email, COURSE_TWO) self.save_tz = os.environ.get('TZ') os.environ['TZ'] = 'GMT' time.tzset() def tearDown(self): if self.save_tz: os.environ['TZ'] = self.save_tz else: del os.environ['TZ'] time.tzset() def _clean_jobs(self, max_age): return mapreduce_module.CronMapreduceCleanupHandler._clean_mapreduce( max_age) def _get_num_root_jobs(self, course_name): with common_utils.Namespace('ns_' + course_name): return len(pipeline.get_root_list()['pipelines']) def _get_blobstore_paths(self, course_name): ret = set() with common_utils.Namespace('ns_' + course_name): for state in pipeline.get_root_list()['pipelines']: root_key = db.Key.from_path( pipeline_models._PipelineRecord.kind(), state['pipelineId']) paths = (mapreduce_module.CronMapreduceCleanupHandler ._collect_blobstore_paths(root_key)) ret = ret.union(paths) return ret def _assert_blobstore_paths_removed(self, course_name, paths): with common_utils.Namespace('ns_' + course_name): for path in paths: with self.assertRaises(files.FinalizationError): files.open(path) def _force_finalize(self, job): # For reasons that I do not grok, running the deferred task list # until it empties out in test mode does not wind up marking the # root job as 'done'. (Whereas when running the actual service, # the job does get marked 'done'.) This has already cost me most # of two hours of debugging, and I'm no closer to figuring out why, # much less having a monkey-patch into the Map/Reduce or Pipeline # libraries that would correct this. Cleaner to just transition # the job into a completed state manually. root_pipeline_id = jobs.MapReduceJob.get_root_pipeline_id(job.load()) with common_utils.Namespace(job._namespace): p = pipeline.Pipeline.from_id(root_pipeline_id) context = pipeline._PipelineContext('', 'default', '') context.transition_complete(p._pipeline_key) def test_non_admin_cannot_cleanup(self): actions.login('joe_user@foo.com') response = self.get('/cron/mapreduce/cleanup', expect_errors=True) self.assertEquals(400, response.status_int) def test_admin_cleanup_gets_200_ok(self): response = self.get('/cron/mapreduce/cleanup', expect_errors=True) self.assertEquals(200, response.status_int) def test_no_jobs_no_cleanup(self): self.assertEquals(0, self._clean_jobs(datetime.timedelta(seconds=0))) def test_unstarted_job_not_cleaned(self): mapper = rest_providers.LabelsOnStudentsGenerator(self.course_one) mapper.submit() self.assertEquals(1, self._get_num_root_jobs(COURSE_ONE)) self.assertEquals(0, self._clean_jobs(datetime.timedelta(minutes=1))) def test_active_job_not_cleaned(self): mapper = rest_providers.LabelsOnStudentsGenerator(self.course_one) mapper.submit() self.execute_all_deferred_tasks(iteration_limit=1) self.assertEquals(1, self._get_num_root_jobs(COURSE_ONE)) self.assertEquals(0, self._clean_jobs(datetime.timedelta(minutes=1))) def test_completed_job_is_not_cleaned(self): mapper = rest_providers.LabelsOnStudentsGenerator(self.course_one) mapper.submit() self.execute_all_deferred_tasks() self._force_finalize(mapper) self.assertEquals(1, self._get_num_root_jobs(COURSE_ONE)) self.assertEquals(0, self._clean_jobs(datetime.timedelta(minutes=1))) def test_terminated_job_with_no_start_time_is_cleaned(self): mapper = rest_providers.LabelsOnStudentsGenerator(self.course_one) mapper.submit() self.execute_all_deferred_tasks(iteration_limit=1) mapper.cancel() self.execute_all_deferred_tasks() self.assertEquals(1, self._get_num_root_jobs(COURSE_ONE)) self.assertEquals(1, self._clean_jobs(datetime.timedelta(minutes=1))) self.execute_all_deferred_tasks(iteration_limit=1) self.assertEquals(0, self._get_num_root_jobs(COURSE_ONE)) def test_incomplete_job_cleaned_if_time_expired(self): mapper = rest_providers.LabelsOnStudentsGenerator(self.course_one) mapper.submit() self.execute_all_deferred_tasks(iteration_limit=1) self.assertEquals(1, self._get_num_root_jobs(COURSE_ONE)) self.assertEquals(1, self._clean_jobs(datetime.timedelta(seconds=0))) self.execute_all_deferred_tasks() # Run deferred deletion task. self.assertEquals(0, self._get_num_root_jobs(COURSE_ONE)) def test_completed_job_cleaned_if_time_expired(self): mapper = rest_providers.LabelsOnStudentsGenerator(self.course_one) mapper.submit() self.execute_all_deferred_tasks() self.assertEquals(1, self._get_num_root_jobs(COURSE_ONE)) self.assertEquals(1, self._clean_jobs(datetime.timedelta(seconds=0))) paths = self._get_blobstore_paths(COURSE_ONE) self.assertEquals(8, len(paths)) self.execute_all_deferred_tasks() # Run deferred deletion task. self.assertEquals(0, self._get_num_root_jobs(COURSE_ONE)) self._assert_blobstore_paths_removed(COURSE_ONE, paths) def test_multiple_runs_cleaned(self): mapper = rest_providers.LabelsOnStudentsGenerator(self.course_one) for _ in range(0, 3): mapper.submit() self.execute_all_deferred_tasks() self.assertEquals(3, self._get_num_root_jobs(COURSE_ONE)) self.assertEquals(3, self._clean_jobs(datetime.timedelta(seconds=0))) paths = self._get_blobstore_paths(COURSE_ONE) self.assertEquals(24, len(paths)) self.execute_all_deferred_tasks() # Run deferred deletion task. self.assertEquals(0, self._get_num_root_jobs(COURSE_ONE)) self._assert_blobstore_paths_removed(COURSE_ONE, paths) def test_cleanup_modifies_incomplete_status(self): mapper = rest_providers.LabelsOnStudentsGenerator(self.course_one) mapper.submit() self.execute_all_deferred_tasks(iteration_limit=1) self.assertEquals(jobs.STATUS_CODE_STARTED, mapper.load().status_code) self.assertEquals(1, self._clean_jobs(datetime.timedelta(seconds=0))) self.assertEquals(jobs.STATUS_CODE_FAILED, mapper.load().status_code) self.assertIn('assumed to have failed', mapper.load().output) def test_cleanup_does_not_modify_completed_status(self): mapper = rest_providers.LabelsOnStudentsGenerator(self.course_one) mapper.submit() self.execute_all_deferred_tasks() self.assertEquals(jobs.STATUS_CODE_COMPLETED, mapper.load().status_code) self.assertEquals(1, self._clean_jobs(datetime.timedelta(seconds=0))) self.assertEquals(jobs.STATUS_CODE_COMPLETED, mapper.load().status_code) def test_cleanup_in_multiple_namespaces(self): mapper_one = rest_providers.LabelsOnStudentsGenerator(self.course_one) mapper_two = rest_providers.LabelsOnStudentsGenerator(self.course_two) for _ in range(0, 2): mapper_one.submit() mapper_two.submit() self.execute_all_deferred_tasks() self.assertEquals(2, self._get_num_root_jobs(COURSE_ONE)) course_one_paths = self._get_blobstore_paths(COURSE_ONE) self.assertEquals(16, len(course_one_paths)) self.assertEquals(2, self._get_num_root_jobs(COURSE_TWO)) course_two_paths = self._get_blobstore_paths(COURSE_TWO) self.assertEquals(16, len(course_two_paths)) self.assertEquals(4, self._clean_jobs(datetime.timedelta(seconds=0))) self.execute_all_deferred_tasks() # Run deferred deletion task. self.assertEquals(0, self._get_num_root_jobs(COURSE_ONE)) self.assertEquals(0, self._get_num_root_jobs(COURSE_TWO)) self._assert_blobstore_paths_removed(COURSE_ONE, course_one_paths) self._assert_blobstore_paths_removed(COURSE_TWO, course_two_paths) def test_cleanup_handler(self): mapper = rest_providers.LabelsOnStudentsGenerator(self.course_one) mapper.submit() self.execute_all_deferred_tasks(iteration_limit=1) mapper.cancel() self.execute_all_deferred_tasks() self.assertEquals(1, self._get_num_root_jobs(COURSE_ONE)) # Check that hitting the cron handler via GET works as well. # Note that since the actual handler uses a max time limit of # a few days, we need to set up a canceled job which, having # no defined start-time will be cleaned up immediately. self.get('/cron/mapreduce/cleanup') self.execute_all_deferred_tasks(iteration_limit=1) self.assertEquals(0, self._get_num_root_jobs(COURSE_ONE)) class DummyEntity(entities.BaseEntity): NUM_ENTITIES = 1000 data = db.TextProperty(indexed=False) class DummyDTO(object): def __init__(self, the_id, the_dict): self.id = the_id self.dict = the_dict class DummyDAO(models.BaseJsonDao): DTO = DummyDTO ENTITY = DummyEntity ENTITY_KEY_TYPE = models.BaseJsonDao.EntityKeyTypeId CURRENT_VERSION = '1.0' @classmethod def upsert(cls, the_id, the_dict): dto = cls.load(the_id) if not dto: dto = DummyDTO(the_id, the_dict) cls.save(dto) class DummyMapReduceJob(jobs.MapReduceJob): NUM_SHARDS = 10 BOGUS_VALUE_ADDED_IN_COMBINE_STEP = 3 TOTAL_AGGREGATION_KEY = 'total' def entity_class(self): return DummyEntity @staticmethod def map(item): # Count up by 1 for this shard. yield item.key().id() % DummyMapReduceJob.NUM_SHARDS, 1 # Count up by 1 for the total number of items processed by M/R job. yield DummyMapReduceJob.TOTAL_AGGREGATION_KEY, 1 @staticmethod def combine(key, values, prev_combine_results=None): if key != DummyMapReduceJob.TOTAL_AGGREGATION_KEY: # Here, we are pretending that the individual key/values # other than 'total' are not combine-able. We thus pass # through the individual values for each item unchanged. # Note that this verifies that it is supported that # combine() may yield multiple values for a single key. for value in values: yield value if prev_combine_results: for value in prev_combine_results: yield value else: # Aggregate values for 'total' here in combine step. ret = 0 for value in values: ret += int(value) if prev_combine_results: for value in prev_combine_results: ret += int(value) # Add a weird value to prove that combine() has been called. ret += DummyMapReduceJob.BOGUS_VALUE_ADDED_IN_COMBINE_STEP yield ret @staticmethod def reduce(key, values): ret = 0 for value in values: ret += int(value) yield key, ret class MapReduceSimpleTest(actions.TestBase): def setUp(self): super(MapReduceSimpleTest, self).setUp() admin_email = 'admin@foo.com' self.context = actions.simple_add_course('mr_test', admin_email, 'Test') actions.login(admin_email, is_admin=True) with common_utils.Namespace('ns_mr_test'): # Start range at 1 because 0 is a reserved ID. for key in range(1, DummyEntity.NUM_ENTITIES + 1): DummyDAO.upsert(key, {}) def test_basic_operation(self): job = DummyMapReduceJob(self.context) job.submit() self.execute_all_deferred_tasks() results = jobs.MapReduceJob.get_results(job.load()) # Expect to see a quantity of results equal to the number of shards, # plus one for the 'total' result. self.assertEquals(DummyMapReduceJob.NUM_SHARDS + 1, len(results)) for key, value in results: if key == DummyMapReduceJob.TOTAL_AGGREGATION_KEY: # Here, we are making the entirely unwarranted assumption that # combine() will be called exactly once. However, given that # the entire m/r is being done on a chunk of values that's # within the library's single-chunk size, and given that it's # running all on one host, etc., it turns out to be reliably # true that combine() is called exactly once. self.assertEquals( DummyEntity.NUM_ENTITIES + DummyMapReduceJob.BOGUS_VALUE_ADDED_IN_COMBINE_STEP, value) else: # Here, check that each shard has been correctly aggregated by # the reduce step (and implicitly that the values for the # indivdual shards made it through the combine() step # unchanged) self.assertEquals( DummyEntity.NUM_ENTITIES / DummyMapReduceJob.NUM_SHARDS, value)
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for modules/courses/.""" __author__ = 'Glenn De Jonghe (gdejonghe@google.com)' import actions from models import courses from models import models from modules.courses import courses as courses_module from google.appengine.api import namespace_manager class AccessDraftsTestCase(actions.TestBase): COURSE_NAME = 'draft_access' ADMIN_EMAIL = 'admin@foo.com' USER_EMAIL = 'user@foo.com' ROLE = 'test_role' ACTION = 'test_action' def setUp(self): super(AccessDraftsTestCase, self).setUp() actions.login(self.ADMIN_EMAIL, is_admin=True) self.base = '/' + self.COURSE_NAME self.context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'Access Draft Testing') self.course = courses.Course(None, self.context) self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME) role_dto = models.RoleDTO(None, { 'name': self.ROLE, 'users': [self.USER_EMAIL], 'permissions': { courses_module.custom_module.name: [ courses_module.SEE_DRAFTS_PERMISSION] } }) models.RoleDAO.save(role_dto) actions.logout() def tearDown(self): namespace_manager.set_namespace(self.old_namespace) super(AccessDraftsTestCase, self).tearDown() def test_access_assessment(self): assessment = self.course.add_assessment() assessment.is_draft = True self.course.save() self.assertEquals( self.get('assessment?name=%s' % assessment.unit_id).status_int, 302) actions.login(self.USER_EMAIL, is_admin=False) self.assertEquals( self.get('assessment?name=%s' % assessment.unit_id).status_int, 200) actions.logout() def test_access_lesson(self): unit = self.course.add_unit() unit.is_draft = True lesson = self.course.add_lesson(unit) lesson.is_draft = True self.course.save() self.assertEquals( self.get('unit?unit=%s&lesson=%s' % ( unit.unit_id, lesson.lesson_id)).status_int, 302) actions.login(self.USER_EMAIL, is_admin=False) self.assertEquals( self.get('unit?unit=%s&lesson=%s' % ( unit.unit_id, lesson.lesson_id)).status_int, 200) actions.logout()
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for modules/courses/.""" __author__ = 'Mike Gainer (mgainer@google.com)' import datetime import time import actions import apiclient from common import catch_and_log from common import schema_fields from common import utils as common_utils from models import courses from models import data_sources from models import jobs from models import models from models import transforms from modules.data_pump import data_pump from modules.data_source_providers import rest_providers from google.appengine.ext import deferred COURSE_NAME = 'data_pump' ADMIN_EMAIL = 'admin@foo.com' USER_EMAIL = 'user@foo.com' USER_NAME = 'Some User' class TrivialDataSource(data_sources.AbstractRestDataSource): @classmethod def get_name(cls): return 'trivial_data_source' @classmethod def get_title(cls): return 'Trivial Data Source' @classmethod def exportable(cls): return True @classmethod def get_schema(cls, unused_app_context, unused_log, data_source_context): reg = schema_fields.FieldRegistry('Trivial') reg.add_property(schema_fields.SchemaField( 'thing', 'Thing', 'integer', description='stuff')) if data_source_context.send_uncensored_pii_data: reg.add_property(schema_fields.SchemaField( 'ssn', 'SSN', 'string', description='Social Security Number')) return reg.get_json_schema_dict()['properties'] @classmethod def get_default_chunk_size(cls): return 3 @classmethod def get_context_class(cls): return TrivialDataSourceContext @classmethod def _make_item(cls, value, source_context): item = {'thing': value} if source_context.send_uncensored_pii_data: ssn = '%d%d%d-%d%d-%d%d%d%d' % ([value] * 9) return item @classmethod def fetch_values(cls, app_context, source_context, schema, log, page): if page in (0, 1, 2): ret = [] for count in range(0, 3): ret.append(cls._make_item(page * 3 + count, source_context)) return ret, page else: return [cls._make_item(9, source_context)], 3 class TrivialDataSourceContext(data_sources.AbstractContextManager): def __init__(self): self.chunk_size = 3 self.send_uncensored_pii_data = False @classmethod def build_from_web_request(cls, *unused_args, **unused_kwargs): return TrivialDataSourceContext() @classmethod def build_from_dict(cls, context_dict): return TrivialDataSourceContext() @classmethod def build_blank_default(cls, *unused_args, **unused_kwargs): return TrivialDataSourceContext() @classmethod def save_to_dict(cls, context): return {'chunk_size': 3} @classmethod def get_public_params_for_display(cls, context): return {'chunk_size': 3} @classmethod def equivalent(cls, a, b): return True @classmethod def _build_secret(cls, params): return None class StudentSchemaValidationTests(actions.TestBase): """Verify that Student schema (with/without PII) is correctly validated.""" def setUp(self): super(StudentSchemaValidationTests, self).setUp() self.app_context = actions.simple_add_course( COURSE_NAME, ADMIN_EMAIL, 'Data Pump') actions.login(USER_EMAIL, is_admin=False) actions.register(self, USER_NAME, COURSE_NAME) actions.login(ADMIN_EMAIL, is_admin=True) def _build_student_fetch_params(self, with_pii): ctx_class = rest_providers.StudentsDataSource.get_context_class() data_source_context = ctx_class.build_blank_default( params={'data_source_token': 'xyzzy'}, default_chunk_size=1) data_source_context.send_uncensored_pii_data = with_pii catch_and_log_ = catch_and_log.CatchAndLog() schema = rest_providers.StudentsDataSource.get_schema( self.app_context, catch_and_log_, data_source_context) return data_source_context, schema, catch_and_log_ def _test_student_schema(self, with_pii): source_ctx, schema, log_ = self._build_student_fetch_params(with_pii) values, _ = rest_providers.StudentsDataSource.fetch_values( self.app_context, source_ctx, schema, log_, 0) self.assertEquals(1, len(values)) complaints = transforms.validate_object_matches_json_schema( values[0], schema) self.assertEquals(0, len(complaints)) def test_student_schema_without_pii(self): self._test_student_schema(with_pii=False) def test_student_schema_including_pii(self): self._test_student_schema(with_pii=True) class SchemaConversionTests(actions.TestBase): def setUp(self): super(SchemaConversionTests, self).setUp() actions.login(ADMIN_EMAIL, is_admin=True) self.app_context = actions.simple_add_course( COURSE_NAME, ADMIN_EMAIL, 'Data Pump') data_sources.Registry.register(TrivialDataSource) self.job = data_pump.DataPumpJob(self.app_context, TrivialDataSource.__name__) def tearDown(self): data_sources.Registry.unregister(TrivialDataSource) def test_complex_conversion(self): reg = schema_fields.FieldRegistry('Complex') reg.add_property(schema_fields.SchemaField( 'an_integer', 'An Integer', 'integer', optional=True, description='an integer')) reg.add_property(schema_fields.SchemaField( 'a_string', 'A String', 'string', description='a string')) reg.add_property(schema_fields.SchemaField( 'some text', 'Some Text', 'text', description='some text')) reg.add_property(schema_fields.SchemaField( 'some html', 'Some HTML', 'html', description='some html')) reg.add_property(schema_fields.SchemaField( 'a url', 'A URL', 'url', description='a url')) reg.add_property(schema_fields.SchemaField( 'a file', 'A File', 'file', description='a file')) reg.add_property(schema_fields.SchemaField( 'a number', 'A Number', 'number', description='a number')) reg.add_property(schema_fields.SchemaField( 'a boolean', 'A Boolean', 'boolean', description='a boolean')) reg.add_property(schema_fields.SchemaField( 'a date', 'A Date', 'date', description='a date')) reg.add_property(schema_fields.SchemaField( 'a datetime', 'A DateTime', 'datetime', description='a datetime')) sub_registry = schema_fields.FieldRegistry('subregistry') sub_registry.add_property(schema_fields.SchemaField( 'name', 'Name', 'string', description='user name')) sub_registry.add_property(schema_fields.SchemaField( 'city', 'City', 'string', description='city name')) reg.add_sub_registry('sub_registry', title='Sub Registry', description='a sub-registry', registry=sub_registry) reg.add_property(schema_fields.FieldArray( 'simple_array', 'Simple Array', description='a simple array', item_type=schema_fields.SchemaField( 'array_int', 'Array Int', 'integer', description='array int'))) complex_array_type = schema_fields.FieldRegistry('complex_array_type') complex_array_type.add_property(schema_fields.SchemaField( 'this', 'This', 'string', description='the this')) complex_array_type.add_property(schema_fields.SchemaField( 'that', 'That', 'number', description='the that')) complex_array_type.add_property(schema_fields.SchemaField( 'these', 'These', 'datetime', description='the these')) reg.add_property(schema_fields.FieldArray( 'complex_array', 'Complex Array', description='complex array', item_type=complex_array_type)) actual_schema = self.job._json_schema_to_bigquery_schema( reg.get_json_schema_dict()['properties']) expected_schema = [ {'mode': 'NULLABLE', 'type': 'INTEGER', 'name': 'an_integer', 'description': 'an integer'}, {'mode': 'REQUIRED', 'type': 'STRING', 'name': 'a_string', 'description': 'a string'}, {'mode': 'REQUIRED', 'type': 'STRING', 'name': 'some text', 'description': 'some text'}, {'mode': 'REQUIRED', 'type': 'STRING', 'name': 'some html', 'description': 'some html'}, {'mode': 'REQUIRED', 'type': 'STRING', 'name': 'a url', 'description': 'a url'}, {'mode': 'REQUIRED', 'type': 'STRING', 'name': 'a file', 'description': 'a file'}, {'mode': 'REQUIRED', 'type': 'FLOAT', 'name': 'a number', 'description': 'a number'}, {'mode': 'REQUIRED', 'type': 'BOOLEAN', 'name': 'a boolean', 'description': 'a boolean'}, {'mode': 'REQUIRED', 'type': 'TIMESTAMP', 'name': 'a date', 'description': 'a date'}, {'mode': 'REQUIRED', 'type': 'TIMESTAMP', 'name': 'a datetime', 'description': 'a datetime'}, {'mode': 'REPEATED', 'type': 'INTEGER', 'name': 'simple_array', 'description': 'array int'}, {'fields': [ {'mode': 'REQUIRED', 'type': 'STRING', 'name': 'this', 'description': 'the this'}, {'mode': 'REQUIRED', 'type': 'FLOAT', 'name': 'that', 'description': 'the that'}, {'mode': 'REQUIRED', 'type': 'TIMESTAMP', 'name': 'these', 'description': 'the these'}], 'type': 'RECORD', 'name': 'complex_array', 'mode': 'REPEATED'}, {'fields': [ {'mode': 'REQUIRED', 'type': 'STRING', 'name': 'name', 'description': 'user name'}, {'mode': 'REQUIRED', 'type': 'STRING', 'name': 'city', 'description': 'city name'}], 'type': 'RECORD', 'name': 'sub_registry', 'mode': 'NULLABLE'} ] self.assertEqual(expected_schema, actual_schema) class PiiTests(actions.TestBase): def setUp(self): super(PiiTests, self).setUp() actions.login(ADMIN_EMAIL, is_admin=True) self.app_context = actions.simple_add_course( COURSE_NAME, ADMIN_EMAIL, 'Data Pump') data_sources.Registry.register(TrivialDataSource) self.job = data_pump.DataPumpJob(self.app_context, TrivialDataSource.__name__) def tearDown(self): data_sources.Registry.unregister(TrivialDataSource) def test_cannot_push_unregistered_class(self): class NotRegistered(data_sources.AbstractSmallRestDataSource): pass with self.assertRaises(ValueError): data_pump.DataPumpJob(self.app_context, NotRegistered.__name__) def test_cannot_push_unexportable_class(self): """Ensure classes not marked as exportable cannot be exported. Verify that this is enforced deeper in the code than simply not displaying visual UI elements on a web page, so that we are certain that feeds with PII (RawQuestionAnswers, I'm looking at you) are suppressed for export. """ class NotExportable(data_sources.AbstractSmallRestDataSource): @classmethod def get_name(cls): return 'not_exportable' data_sources.Registry.register(NotExportable) with self.assertRaises(ValueError): data_pump.DataPumpJob(self.app_context, NotExportable.__name__) data_sources.Registry.unregister(NotExportable) def test_get_pii_secret_with_blank_settings(self): secret, end_date = data_pump.DataPumpJob._parse_pii_encryption_token( data_pump.DataPumpJob._get_pii_token(self.app_context)) self.assertEqual(len(secret), data_pump.PII_SECRET_LENGTH) expected_end_date = ( datetime.datetime.now() + common_utils.parse_timedelta_string( data_pump.PII_SECRET_DEFAULT_LIFETIME)) unix_epoch = datetime.datetime(year=1970, month=1, day=1) expected_sec = (expected_end_date - unix_epoch).total_seconds() actual_sec = (end_date - unix_epoch).total_seconds() self.assertLessEqual(expected_sec - actual_sec, 1.0) def test_pii_secret_expiration(self): token = data_pump.DataPumpJob._build_new_pii_encryption_token('1s') self.assertTrue( data_pump.DataPumpJob._is_pii_encryption_token_valid(token)) time.sleep(1) self.assertFalse( data_pump.DataPumpJob._is_pii_encryption_token_valid(token)) def test_course_settings_used(self): course_settings = self.app_context.get_environ() pump_settings = {} course_settings[data_pump.DATA_PUMP_SETTINGS_SCHEMA_SECTION] = ( pump_settings) pump_settings[data_pump.TABLE_LIFETIME] = '2 s' course = courses.Course(None, app_context=self.app_context) course.save_settings(course_settings) old_token = data_pump.DataPumpJob._get_pii_token(self.app_context) time.sleep(2) new_token = data_pump.DataPumpJob._get_pii_token(self.app_context) self.assertNotEqual(old_token, new_token) self.assertFalse(data_pump.DataPumpJob._is_pii_encryption_token_valid( old_token)) self.assertTrue(data_pump.DataPumpJob._is_pii_encryption_token_valid( new_token)) def _test_student_pii_data(self, send_uncensored_pii_data): actions.login(USER_EMAIL) actions.register(self, USER_EMAIL, COURSE_NAME) actions.logout() actions.login(ADMIN_EMAIL) job = data_pump.DataPumpJob(self.app_context, rest_providers.StudentsDataSource.__name__) data_source_context = job._build_data_source_context() data_source_context.pii_secret = job._get_pii_secret(self.app_context) data_source_context.send_uncensored_pii_data = send_uncensored_pii_data data, is_last_page = job._fetch_page_data(self.app_context, data_source_context, 0) self.assertTrue(is_last_page) self.assertEqual(len(data), 1) return data[0] def test_student_pii_data_obscured(self): student_record = self._test_student_pii_data( send_uncensored_pii_data=False) with common_utils.Namespace('ns_' + COURSE_NAME): student = models.Student.get_by_email(USER_EMAIL) self.assertIsNotNone(student.user_id) self.assertIsNotNone(student_record['user_id']) self.assertNotEqual(student.user_id, student_record['user_id']) self.assertNotIn('name', student_record) self.assertNotIn('additional_fields', student_record) def test_student_pii_data_sent_when_commanded(self): student_record = self._test_student_pii_data( send_uncensored_pii_data=True) with common_utils.Namespace('ns_' + COURSE_NAME): student = models.Student.get_by_email(USER_EMAIL) self.assertIsNotNone(student.user_id) self.assertIsNotNone(student_record['user_id']) self.assertEqual(student.user_id, student_record['user_id']) self.assertEquals('user@foo.com', student_record['name']) self.assertEquals( 'user@foo.com', common_utils.find(lambda x: x['name'] == 'form01', student_record['additional_fields'])['value']) class MockResponse(object): def __init__(self, the_dict): self._the_dict = the_dict def get(self, name, default=None): if name in self._the_dict: return self._the_dict[name] return default def __getattr__(self, name): return self._the_dict[name] def __getitem__(self, name): return self._the_dict[name] def __contains__(self, name): return name in self._the_dict class MockHttp(object): def __init__(self): self.responses = [] self.request_args = None self.request_kwargs = None def add_response(self, headers_dict): self.responses.append(headers_dict) def request(self, *args, **kwargs): self.request_args = args self.request_kwargs = kwargs item = self.responses[0] del self.responses[0] if isinstance(item, Exception): raise item else: return MockResponse(item), '' class MockServiceClient(object): def __init__(self, mock_http): self.mock_http = mock_http self.calls = [] self.insert_args = None self.insert_kwargs = None def datasets(self, *unused_args, **unused_kwargs): self.calls.append('datasets') return self def tables(self, *unused_args, **unused_kwargs): self.calls.append('tables') return self def get(self, *unused_args, **unused_kwargs): self.calls.append('get') return self def insert(self, *args, **kwargs): self.calls.append('insert') self.insert_args = args self.insert_kwargs = kwargs return self def delete(self, *unused_args, **unused_kwargs): self.calls.append('delete') return self def execute(self, *unused_args, **unused_kwargs): self.calls.append('execute') return self.mock_http.request() class InteractionTests(actions.TestBase): def setUp(self): super(InteractionTests, self).setUp() actions.login(ADMIN_EMAIL, is_admin=True) self.app_context = actions.simple_add_course( COURSE_NAME, ADMIN_EMAIL, 'Data Pump') # Configure data pump settings. course_settings = self.app_context.get_environ() pump_settings = {} course_settings[data_pump.DATA_PUMP_SETTINGS_SCHEMA_SECTION] = ( pump_settings) pump_settings['project_id'] = 'foo' pump_settings['json_key'] = '{"private_key": "X", "client_email": "Y"}' course = courses.Course(None, app_context=self.app_context) course.save_settings(course_settings) # Remove all other data sources; ensure that we are the only source # causing text to appear on the UI page. Note: must do this by # affecting the array's contents; replacing the array itself will not # affect the references already held by compiled @classmethod # functions. self.save_registered_sources = [] self.save_registered_sources.extend( data_sources.Registry._data_source_classes) del data_sources.Registry._data_source_classes[:] data_sources.Registry.register(TrivialDataSource) # Build mocks for comms to BigQuery self.mock_http = MockHttp() self.mock_service_client = MockServiceClient(self.mock_http) self.save_bigquery_service_function = ( data_pump.DataPumpJob._get_bigquery_service) data_pump.DataPumpJob._get_bigquery_service = ( lambda slf, set: (self.mock_service_client, self.mock_http)) self._set_up_job(no_expiration_date=False, send_uncensored_pii_data=False) def _set_up_job(self, no_expiration_date=False, send_uncensored_pii_data=False): self.job = data_pump.DataPumpJob( self.app_context, TrivialDataSource.__name__, no_expiration_date, send_uncensored_pii_data) self.bigquery_settings = self.job._get_bigquery_settings( self.app_context) def tearDown(self): super(InteractionTests, self).tearDown() data_sources.Registry.unregister(TrivialDataSource) data_pump.DataPumpJob._get_bigquery_service = ( self.save_bigquery_service_function) del data_sources.Registry._data_source_classes[:] data_sources.Registry._data_source_classes.extend( self.save_registered_sources) class BigQueryInteractionTests(InteractionTests): def test_does_not_create_dataset_when_already_exists(self): self.mock_http.add_response({'status': 200}) self.job._maybe_create_course_dataset(self.mock_service_client, self.bigquery_settings) self.assertEqual( ['datasets', 'get', 'execute'], self.mock_service_client.calls) def test_does_create_dataset_when_none_exists(self): self.mock_http.add_response(apiclient.errors.HttpError( MockResponse({'status': 404}), '')) self.mock_http.add_response({'status': 200}) self.job._maybe_create_course_dataset(self.mock_service_client, self.bigquery_settings) self.assertEqual( ['datasets', 'get', 'execute', 'insert', 'execute'], self.mock_service_client.calls) def test_create_dataset_raises_500(self): self.mock_http.add_response(apiclient.errors.HttpError( MockResponse({'status': 500}), '')) with self.assertRaises(apiclient.errors.HttpError): self.job._maybe_create_course_dataset(self.mock_service_client, self.bigquery_settings) def test_delete_table_ignores_404(self): self.mock_http.add_response(apiclient.errors.HttpError( MockResponse({'status': 404}), '')) self.job._maybe_delete_previous_table( self.mock_service_client, self.bigquery_settings, TrivialDataSource) self.assertEqual( ['delete', 'execute'], self.mock_service_client.calls) def test_delete_table_accepts_200(self): self.mock_http.add_response({'status': 200}) self.job._maybe_delete_previous_table( self.mock_service_client, self.bigquery_settings, TrivialDataSource) self.assertEqual( ['delete', 'execute'], self.mock_service_client.calls) def test_delete_table_raises_500(self): self.mock_http.add_response(apiclient.errors.HttpError( MockResponse({'status': 500}), '')) with self.assertRaises(apiclient.errors.HttpError): self.job._maybe_delete_previous_table( self.mock_service_client, self.bigquery_settings, TrivialDataSource) def test_create_data_table_accepts_200(self): self.mock_http.add_response({'status': 200}) self.job._create_data_table( self.mock_service_client, self.bigquery_settings, None, TrivialDataSource) def test_create_data_table_raises_404(self): self.mock_http.add_response(apiclient.errors.HttpError( MockResponse({'status': 404}), '')) with self.assertRaises(apiclient.errors.HttpError): self.job._create_data_table( self.mock_service_client, self.bigquery_settings, None, TrivialDataSource) def test_create_upload_job_accepts_200(self): self.mock_http.add_response({'status': 200, 'location': 'there'}) location = self.job._create_upload_job( self.mock_http, self.bigquery_settings, TrivialDataSource) self.assertEqual(location, 'there') def test_create_upload_receiving_response_without_location_is_error(self): self.mock_http.add_response({'status': 200}) with self.assertRaises(Exception): self.job._create_upload_job( self.mock_http, self.bigquery_settings, TrivialDataSource) def test_create_upload_receiving_non_200_response_is_error(self): self.mock_http.add_response({'status': 204, 'location': 'there'}) with self.assertRaises(Exception): self.job._create_upload_job( self.mock_http, self.bigquery_settings, TrivialDataSource) def _initiate_upload_job(self): self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200, 'location': 'there'}) return self.job._initiate_upload_job( self.mock_service_client, self.bigquery_settings, self.mock_http, self.app_context, self.job._build_data_source_context()) def test_create_data_table_makes_non_pii_schema(self): self._initiate_upload_job() fields = ( self.mock_service_client.insert_kwargs['body']['schema']['fields']) self.assertIsNotNone( common_utils.find(lambda f: f['name'] == 'thing', fields)) self.assertIsNone( common_utils.find(lambda f: f['name'] == 'ssn', fields)) def test_create_data_table_makes_pii_schema(self): self._set_up_job(no_expiration_date=False, send_uncensored_pii_data=True) self._initiate_upload_job() fields = ( self.mock_service_client.insert_kwargs['body']['schema']['fields']) self.assertIsNotNone( common_utils.find(lambda f: f['name'] == 'thing', fields)) self.assertIsNotNone( common_utils.find(lambda f: f['name'] == 'ssn', fields)) def test_create_data_table_sends_default_expiration(self): self._initiate_upload_job() utc_now = datetime.datetime.utcnow() utc_epoch = datetime.datetime.utcfromtimestamp(0) expected = ((utc_now - utc_epoch).total_seconds() + self.bigquery_settings.table_lifetime_seconds) * 1000 # Ensure we have default value (not zero) self.assertEquals(30 * 24 * 60 *60, self.bigquery_settings.table_lifetime_seconds) # Ensure table expiration timestamp sent to BigQuery matches setting. actual = ( self.mock_service_client.insert_kwargs['body']['expirationTime']) self.assertAlmostEqual(expected, actual, delta=2000) def test_create_data_table_sends_configured_expiration(self): course_settings = self.app_context.get_environ() course_settings[data_pump.DATA_PUMP_SETTINGS_SCHEMA_SECTION][ data_pump.TABLE_LIFETIME] = '10 s' course = courses.Course(None, app_context=self.app_context) course.save_settings(course_settings) self._set_up_job(no_expiration_date=False, send_uncensored_pii_data=False) self._initiate_upload_job() utc_now = datetime.datetime.utcnow() utc_epoch = datetime.datetime.utcfromtimestamp(0) expected = ((utc_now - utc_epoch).total_seconds() + self.bigquery_settings.table_lifetime_seconds) * 1000 # Ensure we have override from default value. self.assertEquals(10, self.bigquery_settings.table_lifetime_seconds) # Ensure table expiration timestamp sent to BigQuery matches setting. actual = ( self.mock_service_client.insert_kwargs['body']['expirationTime']) self.assertAlmostEqual(expected, actual, delta=2000) def test_table_expiration_suppressed(self): self._set_up_job(no_expiration_date=True, send_uncensored_pii_data=False) self._initiate_upload_job() self.assertNotIn('expirationTime', self.mock_service_client.insert_kwargs['body']) def test_initiate_upload_job(self): location = self._initiate_upload_job() self.assertEqual(location, 'there') def test_check_state_just_started(self): self.job.submit() # Saves state, but does not run queued item. job_context = self.job._build_job_context('unused', 'unused') self.mock_http.add_response({'status': 308}) next_page, next_status = self.job._check_upload_state( self.mock_http, job_context) self.assertEqual(next_page, 0) self.assertEqual(next_status, jobs.STATUS_CODE_STARTED) self.assertEqual(len(job_context[data_pump.CONSECUTIVE_FAILURES]), 0) def test_check_state_last_page_not_recieved(self): self.job.submit() # Saves state, but does not run queued item. job_context = self.job._build_job_context('unused', 'unused') job_context[data_pump.LAST_PAGE_SENT] = 6 job_context[data_pump.LAST_START_OFFSET] = 5 job_context[data_pump.LAST_END_OFFSET] = 6 self.mock_http.add_response({'status': 308, 'range': '0-5'}) next_page, next_status = self.job._check_upload_state( self.mock_http, job_context) self.assertEqual(next_page, 6) self.assertEqual(next_status, jobs.STATUS_CODE_STARTED) self.assertEqual(len(job_context[data_pump.CONSECUTIVE_FAILURES]), 1) def test_check_state_last_page_received(self): self.job.submit() # Saves state, but does not run queued item. job_context = self.job._build_job_context('unused', 'unused') job_context[data_pump.LAST_PAGE_SENT] = 6 job_context[data_pump.LAST_START_OFFSET] = 5 job_context[data_pump.LAST_END_OFFSET] = 6 self.mock_http.add_response({'status': 308, 'range': '0-6'}) next_page, next_status = self.job._check_upload_state( self.mock_http, job_context) self.assertEqual(next_page, 7) self.assertEqual(next_status, jobs.STATUS_CODE_STARTED) self.assertEqual(len(job_context[data_pump.CONSECUTIVE_FAILURES]), 0) def test_check_state_last_page_has_bad_range_too_low(self): self.job.submit() # Saves state, but does not run queued item. job_context = self.job._build_job_context('unused', 'unused') job_context[data_pump.LAST_PAGE_SENT] = 6 job_context[data_pump.LAST_START_OFFSET] = 5 job_context[data_pump.LAST_END_OFFSET] = 6 self.mock_http.add_response({'status': 308, 'range': '0-3'}) with self.assertRaises(ValueError): self.job._check_upload_state(self.mock_http, job_context) def test_check_state_last_page_has_bad_range_too_high(self): self.job.submit() # Saves state, but does not run queued item. job_context = self.job._build_job_context('unused', 'unused') job_context[data_pump.LAST_PAGE_SENT] = 6 job_context[data_pump.LAST_START_OFFSET] = 5 job_context[data_pump.LAST_END_OFFSET] = 6 self.mock_http.add_response({'status': 308, 'range': '0-7'}) with self.assertRaises(ValueError): self.job._check_upload_state(self.mock_http, job_context) def test_check_state_completed(self): self.job.submit() # Saves state, but does not run queued item. job_context = self.job._build_job_context('unused', 'unused') self.mock_http.add_response({'status': 200}) next_page, next_status = self.job._check_upload_state( self.mock_http, job_context) self.assertEqual(next_page, None) self.assertEqual(next_status, jobs.STATUS_CODE_COMPLETED) self.assertEqual(len(job_context[data_pump.CONSECUTIVE_FAILURES]), 0) def test_check_state_disappeared(self): self.job.submit() # Saves state, but does not run queued item. job_context = self.job._build_job_context('unused', 'unused') self.mock_http.add_response({'status': 404}) next_page, next_status = self.job._check_upload_state( self.mock_http, job_context) self.assertEqual(next_page, None) self.assertEqual(next_status, jobs.STATUS_CODE_QUEUED) self.assertEqual(len(job_context[data_pump.CONSECUTIVE_FAILURES]), 0) def test_check_state_server_error(self): self.job.submit() # Saves state, but does not run queued item. job_context = self.job._build_job_context('unused', 'unused') self.mock_http.add_response({'status': 503}) next_page, next_status = self.job._check_upload_state( self.mock_http, job_context) self.assertEqual(next_page, None) self.assertEqual(next_status, jobs.STATUS_CODE_STARTED) self.assertEqual(len(job_context[data_pump.CONSECUTIVE_FAILURES]), 1) def test_check_state_unexpected_code(self): self.job.submit() # Saves state, but does not run queued item. job_context = self.job._build_job_context('unused', 'unused') self.mock_http.add_response({'status': 400}) with self.assertRaises(ValueError): self.job._check_upload_state(self.mock_http, job_context) def test_check_state_recoverable_failure_then_success(self): self.job.submit() # Saves state, but does not run queued item. job_context = self.job._build_job_context('unused', 'unused') job_context[data_pump.LAST_PAGE_SENT] = 6 job_context[data_pump.LAST_START_OFFSET] = 5 job_context[data_pump.LAST_END_OFFSET] = 6 self.mock_http.add_response({'status': 308, 'range': '0-5'}) self.job._check_upload_state(self.mock_http, job_context) self.assertEqual(len(job_context[data_pump.CONSECUTIVE_FAILURES]), 1) # We want to _not_ see the error clear if we're just checking on # upload. self.mock_http.add_response({'status': 308, 'range': '0-6'}) self.job._check_upload_state(self.mock_http, job_context) self.assertEqual(len(job_context[data_pump.CONSECUTIVE_FAILURES]), 1) def test_send_first_page_as_last_page(self): self.job.submit() # Saves state, but does not run queued item. job_status_object = self.job.load() job_context = self.job._build_job_context('unused', 'unused') data_source_context = self.job._build_data_source_context() self.mock_http.add_response({'status': 308, 'range': '0-1'}) next_state = self.job._send_data_page_to_bigquery( data=[1], is_last_chunk=True, next_page=0, http=self.mock_http, job=job_status_object, sequence_num=job_status_object.sequence_num, job_context=job_context, data_source_context=data_source_context) self.assertEqual(next_state, jobs.STATUS_CODE_STARTED) self.assertEqual( self.mock_http.request_kwargs['headers']['Content-Range'], 'bytes 0-1/2') def test_send_first_page_as_non_last_page(self): self.job.submit() # Saves state, but does not run queued item. job_status_object = self.job.load() job_context = self.job._build_job_context('unused', 'unused') data_source_context = self.job._build_data_source_context() self.mock_http.add_response({'status': 308, 'range': '0-1'}) next_state = self.job._send_data_page_to_bigquery( data=[1], is_last_chunk=False, next_page=0, http=self.mock_http, job=job_status_object, sequence_num=job_status_object.sequence_num, job_context=job_context, data_source_context=data_source_context) self.assertEqual(next_state, jobs.STATUS_CODE_STARTED) self.assertEqual( self.mock_http.request_kwargs['headers']['Content-Range'], 'bytes 0-262143/*') def test_resend_first_page_as_last_page(self): self.job.submit() # Saves state, but does not run queued item. job_status_object = self.job.load() job_context = self.job._build_job_context('unused', 'unused') job_context[data_pump.LAST_PAGE_SENT] = 0 job_context[data_pump.LAST_START_OFFSET] = 0 job_context[data_pump.LAST_END_OFFSET] = 1 data_source_context = self.job._build_data_source_context() self.mock_http.add_response({'status': 308, 'range': '0-1'}) next_state = self.job._send_data_page_to_bigquery( data=[1], is_last_chunk=True, next_page=0, http=self.mock_http, job=job_status_object, sequence_num=job_status_object.sequence_num, job_context=job_context, data_source_context=data_source_context) self.assertEqual(next_state, jobs.STATUS_CODE_STARTED) self.assertEqual( self.mock_http.request_kwargs['headers']['Content-Range'], 'bytes 0-1/2') def test_send_subsequent_page_as_last_page(self): self.job.submit() # Saves state, but does not run queued item. job_status_object = self.job.load() job_context = self.job._build_job_context('unused', 'unused') job_context[data_pump.LAST_PAGE_SENT] = 0 job_context[data_pump.LAST_START_OFFSET] = 0 job_context[data_pump.LAST_END_OFFSET] = 262143 data_source_context = self.job._build_data_source_context() self.mock_http.add_response({'status': 308, 'range': '0-262145'}) next_state = self.job._send_data_page_to_bigquery( data=[1], is_last_chunk=True, next_page=1, http=self.mock_http, job=job_status_object, sequence_num=job_status_object.sequence_num, job_context=job_context, data_source_context=data_source_context) self.assertEqual(next_state, jobs.STATUS_CODE_STARTED) self.assertEqual( self.mock_http.request_kwargs['headers']['Content-Range'], 'bytes 262144-262145/262146') def test_send_failure_then_success(self): self.job.submit() # Saves state, but does not run queued item. job_status_object = self.job.load() job_context = self.job._build_job_context('unused', 'unused') data_source_context = self.job._build_data_source_context() # Here, we have the server respond without a 'Range' header, # indicating that it has not seen _any_ data at all from us, # so we incur a transient failure. self.mock_http.add_response({'status': 308}) self.job._send_data_page_to_bigquery( data=[1], is_last_chunk=True, next_page=0, http=self.mock_http, job=job_status_object, sequence_num=job_status_object.sequence_num, job_context=job_context, data_source_context=data_source_context) self.assertEqual(len(job_context[data_pump.CONSECUTIVE_FAILURES]), 1) # And here, we claim the server has seen everything we need to send, # and so we should also see the consecutive failures list clear out. self.mock_http.add_response({'status': 308, 'range': '0-1'}) self.job._send_data_page_to_bigquery( data=[1], is_last_chunk=True, next_page=0, http=self.mock_http, job=job_status_object, sequence_num=job_status_object.sequence_num, job_context=job_context, data_source_context=data_source_context) self.assertEqual(len(job_context[data_pump.CONSECUTIVE_FAILURES]), 0) def test_excessive_retries_causes_failure(self): self.job.submit() job_object = self.job.load() # Dataset exists; table deletion, table creation, job initiation. self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200, 'location': 'there'}) # Fail on status check, even before sending data N-1 times. for _ in range(0, data_pump.MAX_CONSECUTIVE_FAILURES - 1): self.mock_http.add_response({'status': 500}) self.execute_all_deferred_tasks(iteration_limit=1) job_object = self.job.load() job_context, _ = self.job._load_state(job_object, job_object.sequence_num) self.assertEqual(job_object.status_code, jobs.STATUS_CODE_STARTED) self.assertEqual(0, job_context[data_pump.ITEMS_UPLOADED]) self.assertEqual(-1, job_context[data_pump.LAST_PAGE_SENT]) self.assertEqual(0, job_context[data_pump.LAST_START_OFFSET]) self.assertEqual(-1, job_context[data_pump.LAST_END_OFFSET]) # Last failure pops exception to notify queue to abandon this job. self.mock_http.add_response({'status': 500}) with self.assertRaises(deferred.PermanentTaskFailure): self.execute_all_deferred_tasks(iteration_limit=1) job_object = self.job.load() self.assertEqual(job_object.status_code, jobs.STATUS_CODE_FAILED) # Verify job did not re-queue itself after declaring failure num_tasks = self.execute_all_deferred_tasks(iteration_limit=1) self.assertEqual(0, num_tasks) def test_cancellation(self): self.job.submit() job_object = self.job.load() # Dataset exists; table deletion, table creation, job initiation. self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200, 'location': 'there'}) # Initial page check - no 'range' header when no data sent. # Initial page send; response indicates full recipt of page #0 self.mock_http.add_response({'status': 308}) self.mock_http.add_response({'status': 308, 'range': '0-262143'}) self.execute_all_deferred_tasks(iteration_limit=1) job_object = self.job.load() self.assertEqual(job_object.status_code, jobs.STATUS_CODE_STARTED) # Cancel job. Set mock server to pretend upload completed; # cancellation should take priority. self.job.cancel() self.mock_http.add_response({'status': 200}) num_tasks = self.execute_all_deferred_tasks(iteration_limit=1) job_object = self.job.load() self.assertEqual(1, num_tasks) self.assertEqual(job_object.status_code, jobs.STATUS_CODE_FAILED) # Verify job did not re-queue itself after declaring failure num_tasks = self.execute_all_deferred_tasks(iteration_limit=1) self.assertEqual(0, num_tasks) def test_upload_job_expiration(self): self.job.submit() job_object = self.job.load() # Dataset exists; table deletion, table creation, job initiation. self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200, 'location': 'there'}) # Initial page check - no 'range' header when no data sent. # Initial page send; response indicates full recipt of page #0 self.mock_http.add_response({'status': 308}) self.mock_http.add_response({'status': 308, 'range': '0-262143'}) self.execute_all_deferred_tasks(iteration_limit=1) job_object = self.job.load() job_context, _ = self.job._load_state(job_object, job_object.sequence_num) self.assertEqual(job_object.status_code, jobs.STATUS_CODE_STARTED) self.assertEqual(3, job_context[data_pump.ITEMS_UPLOADED]) self.assertEqual(0, job_context[data_pump.LAST_PAGE_SENT]) self.assertEqual(0, job_context[data_pump.LAST_START_OFFSET]) self.assertEqual(262143, job_context[data_pump.LAST_END_OFFSET]) # Server acepts page #1 correctly as well. Here, we're doing # one more page so that when we check lower down to see where # we are, we will appear to have gone backwards as to how far # the upload has proceeded. This is to verify the full reset # of internal state on upload timeout. self.mock_http.add_response({'status': 308, 'range': '0-262143'}) self.mock_http.add_response({'status': 308, 'range': '262144-524287'}) self.execute_all_deferred_tasks(iteration_limit=1) job_object = self.job.load() job_context, _ = self.job._load_state(job_object, job_object.sequence_num) self.assertEqual(job_object.status_code, jobs.STATUS_CODE_STARTED) self.assertEqual(6, job_context[data_pump.ITEMS_UPLOADED]) self.assertEqual(1, job_context[data_pump.LAST_PAGE_SENT]) self.assertEqual(262144, job_context[data_pump.LAST_START_OFFSET]) self.assertEqual(524287, job_context[data_pump.LAST_END_OFFSET]) self.assertEqual(0, len(job_context[data_pump.CONSECUTIVE_FAILURES])) # Here, we have a job status object claiming we've made some progress. # Now set mock server to claim upload job has been reclaimed due to # long inactivity (return 404) self.mock_http.add_response({'status': 404}) num_tasks = self.execute_all_deferred_tasks(iteration_limit=1) job_object = self.job.load() job_context, _ = self.job._load_state(job_object, job_object.sequence_num) self.assertEqual(job_object.status_code, jobs.STATUS_CODE_QUEUED) # Since we claimed to be queued, logic should start over and # attempt to re-push content. Verify that we have started over # from scratch. self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200, 'location': 'there'}) self.mock_http.add_response({'status': 308}) self.mock_http.add_response({'status': 308, 'range': '0-262143'}) self.execute_all_deferred_tasks(iteration_limit=1) job_object = self.job.load() job_context, _ = self.job._load_state(job_object, job_object.sequence_num) self.assertEqual(job_object.status_code, jobs.STATUS_CODE_STARTED) self.assertEqual(3, job_context[data_pump.ITEMS_UPLOADED]) self.assertEqual(0, job_context[data_pump.LAST_PAGE_SENT]) self.assertEqual(0, job_context[data_pump.LAST_START_OFFSET]) self.assertEqual(262143, job_context[data_pump.LAST_END_OFFSET]) # Here, we have tested everything we need to. Now lie to the # uploader so it will think it has completed. Next, verify that # no items are on the queue (so we don't screw up sibling tests) self.mock_http.add_response({'status': 200}) self.execute_all_deferred_tasks(iteration_limit=1) num_tasks = self.execute_all_deferred_tasks(iteration_limit=1) self.assertEqual(0, num_tasks) def test_full_job_lifecycle(self): self.job.submit() job_object = self.job.load() self.assertEqual(job_object.status_code, jobs.STATUS_CODE_QUEUED) # Dataset exists; table deletion, table creation, job initiation. self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200, 'location': 'there'}) # Initial page check - no 'range' header when no data sent. # Initial page send; response indicates full recipt of page #0 self.mock_http.add_response({'status': 308}) self.mock_http.add_response({'status': 308, 'range': '0-262143'}) self.execute_all_deferred_tasks(iteration_limit=1) job_object = self.job.load() job_context, _ = self.job._load_state(job_object, job_object.sequence_num) self.assertEqual(job_object.status_code, jobs.STATUS_CODE_STARTED) self.assertEqual(3, job_context[data_pump.ITEMS_UPLOADED]) self.assertEqual(0, job_context[data_pump.LAST_PAGE_SENT]) self.assertEqual(0, job_context[data_pump.LAST_START_OFFSET]) self.assertEqual(262143, job_context[data_pump.LAST_END_OFFSET]) # Re-check on re-entry to main function; still have bytes [0..38] # On send of 2nd page, pretend to not have heard, staying at [0..38] self.mock_http.add_response({'status': 308, 'range': '0-262143'}) self.mock_http.add_response({'status': 308, 'range': '0-262143'}) self.execute_all_deferred_tasks(iteration_limit=1) job_object = self.job.load() job_context, _ = self.job._load_state(job_object, job_object.sequence_num) self.assertEqual(job_object.status_code, jobs.STATUS_CODE_STARTED) self.assertEqual(3, job_context[data_pump.ITEMS_UPLOADED]) self.assertEqual(1, job_context[data_pump.LAST_PAGE_SENT]) self.assertEqual(262144, job_context[data_pump.LAST_START_OFFSET]) self.assertEqual(524287, job_context[data_pump.LAST_END_OFFSET]) self.assertEqual(1, len(job_context[data_pump.CONSECUTIVE_FAILURES])) # Pretend server is having trouble and is returning 500's. # Only the status-check call will run; we should not attempt to # upload data to a server that's having trouble. # We expect to see one more item in the consecutive failures # list. We also expect at least 4 seconds to elapse. self.mock_http.add_response({'status': 500}) self.execute_all_deferred_tasks(iteration_limit=1) job_object = self.job.load() job_context, _ = self.job._load_state(job_object, job_object.sequence_num) self.assertEqual(job_object.status_code, jobs.STATUS_CODE_STARTED) self.assertEqual(3, job_context[data_pump.ITEMS_UPLOADED]) self.assertEqual(1, job_context[data_pump.LAST_PAGE_SENT]) self.assertEqual(262144, job_context[data_pump.LAST_START_OFFSET]) self.assertEqual(524287, job_context[data_pump.LAST_END_OFFSET]) self.assertEqual(2, len(job_context[data_pump.CONSECUTIVE_FAILURES])) # OK, server is now well, and accepts page #1 successfully. self.mock_http.add_response({'status': 308, 'range': '0-262143'}) self.mock_http.add_response({'status': 308, 'range': '262144-524287'}) self.execute_all_deferred_tasks(iteration_limit=1) job_object = self.job.load() job_context, _ = self.job._load_state(job_object, job_object.sequence_num) self.assertEqual(job_object.status_code, jobs.STATUS_CODE_STARTED) self.assertEqual(6, job_context[data_pump.ITEMS_UPLOADED]) self.assertEqual(1, job_context[data_pump.LAST_PAGE_SENT]) self.assertEqual(262144, job_context[data_pump.LAST_START_OFFSET]) self.assertEqual(524287, job_context[data_pump.LAST_END_OFFSET]) self.assertEqual(0, len(job_context[data_pump.CONSECUTIVE_FAILURES])) # OK, server is now well, and accepts page #2 successfully. self.mock_http.add_response({'status': 308, 'range': '262144-524287'}) self.mock_http.add_response({'status': 308, 'range': '524288-786431'}) self.execute_all_deferred_tasks(iteration_limit=1) job_object = self.job.load() job_context, _ = self.job._load_state(job_object, job_object.sequence_num) self.assertEqual(job_object.status_code, jobs.STATUS_CODE_STARTED) self.assertEqual(9, job_context[data_pump.ITEMS_UPLOADED]) self.assertEqual(2, job_context[data_pump.LAST_PAGE_SENT]) self.assertEqual(524288, job_context[data_pump.LAST_START_OFFSET]) self.assertEqual(786431, job_context[data_pump.LAST_END_OFFSET]) self.assertEqual(0, len(job_context[data_pump.CONSECUTIVE_FAILURES])) # OK, server is now well, and accepts page #3 successfully. Here, # server acknowledges receipt of last page w/ a 200 rather than a 308; # we should notice that and mark ourselves complete. self.mock_http.add_response({'status': 308, 'range': '524288-786431'}) self.mock_http.add_response({'status': 200, 'range': '786432-786444'}) self.execute_all_deferred_tasks(iteration_limit=1) job_object = self.job.load() job_context, _ = self.job._load_state(job_object, job_object.sequence_num) self.assertEqual(job_object.status_code, jobs.STATUS_CODE_COMPLETED) self.assertEqual(10, job_context[data_pump.ITEMS_UPLOADED]) self.assertEqual(3, job_context[data_pump.LAST_PAGE_SENT]) self.assertEqual(786432, job_context[data_pump.LAST_START_OFFSET]) self.assertEqual(786444, job_context[data_pump.LAST_END_OFFSET]) self.assertEqual(0, len(job_context[data_pump.CONSECUTIVE_FAILURES])) # And verify job did not re-queue itself after declaring success. num_tasks = self.execute_all_deferred_tasks(iteration_limit=1) self.assertEqual(0, num_tasks) class UserInteractionTests(InteractionTests): URL = '/data_pump/dashboard?action=analytics&tab=data_pump' def test_no_data_pump_settings(self): course_settings = self.app_context.get_environ() del course_settings[data_pump.DATA_PUMP_SETTINGS_SCHEMA_SECTION] course = courses.Course(None, app_context=self.app_context) course.save_settings(course_settings) response = self.get(self.URL) self.assertIn( 'Data pump functionality is not currently enabled', response.body) def _get_status_text(self): dom = self.parse_html_string(self.get(self.URL).body) row = dom.find('.//tr[@id="TrivialDataSource"]') cell = row.find('.//td[@class="status-column"]') # Convert all whitespace sequences to single spaces. text = ' '.join(''.join(cell.itertext()).strip().split()) return text def test_full_job_lifecycle(self): self.assertEquals( 'Trivial Data Source ' 'Pump status: Has Never Run ' 'Do not encrypt PII data for this upload ' 'Uploaded data never expires (default expiration is 30 days)', self._get_status_text()) response = self.get(self.URL) self.submit(response.forms['data_pump_form_TrivialDataSource'], response) # Dataset exists; table deletion, table creation, job initiation. self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200, 'location': 'there'}) # Initial page check - no 'range' header when no data sent. # Initial page send; response indicates full recipt of page #0 self.mock_http.add_response({'status': 308}) self.mock_http.add_response({'status': 308, 'range': '0-262143'}) self.execute_all_deferred_tasks(iteration_limit=1) self.assertEqual('Trivial Data Source ' 'Pump status: Started ' 'Uploaded 3 items.', self._get_status_text()) # Re-check on re-entry to main function; still have bytes [0..38] # On send of 2nd page, pretend to not have heard, staying at [0..38] self.mock_http.add_response({'status': 308, 'range': '0-262143'}) self.mock_http.add_response({'status': 308, 'range': '0-262143'}) self.execute_all_deferred_tasks(iteration_limit=1) status_text = self._get_status_text() self.assertIn('Trivial Data Source', status_text) self.assertIn('Pump status: Started', status_text) self.assertIn('Uploaded 3 items.', status_text) self.assertIn('Incomplete upload detected - 0 of 262144 bytes ' 'received for page 1', status_text) # Pretend server is having trouble and is returning 500's. # Only the status-check call will run; we should not attempt to # upload data to a server that's having trouble. # We expect to see one more item in the consecutive failures # list. We also expect at least 4 seconds to elapse. self.mock_http.add_response({'status': 500}) self.execute_all_deferred_tasks(iteration_limit=1) status_text = self._get_status_text() self.assertIn('Trivial Data Source', status_text) self.assertIn('Pump status: Started', status_text) self.assertIn('Uploaded 3 items.', status_text) self.assertIn('Incomplete upload detected - 0 of 262144 bytes ' 'received for page 1', status_text) self.assertIn('Retryable server error 500', status_text) # OK, server is now well, and accepts page #1 successfully. self.mock_http.add_response({'status': 308, 'range': '0-262143'}) self.mock_http.add_response({'status': 308, 'range': '262144-524287'}) self.execute_all_deferred_tasks(iteration_limit=1) status_text = self._get_status_text() # Here note that transient failure messages are now gone. self.assertEquals('Trivial Data Source ' 'Pump status: Started ' 'Uploaded 6 items.', status_text) # OK, server is now well, and accepts page #2 successfully. self.mock_http.add_response({'status': 308, 'range': '262144-524287'}) self.mock_http.add_response({'status': 308, 'range': '524288-786431'}) self.execute_all_deferred_tasks(iteration_limit=1) status_text = self._get_status_text() self.assertEquals('Trivial Data Source ' 'Pump status: Started ' 'Uploaded 9 items.', status_text) # OK, server is now well, and accepts page #3 successfully. Here, # server acknowledges receipt of last page w/ a 200 rather than a 308; # we should notice that and mark ourselves complete. self.mock_http.add_response({'status': 308, 'range': '524288-786431'}) self.mock_http.add_response({'status': 200, 'range': '786432-786444'}) self.execute_all_deferred_tasks(iteration_limit=1) status_text = self._get_status_text() self.assertEquals( 'Trivial Data Source ' 'Pump status: Completed ' 'Uploaded 10 items. ' 'Do not encrypt PII data for this upload ' 'Uploaded data never expires (default expiration is 30 days)', status_text) def test_cancellation(self): self.assertEquals( 'Trivial Data Source ' 'Pump status: Has Never Run ' 'Do not encrypt PII data for this upload ' 'Uploaded data never expires (default expiration is 30 days)', self._get_status_text()) response = self.get(self.URL) self.submit(response.forms['data_pump_form_TrivialDataSource'], response) # Dataset exists; table deletion, table creation, job initiation. self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200, 'location': 'there'}) # Initial page check - no 'range' header when no data sent. # Initial page send; response indicates full recipt of page #0 self.mock_http.add_response({'status': 308}) self.mock_http.add_response({'status': 308, 'range': '0-262143'}) self.execute_all_deferred_tasks(iteration_limit=1) self.assertEqual('Trivial Data Source ' 'Pump status: Started ' 'Uploaded 3 items.', self._get_status_text()) response = self.get(self.URL) self.submit(response.forms['data_pump_form_TrivialDataSource'], response) self.execute_all_deferred_tasks() self.assertIn('Trivial Data Source ' 'Pump status: Failed ' 'Canceled by admin@foo.com', self._get_status_text()) def test_pii_expiration_warning(self): course_settings = self.app_context.get_environ() pump_settings = ( course_settings[data_pump.DATA_PUMP_SETTINGS_SCHEMA_SECTION]) pump_settings[data_pump.TABLE_LIFETIME] = '1 s' course = courses.Course(None, app_context=self.app_context) course.save_settings(course_settings) # Push full content of TrivialDataSource to BigQuery response = self.get(self.URL) self.submit(response.forms['data_pump_form_TrivialDataSource'], response) self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200}) self.mock_http.add_response({'status': 200, 'location': 'there'}) self.mock_http.add_response({'status': 308}) self.mock_http.add_response({'status': 308, 'range': '0-262143'}) self.mock_http.add_response({'status': 308, 'range': '0-262143'}) self.mock_http.add_response({'status': 308, 'range': '262144-524287'}) self.mock_http.add_response({'status': 308, 'range': '262144-524287'}) self.mock_http.add_response({'status': 308, 'range': '524288-786431'}) self.mock_http.add_response({'status': 308, 'range': '524288-786431'}) self.mock_http.add_response({'status': 200, 'range': '786432-786444'}) self.execute_all_deferred_tasks() time.sleep(1) self.assertEquals( 'Trivial Data Source ' 'Pump status: Completed ' 'WARNING: This data source was last uploaded when a different ' 'secret for encoding personal data was in use. Data from this ' 'source will not be correlatable with other data sources ' 'uploaded using the latest secret. You may wish to re-upload ' 'this data. ' 'Uploaded 10 items. ' 'Do not encrypt PII data for this upload ' 'Uploaded data never expires (default expiration is 1 s)', self._get_status_text())
Python
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Functional tests for models/utils.py.""" __author__ = [ 'johncox@google.com (John Cox)', ] from models import counters from models import utils from tests.functional import actions from google.appengine.ext import db class Model(db.Model): create_date = db.DateTimeProperty(auto_now=True, indexed=True) number = db.IntegerProperty(indexed=True) string = db.StringProperty() def process(model, number, string=None): model.number = number model.string = string db.put(model) def stop_mapping_at_5(model): if model.number == 5: raise utils.StopMapping class QueryMapperTest(actions.TestBase): """Tests for utils.QueryMapper.""" def test_raising_stop_mapping_stops_execution(self): db.put([Model(number=x) for x in xrange(11)]) num_processed = utils.QueryMapper( Model.all().order('number')).run(stop_mapping_at_5) self.assertEqual(5, num_processed) def test_run_processes_empty_result_set(self): self.assertEqual( 0, utils.QueryMapper(Model.all()).run(process, 1, string='foo')) def test_run_processes_one_entity(self): """Tests that we can process < batch_size results.""" Model().put() num_processed = utils.QueryMapper( Model.all()).run(process, 1, string='foo') model = Model.all().get() self.assertEqual(1, num_processed) self.assertEqual(1, model.number) self.assertEqual('foo', model.string) def test_run_process_more_than_1000_entities(self): """Tests we can process more entities than the old limit of 1k.""" counter = counters.PerfCounter( 'test-run-process-more-than-1000-entities-counter', 'counter for testing increment by QueryMapper') db.put([Model() for _ in xrange(1001)]) # Also pass custom args to QueryMapper ctor. num_processed = utils.QueryMapper( Model.all(), batch_size=50, counter=counter, report_every=0 ).run(process, 1, string='foo') last_written = Model.all().order('-create_date').get() self.assertEqual(1001, counter.value) self.assertEqual(1001, num_processed) self.assertEqual(1, last_written.number) self.assertEqual('foo', last_written.string)
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the module to support users unsubscribing from notifications.""" __author__ = 'John Orr (jorr@google.com)' import urlparse from common import utils from controllers import sites from modules.unsubscribe import unsubscribe from tests.functional import actions from google.appengine.ext import db class BaseUnsubscribeTests(actions.TestBase): def assertUnsubscribed(self, email, namespace): with utils.Namespace(namespace): self.assertTrue(unsubscribe.has_unsubscribed(email)) def assertSubscribed(self, email, namespace): with utils.Namespace(namespace): self.assertFalse(unsubscribe.has_unsubscribed(email)) class GetUnsubscribeUrlTests(actions.TestBase): def test_get_unsubscribe_url(self): handler = actions.MockHandler( app_context=actions.MockAppContext(slug='new_course')) url = unsubscribe.get_unsubscribe_url(handler, 'test@example.com') parsed_url = urlparse.urlparse(url) self.assertEquals('http', parsed_url.scheme) self.assertEquals('mycourse.appspot.com', parsed_url.netloc) self.assertEquals('/new_course/modules/unsubscribe', parsed_url.path) query_dict = urlparse.parse_qs(parsed_url.query) self.assertEquals(['test@example.com'], query_dict['email']) self.assertRegexpMatches(query_dict['s'][0], r'[0-9a-f]{32}') class SubscribeAndUnsubscribeTests(BaseUnsubscribeTests): EMAIL = 'test@example.com' def setUp(self): super(SubscribeAndUnsubscribeTests, self).setUp() self.namespace = 'namespace' def test_subscription_state_never_set(self): with utils.Namespace(self.namespace): self.assertSubscribed(self.EMAIL, self.namespace) def test_set_subscription_state(self): with utils.Namespace(self.namespace): unsubscribe.set_subscribed(self.EMAIL, False) self.assertUnsubscribed(self.EMAIL, self.namespace) def test_set_then_unset_subscription_state(self): with utils.Namespace(self.namespace): self.assertSubscribed(self.EMAIL, self.namespace) unsubscribe.set_subscribed(self.EMAIL, True) self.assertSubscribed(self.EMAIL, self.namespace) unsubscribe.set_subscribed(self.EMAIL, False) self.assertUnsubscribed(self.EMAIL, self.namespace) def test_subscription_state_entity_must_have_key_name(self): with self.assertRaises(db.BadValueError): unsubscribe.SubscriptionStateEntity() with self.assertRaises(db.BadValueError): unsubscribe.SubscriptionStateEntity(id='23') class UnsubscribeHandlerTests(BaseUnsubscribeTests): def setUp(self): super(UnsubscribeHandlerTests, self).setUp() self.base = '/a' self.namespace = 'ns_a' sites.setup_courses('course:/a::ns_a') self.app_context = actions.MockAppContext( namespace=self.namespace, slug='a') self.handler = actions.MockHandler( base_href='http://localhost/', app_context=self.app_context) self.email = 'test@example.com' actions.login(self.email, is_admin=True) def test_unsubscribe_and_resubscribe(self): self.assertSubscribed(self.email, self.namespace) unsubscribe_url = unsubscribe.get_unsubscribe_url( self.handler, self.email) response = self.get(unsubscribe_url) # Confirm the user has unsubscribed self.assertUnsubscribed(self.email, self.namespace) # Confirm the page content of the response root = self.parse_html_string(response.body).find( './/*[@id="unsubscribe-message"]') confirm_elt = root.find('./p[1]') self.assertTrue('has been unsubscribed' in confirm_elt.text) email_elt = root.find('.//div[1]') self.assertEquals(self.email, email_elt.text.strip()) resubscribe_url = root.find('.//div[2]/button').attrib[ 'data-resubscribe-url'] response = self.get(resubscribe_url) # Confirm the user has now resubscribed self.assertSubscribed(self.email, self.namespace) # Confirm the page content of the response root = self.parse_html_string(response.body).find( './/*[@id="resubscribe-message"]') confirm_elt = root.find('./p[1]') self.assertTrue('has been subscribed' in confirm_elt.text) email_elt = root.find('.//div[1]') self.assertEquals(self.email, email_elt.text.strip()) def test_bad_signature_rejected_with_401(self): response = self.get( 'modules/unsubscribe' '?email=test%40example.com&s=bad_signature', expect_errors=True) self.assertEquals(401, response.status_code) def test_unsubscribe_request_with_no_email_prompts_for_login(self): actions.logout() response = self.get('modules/unsubscribe') self.assertEquals(302, response.status_int) self.assertEquals( 'https://www.google.com/accounts/Login' '?continue=http%3A//localhost/a/modules/unsubscribe', response.headers['Location']) def test_unsubscribe_with_no_email_and_in_session(self): response = self.get('modules/unsubscribe') # Confirm the user has unsubscribed self.assertUnsubscribed(self.email, self.namespace) # Confirm the page content of the response root = self.parse_html_string(response.body).find( './/*[@id="unsubscribe-message"]') confirm_elt = root.find('./p[1]') self.assertTrue('has been unsubscribed' in confirm_elt.text) email_elt = root.find('.//div[1]') self.assertEquals(self.email, email_elt.text.strip()) resubscribe_url = root.find('.//div[2]/button').attrib[ 'data-resubscribe-url'] response = self.get(resubscribe_url) # Confirm the user has now resubscribed self.assertSubscribed(self.email, self.namespace)
Python
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Functional tests for VFS features.""" __author__ = [ 'mgainer@google.com (Mike Gainer)', ] import os import random import StringIO import tempfile from common import utils as common_utils from models import vfs from models import courses from tests.functional import actions from tools.etl import etl LOREM_IPSUM = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque nisl libero, interdum vel lectus eget, lacinia vestibulum eros. Maecenas posuere finibus pulvinar. Aenean eu eros mauris. Quisque maximus feugiat sollicitudin. Vestibulum aliquam vulputate nulla vel volutpat. Donec in pharetra enim. Nullam et nunc sed nisi ornare suscipit. Curabitur sit amet enim eu ante tristique tincidunt. Aliquam ac nunc luctus arcu ornare iaculis vitae nec turpis. Vivamus ut justo pellentesque, accumsan dui ut, iaculis elit. Nullam congue nunc odio, sed laoreet nisl iaculis eget. Aenean urna libero, iaculis ac sapien at, condimentum pellentesque tellus. Phasellus dapibus arcu a dolor sollicitudin, non tempus erat dapibus. Pellentesque id pellentesque nunc. Nullam interdum, nulla sit amet convallis scelerisque, ligula tellus placerat risus, sit amet sodales elit diam sed tellus. Pellentesque sollicitudin orci imperdiet fermentum semper. Curabitur id ornare elit. Proin pharetra, diam ac iaculis sed. """ * 10 class VfsLargeFileSupportTest(actions.TestBase): COURSE_NAME = 'test_course' ADMIN_EMAIL = 'admin@foo.com' NAMESPACE = 'ns_%s' % COURSE_NAME def setUp(self): super(VfsLargeFileSupportTest, self).setUp() self.app_context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'Test Course') self.course = courses.Course(handler=None, app_context=self.app_context) actions.login(self.ADMIN_EMAIL) def test_course_larger_than_datastore_max_size_is_sharded(self): unit = self.course.add_unit() num_lessons = vfs._MAX_VFS_SHARD_SIZE / len(LOREM_IPSUM) for unused in range(num_lessons): lesson = self.course.add_lesson(unit) lesson.objectives = LOREM_IPSUM serializer = courses.PersistentCourse13( next_id=self.course._model.next_id, units=self.course._model.units, lessons=self.course._model.lessons) serialized_length = len(serializer.serialize()) self.assertGreater( serialized_length, vfs._MAX_VFS_SHARD_SIZE, 'Verify that serialized course is larger than the max entity size') self.course.save() # course.save() clears cache, so we don't need to do that here. # Verify contents of course. course = courses.Course(handler=None, app_context=self.app_context) lessons = course.get_lessons(unit.unit_id) self.assertEquals(num_lessons, len(lessons)) for lesson in lessons: self.assertEquals(lesson.objectives, LOREM_IPSUM) # Verify that sharded items exist with appropriate sizes. file_key_names = vfs.DatastoreBackedFileSystem._generate_file_key_names( '/data/course.json', serialized_length) self.assertEquals( 2, len(file_key_names), 'Verify attempting to store a too-large file makes multiple shards') with common_utils.Namespace(self.NAMESPACE): shard_0 = vfs.FileDataEntity.get_by_key_name(file_key_names[0]) self.assertEquals(vfs._MAX_VFS_SHARD_SIZE, len(shard_0.data)) shard_1 = vfs.FileDataEntity.get_by_key_name(file_key_names[1]) self.assertGreater(len(shard_1.data), 0) def test_course_larger_than_datastore_max_can_be_exported_and_loaded(self): unit = self.course.add_unit() num_lessons = vfs._MAX_VFS_SHARD_SIZE / len(LOREM_IPSUM) for unused in range(num_lessons): lesson = self.course.add_lesson(unit) lesson.objectives = LOREM_IPSUM self.course.save() other_course_name = 'other_course' other_course_context = actions.simple_add_course( other_course_name, self.ADMIN_EMAIL, 'Other') # Verify that a large course can be ETL'd out and recovered. fp, archive_file = tempfile.mkstemp(suffix='.zip') os.close(fp) try: parser = etl.create_args_parser() etl.main(parser.parse_args([ 'download', 'course', '/' + self.COURSE_NAME, 'mycourse', 'localhost:8081', '--archive_path', archive_file, '--force_overwrite', '--internal', '--disable_remote'])) etl.main(parser.parse_args([ 'upload', 'course', '/' + other_course_name, 'mycourse', 'localhost:8081', '--archive_path', archive_file, '--force_overwrite', '--internal', '--disable_remote'])) finally: os.unlink(archive_file) # Verify contents of course. course = courses.Course(handler=None, app_context=other_course_context) lessons = course.get_lessons(unit.unit_id) self.assertEquals(num_lessons, len(lessons)) for lesson in lessons: self.assertEquals(lesson.objectives, LOREM_IPSUM) def test_large_volume_of_random_bytes_is_sharded(self): r = random.Random() r.seed(0) orig_data = ''.join( [chr(r.randrange(256)) for x in xrange(int(vfs._MAX_VFS_SHARD_SIZE + 1))]) namespace = 'ns_foo' fs = vfs.DatastoreBackedFileSystem(namespace, '/') filename = '/foo' fs.put(filename, StringIO.StringIO(orig_data)) # fs.put() clears cache, so this will do a direct read. actual = fs.get(filename).read() self.assertEquals(orig_data, actual) # And again, this time from cache. actual = fs.get(filename).read() self.assertEquals(orig_data, actual) # Verify that sharded items exist with appropriate sizes. file_key_names = vfs.DatastoreBackedFileSystem._generate_file_key_names( filename, vfs._MAX_VFS_SHARD_SIZE + 1) self.assertEquals( 2, len(file_key_names), 'Verify attempting to store a too-large file makes multiple shards') with common_utils.Namespace(namespace): shard_0 = vfs.FileDataEntity.get_by_key_name(file_key_names[0]) self.assertEquals(vfs._MAX_VFS_SHARD_SIZE, len(shard_0.data)) shard_1 = vfs.FileDataEntity.get_by_key_name(file_key_names[1]) self.assertEquals(1, len(shard_1.data)) def test_illegal_file_name(self): namespace = 'ns_foo' fs = vfs.DatastoreBackedFileSystem(namespace, '/') with self.assertRaises(ValueError): fs.put('/name:shard:123', StringIO.StringIO('file contents')) def test_too_large_file_is_rejected(self): unit = self.course.add_unit() num_lessons = ( (vfs._MAX_VFS_NUM_SHARDS * vfs._MAX_VFS_SHARD_SIZE) / len(LOREM_IPSUM)) for unused in range(num_lessons): lesson = self.course.add_lesson(unit) lesson.objectives = LOREM_IPSUM with self.assertRaises(ValueError): self.course.save() def test_large_but_not_too_large_file_is_not_rejected(self): unit = self.course.add_unit() num_lessons = ( ((vfs._MAX_VFS_NUM_SHARDS - 1) * vfs._MAX_VFS_SHARD_SIZE) / len(LOREM_IPSUM)) for unused in range(num_lessons): lesson = self.course.add_lesson(unit) lesson.objectives = LOREM_IPSUM # Here, call. Expect no ValueError from VFS, and no complaint # from AppEngine about cross-group transaction having too many # entities involved. self.course.save()
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for modules/certificate/.""" __author__ = 'John Orr (jorr@google.com)' import actions from controllers import sites from models import courses from models import models from models import student_work from modules.certificate import certificate from modules.certificate import custom_criteria from modules.review import domain from modules.review import peer from modules.review import review as review_module from google.appengine.api import namespace_manager from google.appengine.ext import db class MockHandler(object): def gettext(self, text): return text class CertificateHandlerTestCase(actions.TestBase): """Tests for the handler which presents the certificate.""" def setUp(self): super(CertificateHandlerTestCase, self).setUp() # Mock the module's student_is_qualified method self.is_qualified = True self.original_student_is_qualified = certificate.student_is_qualified certificate.student_is_qualified = ( lambda student, course: self.is_qualified) def tearDown(self): certificate.student_is_qualified = self.original_student_is_qualified super(CertificateHandlerTestCase, self).tearDown() def test_student_must_be_enrolled(self): # If student not in session, expect redirect response = self.get('/certificate') self.assertEquals(302, response.status_code) # If student is not enrolled, expect redirect actions.login('test@example.com') response = self.get('/certificate') self.assertEquals(302, response.status_code) self.assertEquals( 'http://localhost/preview', response.headers['Location']) # If the student is enrolled, expect certificate models.Student.add_new_student_for_current_user('Test User', None, self) response = self.get('/certificate') self.assertEquals(200, response.status_code) def test_student_must_be_qualified(self): actions.login('test@example.com') models.Student.add_new_student_for_current_user('Test User', None, self) # If student is not qualified, expect redirect to home page self.is_qualified = False response = self.get('/certificate') self.assertEquals(302, response.status_code) self.assertEquals('http://localhost/', response.headers['Location']) # If student is qualified, expect certificate self.is_qualified = True response = self.get('/certificate') self.assertEquals(200, response.status_code) def test_certificate_should_have_student_nickname(self): actions.login('test@example.com') models.Student.add_new_student_for_current_user('Jane Doe', None, self) response = self.get('/certificate') self.assertEquals(200, response.status_code) self.assertIn('Jane Doe', response.body) def test_download_pdf(self): actions.login('test@example.com') models.Student.add_new_student_for_current_user('Test User', None, self) response = self.get('/certificate.pdf') self.assertEqual('application/pdf', response.headers['Content-Type']) self.assertEqual( 'attachment; filename=certificate.pdf', response.headers['Content-Disposition']) self.assertIn('/Title (Course Builder Certificate)', response.body) def test_certificate_table_entry(self): actions.login('test@example.com') models.Student.add_new_student_for_current_user('Test User', None, self) student = models.Student.get_by_email('test@example.com') all_courses = sites.get_all_courses() app_context = all_courses[0] course = courses.Course(None, app_context=app_context) # If the student is qualified, a link is shown self.is_qualified = True mock_handler = MockHandler() table_entry = certificate.get_certificate_table_entry( mock_handler, student, course) self.assertEquals('Certificate', table_entry[0]) link = str(table_entry[1]) self.assertEquals( '<a href="certificate">Click for certificate</a> ' '| <a href="certificate.pdf">Download PDF</a>', link) # If the student is not qualified, a message is shown self.is_qualified = False table_entry = certificate.get_certificate_table_entry( mock_handler, student, course) self.assertEquals('Certificate', table_entry[0]) self.assertIn( 'You have not yet met the course requirements', table_entry[1]) class CertificateCriteriaTestCase(actions.TestBase): """Tests the different certificate criteria configurations.""" COURSE_NAME = 'certificate_criteria' STUDENT_EMAIL = 'foo@foo.com' ADMIN_EMAIL = 'admin@foo.com' ANALYTICS_URL = ('/' + COURSE_NAME + '/dashboard?action=analytics&tab=certificates_earned') def setUp(self): super(CertificateCriteriaTestCase, self).setUp() self.base = '/' + self.COURSE_NAME context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'Certificate Criteria') self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME) self.course = courses.Course(None, context) self.course.save() actions.login(self.STUDENT_EMAIL) actions.register(self, self.STUDENT_EMAIL) self.student = ( models.StudentProfileDAO.get_enrolled_student_by_email_for( self.STUDENT_EMAIL, context)) # Override course.yaml settings by patching app_context. self.get_environ_old = sites.ApplicationContext.get_environ self.certificate_criteria = [] def get_environ_new(app_context): environ = self.get_environ_old(app_context) environ['certificate_criteria'] = self.certificate_criteria return environ sites.ApplicationContext.get_environ = get_environ_new def tearDown(self): # Clean up app_context. sites.ApplicationContext.get_environ = self.get_environ_old namespace_manager.set_namespace(self.old_namespace) super(CertificateCriteriaTestCase, self).tearDown() def _assert_redirect_to_course_landing_page(self, response): self.assertEquals(302, response.status_code) self.assertEquals('http://localhost/' + self.COURSE_NAME + '/', ( response.headers['Location'])) def test_no_criteria(self): response = self.get('certificate') self._assert_redirect_to_course_landing_page(response) def _run_analytic_and_expect(self, expected_students, expected_active_students, expected_certificates): actions.login(self.ADMIN_EMAIL) response = self.get(self.ANALYTICS_URL) self.submit(response.forms['gcb-run-visualization-certificates_earned'], response) self.execute_all_deferred_tasks() dom = self.parse_html_string(self.get(self.ANALYTICS_URL).body) total_students = int( dom.find('.//span[@id="total_students"]').text) total_active_students = int( dom.find('.//span[@id="total_active_students"]').text) total_certificates = int( dom.find('.//span[@id="total_certificates"]').text) self.assertEquals(expected_students, total_students) self.assertEquals(expected_active_students, total_active_students) self.assertEquals(expected_certificates, total_certificates) actions.login(self.STUDENT_EMAIL) def test_no_criteria_analytic(self): self._run_analytic_and_expect(1, 0, 0) def test_machine_graded(self): assessment = self.course.add_assessment() assessment.title = 'Assessment' assessment.html_content = 'assessment content' assessment.now_available = True self.course.save() self.certificate_criteria.append( {'assessment_id': assessment.unit_id, 'pass_percent': 70.0}) # Student has not yet completed assessment, expect redirect to home page response = self.get('certificate') self._assert_redirect_to_course_landing_page(response) self._run_analytic_and_expect(1, 0, 0) # 1 student, 0 active, no cert. # Submit assessment with low score actions.submit_assessment( self, assessment.unit_id, {'answers': '', 'score': 50.0, 'assessment_type': assessment.unit_id}, presubmit_checks=False ) response = self.get('certificate') self._assert_redirect_to_course_landing_page(response) self._run_analytic_and_expect(1, 1, 0) # 1 student, 1 active, no cert # Submit assessment with expected score actions.submit_assessment( self, assessment.unit_id, {'answers': '', 'score': 70, 'assessment_type': assessment.unit_id}, presubmit_checks=False ) response = self.get('certificate') self.assertEquals(200, response.status_code) self._run_analytic_and_expect(1, 1, 1) # 1 student, 1 active, 1 cert def _submit_review(self, assessment): """Submits a review by the current student. Creates a new user that completes the assessment as well, so that the student can review it. Args: assessment: The assessment to review. """ reviewer_key = self.student.get_key() reviewee = models.Student(key_name='reviewee@example.com') reviewee_key = reviewee.put() submission_key = db.Key.from_path( student_work.Submission.kind(), student_work.Submission.key_name( reviewee_key=reviewee_key, unit_id=str(assessment.unit_id))) summary_key = peer.ReviewSummary( assigned_count=1, reviewee_key=reviewee_key, submission_key=submission_key, unit_id=str(assessment.unit_id) ).put() review_key = student_work.Review( contents='old_contents', reviewee_key=reviewee_key, reviewer_key=reviewer_key, unit_id=str(assessment.unit_id)).put() step_key = peer.ReviewStep( assigner_kind=domain.ASSIGNER_KIND_HUMAN, review_key=review_key, review_summary_key=summary_key, reviewee_key=reviewee_key, reviewer_key=reviewer_key, submission_key=submission_key, state=domain.REVIEW_STATE_ASSIGNED, unit_id=str(assessment.unit_id) ).put() updated_step_key = review_module.Manager.write_review( step_key, 'new_contents') self.assertEqual(step_key, updated_step_key) def test_peer_graded(self): assessment = self.course.add_assessment() assessment.title = 'Assessment' assessment.html_content = 'assessment content' assessment.workflow_yaml = ( '{grader: human,' 'matcher: peer,' 'review_due_date: \'2034-07-01 12:00\',' 'review_min_count: 1,' 'review_window_mins: 20,' 'submission_due_date: \'2034-07-01 12:00\'}') assessment.now_available = True self.course.save() self.certificate_criteria.append( {'assessment_id': assessment.unit_id}) response = self.get('certificate') self._assert_redirect_to_course_landing_page(response) actions.submit_assessment( self, assessment.unit_id, {'answers': '', 'assessment_type': assessment.unit_id}, presubmit_checks=False ) # Submitting assessment without doing required reviews is not enough response = self.get('certificate') self._assert_redirect_to_course_landing_page(response) # Submitting assessment together with required reviews is enough self._submit_review(assessment) response = self.get('certificate') self.assertEquals(200, response.status_code) def test_custom_criteria(self): def test_custom_criterion(unused_student, unused_course): return True CRITERION = 'test_custom_criterion' self.certificate_criteria.append( {'custom_criteria': CRITERION}) setattr(custom_criteria, CRITERION, test_custom_criterion) custom_criteria.registration_table.append(CRITERION) response = self.get('certificate') self.assertEquals(200, response.status_code) def test_combination(self): # Add machine graded assessment machine_graded = self.course.add_assessment() machine_graded.title = 'Machine Graded' machine_graded.html_content = 'assessment content' machine_graded.now_available = True # Add peer graded assessment peer_graded = self.course.add_assessment() peer_graded.title = 'Peer Graded' peer_graded.html_content = 'assessment content' peer_graded.workflow_yaml = ( '{grader: human,' 'matcher: peer,' 'review_due_date: \'2034-07-01 12:00\',' 'review_min_count: 1,' 'review_window_mins: 20,' 'submission_due_date: \'2034-07-01 12:00\'}') peer_graded.now_available = True self.course.save() self.certificate_criteria.extend([ {'assessment_id': machine_graded.unit_id, 'pass_percent': 30}, {'assessment_id': peer_graded.unit_id}]) # Confirm that meeting one criterion is not sufficient actions.submit_assessment( self, machine_graded.unit_id, {'answers': '', 'score': 40, 'assessment_type': machine_graded.unit_id}, presubmit_checks=False ) response = self.get('certificate') self._assert_redirect_to_course_landing_page(response) # Confirm that meeting both criteria is sufficient actions.submit_assessment( self, peer_graded.unit_id, {'answers': '', 'assessment_type': peer_graded.unit_id}, presubmit_checks=False ) self._submit_review(peer_graded) response = self.get('certificate') self.assertEquals(200, response.status_code)
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests that walk through Course Builder pages.""" __author__ = 'Mike Gainer (mgainer@google.com)' import urllib from common import crypto from controllers import sites from models import config from models import roles from models import transforms from modules.course_explorer import course_explorer from tests.functional import actions COURSE_NAME = 'whitelist_test' ADMIN_EMAIL = 'admin@foo.com' STUDENT_EMAIL = 'student@foo.com' NONSTUDENT_EMAIL = 'student@bar.com' STUDENT_WHITELIST = '[%s]' % STUDENT_EMAIL class WhitelistTest(actions.TestBase): _course_added = False _whitelist = '' _get_environ_old = None @classmethod def setUpClass(cls): sites.ApplicationContext.get_environ_old = ( sites.ApplicationContext.get_environ) def get_environ_new(slf): environ = slf.get_environ_old() environ['course']['now_available'] = True environ['course']['whitelist'] = WhitelistTest._whitelist return environ sites.ApplicationContext.get_environ = get_environ_new @classmethod def tearDownClass(cls): sites.ApplicationContext.get_environ = ( sites.ApplicationContext.get_environ_old) def setUp(self): super(WhitelistTest, self).setUp() config.Registry.test_overrides[ course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.name] = True actions.login(ADMIN_EMAIL, is_admin=True) payload_dict = { 'name': COURSE_NAME, 'title': 'Whitelist Test', 'admin_email': ADMIN_EMAIL} request = { 'payload': transforms.dumps(payload_dict), 'xsrf_token': crypto.XsrfTokenManager.create_xsrf_token( 'add-course-put')} response = self.testapp.put('/rest/courses/item?%s' % urllib.urlencode( {'request': transforms.dumps(request)}), {}) self.assertEquals(response.status_int, 200) sites.setup_courses('course:/%s::ns_%s, course:/:/' % ( COURSE_NAME, COURSE_NAME)) actions.logout() def tearDown(self): super(WhitelistTest, self).tearDown() sites.reset_courses() WhitelistTest._whitelist = '' config.Registry.test_overrides.clear() def _expect_visible(self): response = self.get('/explorer') self.assertIn('Whitelist Test', response.body) response = self.get('/whitelist_test/course') self.assertEquals(200, response.status_int) def _expect_invisible(self): response = self.get('/explorer') self.assertNotIn('Whitelist Test', response.body) response = self.get('/whitelist_test/course', expect_errors=True) self.assertEquals(404, response.status_int) def _expect_invisible_with_login_redirect(self): response = self.get('/explorer') self.assertNotIn('Whitelist Test', response.body) # Not quite a standard 'invisible' response - a non-logged-in # user will get redirected to the login page, rather than # just served a 404. response = self.get('/whitelist_test/course') self.assertEquals(302, response.status_int) self.assertIn('accounts/Login', response.location) def test_no_whitelist_not_logged_in(self): self._expect_visible() def test_course_whitelist_not_logged_in(self): WhitelistTest._whitelist = STUDENT_WHITELIST self._expect_invisible_with_login_redirect() def test_course_whitelist_as_admin(self): WhitelistTest._whitelist = STUDENT_WHITELIST actions.login(ADMIN_EMAIL, is_admin=True) self._expect_visible() def test_course_whitelist_as_nonstudent(self): WhitelistTest._whitelist = STUDENT_WHITELIST actions.login(NONSTUDENT_EMAIL) self._expect_invisible() def test_course_whitelist_as_student(self): WhitelistTest._whitelist = STUDENT_WHITELIST actions.login(STUDENT_EMAIL) self._expect_visible() def test_global_whitelist_not_logged_in(self): config.Registry.test_overrides[ roles.GCB_WHITELISTED_USERS.name] = STUDENT_WHITELIST self._expect_invisible_with_login_redirect() def test_global_whitelist_as_admin(self): config.Registry.test_overrides[ roles.GCB_WHITELISTED_USERS.name] = STUDENT_WHITELIST actions.login(ADMIN_EMAIL, is_admin=True) self._expect_visible() def test_global_whitelist_as_nonstudent(self): config.Registry.test_overrides[ roles.GCB_WHITELISTED_USERS.name] = STUDENT_WHITELIST actions.login(NONSTUDENT_EMAIL) self._expect_invisible() def test_global_whitelist_as_student(self): config.Registry.test_overrides[ roles.GCB_WHITELISTED_USERS.name] = STUDENT_WHITELIST actions.login(STUDENT_EMAIL) self._expect_visible() def test_course_whitelist_trumps_global_whitelist(self): # Global whitelist is nonblank, but only lists NONSTUDENT_EMAIL config.Registry.test_overrides[ roles.GCB_WHITELISTED_USERS.name] = '[%s]' % NONSTUDENT_EMAIL # Course whitelist has STUDENT_EMAIL. WhitelistTest._whitelist = STUDENT_WHITELIST actions.login(STUDENT_EMAIL) self._expect_visible() def test_course_whitelist_with_multiple_entries(self): WhitelistTest._whitelist = ( '[%s] ' % NONSTUDENT_EMAIL * 100 + '[%s] ' % STUDENT_EMAIL + '[%s] ' % NONSTUDENT_EMAIL * 100) actions.login(STUDENT_EMAIL) self._expect_visible() def test_global_whitelist_with_multiple_entries(self): config.Registry.test_overrides[ roles.GCB_WHITELISTED_USERS.name] = ( '[%s] ' % NONSTUDENT_EMAIL * 100 + '[%s] ' % STUDENT_EMAIL + '[%s] ' % NONSTUDENT_EMAIL * 100) actions.login(STUDENT_EMAIL) self._expect_visible()
Python
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for modules/analytics/*.""" __author__ = 'Mike Gainer (mgainer@google.com)' import appengine_config import json import os import pprint import urllib import zlib import actions from common import utils as common_utils from models import courses from models import jobs from models import models from models import transforms from models.progress import UnitLessonCompletionTracker from modules.analytics import clustering from modules.analytics import student_aggregate from tests.functional import actions from tools.etl import etl from google.appengine.api import namespace_manager # Note to those extending this set of tests in the future: # - Make a new course named "test_course". # - Use the admin user to set up whatever test situation you need. # - In an incognito window, log in as 'foo@bar.com' and register. # - Perform relevant user actions to generate EventEntity items. # - Download test data via: # # echo "a@b.c" | \ # ./scripts/etl.sh download course /test_course mycourse localhost:8081 \ # --archive_path=tests/functional/modules_analytics/TEST_NAME_HERE/course \ # --internal --archive_type=directory --force_overwrite --no_static_files # # echo "a@b.c" | \ # ./scripts/etl.sh download datastore /test_course mycourse localhost:8081 \ # --archive_path=tests/functional/modules_analytics/TEST_NAME_HERE/datastore \ # --internal --archive_type=directory --force_overwrite --no_static_files # # - Run the following script to dump out the actual values from the # map/reduce analytic run. # # ./scripts/test.sh \ # tests.functional.modules_analytics.NotReallyTest.test_dump_results # # - Verify that the JSON result is as-expected. This is also a good time to # edit the dumped events to change fields to manufacture test conditions # for malformed data, or to set up cases that are not easy to configure # by manual interaction. (E.g., location and locale for localhost dev # environments are not easily changed, but the events are easily edited.) # # - Write your test to verify expected vs. actual output. C.f. # StudentAggregateTest.test_page_views class AbstractModulesAnalyticsTest(actions.TestBase): COURSE_NAME = 'test_course' ADMIN_EMAIL = 'admin@foo.com' def setUp(self): super(AbstractModulesAnalyticsTest, self).setUp() self.app_context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'Analytics Test') self.course = courses.Course(None, app_context=self.app_context) self.maxDiff = None def _get_data_path(self, path): return os.path.join(appengine_config.BUNDLE_ROOT, 'tests', 'functional', 'modules_analytics', 'test_courses', path) def load_course(self, path): data_path = self._get_data_path(path) course_data = os.path.join(data_path, 'course') datastore_data = os.path.join(data_path, 'datastore') # Load the course to the VFS, and populate the DB w/ entities parser = etl.create_args_parser() etl.add_internal_args_support(parser) etl.main(parser.parse_args([ 'upload', 'course', '/' + self.COURSE_NAME, 'mycourse', 'localhost:8081', '--archive_path', course_data, '--internal', '--archive_type', 'directory', '--disable_remote', '--force_overwrite', '--log_level', 'WARNING'])) def load_datastore(self, path): data_path = self._get_data_path(path) course_data = os.path.join(data_path, 'course') datastore_data = os.path.join(data_path, 'datastore') parser = etl.create_args_parser() etl.add_internal_args_support(parser) etl.main(parser.parse_args([ 'upload', 'datastore', '/' + self.COURSE_NAME, 'mycourse', 'localhost:8081', '--archive_path', datastore_data, '--internal', '--archive_type', 'directory', '--disable_remote', '--force_overwrite', '--log_level', 'WARNING', '--exclude_types', ','.join([ 'Submission', 'FileDataEntity', 'FileMetadataEntity'])])) def get_aggregated_data_by_email(self, email): with common_utils.Namespace('ns_' + self.COURSE_NAME): student = models.Student.get_by_email('foo@bar.com') aggregate_entity = ( student_aggregate.StudentAggregateEntity.get_by_key_name( student.user_id)) return transforms.loads(zlib.decompress(aggregate_entity.data)) def load_expected_data(self, path, item): data_path = self._get_data_path(path) expected_path = os.path.join(data_path, 'expected', item) with open(expected_path) as fs: data = fs.read() return transforms.loads(data) def run_aggregator_job(self): job = student_aggregate.StudentAggregateGenerator(self.app_context) job.submit() self.execute_all_deferred_tasks() class NotReallyTest(AbstractModulesAnalyticsTest): def test_dump_results(self): """Convenience "test" to run analytic job and dump results to stdout.""" # Change these values as appropriate to match the test case for which # you wish to dump output. test_data_subdir = 'multiple' test_student_email = 'foo@bar.com' self.load_course('simple_questions') self.load_datastore(test_data_subdir) self.run_aggregator_job() actual = self.get_aggregated_data_by_email(test_student_email) print '############################### Pretty-printed version:' pprint.pprint(actual) print '############################### JSON version:' print transforms.dumps(actual) class StudentAggregateTest(AbstractModulesAnalyticsTest): def test_page_views(self): self.load_course('simple_questions') self.load_datastore('page_views') self.run_aggregator_job() actual = self.get_aggregated_data_by_email('foo@bar.com') # This verifies the following cases: # - Only /course is submitted in URL; correct unit/lesson is found. # - Only /unit is submitted in URL; correct unit/lesson is found # - Full /unit?unit=X&lesson=Y ; correct unit/lesson logged. # - Page enter but not exit # - Page exit but not enter # - YouTube events # - Events are present (and reported on in output) for unit, lesson, # and assessment that have been deleted after events were recorded. expected = self.load_expected_data('page_views', 'page_views.json') expected.sort(key=lambda x: (x['name'], x.get('id'), x.get('start'))) actual['page_views'].sort( key=lambda x: (x['name'], x.get('id'), x.get('start'))) self.assertEqual(expected, actual['page_views']) def test_location_locale_user_agent(self): self.load_course('simple_questions') self.load_datastore('location_locale') self.run_aggregator_job() actual = self.get_aggregated_data_by_email('foo@bar.com') # This verifies the following cases: # - Multiple different countries (4 US, 2 AR, 1 DE, 1 ES) and that # these are reported with their correct fractional weights. expected = self.load_expected_data('location_locale', 'location_frequencies.json') expected.sort(key=lambda x: (x['country'], x['frequency'])) actual['location_frequencies'].sort( key=lambda x: (x['country'], x['frequency'])) self.assertEqual(expected, actual['location_frequencies']) # This verifies the following cases: # - Multiple different locales (4 en_US, 2 es_AR, 1 de_DE, 1 es_ES) # and that these are reported with their correct fractional weights. expected = self.load_expected_data('location_locale', 'locale_frequencies.json') expected.sort(key=lambda x: (x['locale'], x['frequency'])) actual['locale_frequencies'].sort( key=lambda x: (x['locale'], x['frequency'])) self.assertEqual(expected, actual['locale_frequencies']) # This verifies the following cases: # - Multiple different user agents at 50%, 25%, 12.5%, 12.5% # and that these are reported with their correct fractional weights. expected = self.load_expected_data('location_locale', 'user_agent_frequencies.json') expected.sort(key=lambda x: (x['user_agent'], x['frequency'])) actual['user_agent_frequencies'].sort( key=lambda x: (x['user_agent'], x['frequency'])) self.assertEqual(expected, actual['user_agent_frequencies']) def test_scoring(self): self.load_course('simple_questions') self.load_datastore('scoring') self.run_aggregator_job() actual = self.get_aggregated_data_by_email('foo@bar.com') # This verifies the following cases: # - All combinations of: # {Short-Answer, Multiple-Choice} x # {unscored lesson, scored lesson, assessment} x # {bare question, questions in question-group} # - Scoring with weights for: # * different answers within a question # * usage of question within scored lesson # * usage of question within question group # - Answers of various degrees of correctness # - Different usages of the same question on different pages expected = self.load_expected_data('scoring', 'assessments.json') expected.sort(key=lambda x: (x['unit_id'], x['lesson_id'])) actual['assessments'].sort(key=lambda x: (x['unit_id'], x['lesson_id'])) self.assertEqual(expected, actual['assessments']) def test_bad_references_in_assessments(self): self.load_course('bad_references') self.load_datastore('bad_references') self.run_aggregator_job() actual = self.get_aggregated_data_by_email('foo@bar.com') # This verifies the following cases: # - For all below, submission on: lesson, scored-lesson, assessment # - Question, group, and container still present and valid. # - Question and question-group removed, but still referenced # - Question group modified: remove one member (but don't delete member) # - Question group modified: delete referenced question. # - Containers removed. expected = self.load_expected_data('bad_references', 'assessments.json') expected.sort(key=lambda x: (x['unit_id'], x['lesson_id'])) actual['assessments'].sort(key=lambda x: (x['unit_id'], x['lesson_id'])) self.assertEqual(expected, actual['assessments']) def test_multiple_submissions(self): self.load_course('simple_questions') self.load_datastore('multiple') self.run_aggregator_job() actual = self.get_aggregated_data_by_email('foo@bar.com') # This verifies the following items for multiple submissions on the # same assessment: # - min/max/first/last scores # - that multiple submission actually works # - Having gotten 100% on assessment means certificate earned expected = self.load_expected_data('multiple', 'assessments.json') expected.sort(key=lambda x: (x['unit_id'], x['lesson_id'])) actual['assessments'].sort(key=lambda x: (x['unit_id'], x['lesson_id'])) self.assertEqual(expected, actual['assessments']) self.assertTrue(actual['earned_certificate']) def test_youtube_events(self): self.load_course('simple_questions') self.load_datastore('youtube_events') self.run_aggregator_job() actual = self.get_aggregated_data_by_email('foo@bar.com') # This verifies the following items: # - Play video XJk8ijAUCiI from start to finish. # - Play video Kdg2drcUjYI for a couple of seconds, then pause. # - Rewind that video to 0 seconds, and re-start (makes new entry) # - Play video XJk8ijAUCiI for a few seconds, and pause. # - While other is paused, play Kdg2drcUjYI start-to-end # - Resume video XJk8ijAUCiI and play to end. expected = self.load_expected_data('youtube_events', 'youtube.json') # No sorting - items should be presented in order by time, video, etc. self.assertEqual(expected, actual['youtube']) class ClusteringTabTests(actions.TestBase): """Test for the clustering subtab of analytics tab.""" COURSE_NAME = 'clustering_course' ADMIN_EMAIL = 'test@example.com' NON_ADMIN_EMAIL = 'test2@example.com' CLUSTER_TAB_URL = ( '/{}/dashboard?action=analytics&tab=clustering'.format(COURSE_NAME)) def setUp(self): super(ClusteringTabTests, self).setUp() self.base = '/' + self.COURSE_NAME context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'Clustering Course') self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME) actions.login(self.ADMIN_EMAIL, is_admin=True) def tearDown(self): # Clean up app_context. namespace_manager.set_namespace(self.old_namespace) super(ClusteringTabTests, self).tearDown() def test_non_admin_access(self): """With no admin registration expect redirection.""" actions.logout() actions.login(self.NON_ADMIN_EMAIL, is_admin=False) response = self.get(self.CLUSTER_TAB_URL, expect_errors=True) self.assertEquals(302, response.status_int) def _add_clusters(self, clusters_number): """Adds the given clusters_number clusters to the db and saves the keys. """ self.clusters_keys = [] self.description_str = ('This is a fairly good description of the' ' cluster{}') self.name_str = 'strange cluster name{}' for index in range(clusters_number): new_cluster = clustering.ClusterDTO(None, {'name': self.name_str.format(index), 'description': self.description_str.format(index), 'vector': []}) self.clusters_keys.append(clustering.ClusterDAO.save(new_cluster)) def test_all_clusters_listed(self): """All the clusters in the db are listed in the page.""" clusters_number = 100 self._add_clusters(clusters_number) response = self.get(self.CLUSTER_TAB_URL) self.assertEquals(200, response.status_code, msg='Cluster tab not found. Code {}'.format(response.status_code)) dom = self.parse_html_string(response.body) table = dom.find('.//table[@id="gcb-clustering"]') self.assertIsNotNone(table) rows = table.findall('.//tr') self.assertEqual(len(rows), clusters_number + 1) # Title first # Check the names for index in range(clusters_number): self.assertIn(self.name_str.format(index), response.body, msg='Cluster name not present in page') self.assertIn(self.description_str.format(index), response.body, msg='Cluster description not present in page') def test_add_cluster_button(self): """There is a new cluster button in the page""" url = 'dashboard?action=add_cluster' response = self.get(self.CLUSTER_TAB_URL) self.assertIn(url, response.body, msg='No url for add cluster found.') def test_edit_correct_url_present(self): """There is a correct update link for each cluster.""" clusters_number = 10 url = 'dashboard?action=edit_cluster&amp;key={}' self._add_clusters(clusters_number) response = self.get(self.CLUSTER_TAB_URL) for cluster_key in self.clusters_keys: self.assertIn(url.format(cluster_key), response.body) class ClusterRESTHandlerTest(actions.TestBase): """Tests for the add_cluster handler and page.""" COURSE_NAME = 'clustering_course' ADMIN_EMAIL = 'test@example.com' NON_ADMIN_EMAIL = 'test2@example.com' CLUSTER_GET_URL = ('/{}/rest/cluster?key='.format(COURSE_NAME)) CLUSTER_PUT_URL = ('/{}/rest/cluster'.format(COURSE_NAME)) CLUSTER_ADD_URL = ('/{}/dashboard?action=add_cluster'.format(COURSE_NAME)) def setUp(self): super(ClusterRESTHandlerTest, self).setUp() self.base = '/' + self.COURSE_NAME self.app_context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'Clustering Course') self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME) self.course = courses.Course(None, self.app_context) actions.login(self.ADMIN_EMAIL, is_admin=True) self._q_usage_counter = 1000 # To not confuse usage id with ids. self._add_contents() def tearDown(self): namespace_manager.set_namespace(self.old_namespace) super(ClusterRESTHandlerTest, self).tearDown() def _add_unit(self, u_index): """Adds a unit to the course and records the u_index and unit_id.""" unit = self.course.add_unit() unit.title = self.unit_name_str.format(u_index) unit.now_available = True self.unit_keys.append((u_index, unit.unit_id)) return unit def _add_lesson(self, u_index, unit): """Adds a lesson to the course and records the u_index and lesson_id.""" lesson = self.course.add_lesson(unit) lesson.title = self.lesson_name_str.format(u_index) lesson.now_available = True lesson.scored = True lesson.objectives = '' self.lesson_keys.append((u_index, lesson.lesson_id)) return lesson def _add_question(self, q_index, target, target_attr): """Adds a questions in db and in the content of target. Saves the key. """ self._q_usage_counter += 1 question_dto = models.QuestionDTO(None, { 'description': self.descript_str.format(target.unit_id, q_index), 'type': 1}) question_id = models.QuestionDAO.save(question_dto) new_attr = (getattr(target, target_attr) or '') + ( '<question quid="{}" weight="1" instanceid="{}">' '</question>'.format(question_id, self._q_usage_counter)) setattr(target, target_attr, new_attr) lesson_id = getattr(target, 'lesson_id', None) self.questions_keys.append( (target.unit_id, lesson_id, q_index, question_id)) def _add_question_group(self, target, target_attr, items): """Adds a question group to the db and to the content of target.""" self._q_usage_counter += 1 question_group_dto = models.QuestionGroupDTO(None, { 'description': 'Question group', 'items': items, 'version': '1.5'}) question_group_id = models.QuestionGroupDAO.save(question_group_dto) qg_str = '<question-group qgid="{}" instanceid="{}"></question-group>' new_attr = (getattr(target, target_attr, '') + qg_str.format(question_group_id, self._q_usage_counter)) setattr(target, target_attr, new_attr) def _add_assessment(self, u_index): """Adds an assessment to the course and records the u_index and id.""" assessment = self.course.add_assessment() assessment.title = self.assessment_name_str.format(u_index) assessment.now_available = True self.assessment_keys.append((u_index, assessment.unit_id)) return assessment def _add_contents(self): """Adds units, questions and lessons to the course.""" self.units_number = 10 self.question_numbers = 10 self.unit_name_str = 'Very cool and unique unit name{}' self.descript_str = ('Description of a question that you hardly ' 'see unless introduced by this test{}{}') self.lesson_name_str = 'This is a very very good lesson{}' self.assessment_name_str = 'This is the most hard assessment{}' self.unit_keys = [] self.lesson_keys = [] self.questions_keys = [] self.assessment_keys = [] for u_index in range(self.units_number): unit = self._add_unit(u_index) lesson = self._add_lesson(u_index, unit) for q_index in range(self.question_numbers): self._add_question(q_index, lesson, 'objectives') assessment = self._add_assessment(u_index) self._add_question(self.question_numbers+2, assessment, 'html_content') self.course.save() def _add_cluster(self): """Adds the given clusters_number clusters to the db and saves the keys. """ cluster_description = 'This is a good description of the cluster' cluster_name = 'strange cluster name' vector = [{clustering.DIM_TYPE: clustering.DIM_TYPE_UNIT, clustering.DIM_ID: 1, clustering.DIM_LOW: 10, clustering.DIM_HIGH: 50}] new_cluster = clustering.ClusterDTO(None, {'name': cluster_name, 'description': cluster_description, 'version': clustering.ClusterRESTHandler.SCHEMA_VERSIONS[0], 'vector': vector}) return clustering.ClusterDAO.save(new_cluster) def _send_put_resquest(self, key, cluster, xsrf_token): """Build and send a put request. Returns the response.""" request = {} request['key'] = key request['payload'] = json.dumps(cluster) request['xsrf_token'] = xsrf_token return self.put(self.CLUSTER_PUT_URL + '?%s' % urllib.urlencode( {'request': transforms.dumps(request)}), {}) def _dim_from_dict(self, vector, dimension_id, dimension_type): candidates = [dim for dim in vector if dim[clustering.DIM_ID] == dimension_id and dim[clustering.DIM_TYPE] == dimension_type] error_msg = 'Dimension type:{} id:{} not founded' self.assertEqual(len(candidates), 1, msg=error_msg.format(dimension_type, dimension_id)) return candidates[0] def _check_questions(self, vector): for unit_id, lesson_id, q_index, question_key in self.questions_keys: dimension_id = clustering.pack_question_dimid( unit_id, lesson_id, question_key) dim = self._dim_from_dict(vector, dimension_id, clustering.DIM_TYPE_QUESTION) self.assertEqual(dim['name'], self.descript_str.format(unit_id, q_index)) def _check_lessons(self, vector): for l_index, lesson_key in self.lesson_keys: dim = self._dim_from_dict(vector, lesson_key, clustering.DIM_TYPE_LESSON) self.assertEqual(dim['name'], self.lesson_name_str.format(l_index)) def test_all_dimensions_units_scores(self): """All units are listed as dimensions in default content.""" vector = clustering.get_possible_dimensions(self.app_context) for u_index, unit_key in self.unit_keys: dim = self._dim_from_dict(vector, unit_key, clustering.DIM_TYPE_UNIT) self.assertEqual(dim['name'], self.unit_name_str.format(u_index)) self.assertIn(clustering.DIM_EXTRA_INFO, dim) extra_info = json.loads(dim[clustering.DIM_EXTRA_INFO]) self.assertEqual(extra_info['unit_scored_lessons'], 1) def test_all_dimensions_unit_visits(self): """All units must have a visits dimension.""" self._add_unit(self.units_number + 10) self.course.save() u_index, unit_id = self.unit_keys[-1] vector = clustering.get_possible_dimensions(self.app_context) dim = self._dim_from_dict(vector, unit_id, clustering.DIM_TYPE_UNIT_VISIT) self.assertNotEqual(dim['name'], self.unit_name_str.format(u_index)) self.assertIn('visits', dim['name']) def test_all_dimensions_unit_progress(self): """All units must have a progress dimension. This new unit will no be obtained using OrderedQuestionsDataSource. """ self._add_unit(self.units_number + 10) self.course.save() u_index, unit_id = self.unit_keys[-1] vector = clustering.get_possible_dimensions(self.app_context) dim = self._dim_from_dict(vector, unit_id, clustering.DIM_TYPE_UNIT_PROGRESS) self.assertNotEqual(dim['name'], self.unit_name_str.format(u_index)) self.assertIn('progress', dim['name']) def test_all_dimensions_lessons(self): """All lessons are listed as dimensions in default content.""" vector = clustering.get_possible_dimensions(self.app_context) self._check_lessons(vector) def test_all_dimensions_lessons_progress(self): """All lessons must have a progress dimension. This new lesson will no be obtained using OrderedQuestionsDataSource. """ unit = self._add_unit(self.units_number + 10) self._add_lesson(self.units_number + 12, unit) l_index, lesson_id = self.lesson_keys[-1] self.course.save() vector = clustering.get_possible_dimensions(self.app_context) dim = self._dim_from_dict(vector, lesson_id, clustering.DIM_TYPE_LESSON_PROGRESS) self.assertNotEqual(dim['name'], self.lesson_name_str.format(l_index)) self.assertIn('progress', dim['name']) self.assertIn(clustering.DIM_EXTRA_INFO, dim) self.assertEqual(dim[clustering.DIM_EXTRA_INFO], transforms.dumps({'unit_id': unit.unit_id})) def test_all_dimensions_questions(self): """All questions are listed as dimensions in default content.""" vector = clustering.get_possible_dimensions(self.app_context) self._check_questions(vector) def test_all_dimensions_multiple_usage_id(self): """Questions with more than one usage id are listed as dimensions.""" # Get a lesson unit = self.course.find_unit_by_id(self.unit_keys[0][1]) lesson = self.course.find_lesson_by_id(unit, self.lesson_keys[0][1]) question_id = 15 lesson.objectives += ( '<question quid="{}" weight="1" instanceid="{}">' '</question>'.format(question_id, self._q_usage_counter + 1)) self.course.save() vector = clustering.get_possible_dimensions(self.app_context) dimension_id = clustering.pack_question_dimid( unit.unit_id, lesson.lesson_id, question_id) self._dim_from_dict(vector, dimension_id, clustering.DIM_TYPE_QUESTION) def test_all_dimensions_question_group(self): """Questions added in a question group are listed as dimensions.""" unit = self.course.find_unit_by_id(self.unit_keys[0][1]) lesson = self.course.find_lesson_by_id(unit, self.lesson_keys[0][1]) items = [{'question':self.questions_keys[-1][-1]}] self._add_question_group(lesson, 'objectives', items) self.course.save() dimension_id = clustering.pack_question_dimid( unit.unit_id, lesson.lesson_id, self.questions_keys[-1][-1]) vector = clustering.get_possible_dimensions(self.app_context) self._dim_from_dict(vector, dimension_id, clustering.DIM_TYPE_QUESTION) def test_all_dimensions_assessments(self): """All assessments are listed as dimensions in default content.""" vector = clustering.get_possible_dimensions(self.app_context) for u_index, assessment_key in self.assessment_keys: dim = self._dim_from_dict(vector, assessment_key, clustering.DIM_TYPE_UNIT) self.assertEqual(dim['name'], self.assessment_name_str.format(u_index)) def test_no_scored_lesson(self): """Non scored lessons should not be included as possible dimensions. """ unit = self.course.find_unit_by_id(self.unit_keys[0][1]) lesson = self._add_lesson(1, unit) lesson.scored = False self._add_question(6, lesson, 'objectives') self.course.save() vector = clustering.get_possible_dimensions(self.app_context) for dim in vector: if (dim[clustering.DIM_ID] == lesson.lesson_id and dim[clustering.DIM_TYPE] == clustering.DIM_TYPE_LESSON): self.assertTrue(False, msg='Not scored lesson listed as dimension') if (dim[clustering.DIM_ID] == unit.unit_id and dim[clustering.DIM_TYPE] == clustering.DIM_TYPE_UNIT): extra_info = json.loads(dim[clustering.DIM_EXTRA_INFO]) self.assertEqual(extra_info['unit_scored_lessons'], 1, msg='Not scored lesson counted in unit') def test_all_dimensions_pre_assessment(self): """All units pre assessments and their questions as dimensions. """ unit = self.course.find_unit_by_id(self.unit_keys[0][1]) assessment = self._add_assessment(self.units_number + 10) self._add_question(self.question_numbers*self.units_number, assessment, 'html_content') unit.pre_assessment = assessment.unit_id self.course.save() vector = clustering.get_possible_dimensions(self.app_context) # Check the assessment dim = self._dim_from_dict(vector, assessment.unit_id, clustering.DIM_TYPE_UNIT) self.assertIsNotNone(dim) # Check the question question_id = self.questions_keys[-1][-1] question_id = clustering.pack_question_dimid(assessment.unit_id, None, question_id) dim = self._dim_from_dict(vector, question_id, clustering.DIM_TYPE_QUESTION) self.assertIsNotNone(dim) def test_save_name(self): """Save cluster with correct name.""" # get a sample payload response = self.get(self.CLUSTER_GET_URL) transformed_response = transforms.loads(response.body) default_cluster = json.loads(transformed_response['payload']) cluster_name = 'Name for the cluster number one.' default_cluster['name'] = cluster_name response = self._send_put_resquest(None, default_cluster, transformed_response['xsrf_token']) # get the key cid = json.loads(transforms.loads(response.body)['payload'])['key'] cluster = clustering.ClusterDAO.load(cid) self.assertIsNotNone(cluster, msg='Cluster not saved.') self.assertEqual(cluster.name, cluster_name, msg='Wrong name saved') def test_save_empty_name(self): """If the cluster has no name expect error.""" # get a sample payload response = self.get(self.CLUSTER_GET_URL) transformed_response = transforms.loads(response.body) default_cluster = json.loads(transformed_response['payload']) response = self._send_put_resquest(None, default_cluster, transformed_response['xsrf_token']) self.assertIn('"status": 412', response.body) def test_save_description(self): """Save cluster with correct description.""" # get a sample payload response = self.get(self.CLUSTER_GET_URL) transformed_response = transforms.loads(response.body) default_cluster = json.loads(transformed_response['payload']) cluster_description = 'Description for the cluster number one.' default_cluster['name'] = 'Name for the cluster number one.' default_cluster['description'] = cluster_description response = self._send_put_resquest(None, default_cluster, transformed_response['xsrf_token']) # get the key cid = json.loads(transforms.loads(response.body)['payload'])['key'] cluster = clustering.ClusterDAO.load(cid) self.assertIsNotNone(cluster, msg='Cluster not saved.') self.assertEqual(cluster.description, cluster_description, msg='Wrong description saved') def test_save_no_range(self): """The dimensions with no range are not saved""" # get a sample payload response = self.get(self.CLUSTER_GET_URL) transformed_response = transforms.loads(response.body) default_cluster = json.loads(transformed_response['payload']) vector = [{clustering.DIM_ID: clustering.ClusterRESTHandler.pack_id( '2', clustering.DIM_TYPE_LESSON)}] cluster_name = 'Name for the cluster number one.' default_cluster['name'] = cluster_name default_cluster['vector'] = vector response = self._send_put_resquest(None, default_cluster, transformed_response['xsrf_token']) # get the key cid = json.loads(transforms.loads(response.body)['payload'])['key'] cluster = clustering.ClusterDAO.load(cid) self.assertIsNotNone(cluster, msg='Cluster not saved.') self.assertEqual(cluster.vector, [], msg='Empty dimension saved.') def test_xsrf_token(self): """Check XSRF is required""" response = self.get(self.CLUSTER_GET_URL) transformed_response = transforms.loads(response.body) default_cluster = json.loads(transformed_response['payload']) request = {} request['key'] = None request['payload'] = json.dumps(default_cluster) response = self.put(self.CLUSTER_PUT_URL + '?%s' % urllib.urlencode( {'request': transforms.dumps(request)}), {}) self.assertEqual(response.status_int, 200) self.assertIn('"status": 403', response.body) def test_save_range0(self): """The dimensions with range (0, 0) are saved""" response = self.get(self.CLUSTER_GET_URL) transformed_response = transforms.loads(response.body) default_cluster = json.loads(transformed_response['payload']) default_cluster['name'] = 'ClusterName' dim_id = clustering.ClusterRESTHandler.pack_id( '2', clustering.DIM_TYPE_LESSON) vector = [{ clustering.DIM_ID: dim_id, clustering.DIM_LOW: 0, clustering.DIM_HIGH: 0}] default_cluster['vector'] = vector response = self._send_put_resquest(None, default_cluster, transformed_response['xsrf_token']) # get the key cid = json.loads(transforms.loads(response.body)['payload'])['key'] cluster = clustering.ClusterDAO.load(cid) self.assertEqual(len(cluster.vector), 1, msg='Wrong dimensions number') dimension = cluster.vector[0] self.assertEqual(dimension[clustering.DIM_LOW], 0, msg='Cluster saved with wrong dimension range') self.assertEqual(dimension[clustering.DIM_HIGH], 0, msg='Cluster saved with wrong dimension range') def test_save_range_incomplete_left(self): """One side ranges completed to None.""" response = self.get(self.CLUSTER_GET_URL) transformed_response = transforms.loads(response.body) default_cluster = json.loads(transformed_response['payload']) default_cluster['name'] = 'ClusterName' dim_id = clustering.ClusterRESTHandler.pack_id( '2', clustering.DIM_TYPE_LESSON) vector = [{clustering.DIM_ID: dim_id, clustering.DIM_HIGH: '0'}] default_cluster['vector'] = vector response = self._send_put_resquest(None, default_cluster, transformed_response['xsrf_token']) # get the key cid = json.loads(transforms.loads(response.body)['payload'])['key'] cluster = clustering.ClusterDAO.load(cid) self.assertEqual(len(cluster.vector), 1, msg='Wrong dimension number') dimension = cluster.vector[0] self.assertIn(clustering.DIM_LOW, dimension) self.assertIsNone(dimension[clustering.DIM_LOW], msg='Cluster saved with incomplete left side of dimension range') def test_save_range_incomplete_right(self): """One side ranges completed to None.""" response = self.get(self.CLUSTER_GET_URL) transformed_response = transforms.loads(response.body) default_cluster = json.loads(transformed_response['payload']) default_cluster['name'] = 'ClusterName' dim_id = clustering.ClusterRESTHandler.pack_id( '2', clustering.DIM_TYPE_LESSON) vector = [{clustering.DIM_ID: dim_id, clustering.DIM_LOW: '0.55'}] default_cluster['vector'] = vector response = self._send_put_resquest(None, default_cluster, transformed_response['xsrf_token']) # get the key cid = json.loads(transforms.loads(response.body)['payload'])['key'] cluster = clustering.ClusterDAO.load(cid) self.assertEqual(len(cluster.vector), 1, msg='Wrong dimension number') dimension = cluster.vector[0] self.assertIn(clustering.DIM_HIGH, dimension) self.assertIsNone(dimension[clustering.DIM_HIGH], msg='Cluster saved with incomplete right side of dimension range') def test_save_incosistent_range(self): """If left part of the range is greater than right expect error.""" # get a sample payload response = self.get(self.CLUSTER_GET_URL) transformed_response = transforms.loads(response.body) default_cluster = json.loads(transformed_response['payload']) default_cluster['name'] = 'ClusterName' dim_id = clustering.ClusterRESTHandler.pack_id( '2', clustering.DIM_TYPE_LESSON) vector = [{ clustering.DIM_ID: dim_id, clustering.DIM_HIGH: '0', clustering.DIM_LOW: '20'}] default_cluster['vector'] = vector response = self._send_put_resquest(None, default_cluster, transformed_response['xsrf_token']) self.assertIn('"status": 412', response.body) def test_save_non_numeric_range_left(self): """If range cant be converted to a number expect error response.""" # get a sample payload response = self.get(self.CLUSTER_GET_URL) transformed_response = transforms.loads(response.body) default_cluster = json.loads(transformed_response['payload']) default_cluster['name'] = 'ClusterName' dim_id = clustering.ClusterRESTHandler.pack_id( '2', clustering.DIM_TYPE_LESSON) vector = [{ clustering.DIM_ID: dim_id, clustering.DIM_HIGH: '0', clustering.DIM_LOW: 'Non numeric'}] default_cluster['vector'] = vector response = self._send_put_resquest(None, default_cluster, transformed_response['xsrf_token']) self.assertIn('"status": 412', response.body) def test_save_non_numeric_range_right(self): """If range cant be converted to a number expect error response.""" # get a sample payload response = self.get(self.CLUSTER_GET_URL) transformed_response = transforms.loads(response.body) default_cluster = json.loads(transformed_response['payload']) default_cluster['name'] = 'ClusterName' dim_id = clustering.ClusterRESTHandler.pack_id( '2', clustering.DIM_TYPE_LESSON) vector = [{ clustering.DIM_ID: dim_id, clustering.DIM_HIGH: 'Non numeric'}] default_cluster['vector'] = vector response = self._send_put_resquest(None, default_cluster, transformed_response['xsrf_token']) self.assertIn('"status": 412', response.body) def test_save_correct_url(self): """Test if the save button is posting to the correct url.""" response = self.get(self.CLUSTER_ADD_URL) self.assertIn(self.CLUSTER_PUT_URL, response.body) def test_edit_correct_url(self): cluster_key = self._add_cluster() url = 'dashboard?action=edit_cluster&key={}' response = self.get(url.format(cluster_key)) self.assertEqual(response.status_code, 200) def test_non_admin_get(self): """No admid users can't perform GET request.""" actions.logout() actions.login(self.NON_ADMIN_EMAIL, is_admin=False) response = self.get(self.CLUSTER_GET_URL) self.assertEquals(200, response.status_code) self.assertIn('"status": 401', response.body) def test_non_admin_put(self): """No admid users can't perform PUT request.""" actions.logout() actions.login(self.NON_ADMIN_EMAIL, is_admin=False) response = self.get(self.CLUSTER_PUT_URL) self.assertEquals(200, response.status_code) self.assertIn('"status": 401', response.body) def test_edit_fill_correct_data(self): """In the edit page the name, description and range must be present. """ cluster_key = self._add_cluster() cluster = clustering.ClusterDAO.load(cluster_key) response = self.get(self.CLUSTER_GET_URL + str(cluster_key)) self.assertEquals(200, response.status_code) transformed_response = transforms.loads(response.body) payload_cluster = json.loads(transformed_response['payload']) self.assertEqual(cluster.name, payload_cluster['name']) self.assertEqual(cluster.description, payload_cluster['description']) def test_save_name_after_edit(self): """The edited values are saved correctly.""" cluster_key = self._add_cluster() old_cluster = clustering.ClusterDAO.load(cluster_key) response = self.get(self.CLUSTER_GET_URL + str(cluster_key)) transformed_response = transforms.loads(response.body) new_cluster = json.loads(transformed_response['payload']) new_cluster_name = 'Name for the cluster number one.' new_cluster['name'] = new_cluster_name response = self._send_put_resquest(cluster_key, new_cluster, transformed_response['xsrf_token']) new_cluster = clustering.ClusterDAO.load(cluster_key) self.assertEqual(new_cluster.name, new_cluster_name) def test_save_dimension_after_edit(self): """The edited values are saved correctly.""" cluster_key = self._add_cluster() old_cluster = clustering.ClusterDAO.load(cluster_key) response = self.get(self.CLUSTER_GET_URL + str(cluster_key)) transformed_response = transforms.loads(response.body) new_cluster = json.loads(transformed_response['payload']) new_cluster['vector'][0][clustering.DIM_LOW] = 50 new_cluster['vector'][0][clustering.DIM_HIGH] = 60 packed_dimension_key = new_cluster['vector'][-1][clustering.DIM_ID] self.assertIsNotNone(packed_dimension_key) response = self._send_put_resquest(cluster_key, new_cluster, transformed_response['xsrf_token']) new_cluster = clustering.ClusterDAO.load(cluster_key) new_dimension = new_cluster.vector[0] dim_id, dim_type = clustering.ClusterRESTHandler.unpack_id( packed_dimension_key) self.assertEqual(new_dimension[clustering.DIM_ID], dim_id, msg='Cluster saved with wrong dimension id.') self.assertEqual(new_dimension[clustering.DIM_TYPE], dim_type, msg='Cluster saved with wrong dimension type.') self.assertEqual(new_dimension[clustering.DIM_LOW], 50, msg='Cluster saved with wrong dimension low.') self.assertEqual(new_dimension[clustering.DIM_HIGH], 60, msg='Cluster saved with wrong dimension high.') class StudentVectorGeneratorTests(actions.TestBase): COURSE_NAME = 'test_course' ADMIN_EMAIL = 'admin@foo.com' def setUp(self): super(StudentVectorGeneratorTests, self).setUp() self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME) self.app_context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'Analytics Test') self.course = courses.Course(None, app_context=self.app_context) self._load_initial_data() self.dimensions = [ # Data obteined from assessments.json {clustering.DIM_TYPE: clustering.DIM_TYPE_UNIT, clustering.DIM_ID: '4', clustering.DIM_EXTRA_INFO: json.dumps({'unit_scored_lessons': 0}), 'expected_value': 187.0}, {clustering.DIM_TYPE: clustering.DIM_TYPE_UNIT, clustering.DIM_ID: '1', clustering.DIM_EXTRA_INFO: json.dumps({'unit_scored_lessons': 1}), 'expected_value': 8.5}, {clustering.DIM_TYPE: clustering.DIM_TYPE_LESSON, clustering.DIM_ID: '3', 'expected_value': 8.5}, {clustering.DIM_TYPE: clustering.DIM_TYPE_QUESTION, clustering.DIM_ID: clustering.pack_question_dimid('1', '2', '5629499534213120'), 'expected_value': 0.5}, {clustering.DIM_TYPE: clustering.DIM_TYPE_QUESTION, clustering.DIM_ID: clustering.pack_question_dimid('1', '2', '5066549580791808'), 'expected_value': 0.75}, # Last weighted score {clustering.DIM_TYPE: clustering.DIM_TYPE_QUESTION, clustering.DIM_ID: clustering.pack_question_dimid('1', '3', '5629499534213120'), 'expected_value': (1.0 + 2.5) / 2}, # Average in submission. {clustering.DIM_TYPE: clustering.DIM_TYPE_QUESTION, clustering.DIM_ID: clustering.pack_question_dimid('1', '3', '5066549580791808'), 'expected_value': (3.5 + 1.5) / 2}, {clustering.DIM_TYPE: clustering.DIM_TYPE_QUESTION, clustering.DIM_ID: clustering.pack_question_dimid('4', None, '5629499534213120'), 'expected_value': (55.0 + 22.0) / 2}, {clustering.DIM_TYPE: clustering.DIM_TYPE_QUESTION, clustering.DIM_ID: clustering.pack_question_dimid('4', None, '5066549580791808'), 'expected_value': (77.0 + 33.0) / 2}, {clustering.DIM_TYPE: clustering.DIM_TYPE_UNIT_VISIT, clustering.DIM_ID: '3', 'expected_value': 2}, {clustering.DIM_TYPE: clustering.DIM_TYPE_UNIT_VISIT, clustering.DIM_ID: '6', 'expected_value': 2} ] def tearDown(self): # Clean up app_context. namespace_manager.set_namespace(self.old_namespace) super(StudentVectorGeneratorTests, self).tearDown() def _get_data_path(self, path): return os.path.join(appengine_config.BUNDLE_ROOT, 'tests', 'functional', 'modules_analytics', 'test_courses', path) def _load_initial_data(self): """Creates several StudentAggregateEntity based on the file item.""" self.aggregate_entity = student_aggregate.StudentAggregateEntity() # Upload data from scoring data_path = self._get_data_path('scoring') expected_path = os.path.join(data_path, 'expected', 'assessments.json') raw_assessment_data = None with open(expected_path) as fs: raw_assessment_data = transforms.loads(fs.read()) raw_views_data = None data_path = self._get_data_path('page_views') expected_path = os.path.join(data_path, 'expected', 'page_views.json') with open(expected_path) as fs: raw_views_data = transforms.loads(fs.read()) self.aggregate_entity.data = zlib.compress(transforms.dumps({ 'assessments': raw_assessment_data, 'page_views': raw_views_data})) self.aggregate_entity.put() self.raw_activities = raw_assessment_data self.raw_views_data = raw_views_data def test_inverse_submission_data(self): """inverse_submission_data returns a dictionary keys by dimension id. For every dimension of submissions the dictionary has a value with the same information as the original submission data. The value will be a list with all the submission relevant to that dimension. If an assessment is included inside a unit as pre or post assessment, the aggregator will put it in the first level as any other unit. """ def get_questions(unit_id, lesson_id, question_id): result = [] for activity in self.raw_activities: if not (activity.get('unit_id') == str(unit_id) and activity.get('lesson_id') == str(lesson_id)): continue for submission in activity['submissions']: for question in submission['answers']: if question.get('question_id') == question_id: question['timestamp'] = submission['timestamp'] result.append(question) return result result = clustering.StudentVectorGenerator._inverse_submission_data( self.dimensions, self.raw_activities) for dim in self.dimensions: dim_type = dim[clustering.DIM_TYPE] dim_id = dim[clustering.DIM_ID] entry = sorted(result[dim_type, dim_id]) expected = None if dim_type == clustering.DIM_TYPE_UNIT: expected = [activity for activity in self.raw_activities if activity['unit_id'] == dim_id] elif dim_type == clustering.DIM_TYPE_LESSON: expected = [activity for activity in self.raw_activities if activity['lesson_id'] == dim_id] elif dim_type == clustering.DIM_TYPE_QUESTION: unit_id, lesson_id, q_id = clustering.unpack_question_dimid( dim_id) expected = get_questions(unit_id, lesson_id, q_id) if not expected: continue expected.sort() self.assertEqual(entry, expected, msg='Bad entry {} {}: {}. Expected: {}'.format( dim_type, dim_id, entry, expected)) def test_inverse_page_view_data(self): """inverse_page_view_data returns a dictionary keys by dimension id. """ result = clustering.StudentVectorGenerator._inverse_page_view_data( self.raw_views_data) for dim in self.dimensions: dim_type = dim[clustering.DIM_TYPE] dim_id = dim[clustering.DIM_ID] entry = sorted(result[dim_type, dim_id]) if dim_type == clustering.DIM_TYPE_UNIT_VISIT: expected = [page_view for page_view in self.raw_views_data if page_view['name'] in ['unit', 'assessment'] and page_view['item_id'] == dim_id] expected.sort() self.assertEqual(entry, expected) def run_generator_job(self): def mock_mapper_params(unused_self, unused_app_context): return {'possible_dimensions': self.dimensions} mock_generator = clustering.StudentVectorGenerator mock_generator.build_additional_mapper_params = mock_mapper_params job = mock_generator(self.app_context) job.submit() self.execute_all_deferred_tasks() def test_map_reduce(self): """The generator is producing the expected output vector.""" self.run_generator_job() self.assertEqual(clustering.StudentVector.all().count(), 1) student_vector = clustering.StudentVector.get_by_key_name( str(self.aggregate_entity.key().name())) for expected_dim in self.dimensions: obtained_value = clustering.StudentVector.get_dimension_value( transforms.loads(student_vector.vector), expected_dim[clustering.DIM_ID], expected_dim[clustering.DIM_TYPE]) self.assertEqual(expected_dim['expected_value'], obtained_value) def test_map_reduce_no_assessment(self): self.aggregate_entity.data = zlib.compress(transforms.dumps({})) self.aggregate_entity.put() self.run_generator_job() student_vector = clustering.StudentVector.get_by_key_name( str(self.aggregate_entity.key().id())) self.assertIsNone(student_vector) def test_get_unit_score(self): """The score of a unit is the average score of its scored lessons. This is testing the following extra cases: - Submissions with no lesson_id """ data = clustering.StudentVectorGenerator._inverse_submission_data( self.dimensions, self.raw_activities) for dim in self.dimensions: if dim[clustering.DIM_TYPE] == clustering.DIM_TYPE_UNIT: value = clustering.StudentVectorGenerator._get_unit_score( data[dim[clustering.DIM_TYPE], dim[clustering.DIM_ID]], dim) self.assertEqual(value, dim['expected_value']) def test_get_lesson_score(self): """The score of a lesson is its last score. This is testing the following extra cases: - Submissions with no lesson_id """ data = clustering.StudentVectorGenerator._inverse_submission_data( self.dimensions, self.raw_activities) for dim in self.dimensions: if dim[clustering.DIM_TYPE] == clustering.DIM_TYPE_LESSON: value = clustering.StudentVectorGenerator._get_lesson_score( data[dim[clustering.DIM_TYPE], dim[clustering.DIM_ID]], dim) self.assertEqual(value, dim['expected_value']) def test_get_question_score(self): """The score of a question is its last score. This is testing the following extra cases: - Multiple submissions of the same question. - Save question multiple times in the same submission. - Submissions to assesments (no lesson id). """ data = clustering.StudentVectorGenerator._inverse_submission_data( self.dimensions, self.raw_activities) for dim in self.dimensions: if dim[clustering.DIM_TYPE] == clustering.DIM_TYPE_QUESTION: value = clustering.StudentVectorGenerator._get_question_score( data[dim[clustering.DIM_TYPE], dim[clustering.DIM_ID]], dim) self.assertEqual(value, dim['expected_value']) def test_get_unit_visits(self): """Count the number of visits for a unit or an assessment. """ data = clustering.StudentVectorGenerator._inverse_page_view_data( self.raw_views_data) for dim in self.dimensions: if dim[clustering.DIM_TYPE] == clustering.DIM_TYPE_UNIT_VISIT: value = clustering.StudentVectorGenerator._get_unit_visits( data[dim[clustering.DIM_TYPE], dim[clustering.DIM_ID]], dim) self.assertEqual(value, dim['expected_value']) def test_score_no_submitted_unit(self): """If there is no submission of a unit the value is 0.""" extra_dimension = { clustering.DIM_TYPE: clustering.DIM_TYPE_UNIT, clustering.DIM_ID: '10'} data = clustering.StudentVectorGenerator._inverse_submission_data( [extra_dimension], self.raw_activities) value = clustering.StudentVectorGenerator._get_unit_score( data[extra_dimension[clustering.DIM_TYPE], '10'], extra_dimension) self.assertEqual(value, 0) def test_score_no_submitted_lesson(self): """If there is no submission of a lesson the value is 0.""" extra_dimension = { clustering.DIM_TYPE: clustering.DIM_TYPE_LESSON, clustering.DIM_ID: '10' } data = clustering.StudentVectorGenerator._inverse_submission_data( [extra_dimension], self.raw_activities) value = clustering.StudentVectorGenerator._get_lesson_score( data[extra_dimension[clustering.DIM_TYPE], '10'], extra_dimension) self.assertEqual(value, 0) def test_score_no_submitted_question(self): """If there is no submission of a question the value is 0.""" extra_dimension = { clustering.DIM_TYPE: clustering.DIM_TYPE_QUESTION, clustering.DIM_ID: clustering.pack_question_dimid('1', '3', '00000') } data = clustering.StudentVectorGenerator._inverse_submission_data( [extra_dimension], self.raw_activities) value = clustering.StudentVectorGenerator._get_question_score( data[extra_dimension[clustering.DIM_TYPE], '10'], extra_dimension) self.assertEqual(value, 0) def test_get_unit_score_multiple_lessons(self): """The score of a unit is the average score of its scored lessons.""" raw_assessment_data = self.raw_activities + [{ 'last_score':10.5, 'unit_id':'1', 'lesson_id':'5', }] dimension = { clustering.DIM_TYPE: clustering.DIM_TYPE_UNIT, clustering.DIM_ID: '1', clustering.DIM_EXTRA_INFO : json.dumps({ 'unit_scored_lessons': 2 }) } expected = (10.5 + 8.5) / 2 value = clustering.StudentVectorGenerator._get_unit_score( raw_assessment_data, dimension) self.assertEqual(value, expected, msg='Wrong score for unit with multiple lessons. ' 'Expected {}. Got {}'.format(expected, value)) class StudentVectorGeneratorProgressTests(actions.TestBase): """Tests the calculation of the progress dimensions.""" COURSE_NAME = 'test_course' ADMIN_EMAIL = 'admin@foo.com' def setUp(self): super(StudentVectorGeneratorProgressTests, self).setUp() self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME) self.app_context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'Analytics Test') self.course = courses.Course(None, app_context=self.app_context) self._create_entities() def tearDown(self): # Clean up app_context. namespace_manager.set_namespace(self.old_namespace) super(StudentVectorGeneratorProgressTests, self).tearDown() def _create_entities(self): # Add course content unit = self.course.add_unit() unit.title = 'Unit number 1' unit.now_available = True lesson = self.course.add_lesson(unit) lesson.title = 'Lesson' lesson.now_available = True self.course.save() self.student_id = '1' self.student = models.Student(user_id=self.student_id) self.student.put() self.aggregate_entity = student_aggregate.StudentAggregateEntity( key_name=self.student_id, data=zlib.compress(transforms.dumps({}))) self.aggregate_entity.put() self.progress = UnitLessonCompletionTracker.get_or_create_progress( self.student) self.progress.value = transforms.dumps( {"u.{}.l.{}".format(unit.unit_id, lesson.lesson_id): 2, "u.{}".format(unit.unit_id): 1}) self.progress.put() self.dimensions = [ {clustering.DIM_TYPE: clustering.DIM_TYPE_UNIT_PROGRESS, clustering.DIM_ID: unit.unit_id, 'expected_value': 1}, {clustering.DIM_TYPE: clustering.DIM_TYPE_LESSON_PROGRESS, clustering.DIM_ID: lesson.lesson_id, 'expected_value': 2, clustering.DIM_EXTRA_INFO: transforms.dumps({'unit_id': 1})} ] def run_generator_job(self): def mock_mapper_params(unused_self, unused_app_context): return {'possible_dimensions': self.dimensions} mock_generator = clustering.StudentVectorGenerator mock_generator.build_additional_mapper_params = mock_mapper_params job = mock_generator(self.app_context) job.submit() self.execute_all_deferred_tasks() def test_map_reduce(self): """The generator is producing the expected output vector.""" self.run_generator_job() self.assertEqual(clustering.StudentVector.all().count(), 1) student_vector = clustering.StudentVector.get_by_key_name( str(self.aggregate_entity.key().name())) for expected_dim in self.dimensions: obtained_value = clustering.StudentVector.get_dimension_value( transforms.loads(student_vector.vector), expected_dim[clustering.DIM_ID], expected_dim[clustering.DIM_TYPE]) self.assertEqual(expected_dim['expected_value'], obtained_value) def test_map_reduce_no_progress(self): """The student has no progress.""" self.progress.value = None self.progress.put() self.run_generator_job() self.assertEqual(clustering.StudentVector.all().count(), 0) class ClusteringGeneratorTests(actions.TestBase): """Tests for the ClusteringGenerator job and auxiliary functions.""" COURSE_NAME = 'test_course' ADMIN_EMAIL = 'admin@foo.com' def setUp(self): super(ClusteringGeneratorTests, self).setUp() self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME) self.app_context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'Analytics Test') self.course = courses.Course(None, app_context=self.app_context) self.dim_number = 10 self.dimensions = [ {clustering.DIM_TYPE: clustering.DIM_TYPE_QUESTION, clustering.DIM_ID: str(i)} for i in range(self.dim_number)] self.student_vector_keys = [] def tearDown(self): # Clean up app_context. namespace_manager.set_namespace(self.old_namespace) super(ClusteringGeneratorTests, self).tearDown() def _add_student_vector(self, student_id, values): """Creates a StudentVector in the db using the given id and values. Values is a list of numbers, one for each dimension. It must not have more items than self.dimensions. """ new_sv = clustering.StudentVector(key_name=student_id) for index, value in enumerate(values): self.dimensions[index][clustering.DIM_VALUE] = value new_sv.vector = transforms.dumps(self.dimensions) self.student_vector_keys.append(new_sv.put()) def _add_cluster(self, values): """Creates a ClusterEntity in the db using the given id and values. Values is a list of 2-uples, one for each dimension. It must not have more items than self.dimensions.""" for index, value in enumerate(values): self.dimensions[index][clustering.DIM_LOW] = value[0] self.dimensions[index][clustering.DIM_HIGH] = value[1] new_cluster = clustering.ClusterDTO(None, {'name': 'Cluster {}'.format(len(values) + 1), 'vector': self.dimensions}) return clustering.ClusterDAO.save(new_cluster) def run_generator_job(self): job = clustering.ClusteringGenerator(self.app_context) job.submit() self.execute_all_deferred_tasks() def _add_entities(self): """Creates the entities in the db needed to run the job.""" self.sv_number = 20 # Add StudentVectors for index in range(self.sv_number): values = range(index + 1, index + self.dim_number + 1) student = models.Student(user_id=str(index)) student.put() self._add_student_vector(student.user_id, values) # Add extra student with no student vector models.Student(user_id=str(self.sv_number)).put() # Add cluster cluster_values = [(i, i*2) for i in range(1, self.dim_number+1)] cluster1_key = self._add_cluster(cluster_values) # expected distances vector 1: 0 0 1 2 3 4 ... cluster_values = [(i, i+1) for i in range(1, self.dim_number+1)] cluster2_key = self._add_cluster(cluster_values) # expected distances vector 2: 0 0 10 10 10 10 ... return cluster1_key, cluster2_key def test_mapreduce_clusters(self): """Tests clusters stored in StudentVector after map reduce job. The job must update the clusters attribute in each StudentVector with a dictionary where the keys are the clusters' ids and the values are the distances, as long as the distance is in the correct range. """ cluster1_key, cluster2_key = self._add_entities() self.run_generator_job() # Check the StudentVector clusters expected_distances1 = [0, 0, 1, 2] expected_distances2 = [0, 0] for index, key in enumerate(self.student_vector_keys[:4]): student_clusters = clustering.StudentClusters.get_by_key_name( key.name()) clusters = transforms.loads(student_clusters.clusters) self.assertIn(str(cluster1_key), clusters) self.assertEqual(clusters[str(cluster1_key)], expected_distances1[index], msg='Wrong distance vector {}'.format(index)) for index, key in enumerate(self.student_vector_keys[:2]): student_clusters = clustering.StudentClusters.get_by_key_name( key.name()) clusters = transforms.loads(student_clusters.clusters) self.assertIn(str(cluster2_key), clusters) self.assertEqual(clusters[str(cluster2_key)], expected_distances2[index], msg='Wrong distance vector {}'.format(index)) def test_mapreduce_stats(self): """Tests clusters stats generated after map reduce job. The expected result of the job is a list of tuples. The first element of the tuple is going to be the metric name and the second a dictionary. The values of the dictionary are lists. [ ('count', ['1', [2, 1, 1, ...]]), ('count', ['2', [2, 0, 0, ...]]), ('intersection', [('1', '2'), [2, 2, 2, ...]]), ('student_count', 20) ... ] """ cluster1_key, cluster2_key = self._add_entities() self.run_generator_job() job = clustering.ClusteringGenerator(self.app_context).load() result = jobs.MapReduceJob.get_results(job) self.assertEqual(4, len(result), msg='Wrong response number') # All tuples are converted to lists after map reduce. self.assertIn(['count', [cluster1_key, [2, 1, 1]]], result) self.assertIn(['count', [cluster2_key, [2]]], result) self.assertIn(['intersection', [[cluster1_key, cluster2_key], [2]]], result) self.assertIn(['student_count', self.sv_number + 1], result) def _check_hamming(self, cluster_vector, student_vector, value): self.assertEqual(clustering.hamming_distance( cluster_vector, student_vector), value) def test_hamming_distance(self): cluster_vector = [ {clustering.DIM_TYPE: clustering.DIM_TYPE_UNIT, clustering.DIM_ID: '1', clustering.DIM_HIGH: 10, clustering.DIM_LOW: None}, {clustering.DIM_TYPE: clustering.DIM_TYPE_UNIT, clustering.DIM_ID: '2', clustering.DIM_HIGH: 80, clustering.DIM_LOW: 60}, ] student_vector = [ {clustering.DIM_TYPE: clustering.DIM_TYPE_UNIT, clustering.DIM_ID: '1', clustering.DIM_VALUE: 7}, # Match {clustering.DIM_TYPE: clustering.DIM_TYPE_UNIT, clustering.DIM_ID: '2', clustering.DIM_VALUE: 100}, # Don't mach {clustering.DIM_TYPE: clustering.DIM_TYPE_UNIT, clustering.DIM_ID: '3', clustering.DIM_VALUE: 4} # Match ] self._check_hamming(cluster_vector, student_vector, 1) def test_hamming_equal_left(self): """The limit of the dimension range must be considered.""" cluster_vector = [ {clustering.DIM_TYPE: clustering.DIM_TYPE_UNIT, clustering.DIM_ID: '4', clustering.DIM_HIGH: 7, clustering.DIM_LOW: 6}, ] student_vector = [ {clustering.DIM_TYPE: clustering.DIM_TYPE_UNIT, clustering.DIM_ID: '1', clustering.DIM_VALUE: 7}, ] self._check_hamming(cluster_vector, student_vector, 1) def test_hamming_equal_right(self): """The limit of the dimension range must be considered.""" cluster_vector = [ {clustering.DIM_TYPE: clustering.DIM_TYPE_UNIT, clustering.DIM_ID: '4', clustering.DIM_HIGH: 9, clustering.DIM_LOW: 7}, ] student_vector = [ {clustering.DIM_TYPE: clustering.DIM_TYPE_UNIT, clustering.DIM_ID: '1', clustering.DIM_VALUE: 7}, ] self._check_hamming(cluster_vector, student_vector, 1) def test_hamming_missing_dim_student(self): """If a student has no matching dimension assume the value 0.""" cluster_vector = [ {clustering.DIM_TYPE: clustering.DIM_TYPE_UNIT, clustering.DIM_ID: '4', clustering.DIM_HIGH: 7, clustering.DIM_LOW: 3}, ] self._check_hamming(cluster_vector, [], 1) class TestClusterStatisticsDataSource(actions.TestBase): def _add_clusters(self): self.clusters_map = {} n_clusters = 4 dimension = {"type": "lp", "low": 1.0, "high": 1.0, "id": "8"} for index in range(n_clusters): name = 'Cluster {}'.format(index) new_cluster = clustering.ClusterDTO(None, {'name': name, 'vector': [dimension] * (index + 1)}) key = clustering.ClusterDAO.save(new_cluster) self.clusters_map[key] = name def _add_student_vectors(self): self.n_students = 6 for i in range(self.n_students): clustering.StudentVector().put() def test_fetch_values_count(self): """Tests the result of the count statistics""" self._add_clusters() keys = self.clusters_map.keys() job_result = [ ('count', (keys[0], [1, 1])), ('count', (keys[1], [0])), ('count', (keys[2], [1, 1, 2])), ('student_count', 6) ] expected_result = [ [self.clusters_map[keys[0]], 1, 0, 0, 5], # one dimension [self.clusters_map[keys[1]], 0, 0, 0, 6], # two dimensions [self.clusters_map[keys[2]], 1, 1, 2, 2], # three dimensions [self.clusters_map[keys[3]], 0, 0, 0, 6], ] result = clustering.ClusterStatisticsDataSource._process_job_result( job_result) self.assertEqual(expected_result, result[0]) def test_fetch_values_intersection(self): """Tests the result of the count statistics""" self._add_clusters() self._add_student_vectors() keys = self.clusters_map.keys() job_result = [ ('count', (keys[0], [1, 1, 2])), # [1, 2, 4] ('count', (keys[1], [2])), # [2, 2, 2] ('count', (keys[2], [2, 1])), # [2, 3, 3] ('count', (keys[3], [1, 1])), # [1, 2, 2] ('intersection', ((keys[0], keys[1]), [1, 1, 2])), ('intersection', ((keys[1], keys[2]), [1, 2])), ('intersection', ((keys[3], keys[2]), [0])), ('student_count', self.n_students) ] expected_mapping = [self.clusters_map[k] for k in keys] # names expected0 = { 'count': {0: {1: 1}, 1: {2: 1}, 3: {2: 0}}, 'percentage': {0: {1: 16.67}, 1: {2: 16.67}, 3: {2: 0.00}}, 'probability': {0: {1: 1.0}, 1: {0: 0.5, 2: 0.5}, 2: {1: 0.5, 3: 0.0}, 3: {2: 0.0}} } expected1 = { 'count': {0: {1: 1}, 1: {2: 2}, 3: {2: 0}}, 'percentage': {0: {1: 16.67}, 1: {2: 33.33}, 3: {2: 0.00}}, 'probability': {0: {1: 0.5}, 1: {0: 0.5, 2: 1.0}, 2: {1: 0.67, 3: 0}, 3: {2: 0.0}} } expected2 = { 'count': {0: {1: 2}, 1: {2: 2}, 3: {2: 0}}, 'percentage': {0: {1: 33.33}, 1: {2: 33.33}, 3: {2: 0.00}}, 'probability': {0: {1: 0.5}, 1: {0: 1.0, 2: 1.0}, 2: {1: 0.67, 3: 0.0}, 3: {2: 0.0}} } result = clustering.ClusterStatisticsDataSource._process_job_result( job_result) self.assertEqual(result[1], [expected0, expected1, expected2]) self.assertEqual(result[2], expected_mapping)
Python
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for modules/admin. (See also test_classes.AdminAspectTest.""" __author__ = 'John Orr (jorr@google.com)' from controllers import sites from models import courses from tests.functional import actions from google.appengine.api import namespace_manager class AdminDashboardTabTests(actions.TestBase): ADMIN_EMAIL = 'adin@foo.com' COURSE_NAME = 'admin_tab_test_course' def setUp(self): super(AdminDashboardTabTests, self).setUp() self.base = '/' + self.COURSE_NAME context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'I18N Course') self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME) self.course = courses.Course(None, context) def tearDown(self): del sites.Registry.test_overrides[sites.GCB_COURSES_CONFIG.name] namespace_manager.set_namespace(self.old_namespace) super(AdminDashboardTabTests, self).tearDown() def get_nav_bar(self, dom, level=1): return dom.find( './/tr[@class="gcb-nav-bar-level-%s"]' % level) def test_admin_tab_not_present_for_non_admin(self): actions.login(self.ADMIN_EMAIL, is_admin=False) dom = self.parse_html_string(self.get('/dashboard').body) self.assertIsNone(dom.find('.//a[@href="admin?action=admin"]')) def test_admin_tab_is_present_for_admin(self): actions.login(self.ADMIN_EMAIL, is_admin=True) dom = self.parse_html_string(self.get('/dashboard').body) self.assertIsNotNone(dom.find('.//a[@href="admin?action=admin"]')) def test_admin_actions_unavailable_for_non_admin(self): actions.login(self.ADMIN_EMAIL, is_admin=False) response = self.get('admin?action=admin') self.assertEqual(302, response.status_int) response = self.post( 'admin?action=config_reset&name=gcb_admin_user_emails', {}) self.assertEqual(302, response.status_int) def test_admin_actions_available_for_admin(self): actions.login(self.ADMIN_EMAIL, is_admin=True) dom = self.parse_html_string(self.get('admin?action=admin').body) self.assertEqual( 'Site Admin', self.get_nav_bar(dom).find('.//a[@class="selected"]').text)
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests that walk through Course Builder pages.""" __author__ = 'Mike Gainer (mgainer@google.com)' import re from common import crypto from common import utils as common_utils from controllers import sites from controllers import utils from models import config from models import courses from models import models from modules.dashboard import unit_lesson_editor from tests.functional import actions from tools import verify COURSE_NAME = 'unit_pre_post' COURSE_TITLE = 'Unit Pre/Post Assessments' NAMESPACE = 'ns_%s' % COURSE_NAME ADMIN_EMAIL = 'admin@foo.com' BASE_URL = '/' + COURSE_NAME COURSE_URL = BASE_URL + '/course' DASHBOARD_URL = BASE_URL + '/dashboard' STUDENT_EMAIL = 'foo@foo.com' class UnitPrePostAssessmentTest(actions.TestBase): def setUp(self): super(UnitPrePostAssessmentTest, self).setUp() context = actions.simple_add_course( COURSE_NAME, ADMIN_EMAIL, COURSE_TITLE) self.course = courses.Course(None, context) self.unit_no_lessons = self.course.add_unit() self.unit_no_lessons.title = 'No Lessons' self.unit_no_lessons.now_available = True self.unit_one_lesson = self.course.add_unit() self.unit_one_lesson.title = 'One Lesson' self.unit_one_lesson.now_available = True self.lesson = self.course.add_lesson(self.unit_one_lesson) self.lesson.title = 'Lesson One' self.lesson.objectives = 'body of lesson' self.lesson.now_available = True self.assessment_one = self.course.add_assessment() self.assessment_one.title = 'Assessment One' self.assessment_one.html_content = 'assessment one content' self.assessment_one.now_available = True self.assessment_two = self.course.add_assessment() self.assessment_two.title = 'Assessment Two' self.assessment_two.html_content = 'assessment two content' self.assessment_two.now_available = True self.course.save() actions.login(STUDENT_EMAIL) actions.register(self, STUDENT_EMAIL, COURSE_NAME) config.Registry.test_overrides[ utils.CAN_PERSIST_ACTIVITY_EVENTS.name] = True with common_utils.Namespace(NAMESPACE): self.track_one_id = models.LabelDAO.save(models.LabelDTO( None, {'title': 'Track One', 'descripton': 'track_one', 'type': models.LabelDTO.LABEL_TYPE_COURSE_TRACK})) self.general_one_id = models.LabelDAO.save(models.LabelDTO( None, {'title': 'Track One', 'descripton': 'track_one', 'type': models.LabelDTO.LABEL_TYPE_GENERAL})) def _get_unit_page(self, unit): return self.get(BASE_URL + '/unit?unit=' + str(unit.unit_id)) def _click_button(self, class_name, response): matches = re.search( r'<div class="%s">\s*<a href="([^"]*)"' % class_name, response.body) url = matches.group(1).replace('&amp;', '&') return self.get(url, response) def _click_next_button(self, response): return self._click_button('gcb-next-button', response) def _click_prev_button(self, response): return self._click_button('gcb-prev-button', response) def _assert_contains_in_order(self, response, expected): index = 0 for item in expected: index = response.body.find(item, index) if index == -1: self.fail('Did not find expected content "%s" ' % item) def test_assements_in_units_not_shown_on_course_page(self): response = self.get(COURSE_URL) self.assertIn(self.unit_no_lessons.title, response.body) self.assertIn(self.unit_one_lesson.title, response.body) self.assertIn(self.assessment_one.title, response.body) self.assertIn(self.assessment_two.title, response.body) self.unit_no_lessons.pre_assessment = self.assessment_one.unit_id self.unit_no_lessons.post_assessment = self.assessment_two.unit_id self.course.save() response = self.get(COURSE_URL) self.assertIn(self.unit_no_lessons.title, response.body) self.assertIn(self.unit_one_lesson.title, response.body) self.assertNotIn(self.assessment_one.title, response.body) self.assertNotIn(self.assessment_two.title, response.body) def test_pre_assessment_as_only_lesson(self): self.unit_no_lessons.pre_assessment = self.assessment_one.unit_id self.course.save() response = self._get_unit_page(self.unit_no_lessons) self.assertNotIn('This unit has no content', response.body) self.assertIn(self.assessment_one.title, response.body) self.assertIn(self.assessment_one.html_content, response.body) self.assertIn('Submit Answers', response.body) self.assertNotIn('Previous Page', response.body) self.assertNotIn('Next Page', response.body) self.assertIn(' End ', response.body) def test_post_assessment_as_only_lesson(self): self.unit_no_lessons.post_assessment = self.assessment_one.unit_id self.course.save() response = self._get_unit_page(self.unit_no_lessons) self.assertNotIn('This unit has no content', response.body) self.assertIn(self.assessment_one.title, response.body) self.assertIn(self.assessment_one.html_content, response.body) self.assertIn('Submit Answers', response.body) self.assertNotIn('Previous Page', response.body) self.assertNotIn('Next Page', response.body) self.assertIn(' End ', response.body) def test_pre_and_post_assessment_as_only_lessons(self): self.unit_no_lessons.pre_assessment = self.assessment_one.unit_id self.unit_no_lessons.post_assessment = self.assessment_two.unit_id self.course.save() response = self._get_unit_page(self.unit_no_lessons) self.assertIn(self.assessment_one.title, response.body) self.assertIn(self.assessment_two.title, response.body) self.assertIn(self.assessment_one.html_content, response.body) self.assertNotIn('Previous Page', response.body) self.assertIn('Next Page', response.body) self.assertNotIn(' End ', response.body) response = self._click_next_button(response) self.assertIn(self.assessment_one.title, response.body) self.assertIn(self.assessment_two.title, response.body) self.assertIn(self.assessment_two.html_content, response.body) self.assertIn('Previous Page', response.body) self.assertNotIn('Next Page', response.body) self.assertIn(' End ', response.body) response = self._click_prev_button(response) self.assertIn(self.assessment_one.html_content, response.body) def test_pre_and_post_assessment_with_other_lessons(self): self.unit_one_lesson.pre_assessment = self.assessment_one.unit_id self.unit_one_lesson.post_assessment = self.assessment_two.unit_id self.course.save() response = self._get_unit_page(self.unit_one_lesson) self.assertIn(self.assessment_one.title, response.body) self.assertIn('2.1 ' + self.lesson.title, response.body) self.assertIn(self.assessment_two.title, response.body) self.assertIn(self.assessment_one.html_content, response.body) self.assertNotIn('Previous Page', response.body) self.assertIn('Next Page', response.body) self.assertNotIn(' End ', response.body) response = self._click_next_button(response) self.assertIn(self.lesson.objectives, response.body) response = self._click_next_button(response) self.assertIn(self.assessment_two.html_content, response.body) response = self._click_next_button(response) # Back to /course page self.assertIn(self.unit_no_lessons.title, response.body) self.assertIn(self.unit_one_lesson.title, response.body) self.assertNotIn(self.assessment_one.title, response.body) self.assertNotIn(self.assessment_two.title, response.body) def _assert_progress_state(self, expected, lesson_title, response): title_index = response.body.index(lesson_title) alt_marker = 'alt="' state_start = response.body.rfind( alt_marker, 0, title_index) + len(alt_marker) state_end = response.body.find('"', state_start) self.assertEquals(expected, response.body[state_start:state_end]) def test_progress_via_next_buttons(self): self.unit_one_lesson.pre_assessment = self.assessment_one.unit_id self.unit_one_lesson.post_assessment = self.assessment_two.unit_id self.course.save() response = self.get(COURSE_URL) self._assert_progress_state( 'Not yet started', 'Unit 2 - %s</a>' % self.unit_one_lesson.title, response) # On pre-assessment; no progress markers on any lesson. response = self._get_unit_page(self.unit_one_lesson) self._assert_progress_state( 'Not yet submitted', self.assessment_one.title, response) self._assert_progress_state( 'Not yet started', '2.1 ' + self.lesson.title, response) self._assert_progress_state( 'Not yet submitted', self.assessment_two.title, response) # On actual lesson; no progress markers set when lesson first shown. response = self._click_next_button(response) self._assert_progress_state( 'Not yet submitted', self.assessment_one.title, response) self._assert_progress_state( 'Not yet started', '2.1 ' + self.lesson.title, response) self._assert_progress_state( 'Not yet submitted', self.assessment_two.title, response) # On post-assessment; progress for lesson, but not for pre-assessment. response = self._click_next_button(response) self._assert_progress_state( 'Not yet submitted', self.assessment_one.title, response) self._assert_progress_state( 'Completed', '2.1 ' + self.lesson.title, response) self._assert_progress_state( 'Not yet submitted', self.assessment_two.title, response) # Back on course page; expect partial progress. response = self._click_next_button(response) self._assert_progress_state( 'In progress', 'Unit 2 - %s</a>' % self.unit_one_lesson.title, response) def _post_assessment(self, assessment_id): return self.post(BASE_URL + '/answer', { 'xsrf_token': crypto.XsrfTokenManager.create_xsrf_token( 'assessment-post'), 'assessment_type': assessment_id, 'score': '1'}) def test_progress_via_assessment_submission(self): self.unit_one_lesson.pre_assessment = self.assessment_one.unit_id self.unit_one_lesson.post_assessment = self.assessment_two.unit_id self.course.save() # Submit pre-assessment; verify completion status. response = self._get_unit_page(self.unit_one_lesson) response = self._post_assessment(self.assessment_one.unit_id).follow() self._assert_progress_state( 'Completed', self.assessment_one.title, response) self._assert_progress_state( 'Not yet started', '2.1 ' + self.lesson.title, response) self._assert_progress_state( 'Not yet submitted', self.assessment_two.title, response) # Verify that we're on the assessment confirmation page. self.assertIn('Thank you for taking the assessment one', response.body) response = self._click_next_button(response) # Next-button past the lesson content response = self._click_next_button(response) self._assert_progress_state( 'Completed', self.assessment_one.title, response) self._assert_progress_state( 'Completed', '2.1 ' + self.lesson.title, response) self._assert_progress_state( 'Not yet submitted', self.assessment_two.title, response) # Submit post-assessment; unit should now be marked complete. response = self._post_assessment(self.assessment_two.unit_id).follow() # Verify that we get confirmation page on post-assessment self.assertIn('Thank you for taking the assessment two', response.body) self._assert_progress_state( 'Completed', self.assessment_one.title, response) self._assert_progress_state( 'Completed', '2.1 ' + self.lesson.title, response) self._assert_progress_state( 'Completed', self.assessment_two.title, response) # Verify that the overall course state is completed. response = self._click_next_button(response) self._assert_progress_state( 'Completed', 'Unit 2 - %s</a>' % self.unit_one_lesson.title, response) def _get_selection_choices(self, schema, match): ret = {} for item in schema: if item[0] == match: for choice in item[1]['choices']: ret[choice['label']] = choice['value'] return ret def test_old_assessment_availability(self): new_course_context = actions.simple_add_course( 'new_course', ADMIN_EMAIL, 'My New Course') new_course = courses.Course(None, new_course_context) new_course.import_from( sites.get_all_courses(rules_text='course:/:/')[0]) new_course.save() # Prove that there are at least some assessments in this course. assessments = new_course.get_units_of_type(verify.UNIT_TYPE_ASSESSMENT) self.assertIsNotNone(assessments[0]) # Get the first Unit unit = new_course.get_units_of_type(verify.UNIT_TYPE_UNIT)[0] unit_rest_handler = unit_lesson_editor.UnitRESTHandler() schema = unit_rest_handler.get_annotations_dict( new_course, unit.unit_id) # Verify that there are 4 valid choices for pre- or post-asssments # for this unit choices = self._get_selection_choices( schema, ['properties', 'pre_assessment', '_inputex']) self.assertEquals(5, len(choices)) self.assertEquals(-1, choices['-- None --']) choices = self._get_selection_choices( schema, ['properties', 'post_assessment', '_inputex']) self.assertEquals(5, len(choices)) self.assertEquals(-1, choices['-- None --']) def test_old_assessment_assignment(self): new_course_context = actions.simple_add_course( 'new_course', ADMIN_EMAIL, 'My New Course') new_course = courses.Course(None, new_course_context) new_course.import_from( sites.get_all_courses(rules_text='course:/:/')[0]) new_course.save() unit_rest_handler = unit_lesson_editor.UnitRESTHandler() unit_rest_handler.app_context = new_course_context # Use REST handler function to save pre/post handlers on one unit. errors = [] unit = new_course.get_units_of_type(verify.UNIT_TYPE_UNIT)[0] assessment = new_course.get_units_of_type( verify.UNIT_TYPE_ASSESSMENT)[0] unit_rest_handler.apply_updates( unit, { 'title': unit.title, 'now_available': unit.now_available, 'label_groups': [], 'pre_assessment': assessment.unit_id, 'post_assessment': -1, 'show_contents_on_one_page': False, 'manual_progress': False, 'description': None, 'unit_header': None, 'unit_footer': None, }, errors) assert not errors def test_new_assessment_availability(self): unit_rest_handler = unit_lesson_editor.UnitRESTHandler() schema = unit_rest_handler.get_annotations_dict( self.course, self.unit_no_lessons.unit_id) choices = self._get_selection_choices( schema, ['properties', 'pre_assessment', '_inputex']) self.assertEquals({ '-- None --': -1, self.assessment_one.title: self.assessment_one.unit_id, self.assessment_two.title: self.assessment_two.unit_id}, choices) choices = self._get_selection_choices( schema, ['properties', 'post_assessment', '_inputex']) self.assertEquals({ '-- None --': -1, self.assessment_one.title: self.assessment_one.unit_id, self.assessment_two.title: self.assessment_two.unit_id}, choices) def test_rest_unit_assignment(self): unit_rest_handler = unit_lesson_editor.UnitRESTHandler() unit_rest_handler.app_context = self.course.app_context # Use REST handler function to save pre/post handlers on one unit. errors = [] unit_rest_handler.apply_updates( self.unit_no_lessons, { 'title': self.unit_no_lessons.title, 'now_available': self.unit_no_lessons.now_available, 'label_groups': [], 'pre_assessment': self.assessment_one.unit_id, 'post_assessment': self.assessment_two.unit_id, 'show_contents_on_one_page': False, 'manual_progress': False, 'description': None, 'unit_header': None, 'unit_footer': None, }, errors) self.assertEquals([], errors) self.assertEquals(self.unit_no_lessons.pre_assessment, self.assessment_one.unit_id) self.assertEquals(self.unit_no_lessons.post_assessment, self.assessment_two.unit_id) self.course.save() # Verify that the assessments are no longer available for choosing # on the other unit. schema = unit_rest_handler.get_annotations_dict( self.course, self.unit_one_lesson.unit_id) choices = self._get_selection_choices( schema, ['properties', 'pre_assessment', '_inputex']) self.assertEquals({'-- None --': -1}, choices) # Verify that they are available for choosing on the unit where # they are assigned. schema = unit_rest_handler.get_annotations_dict( self.course, self.unit_no_lessons.unit_id) choices = self._get_selection_choices( schema, ['properties', 'pre_assessment', '_inputex']) self.assertEquals({ '-- None --': -1, self.assessment_one.title: self.assessment_one.unit_id, self.assessment_two.title: self.assessment_two.unit_id}, choices) # Verify that attempting to set pre/post assessments that # are already in use fails. errors = [] unit_rest_handler.apply_updates( self.unit_one_lesson, { 'title': self.unit_one_lesson.title, 'now_available': self.unit_one_lesson.now_available, 'label_groups': [], 'pre_assessment': self.assessment_one.unit_id, 'post_assessment': self.assessment_two.unit_id, 'show_contents_on_one_page': False, 'manual_progress': False, 'description': None, 'unit_header': None, 'unit_footer': None, }, errors) self.assertEquals( ['Assessment "Assessment One" is already ' 'asssociated to unit "No Lessons"', 'Assessment "Assessment Two" is already ' 'asssociated to unit "No Lessons"'], errors) self.assertEquals(self.unit_one_lesson.pre_assessment, None) self.assertEquals(self.unit_one_lesson.post_assessment, None) self.course.save() # Verify that swapping the order of pre/post assessments on the # unit that already has them is fine. errors = [] unit_rest_handler.apply_updates( self.unit_no_lessons, { 'title': self.unit_no_lessons.title, 'now_available': self.unit_no_lessons.now_available, 'label_groups': [], 'pre_assessment': self.assessment_two.unit_id, 'post_assessment': self.assessment_one.unit_id, 'show_contents_on_one_page': False, 'manual_progress': False, 'description': None, 'unit_header': None, 'unit_footer': None, }, errors) self.assertEquals([], errors) self.assertEquals(self.unit_no_lessons.pre_assessment, self.assessment_two.unit_id) self.assertEquals(self.unit_no_lessons.post_assessment, self.assessment_one.unit_id) self.course.save() # Verify that using the same assessment as both pre and post fails. errors = [] unit_rest_handler.apply_updates( self.unit_no_lessons, { 'title': self.unit_no_lessons.title, 'now_available': self.unit_no_lessons.now_available, 'label_groups': [], 'pre_assessment': self.assessment_one.unit_id, 'post_assessment': self.assessment_one.unit_id, 'show_contents_on_one_page': False, 'manual_progress': False, 'description': None, 'unit_header': None, 'unit_footer': None, }, errors) self.assertEquals([ 'The same assessment cannot be used as both the pre ' 'and post assessment of a unit.'], errors) self.assertEquals(self.unit_no_lessons.pre_assessment, self.assessment_one.unit_id) self.assertEquals(self.unit_no_lessons.post_assessment, None) self.course.save() def test_admin_page_display_ordering(self): actions.login(ADMIN_EMAIL, is_admin=True) response = self.get(DASHBOARD_URL) # In order declared. self._assert_contains_in_order(response, [ 'No Lessons', 'One Lesson', 'Lesson One', 'Assessment One', 'Assessment Two', ]) # Assessments attached to 'No Lessons' unit self.unit_no_lessons.pre_assessment = self.assessment_one.unit_id self.unit_no_lessons.post_assessment = self.assessment_two.unit_id self.course.save() response = self.get(DASHBOARD_URL) self._assert_contains_in_order(response, [ 'No Lessons', 'Assessment One', 'Assessment Two', 'One Lesson', 'Lesson One', ]) # Assessments attached to 'One Lesson' unit self.unit_no_lessons.pre_assessment = None self.unit_no_lessons.post_assessment = None self.unit_one_lesson.pre_assessment = self.assessment_one.unit_id self.unit_one_lesson.post_assessment = self.assessment_two.unit_id self.course.save() response = self.get(DASHBOARD_URL) self._assert_contains_in_order(response, [ 'No Lessons', 'One Lesson', 'Assessment One', 'Lesson One', 'Assessment Two', ]) # One as pre-asssesment on one unit, one as post- on the other. self.unit_no_lessons.pre_assessment = None self.unit_no_lessons.post_assessment = self.assessment_two.unit_id self.unit_one_lesson.pre_assessment = self.assessment_one.unit_id self.unit_one_lesson.post_assessment = None self.course.save() response = self.get(DASHBOARD_URL) self._assert_contains_in_order(response, [ 'No Lessons', 'Assessment Two', 'One Lesson', 'Assessment One', 'Lesson One', ]) def test_delete_assessment_as_lesson(self): self.unit_no_lessons.pre_assessment = self.assessment_one.unit_id self.unit_no_lessons.post_assessment = self.assessment_two.unit_id self.course.save() self.course.delete_unit(self.assessment_one) self.course.delete_unit(self.assessment_two) self.course.save() actions.login(ADMIN_EMAIL, is_admin=True) response = self.get(DASHBOARD_URL) self.assertEquals(200, response.status_int) def test_assessments_with_tracks_not_settable_as_pre_post(self): self.assessment_one.labels = str(self.track_one_id) self.assessment_two.labels = str(self.track_one_id) self.course.save() unit_rest_handler = unit_lesson_editor.UnitRESTHandler() unit_rest_handler.app_context = self.course.app_context with common_utils.Namespace(NAMESPACE): errors = [] unit_rest_handler.apply_updates( self.unit_no_lessons, { 'title': self.unit_no_lessons.title, 'now_available': self.unit_no_lessons.now_available, 'label_groups': [], 'pre_assessment': self.assessment_one.unit_id, 'post_assessment': self.assessment_two.unit_id, 'show_contents_on_one_page': False, 'manual_progress': False, 'description': None, 'unit_header': None, 'unit_footer': None, }, errors) self.assertEquals([ 'Assessment "Assessment One" has track labels, so it ' 'cannot be used as a pre/post unit element', 'Assessment "Assessment Two" has track labels, so it ' 'cannot be used as a pre/post unit element'], errors) def _test_assessments_as_pre_post_labels(self, label_id, expected_errors): self.unit_no_lessons.pre_assessment = self.assessment_one.unit_id self.unit_no_lessons.post_assessment = self.assessment_two.unit_id self.course.save() assessment_rest_handler = unit_lesson_editor.AssessmentRESTHandler() assessment_rest_handler.app_context = self.course.app_context with common_utils.Namespace(NAMESPACE): errors = [] properties = assessment_rest_handler.unit_to_dict( self.assessment_one) properties['label_groups'] = [{ 'labels': [{ 'checked': True, 'id': label_id }] }] assessment_rest_handler.apply_updates(self.assessment_one, properties, errors) self.assertEquals(expected_errors, errors) def test_assessments_as_pre_post_cannot_have_tracks_added(self): self._test_assessments_as_pre_post_labels( self.track_one_id, ['Cannot set track labels on entities which are ' 'used within other units.']) def test_assessments_as_pre_post_can_have_general_labels_added(self): self._test_assessments_as_pre_post_labels(self.general_one_id, []) def test_suppress_next_prev_buttons(self): # Set up one-lesson unit w/ pre, post assessment. Set course # settings to suppress prev/next buttons only on assessments. actions.login(ADMIN_EMAIL) actions.update_course_config(COURSE_NAME, { 'unit': {'hide_assessment_navigation_buttons': True}}) actions.login(STUDENT_EMAIL) self.unit_one_lesson.pre_assessment = self.assessment_one.unit_id self.unit_one_lesson.post_assessment = self.assessment_two.unit_id self.course.save() # Verify we have suppressed prev/next/end buttons on pre-assessment. response = self._get_unit_page(self.unit_one_lesson) self.assertNotIn('Previous Page', response.body) self.assertNotIn('Next Page', response.body) self.assertNotIn(' End ', response.body) # Submit assessment. Verify confirmation page _does_ have prev/next. response = self._post_assessment(self.assessment_one.unit_id).follow() self.assertIn('Previous Page', response.body) self.assertIn('Next Page', response.body) # Click to lesson. Verify have prev/next. response = self._click_next_button(response) self.assertIn('Previous Page', response.body) self.assertIn('Next Page', response.body) # Verify we have suppressed prev/next/end buttons on post-assessment. response = self._click_next_button(response) self.assertNotIn('Previous Page', response.body) self.assertNotIn('Next Page', response.body) self.assertNotIn(' End ', response.body) # Submit post-assessment; verify we have prev/end buttons response = self._post_assessment(self.assessment_two.unit_id).follow() self.assertIn('Previous Page', response.body) self.assertNotIn('Next Page', response.body) self.assertIn(' End ', response.body)
Python
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for modules/usage_reporting/*""" __author__ = 'Mike Gainer (mgainer@google.com)' import collections import copy import os import time import urlparse from common import crypto from common import utils as common_utils from controllers import sites from models import courses from models import transforms from modules.usage_reporting import config from modules.usage_reporting import course_creation from modules.usage_reporting import enrollment from modules.usage_reporting import messaging from modules.usage_reporting import usage_reporting from tests.functional import actions from google.appengine.api import namespace_manager from google.appengine.api import urlfetch ADMIN_EMAIL = 'admin@foo.com' FAKE_COURSE_ID = 'CCCCCCCCCCCCCCCCCCCCC' FAKE_INSTALLATION_ID = 'IIIIIIIIIIIIIIIIIIII' FAKE_TIMESTAMP = 1234567890 class MockSender(messaging.Sender): _messages = [] @classmethod def send_message(cls, the_dict): cls._messages.append(the_dict) @classmethod def get_sent(cls): return copy.deepcopy(cls._messages) @classmethod def clear_sent(cls): del cls._messages[:] class MockMessage(messaging.Message): @classmethod def _get_random_course_id(cls, course): return FAKE_COURSE_ID @classmethod def _get_random_installation_id(cls): return FAKE_INSTALLATION_ID @classmethod def _get_time(cls): return FAKE_TIMESTAMP class UsageReportingTestBase(actions.TestBase): def setUp(self): super(UsageReportingTestBase, self).setUp() self.save_sender = messaging.Sender self.save_message = messaging.Message messaging.Sender = MockSender messaging.Message = MockMessage messaging.ENABLED_IN_DEV_FOR_TESTING = True actions.login(ADMIN_EMAIL, is_admin=True) def tearDown(self): MockSender.clear_sent() messaging.ENABLED_IN_DEV_FOR_TESTING = False messaging.Sender = self.save_sender messaging.Message = self.save_message sites.reset_courses() super(UsageReportingTestBase, self).tearDown() class ConfigTests(UsageReportingTestBase): def test_set_report_allowed(self): config.set_report_allowed(True) self.assertEquals(True, config.REPORT_ALLOWED.value) config.set_report_allowed(False) self.assertEquals(False, config.REPORT_ALLOWED.value) config.set_report_allowed(True) self.assertEquals(True, config.REPORT_ALLOWED.value) config.set_report_allowed(False) self.assertEquals(False, config.REPORT_ALLOWED.value) def test_on_change_report_allowed(self): config.set_report_allowed(True) config._on_change_report_allowed(config.REPORT_ALLOWED, False) config.set_report_allowed(False) config._on_change_report_allowed(config.REPORT_ALLOWED, True) expected = [{ messaging.Message._INSTALLATION: FAKE_INSTALLATION_ID, messaging.Message._TIMESTAMP: FAKE_TIMESTAMP, messaging.Message._VERSION: os.environ['GCB_PRODUCT_VERSION'], messaging.Message._METRIC: messaging.Message.METRIC_REPORT_ALLOWED, messaging.Message._VALUE: True, messaging.Message._SOURCE: messaging.Message.ADMIN_SOURCE, }, { messaging.Message._INSTALLATION: FAKE_INSTALLATION_ID, messaging.Message._TIMESTAMP: FAKE_TIMESTAMP, messaging.Message._VERSION: os.environ['GCB_PRODUCT_VERSION'], messaging.Message._METRIC: messaging.Message.METRIC_REPORT_ALLOWED, messaging.Message._VALUE: False, messaging.Message._SOURCE: messaging.Message.ADMIN_SOURCE, }] self.assertEquals(expected, MockSender.get_sent()) def test_admin_post_change_report_allowed(self): xsrf_token = crypto.XsrfTokenManager.create_xsrf_token( 'config_override') response = self.post( '/admin?action=config_override&name=%s' % config.REPORT_ALLOWED.name, {'xsrf_token': xsrf_token}) response = self.get('/rest/config/item?key=%s' % config.REPORT_ALLOWED.name) payload = { 'name': config.REPORT_ALLOWED.name, 'value': True, 'is_draft': False, } message = { 'key': config.REPORT_ALLOWED.name, 'payload': transforms.dumps(payload), 'xsrf_token': crypto.XsrfTokenManager.create_xsrf_token( 'config-property-put'), } response = self.put('/rest/config/item', {'request': transforms.dumps(message)}) self.assertEqual(200, response.status_int) payload = { 'name': config.REPORT_ALLOWED.name, 'value': False, 'is_draft': False, } message = { 'key': config.REPORT_ALLOWED.name, 'payload': transforms.dumps(payload), 'xsrf_token': crypto.XsrfTokenManager.create_xsrf_token( 'config-property-put'), } response = self.put('/rest/config/item', {'request': transforms.dumps(message)}) self.assertEqual(200, response.status_int) expected = [{ messaging.Message._INSTALLATION: FAKE_INSTALLATION_ID, messaging.Message._TIMESTAMP: FAKE_TIMESTAMP, messaging.Message._VERSION: os.environ['GCB_PRODUCT_VERSION'], messaging.Message._METRIC: messaging.Message.METRIC_REPORT_ALLOWED, messaging.Message._VALUE: True, messaging.Message._SOURCE: messaging.Message.ADMIN_SOURCE, }, { messaging.Message._INSTALLATION: FAKE_INSTALLATION_ID, messaging.Message._TIMESTAMP: FAKE_TIMESTAMP, messaging.Message._VERSION: os.environ['GCB_PRODUCT_VERSION'], messaging.Message._METRIC: messaging.Message.METRIC_REPORT_ALLOWED, messaging.Message._VALUE: False, messaging.Message._SOURCE: messaging.Message.ADMIN_SOURCE, }] self.assertEquals(expected, MockSender.get_sent()) class CourseCreationTests(UsageReportingTestBase): def test_welcome_page(self): with actions.OverriddenConfig(sites.GCB_COURSES_CONFIG.name, ''): response = self.get('/admin/welcome') self.assertEquals(200, response.status_int) self.assertIn('Explore Sample Course', response.body) self.assertIn('Create Empty Course', response.body) self.assertIn( 'I agree that Google may collect information about this', response.body) self.assertIn( 'name="%s"' % course_creation.USAGE_REPORTING_CONSENT_CHECKBOX_NAME, response.body) def test_welcome_page_checkbox_state(self): # Expect checkbox checked when no setting made dom = self.parse_html_string(self.get('/admin/welcome').body) checkbox = dom.find('.//input[@type="checkbox"]') self.assertEqual('checked', checkbox.attrib['checked']) # Expect checkbox unchecked when setting is False config.set_report_allowed(False) dom = self.parse_html_string(self.get('/admin/welcome').body) checkbox = dom.find('.//input[@type="checkbox"]') self.assertNotIn('checked', checkbox.attrib) # Expect checkbox checked when setting is True config.set_report_allowed(True) dom = self.parse_html_string(self.get('/admin/welcome').body) checkbox = dom.find('.//input[@type="checkbox"]') self.assertEqual('checked', checkbox.attrib['checked']) def test_submit_welcome_with_accept_checkbox_checked(self): xsrf_token = crypto.XsrfTokenManager.create_xsrf_token( 'add_first_course') response = self.post( '/admin/welcome', { 'action': 'add_first_course', 'xsrf_token': xsrf_token, course_creation.USAGE_REPORTING_CONSENT_CHECKBOX_NAME: course_creation.USAGE_REPORTING_CONSENT_CHECKBOX_VALUE, }) self.assertEquals(True, config.REPORT_ALLOWED.value) expected = [{ messaging.Message._INSTALLATION: FAKE_INSTALLATION_ID, messaging.Message._TIMESTAMP: FAKE_TIMESTAMP, messaging.Message._VERSION: os.environ['GCB_PRODUCT_VERSION'], messaging.Message._METRIC: messaging.Message.METRIC_REPORT_ALLOWED, messaging.Message._VALUE: True, messaging.Message._SOURCE: messaging.Message.WELCOME_SOURCE, }] self.assertEquals(expected, MockSender.get_sent()) def test_submit_welcome_with_accept_checkbox_unchecked(self): xsrf_token = crypto.XsrfTokenManager.create_xsrf_token( 'add_first_course') response = self.post( '/admin/welcome', { 'action': 'add_first_course', 'xsrf_token': xsrf_token, course_creation.USAGE_REPORTING_CONSENT_CHECKBOX_NAME: '', }) self.assertEquals(False, config.REPORT_ALLOWED.value) expected = [{ messaging.Message._INSTALLATION: FAKE_INSTALLATION_ID, messaging.Message._TIMESTAMP: FAKE_TIMESTAMP, messaging.Message._VERSION: os.environ['GCB_PRODUCT_VERSION'], messaging.Message._METRIC: messaging.Message.METRIC_REPORT_ALLOWED, messaging.Message._VALUE: False, messaging.Message._SOURCE: messaging.Message.WELCOME_SOURCE, }] self.assertEquals(expected, MockSender.get_sent()) class EnrollmentTests(UsageReportingTestBase): def test_unexpected_field_raises(self): with self.assertRaises(ValueError): enrollment.StudentEnrollmentEventDTO(None, {'bad_field': 'x'}) def test_enrollment_map_reduce_job(self): self.maxDiff = None MOCK_NOW = 1427247511 COURSE = 'xyzzy' NAMESPACE = 'ns_xyzzy' MIN_TIMESTAMP = ( MOCK_NOW - (MOCK_NOW % enrollment.SECONDS_PER_HOUR) - enrollment.StudentEnrollmentEventCounter.MAX_AGE) # Insert some bogus StudentEnrollmentEventEntity for the M/R job # to count or delete. very_old_enroll = enrollment.StudentEnrollmentEventDTO(None, {}) very_old_enroll.timestamp = 0 very_old_enroll.metric = messaging.Message.METRIC_ENROLLED very_old_unenroll = enrollment.StudentEnrollmentEventDTO(None, {}) very_old_unenroll.timestamp = 0 very_old_unenroll.metric = messaging.Message.METRIC_UNENROLLED just_too_old_enroll = enrollment.StudentEnrollmentEventDTO(None, {}) just_too_old_enroll.timestamp = MIN_TIMESTAMP - 1 just_too_old_enroll.metric = messaging.Message.METRIC_ENROLLED just_too_old_unenroll = enrollment.StudentEnrollmentEventDTO(None, {}) just_too_old_unenroll.timestamp = MIN_TIMESTAMP - 1 just_too_old_unenroll.metric = messaging.Message.METRIC_UNENROLLED young_enough_enroll = enrollment.StudentEnrollmentEventDTO(None, {}) young_enough_enroll.timestamp = MIN_TIMESTAMP young_enough_enroll.metric = messaging.Message.METRIC_ENROLLED young_enough_unenroll = enrollment.StudentEnrollmentEventDTO(None, {}) young_enough_unenroll.timestamp = MIN_TIMESTAMP young_enough_unenroll.metric = messaging.Message.METRIC_UNENROLLED now_enroll = enrollment.StudentEnrollmentEventDTO(None, {}) now_enroll.timestamp = MOCK_NOW now_enroll.metric = messaging.Message.METRIC_ENROLLED now_unenroll = enrollment.StudentEnrollmentEventDTO(None, {}) now_unenroll.timestamp = MOCK_NOW now_unenroll.metric = messaging.Message.METRIC_UNENROLLED dtos = [ very_old_enroll, very_old_unenroll, just_too_old_enroll, just_too_old_unenroll, young_enough_enroll, young_enough_unenroll, now_enroll, now_unenroll, ] app_context = actions.simple_add_course(COURSE, ADMIN_EMAIL, 'Test') with common_utils.Namespace(NAMESPACE): enrollment.StudentEnrollmentEventDAO.save_all(dtos) # Run map/reduce job with a setup function replaced so that it will # always choose the same timestamp as the start time. job_class = enrollment.StudentEnrollmentEventCounter save_b_a_m_p = job_class.build_additional_mapper_params try: def fixed_time_b_a_m_p(self, app_context): return {self.MIN_TIMESTAMP: MIN_TIMESTAMP} job_class.build_additional_mapper_params = fixed_time_b_a_m_p # Actually run the job. enrollment.StudentEnrollmentEventCounter(app_context).submit() self.execute_all_deferred_tasks() finally: job_class.build_additional_mapper_params = save_b_a_m_p # Verify that the DTOs older than the cutoff have been removed from # the datastore. with common_utils.Namespace(NAMESPACE): dtos = enrollment.StudentEnrollmentEventDAO.get_all() dtos.sort(key=lambda dto: (dto.timestamp, dto.metric)) self.assertEqual( [young_enough_enroll.dict, young_enough_unenroll.dict, now_enroll.dict, now_unenroll.dict], [d.dict for d in dtos]) # Verify that we have messages for the new-enough items, and no # messages for the older items. messages = MockSender.get_sent() messages.sort(key=lambda m: (m['timestamp'], m['metric'])) MOCK_NOW_HOUR = MOCK_NOW - (MOCK_NOW % enrollment.SECONDS_PER_HOUR) expected = [{ messaging.Message._INSTALLATION: FAKE_INSTALLATION_ID, messaging.Message._COURSE: FAKE_COURSE_ID, messaging.Message._TIMESTAMP: MIN_TIMESTAMP, messaging.Message._VERSION: os.environ['GCB_PRODUCT_VERSION'], messaging.Message._METRIC: messaging.Message.METRIC_ENROLLED, messaging.Message._VALUE: 1, }, { messaging.Message._INSTALLATION: FAKE_INSTALLATION_ID, messaging.Message._COURSE: FAKE_COURSE_ID, messaging.Message._TIMESTAMP: MIN_TIMESTAMP, messaging.Message._VERSION: os.environ['GCB_PRODUCT_VERSION'], messaging.Message._METRIC: messaging.Message.METRIC_UNENROLLED, messaging.Message._VALUE: 1, }, { messaging.Message._INSTALLATION: FAKE_INSTALLATION_ID, messaging.Message._COURSE: FAKE_COURSE_ID, messaging.Message._TIMESTAMP: MOCK_NOW_HOUR, messaging.Message._VERSION: os.environ['GCB_PRODUCT_VERSION'], messaging.Message._METRIC: messaging.Message.METRIC_ENROLLED, messaging.Message._VALUE: 1, }, { messaging.Message._INSTALLATION: FAKE_INSTALLATION_ID, messaging.Message._COURSE: FAKE_COURSE_ID, messaging.Message._TIMESTAMP: MOCK_NOW_HOUR, messaging.Message._VERSION: os.environ['GCB_PRODUCT_VERSION'], messaging.Message._METRIC: messaging.Message.METRIC_UNENROLLED, messaging.Message._VALUE: 1, }] self.assertEquals(expected, messages) sites.reset_courses() def test_end_to_end(self): """Actually enroll and unenroll students; verify reporting counts.""" COURSE_NAME_BASE = 'test' NUM_COURSES = 2 NUM_STUDENTS = 3 THE_TIMESTAMP = 1427245200 for course_num in range(NUM_COURSES): course_name = '%s_%d' % (COURSE_NAME_BASE, course_num) actions.simple_add_course(course_name, ADMIN_EMAIL, course_name) actions.update_course_config( course_name, { 'course': { 'now_available': True, 'browsable': True, }, }) for student_num in range(NUM_STUDENTS): name = '%s_%d_%d' % (COURSE_NAME_BASE, course_num, student_num) actions.login(name + '@foo.com') actions.register(self, name, course_name) if student_num == 0: actions.unregister(self, course_name) actions.logout() # Expect no messages yet; haven't run job. self.assertEquals([], MockSender.get_sent()) # Run all counting jobs. usage_reporting.StartReportingJobs._submit_jobs() self.execute_all_deferred_tasks() # Verify counts. (Ignore dates, these are fickle and subject to # weirdness on hour boundaries. Also ignore course/instance IDs; # they are non-random and thus all the same.) num_enrolled_msgs = 0 num_unenrolled_msgs = 0 num_student_count_msgs = 0 for message in MockSender.get_sent(): if (message[messaging.Message._METRIC] == messaging.Message.METRIC_STUDENT_COUNT): num_student_count_msgs += 1 self.assertEquals( NUM_STUDENTS, message[messaging.Message._VALUE]) elif (message[messaging.Message._METRIC] == messaging.Message.METRIC_ENROLLED): num_enrolled_msgs += 1 self.assertEquals( NUM_STUDENTS, message[messaging.Message._VALUE]) elif (message[messaging.Message._METRIC] == messaging.Message.METRIC_UNENROLLED): num_unenrolled_msgs += 1 self.assertEquals( 1, message[messaging.Message._VALUE]) self.assertEquals(NUM_COURSES, num_enrolled_msgs) self.assertEquals(NUM_COURSES, num_unenrolled_msgs) self.assertEquals(NUM_COURSES, num_student_count_msgs) sites.reset_courses() class UsageReportingTests(UsageReportingTestBase): def test_disallowed(self): config.set_report_allowed(False) response = self.get(usage_reporting.StartReportingJobs.URL) self.assertEquals(200, response.status_int) self.assertEquals('Disabled.', response.body) def test_not_from_cron(self): config.set_report_allowed(True) response = self.get(usage_reporting.StartReportingJobs.URL, expect_errors=True) self.assertEquals(403, response.status_int) self.assertEquals('Forbidden.', response.body) def test_jobs_run(self): COURSE = 'test' app_context = actions.simple_add_course(COURSE, ADMIN_EMAIL, 'Test') actions.register(self, 'Joe Admin', COURSE) config.set_report_allowed(True) response = self.get(usage_reporting.StartReportingJobs.URL, headers={'X-AppEngine-Cron': 'True'}) self.assertEquals(200, response.status_int) self.assertEquals('OK.', response.body) now = int(time.time()) self.execute_all_deferred_tasks() expected = [{ messaging.Message._INSTALLATION: FAKE_INSTALLATION_ID, messaging.Message._COURSE: FAKE_COURSE_ID, messaging.Message._TIMESTAMP: FAKE_TIMESTAMP, messaging.Message._VERSION: os.environ['GCB_PRODUCT_VERSION'], messaging.Message._METRIC: messaging.Message.METRIC_STUDENT_COUNT, messaging.Message._VALUE: 1, }, { messaging.Message._INSTALLATION: FAKE_INSTALLATION_ID, messaging.Message._COURSE: FAKE_COURSE_ID, messaging.Message._TIMESTAMP: now - (now % 3600), messaging.Message._VERSION: os.environ['GCB_PRODUCT_VERSION'], messaging.Message._METRIC: messaging.Message.METRIC_ENROLLED, messaging.Message._VALUE: 1, }] actual = MockSender.get_sent() actual.sort(key=lambda x: x['timestamp']) self.assertEquals(expected, actual) sites.reset_courses() class MessageCatcher(object): URL = 'https://docs.google.com/a/google.com/forms/d/<IDNUMBER>/formResponse' FORM_FIELD = 'entry.12345' DEFAULT_CONFIG = transforms.dumps({ messaging.Sender._REPORT_ENABLED: True, messaging.Sender._REPORT_TARGET: URL, messaging.Sender._REPORT_FORM_FIELD: FORM_FIELD, }) _config = DEFAULT_CONFIG _return_code = 200 _messages = [] Response = collections.namedtuple('Response', ['status_code', 'content']) @classmethod def get(cls): return cls.Response(cls._return_code, cls._config) @classmethod def post(cls, request): if cls._return_code == 200: # Pretend to not have seen the message if reporting a failure. message = transforms.loads(request.get(cls.FORM_FIELD)[0]) cls._messages.append(message) return cls.Response(cls._return_code, '') @classmethod def get_sent(cls): return copy.deepcopy(cls._messages) @classmethod def clear_sent(cls): del cls._messages[:] @classmethod def set_return_code(cls, return_code): cls._return_code = return_code @classmethod def set_config(cls, cfg): cls._config = cfg class MessagingTests(actions.TestBase): COURSE_NAME = 'test' NAMESPACE = 'ns_test' # Object to emulate response from urlfetch.fetch for our mock. Response = collections.namedtuple('Response', ('status_code', 'content')) def mock_urlfetch_fetch(self, url, method=None, payload=None, follow_redirects=None): """Override of urlfetch.fetch method; forwards to self.get/post.""" if not url.startswith('https://'): raise urlfetch.Error('Malformed URL') if method == 'GET': return MessageCatcher.get() elif method == 'POST': return MessageCatcher.post(urlparse.parse_qs(payload)) def setUp(self): super(MessagingTests, self).setUp() messaging.ENABLED_IN_DEV_FOR_TESTING = True self.save_urlfetch_fetch = urlfetch.fetch urlfetch.fetch = self.mock_urlfetch_fetch actions.login(ADMIN_EMAIL, is_admin=True) self.app_config = actions.simple_add_course( self.COURSE_NAME, ADMIN_EMAIL, self.COURSE_NAME) def tearDown(self): messaging.ENABLED_IN_DEV_FOR_TESTING = False messaging.Sender._report_settings_timestamp = 0 urlfetch.fetch = self.save_urlfetch_fetch MessageCatcher.clear_sent() MessageCatcher.set_return_code(200) MessageCatcher.set_config(MessageCatcher.DEFAULT_CONFIG) sites.reset_courses() super(MessagingTests, self).tearDown() def test_blue_sky_instance_message(self): messaging.Message.send_instance_message( messaging.Message.METRIC_REPORT_ALLOWED, True) messages = MessageCatcher.get_sent() self.assertEquals(1, len(messages)) message = messages[0] self.assertEquals(messaging.Message.METRIC_REPORT_ALLOWED, message[messaging.Message._METRIC]) self.assertEquals(True, message[messaging.Message._VALUE]) self.assertAlmostEqual(int(time.time()), message[messaging.Message._TIMESTAMP], delta=10) self.assertEquals(os.environ['GCB_PRODUCT_VERSION'], message[messaging.Message._VERSION]) self.assertNotEquals(0, len(message[messaging.Message._INSTALLATION])) self.assertNotIn(messaging.Message._COURSE, message) def test_blue_sky_course_message(self): student_count = 1453 with common_utils.Namespace(self.NAMESPACE): messaging.Message.send_course_message( messaging.Message.METRIC_STUDENT_COUNT, student_count) messages = MessageCatcher.get_sent() self.assertEquals(1, len(messages)) message = messages[0] self.assertEquals(messaging.Message.METRIC_STUDENT_COUNT, message[messaging.Message._METRIC]) self.assertEquals(student_count, message[messaging.Message._VALUE]) self.assertAlmostEqual(int(time.time()), message[messaging.Message._TIMESTAMP], delta=10) self.assertEquals(os.environ['GCB_PRODUCT_VERSION'], message[messaging.Message._VERSION]) self.assertNotEquals(0, len(message[messaging.Message._INSTALLATION])) self.assertNotEquals(0, len(message[messaging.Message._COURSE])) def test_random_ids_are_consistent(self): num_messages = 10 student_count = 123 with common_utils.Namespace(self.NAMESPACE): for unused in range(num_messages): messaging.Message.send_course_message( messaging.Message.METRIC_STUDENT_COUNT, student_count) messages = MessageCatcher.get_sent() self.assertEquals(num_messages, len(messages)) for message in messages: self.assertEquals( messages[0][messaging.Message._INSTALLATION], message[messaging.Message._INSTALLATION]) self.assertEquals( messages[0][messaging.Message._COURSE], message[messaging.Message._COURSE]) def test_report_disabled_by_config(self): MessageCatcher.set_config( transforms.dumps({ messaging.Sender._REPORT_ENABLED: False, messaging.Sender._REPORT_TARGET: 'irrelevant', messaging.Sender._REPORT_FORM_FIELD: 'irrelevant', })) messaging.Message.send_instance_message( messaging.Message.METRIC_REPORT_ALLOWED, True) # Should have no messages sent, and nothing queued. messages = MessageCatcher.get_sent() self.assertEquals(0, len(messages)) tasks = self.taskq.GetTasks('default') self.assertEquals(0, len(tasks)) def _assert_message_queued_and_succeeds(self): # Should have no messages sent, and one item queued. messages = MessageCatcher.get_sent() self.assertEquals(0, len(messages)) # Now execute background tasks; expect one message. self.execute_all_deferred_tasks() messages = MessageCatcher.get_sent() self.assertEquals(1, len(messages)) message = messages[0] self.assertEquals(messaging.Message.METRIC_REPORT_ALLOWED, message[messaging.Message._METRIC]) self.assertEquals(True, message[messaging.Message._VALUE]) self.assertAlmostEqual(int(time.time()), message[messaging.Message._TIMESTAMP], delta=10) self.assertEquals(os.environ['GCB_PRODUCT_VERSION'], message[messaging.Message._VERSION]) self.assertNotEquals(0, len(message[messaging.Message._INSTALLATION])) self.assertNotIn(messaging.Message._COURSE, message) def test_report_queued_when_config_malformed(self): MessageCatcher.set_config( 'this will not properly decode as JSON') messaging.Message.send_instance_message( messaging.Message.METRIC_REPORT_ALLOWED, True) MessageCatcher.set_config(MessageCatcher.DEFAULT_CONFIG) self._assert_message_queued_and_succeeds() def test_report_queued_when_config_unavailable(self): MessageCatcher.set_return_code(500) messaging.Message.send_instance_message( messaging.Message.METRIC_REPORT_ALLOWED, True) MessageCatcher.set_return_code(200) self._assert_message_queued_and_succeeds() def test_report_queued_when_config_url_malformed(self): MessageCatcher.set_config( transforms.dumps({ messaging.Sender._REPORT_ENABLED: True, messaging.Sender._REPORT_TARGET: 'a malformed url', messaging.Sender._REPORT_FORM_FIELD: 'entry.12345', })) messaging.Message.send_instance_message( messaging.Message.METRIC_REPORT_ALLOWED, True) MessageCatcher.set_config(MessageCatcher.DEFAULT_CONFIG) self._assert_message_queued_and_succeeds() def test_report_queued_when_post_receives_non_200(self): # Send one message through cleanly; this will get the messaging # module to retain its notion of the destination URL and not re-get # it on the next message. messaging.Message.send_instance_message( messaging.Message.METRIC_REPORT_ALLOWED, True) MessageCatcher.clear_sent() # Set reponse code so that the POST fails; verify that that retries # using the deferred task queue. MessageCatcher.set_return_code(500) messaging.Message.send_instance_message( messaging.Message.METRIC_REPORT_ALLOWED, True) MessageCatcher.set_return_code(200) self._assert_message_queued_and_succeeds() class ConsentBannerTests(UsageReportingTestBase): COURSE_NAME = 'test_course' SUPER_MESSAGE = 'Would you like to help improve Course Builder?' NOT_SUPER_MESSAGE = 'Please ask your Course Builder Administrator' NOT_SUPER_EMAIL = 'not-super@test.com' def setUp(self): super(ConsentBannerTests, self).setUp() self.base = '/' + self.COURSE_NAME self.app_context = actions.simple_add_course( self.COURSE_NAME, ADMIN_EMAIL, 'Banner Test Course') self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME) courses.Course.ENVIRON_TEST_OVERRIDES = { 'course': {'admin_user_emails': self.NOT_SUPER_EMAIL}} def tearDown(self): del sites.Registry.test_overrides[sites.GCB_COURSES_CONFIG.name] namespace_manager.set_namespace(self.old_namespace) courses.Course.ENVIRON_TEST_OVERRIDES = {} super(ConsentBannerTests, self).tearDown() def test_banner_with_buttons_shown_to_super_user_on_dashboard(self): dom = self.parse_html_string(self.get('dashboard').body) banner = dom.find('.//div[@class="consent-banner"]') self.assertIsNotNone(banner) self.assertIn(self.SUPER_MESSAGE, banner.find('.//h1').text) self.assertEqual(2, len(banner.findall('.//button'))) def test_banner_with_buttons_shown_to_super_user_on_global_admin(self): dom = self.parse_html_string(self.get('/admin/global').body) banner = dom.find('.//div[@class="consent-banner"]') self.assertIsNotNone(banner) self.assertIn(self.SUPER_MESSAGE, banner.find('.//h1').text) self.assertEqual(2, len(banner.findall('.//button'))) def test_banner_without_buttons_shown_to_instructor_on_dashboard(self): actions.logout() actions.login(self.NOT_SUPER_EMAIL, is_admin=False) dom = self.parse_html_string(self.get('dashboard').body) banner = dom.find('.//div[@class="consent-banner"]') self.assertIsNotNone(banner) self.assertIn(self.NOT_SUPER_MESSAGE, banner.findall('.//p')[1].text) self.assertEqual(0, len(banner.findall('.//button'))) def test_banner_not_shown_when_choices_have_been_made(self): config.set_report_allowed(False) # Check super-user role; global admin dom = self.parse_html_string(self.get('/admin/global').body) self.assertIsNone(dom.find('.//div[@class="consent-banner"]')) # check super-user role; dashboard dom = self.parse_html_string(self.get('dashboard').body) self.assertIsNone(dom.find('.//div[@class="consent-banner"]')) # Check non-super role; dashboadd actions.logout() actions.login(self.NOT_SUPER_EMAIL, is_admin=False) dom = self.parse_html_string(self.get('dashboard').body) self.assertIsNone(dom.find('.//div[@class="consent-banner"]')) class ConsentBannerRestHandlerTests(UsageReportingTestBase): URL = '/rest/modules/usage_reporting/consent' XSRF_TOKEN = 'usage_reporting_consent_banner' def do_post(self, xsrf_token, is_allowed): request = { 'xsrf_token': xsrf_token, 'payload': transforms.dumps({'is_allowed': is_allowed}) } return self.post(self.URL, {'request': transforms.dumps(request)}) def test_handler_rejects_bad_xsrf_token(self): response = self.do_post('bad_xsrf_token', False) self.assertEqual(200, response.status_int) response_dict = transforms.loads(response.body) self.assertEqual(403, response_dict['status']) self.assertIn('Bad XSRF token.', response_dict['message']) def test_handler_rejects_non_super_user(self): actions.logout() xsrf_token = crypto.XsrfTokenManager.create_xsrf_token(self.XSRF_TOKEN) response = self.do_post(xsrf_token, False) self.assertEqual(200, response.status_int) response_dict = transforms.loads(response.body) self.assertEqual(401, response_dict['status']) self.assertIn('Access denied.', response_dict['message']) def test_handler_sets_consent_and_sends_message(self): self.assertFalse(config.is_consent_set()) xsrf_token = crypto.XsrfTokenManager.create_xsrf_token(self.XSRF_TOKEN) response = self.do_post(xsrf_token, True) self.assertTrue(config.is_consent_set()) self.assertTrue(config.REPORT_ALLOWED.value) response = self.do_post(xsrf_token, False) self.assertFalse(config.REPORT_ALLOWED.value) expected = [{ messaging.Message._INSTALLATION: FAKE_INSTALLATION_ID, messaging.Message._TIMESTAMP: FAKE_TIMESTAMP, messaging.Message._VERSION: os.environ['GCB_PRODUCT_VERSION'], messaging.Message._METRIC: messaging.Message.METRIC_REPORT_ALLOWED, messaging.Message._VALUE: True, messaging.Message._SOURCE: messaging.Message.BANNER_SOURCE, }, { messaging.Message._INSTALLATION: FAKE_INSTALLATION_ID, messaging.Message._TIMESTAMP: FAKE_TIMESTAMP, messaging.Message._VERSION: os.environ['GCB_PRODUCT_VERSION'], messaging.Message._METRIC: messaging.Message.METRIC_REPORT_ALLOWED, messaging.Message._VALUE: False, messaging.Message._SOURCE: messaging.Message.BANNER_SOURCE, }] self.assertEquals(expected, MockSender.get_sent()) class DevServerTests(UsageReportingTestBase): """Test that consent widgets are turned off in normal dev mode.""" def test_welcome_page_message_not_shown_in_dev(self): # First check the text is present in test mode response = self.get('/admin/welcome') self.assertIn( 'I agree that Google may collect information about this', response.body) # Switch off test mode messaging.ENABLED_IN_DEV_FOR_TESTING = False # Expect text is missing response = self.get('/admin/welcome') self.assertNotIn( 'I agree that Google may collect information about this', response.body) def test_consent_banner_not_shown_in_dev(self): # First check banner is present in test mode dom = self.parse_html_string(self.get('/admin/global').body) banner = dom.find('.//div[@class="consent-banner"]') self.assertIsNotNone(banner) # Switch off test mode messaging.ENABLED_IN_DEV_FOR_TESTING = False # Expect to see banner missing dom = self.parse_html_string(self.get('/admin/global').body) banner = dom.find('.//div[@class="consent-banner"]') self.assertIsNone(banner)
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the rating widget.""" __author__ = 'John Orr (jorr@google.com)' import urllib from controllers import utils from common import crypto from models import courses from models import models from models import transforms from models.data_sources import utils as data_sources_utils from modules.rating import rating from tests.functional import actions from google.appengine.api import namespace_manager from google.appengine.api import users ADMIN_EMAIL = 'admin@foo.com' COURSE_NAME = 'rating_course' SENDER_EMAIL = 'sender@foo.com' STUDENT_EMAIL = 'student@foo.com' STUDENT_NAME = 'A. Student' RATINGS_DISABLED = {'unit': {'ratings_module': {'enabled': False}}} RATINGS_ENABLED = {'unit': {'ratings_module': {'enabled': True}}} class BaseRatingsTests(actions.TestBase): def setUp(self): super(BaseRatingsTests, self).setUp() self.base = '/' + COURSE_NAME context = actions.simple_add_course( COURSE_NAME, ADMIN_EMAIL, 'Ratings Course') self.course = courses.Course(None, context) self.unit = self.course.add_unit() self.unit.now_available = True self.lesson = self.course.add_lesson(self.unit) self.lesson.objectives = 'Some lesson content' self.lesson.now_available = True self.course.save() self.key = '/%s/unit?unit=%s&lesson=%s' % ( COURSE_NAME, self.unit.unit_id, self.lesson.lesson_id) self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % COURSE_NAME) def tearDown(self): namespace_manager.set_namespace(self.old_namespace) super(BaseRatingsTests, self).tearDown() def register_student(self): actions.login(STUDENT_EMAIL, is_admin=False) actions.register(self, STUDENT_NAME) def get_lesson_dom(self): response = self.get('unit?unit=%s&lesson=%s' % ( self.unit.unit_id, self.lesson.lesson_id)) self.assertEquals(200, response.status_int) return self.parse_html_string(response.body) class ExtraContentProvideTests(BaseRatingsTests): def test_returns_none_when_ratings_disabled_in_course_settings(self): with actions.OverriddenEnvironment(RATINGS_DISABLED): self.register_student() dom = self.get_lesson_dom() self.assertFalse(dom.find('.//div[@class="gcb-ratings-widget"]')) def test_returns_none_when_no_user_in_session(self): with actions.OverriddenEnvironment(RATINGS_ENABLED): dom = self.get_lesson_dom() self.assertFalse(dom.find('.//div[@class="gcb-ratings-widget"]')) def test_returns_none_when_user_not_registered(self): with actions.OverriddenEnvironment(RATINGS_ENABLED): actions.login(STUDENT_EMAIL, is_admin=False) dom = self.get_lesson_dom() self.assertFalse(dom.find('.//div[@class="gcb-ratings-widget"]')) def test_widget_html(self): with actions.OverriddenEnvironment(RATINGS_ENABLED): self.register_student() dom = self.get_lesson_dom() self.assertTrue(dom.find('.//div[@class="gcb-ratings-widget"]')) class RatingHandlerTests(BaseRatingsTests): def setUp(self): super(RatingHandlerTests, self).setUp() courses.Course.ENVIRON_TEST_OVERRIDES = RATINGS_ENABLED def tearDown(self): courses.Course.ENVIRON_TEST_OVERRIDES = {} super(RatingHandlerTests, self).tearDown() def get_data(self, key=None, xsrf_token=None): if key is None: key = self.key if xsrf_token is None: xsrf_token = utils.XsrfTokenManager.create_xsrf_token('rating') request = { 'xsrf_token': xsrf_token, 'payload': transforms.dumps({'key': key}) } return transforms.loads( self.get('rest/modules/rating?%s' % urllib.urlencode( {'request': transforms.dumps(request)})).body) def post_data( self, key=None, rating_int=None, additional_comments=None, xsrf_token=None): if key is None: key = self.key if xsrf_token is None: xsrf_token = utils.XsrfTokenManager.create_xsrf_token('rating') request = { 'xsrf_token': xsrf_token, 'payload': transforms.dumps({ 'key': key, 'rating': rating_int, 'additional_comments': additional_comments}) } return transforms.loads(self.post( 'rest/modules/rating?%s', {'request': transforms.dumps(request)}).body) def test_get_requires_ratings_enabled(self): courses.Course.ENVIRON_TEST_OVERRIDES = RATINGS_DISABLED self.register_student() response = self.get_data() self.assertEquals(401, response['status']) self.assertIn('Access denied', response['message']) def test_get_requires_valid_xsrf_token(self): response = self.get_data(xsrf_token='bad-xsrf-key') self.assertEquals(403, response['status']) self.assertIn('Bad XSRF token', response['message']) def test_get_requires_user_in_session(self): response = self.get_data() self.assertEquals(401, response['status']) self.assertIn('Access denied', response['message']) def test_get_requires_registered_student(self): actions.login(STUDENT_EMAIL, is_admin=False) response = self.get_data() self.assertEquals(401, response['status']) self.assertIn('Access denied', response['message']) def test_get_returns_null_for_no_existing_rating(self): self.register_student() response = self.get_data() self.assertEquals(200, response['status']) payload = transforms.loads(response['payload']) self.assertIsNone(payload['rating']) def test_get_returns_existing_rating(self): self.register_student() student = models.Student.get_enrolled_student_by_email(STUDENT_EMAIL) prop = rating.StudentRatingProperty.load_or_create(student) prop.set_rating(self.key, 3) prop.put() response = self.get_data() self.assertEquals(200, response['status']) payload = transforms.loads(response['payload']) self.assertEquals(3, payload['rating']) def test_post_requires_ratings_enabled(self): courses.Course.ENVIRON_TEST_OVERRIDES = RATINGS_DISABLED self.register_student() response = self.post_data(rating_int=2) self.assertEquals(401, response['status']) self.assertIn('Access denied', response['message']) def test_post_requires_valid_xsrf_token(self): response = self.post_data(rating_int=3, xsrf_token='bad-xsrf=token') self.assertEquals(403, response['status']) self.assertIn('Bad XSRF token', response['message']) def test_post_requires_user_in_session(self): response = self.post_data(rating_int=3) self.assertEquals(401, response['status']) self.assertIn('Access denied', response['message']) def test_post_requires_registered_student(self): actions.login(STUDENT_EMAIL, is_admin=False) response = self.post_data(rating_int=3) self.assertEquals(401, response['status']) self.assertIn('Access denied', response['message']) def test_post_records_rating_in_property(self): self.register_student() response = self.post_data(rating_int=2) self.assertEquals(200, response['status']) self.assertIn('Thank you for your feedback', response['message']) student = models.Student.get_enrolled_student_by_email(STUDENT_EMAIL) prop = rating.StudentRatingProperty.load_or_create(student) self.assertEquals(2, prop.get_rating(self.key)) def test_post_records_rating_and_comment_in_event(self): self.register_student() response = self.post_data( rating_int=2, additional_comments='Good lesson') self.assertEquals(200, response['status']) self.assertIn('Thank you for your feedback', response['message']) event_list = rating.StudentRatingEvent.all().fetch(100) self.assertEquals(1, len(event_list)) event = event_list[0] event_data = transforms.loads(event.data) self.assertEquals('rating-event', event.source) self.assertEquals(users.get_current_user().user_id(), event.user_id) self.assertEquals(2, event_data['rating']) self.assertEquals('Good lesson', event_data['additional_comments']) self.assertEquals(self.key, event_data['key']) def test_for_export_scrubs_extraneous_data(self): def transform_fn(s): return s.upper() event = rating.StudentRatingEvent() event.source = 'rating-event' event.user_id = 'a_user' event.data = transforms.dumps({ 'key': self.key, 'rating': 1, 'additional_comments': 'Good lesson', 'bizarre_unforeseen_extra_field': 'odd...' }) event.put() event = event.for_export(transform_fn) self.assertEquals('rating-event', event.source) self.assertEquals('A_USER', event.user_id) self.assertEquals( { 'key': self.key, 'rating': 1, 'additional_comments': 'Good lesson'}, transforms.loads(event.data)) def test_data_source(self): # Register a student and give some feedback self.register_student() student = models.Student.get_enrolled_student_by_email(STUDENT_EMAIL) response = self.post_data( rating_int=2, additional_comments='Good lesson') self.assertEquals(200, response['status']) self.assertIn('Thank you for your feedback', response['message']) # Log in as admin for the data query actions.logout() actions.login(ADMIN_EMAIL, is_admin=True) xsrf_token = crypto.XsrfTokenManager.create_xsrf_token( data_sources_utils.DATA_SOURCE_ACCESS_XSRF_ACTION) pii_secret = crypto.generate_transform_secret_from_xsrf_token( xsrf_token, data_sources_utils.DATA_SOURCE_ACCESS_XSRF_ACTION) safe_user_id = crypto.hmac_sha_2_256_transform( pii_secret, student.user_id) response = self.get( 'rest/data/rating_events/items?' 'data_source_token=%s&page_number=0' % xsrf_token) data = transforms.loads(response.body)['data'] self.assertEqual(1, len(data)) record = data[0] self.assertEqual(7, len(record)) self.assertEqual(safe_user_id, record['user_id']) self.assertEqual('2', record['rating']) self.assertEqual('Good lesson', record['additional_comments']) self.assertEqual( '/rating_course/unit?unit=%s&lesson=%s' % ( self.unit.unit_id, self.lesson.lesson_id), record['content_url']) self.assertEqual(str(self.unit.unit_id), record['unit_id']) self.assertEqual(str(self.lesson.lesson_id), record['lesson_id']) self.assertIn('recorded_on', record) def test_data_source_is_exportable(self): self.assertTrue(rating.RatingEventDataSource.exportable())
Python
# -*- coding: utf-8 -*- # Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests related to content translation to multiple languages.""" __author__ = 'Pavel Simakov (psimakov@google.com)' import json import os import yaml import appengine_config from common import schema_fields from common import xcontent from models import courses from modules.dashboard.question_editor import McQuestionRESTHandler from tests.functional import actions COURSE_NAME = 'i18n_tests' NAMESPACE = 'ns_%s' % COURSE_NAME COURSE_TITLE = 'I18N Tests' ADMIN_EMAIL = 'admin@foo.com' BASE_URL = '/' + COURSE_NAME STUDENT_EMAIL = 'foo@foo.com' FIELD_FILTER = schema_fields.FieldFilter( type_names=['string', 'html', 'url'], hidden_values=[False], i18n_values=[None, True], editable_values=[True]) def _filter(binding): """Filter out translatable strings.""" return FIELD_FILTER.filter_value_to_type_binding(binding) class I18NCourseSettingsTests(actions.TestBase): """Tests for various course settings transformations I18N relies upon.""" def _build_mapping(self, translations=None, errors=None): """Build mapping of course.yaml properties to their translations.""" if translations is None: translations = {} binding = schema_fields.ValueToTypeBinding.bind_entity_to_schema( self.course_yaml, self.schema) desired = _filter(binding) mappings = xcontent.SourceToTargetDiffMapping.map_source_to_target( binding, existing_mappings=translations, allowed_names=desired, errors=errors) if errors: self.assertEqual(len(mappings) + len(errors), len(desired)) else: self.assertEqual(len(mappings), len(desired)) for mapping in mappings: self.assertTrue(mapping.name in desired) return binding, mappings def setUp(self): super(I18NCourseSettingsTests, self).setUp() context = actions.simple_add_course( COURSE_NAME, ADMIN_EMAIL, COURSE_TITLE) self.course = courses.Course(None, context) course_yaml = os.path.join(appengine_config.BUNDLE_ROOT, 'course.yaml') self.schema = courses.Course.create_settings_schema(self.course) self.schema.add_property(schema_fields.SchemaField( 'test:i18n_test', 'Test Text', 'url', i18n=True)) course_yaml_text = open(course_yaml).read() course_yaml_text = '%s\ntest:i18n_test: \'Test!\'' % course_yaml_text self.course_yaml = yaml.safe_load(course_yaml_text) def tearDown(self): super(I18NCourseSettingsTests, self).tearDown() def test_course_yaml_schema_binding(self): binding = schema_fields.ValueToTypeBinding.bind_entity_to_schema( self.course_yaml, self.schema) expected_unmapped = [ 'html_hooks:preview:after_main_content_ends', 'html_hooks:preview:after_top_content_ends', 'html_hooks:unit:after_content_begins', 'html_hooks:unit:after_leftnav_begins', 'html_hooks:unit:before_content_ends', 'html_hooks:unit:before_leftnav_ends', 'reg_form:whitelist', ] self.assertEqual(expected_unmapped, sorted(binding.unmapped_names)) self.assertEqual(len(binding.name_to_field), len(binding.name_to_value)) value = binding.find_value('test:i18n_test') self.assertTrue(value.field.i18n) self.assertEqual('url', value.field.type) self.assertEqual('Test!', value.value) self.assertEqual(binding.name_to_field['test:i18n_test'], value.field) value = binding.find_value('course:title') self.assertTrue(value.field.i18n is None) self.assertEqual('string', value.field.type) self.assertEqual('Power Searching with Google', value.value) self.assertEqual(binding.name_to_field['course:title'], value.field) forum_url_field = binding.find_field('course:forum_url') self.assertEquals('string', forum_url_field.type) blurb_field = binding.find_field('course:blurb') self.assertEquals('html', blurb_field.type) now_avail_field = binding.find_field('course:now_available') self.assertEquals('boolean', now_avail_field.type) def test_extract_translatable_fields(self): binding = schema_fields.ValueToTypeBinding.bind_entity_to_schema( self.course_yaml, self.schema) value_names_to_translate = _filter(binding) self.assertTrue('course:locale' in binding.name_to_value) self.assertFalse('course:locale' in value_names_to_translate) self.assertTrue('course:title' in binding.name_to_value) self.assertTrue('course:title' in value_names_to_translate) def test_translate_never_before_translated(self): _, mappings = self._build_mapping() for mapping in mappings: self.assertEqual( mapping.verb, xcontent.SourceToTargetDiffMapping.VERB_NEW) self.assertEqual(mapping.target_value, None) def test_translations_must_have_same_type(self): translation = xcontent.SourceToTargetMapping( 'course:title', 'Title', 'unknown_type', 'Power Searching with Google', 'POWER SEARCHING WITH Google') errors = [] binding, _ = self._build_mapping( translations=[translation], errors=errors) error_at_index = None for index, value_field in enumerate(binding.value_list): if 'course:title' == value_field.name: error_at_index = index break self.assertTrue(error_at_index is not None) self.assertEqual(error_at_index, errors[0].index) self.assertEqual( 'Source and target types don\'t match: ' 'string, unknown_type.', errors[0].original_exception.message) def test_retranslate_already_translated_verb_same(self): translation = xcontent.SourceToTargetMapping( 'course:title', 'Title', 'string', 'Power Searching with Google', 'POWER SEARCHING WITH Google',) translations = [translation] _, mappings = self._build_mapping(translations) mapping = xcontent.SourceToTargetMapping.find_mapping( mappings, 'course:title') self.assertEqual( mapping.verb, xcontent.SourceToTargetDiffMapping.VERB_CURRENT) self.assertEqual('Power Searching with Google', mapping.source_value) self.assertEqual('POWER SEARCHING WITH Google', mapping.target_value) mapping = xcontent.SourceToTargetMapping.find_mapping( mappings, 'course:forum_url') self.assertEqual( mapping.verb, xcontent.SourceToTargetDiffMapping.VERB_NEW) self.assertEqual(None, mapping.target_value) mapping = xcontent.SourceToTargetMapping.find_mapping( mappings, 'course:locale') self.assertEqual(None, mapping) def test_retranslate_already_translated_verb_changed(self): translation = xcontent.SourceToTargetMapping( 'course:title', 'Title', 'string', 'Power Searching with Google (old)', 'POWER SEARCHING WITH Google (old)') translations = [translation] _, mappings = self._build_mapping(translations) mapping = xcontent.SourceToTargetMapping.find_mapping( mappings, 'course:title') self.assertEqual( mapping.verb, xcontent.SourceToTargetDiffMapping.VERB_CHANGED) self.assertEqual('Power Searching with Google', mapping.source_value) self.assertEqual( 'POWER SEARCHING WITH Google (old)', mapping.target_value) def test_schema_with_array_element_type(self): self.course_yaml['course']['extra_tabs'] = [ { 'label': 'FAQ', 'position': 'left', 'visibility': 'student', 'url': '', 'content': 'Frequently asked questions'}, { 'label': 'Resources', 'position': 'right', 'visibility': 'student', 'url': '', 'content': 'Links to resources'}] binding = schema_fields.ValueToTypeBinding.bind_entity_to_schema( self.course_yaml, self.schema) expected_names = [ ('course:extra_tabs', None), ('course:extra_tabs:[0]:label', 'FAQ'), ('course:extra_tabs:[0]:position', 'left'), ('course:extra_tabs:[0]:visibility', 'student'), ('course:extra_tabs:[0]:url', ''), ('course:extra_tabs:[0]:content', 'Frequently asked questions'), ('course:extra_tabs:[1]:label', 'Resources'), ('course:extra_tabs:[1]:position', 'right'), ('course:extra_tabs:[1]:visibility', 'student'), ('course:extra_tabs:[1]:url', ''), ('course:extra_tabs:[1]:content', 'Links to resources')] for name, value in expected_names: self.assertIn(name, binding.name_to_field.keys()) if value is not None: self.assertEquals(value, binding.name_to_value[name].value) class I18NMultipleChoiceQuestionTests(actions.TestBase): """Tests for multiple choice object transformations I18N relies upon.""" def setUp(self): super(I18NMultipleChoiceQuestionTests, self).setUp() self.schema = McQuestionRESTHandler.get_schema() self.question = json.loads("""{ "description": "sky", "multiple_selections": false, "question": "What color is the sky?", "choices": [ {"text": "red", "score": 0.0, "feedback": "Wrong!"}, {"text": "blue", "score": 1.0, "feedback": "Correct!"}, {"text": "green", "score": 0.0, "feedback": "Close..."}], "version": "1.5", "type": 0} """) def test_schema_with_array_element_type(self): binding = schema_fields.ValueToTypeBinding.bind_entity_to_schema( self.question, self.schema) expected_names = [ 'choices', 'choices:[0]:feedback', 'choices:[0]:score', 'choices:[0]:text', 'choices:[1]:feedback', 'choices:[1]:score', 'choices:[1]:text', 'choices:[2]:feedback', 'choices:[2]:score', 'choices:[2]:text', 'description', 'multiple_selections', 'question', 'version'] self.assertEquals( expected_names, sorted(binding.name_to_field.keys())) self.assertEquals( expected_names, sorted(binding.name_to_value.keys())) self.assertEquals(set(['type']), binding.unmapped_names) field = binding.find_field('choices') self.assertEqual('array', field.type) value = binding.find_value('choices') self.assertEqual(3, len(value.value)) field = binding.find_field('choices:[0]:feedback') self.assertEqual('html', field.type) field = binding.find_field('choices:[0]:text') self.assertEqual('html', field.type) field = binding.find_field('choices:[0]:score') self.assertEqual('string', field.type) value = binding.find_value('choices:[1]:feedback') self.assertEqual('Correct!', value.value) value = binding.find_value('choices:[1]:text') self.assertEqual('blue', value.value) value = binding.find_value('choices:[1]:score') self.assertEqual(1.0, value.value) def test_translate_never_before_translated(self): binding = schema_fields.ValueToTypeBinding.bind_entity_to_schema( self.question, self.schema) desired = _filter(binding) expected_desired = [ 'choices:[0]:feedback', 'choices:[0]:text', 'choices:[1]:feedback', 'choices:[1]:text', 'choices:[2]:feedback', 'choices:[2]:text', 'description', 'question'] self.assertEqual(expected_desired, sorted(desired)) mappings = xcontent.SourceToTargetDiffMapping.map_source_to_target( binding, allowed_names=desired) expected_source_values = [ 'sky', 'What color is the sky?', 'red', 'Wrong!', 'blue', 'Correct!', 'green', 'Close...'] self.assertEqual( expected_source_values, [mapping.source_value for mapping in mappings]) def test_retranslate_already_translated_verb_same(self): binding = schema_fields.ValueToTypeBinding.bind_entity_to_schema( self.question, self.schema) desired = _filter(binding) translation = xcontent.SourceToTargetMapping( 'choices:[1]:feedback', 'Feedback', 'html', 'Correct!', 'CORRECT!') mappings = xcontent.SourceToTargetDiffMapping.map_source_to_target( binding, existing_mappings=[translation], allowed_names=desired) expected_mappings = [ (None, xcontent.SourceToTargetDiffMapping.VERB_NEW), (None, xcontent.SourceToTargetDiffMapping.VERB_NEW), (None, xcontent.SourceToTargetDiffMapping.VERB_NEW), (None, xcontent.SourceToTargetDiffMapping.VERB_NEW), (None, xcontent.SourceToTargetDiffMapping.VERB_NEW), ('CORRECT!', xcontent.SourceToTargetDiffMapping.VERB_CURRENT), (None, xcontent.SourceToTargetDiffMapping.VERB_NEW), (None, xcontent.SourceToTargetDiffMapping.VERB_NEW)] self.assertEqual( expected_mappings, [(mapping.target_value, mapping.verb) for mapping in mappings]) mapping = xcontent.SourceToTargetMapping.find_mapping( mappings, 'choices:[1]:feedback') self.assertEqual( mapping.verb, xcontent.SourceToTargetDiffMapping.VERB_CURRENT) self.assertEqual('Correct!', mapping.source_value) self.assertEqual('CORRECT!', translation.target_value) def test_retranslate_already_translated_verb_changed(self): binding = schema_fields.ValueToTypeBinding.bind_entity_to_schema( self.question, self.schema) desired = _filter(binding) translation = xcontent.SourceToTargetMapping( 'choices:[1]:feedback', 'Feedback', 'html', 'Correct (old)!', 'CORRECT (old)!') mappings = xcontent.SourceToTargetDiffMapping.map_source_to_target( binding, existing_mappings=[translation], allowed_names=desired) mapping = xcontent.SourceToTargetMapping.find_mapping( mappings, 'choices:[1]:feedback') self.assertEqual( mapping.verb, xcontent.SourceToTargetDiffMapping.VERB_CHANGED) self.assertEqual('Correct!', mapping.source_value) self.assertEqual('CORRECT (old)!', mapping.target_value) def test_retranslate_already_translated_with_list_reordered(self): binding = schema_fields.ValueToTypeBinding.bind_entity_to_schema( self.question, self.schema) desired = _filter(binding) translation = xcontent.SourceToTargetMapping( 'choices:[0]:feedback', 'Feedback', 'html', 'Correct (old)!', 'CORRECT!') mappings = xcontent.SourceToTargetDiffMapping.map_source_to_target( binding, existing_mappings=[translation], allowed_names=desired) mapping = xcontent.SourceToTargetMapping.find_mapping( mappings, 'choices:[0]:feedback') self.assertEqual( mapping.verb, xcontent.SourceToTargetDiffMapping.VERB_CHANGED) self.assertEqual('Wrong!', mapping.source_value) self.assertEqual('CORRECT!', mapping.target_value) def test_retranslate_already_translated_with_list_reordered_matched(self): binding = schema_fields.ValueToTypeBinding.bind_entity_to_schema( self.question, self.schema) desired = _filter(binding) translation = xcontent.SourceToTargetMapping( 'choices:[0]:feedback', 'Feedback', 'html', 'Correct (old)!', 'CORRECT!') try: mappings = xcontent.SourceToTargetDiffMapping.map_source_to_target( binding, existing_mappings=[translation], allowed_names=desired, allow_list_reorder=True) mapping = xcontent.SourceToTargetMapping.find_mapping( mappings, 'choices:[0]:feedback') self.assertEqual( mapping.verb, xcontent.SourceToTargetDiffMapping.VERB_CHANGED) self.assertEqual('Correct!', mapping.source_value) self.assertEqual('CORRECT!', mapping.target_value) raise Exception('Must have failed.') # TODO(psimakov): fix allow_list_reorder=True to stop this failure except NotImplementedError: pass
Python
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the skill mapping module.""" __author__ = 'John Orr (jorr@google.com)' import cgi import json import cStringIO import StringIO import time import urllib import zipfile from babel.messages import pofile from networkx import DiGraph from xml.etree import cElementTree from common import crypto from common import resource from controllers import sites from models import courses from models import jobs from models import models from models import transforms from models.progress import UnitLessonCompletionTracker from modules.i18n_dashboard import i18n_dashboard from modules.skill_map.skill_map import CountSkillCompletion from modules.skill_map.skill_map import LESSON_SKILL_LIST_KEY from modules.skill_map.skill_map import ResourceSkill from modules.skill_map.skill_map import Skill from modules.skill_map.skill_map import SkillAggregateRestHandler from modules.skill_map.skill_map import SkillGraph from modules.skill_map.skill_map import SkillMap from modules.skill_map.skill_map import SkillRestHandler from modules.skill_map.skill_map import SkillCompletionAggregate from modules.skill_map.skill_map import _SkillDao from modules.skill_map.skill_map import SkillCompletionTracker from modules.skill_map.skill_map_metrics import SkillMapMetrics from modules.skill_map.skill_map_metrics import CHAINS_MIN_LENGTH from tests.functional import actions from google.appengine.api import namespace_manager ADMIN_EMAIL = 'admin@foo.com' COURSE_NAME = 'skill_map_course' SKILL_NAME = 'rock climbing' SKILL_DESC = 'Knows how to climb rocks' SKILL_NAME_2 = 'ice skating' SKILL_DESC_2 = 'Knows how to ice skate' SKILL_NAME_3 = 'skiing' SKILL_DESC_3 = 'Knows how to ski' class BaseSkillMapTests(actions.TestBase): def setUp(self): super(BaseSkillMapTests, self).setUp() self.base = '/' + COURSE_NAME self.app_context = actions.simple_add_course( COURSE_NAME, ADMIN_EMAIL, 'Skills Map Course') self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % COURSE_NAME) self.course = courses.Course(None, self.app_context) def tearDown(self): del sites.Registry.test_overrides[sites.GCB_COURSES_CONFIG.name] namespace_manager.set_namespace(self.old_namespace) super(BaseSkillMapTests, self).tearDown() def _build_sample_graph(self): # a # \ # d # / # b # c--e--f self.skill_graph = SkillGraph.load() self.sa = self.skill_graph.add(Skill.build('a', '')) self.sb = self.skill_graph.add(Skill.build('b', '')) self.sd = self.skill_graph.add(Skill.build('d', '')) self.skill_graph.add_prerequisite(self.sd.id, self.sa.id) self.skill_graph.add_prerequisite(self.sd.id, self.sb.id) self.sc = self.skill_graph.add(Skill.build('c', '')) self.se = self.skill_graph.add(Skill.build('e', '')) self.skill_graph.add_prerequisite(self.se.id, self.sc.id) self.sf = self.skill_graph.add(Skill.build('f', '')) self.skill_graph.add_prerequisite(self.sf.id, self.se.id) def _create_lessons(self): """Creates 3 lessons for unit 1.""" self.unit = self.course.add_unit() self.unit.title = 'Test Unit' self.lesson1 = self.course.add_lesson(self.unit) self.lesson1.title = 'Test Lesson 1' self.lesson2 = self.course.add_lesson(self.unit) self.lesson2.title = 'Test Lesson 2' self.lesson3 = self.course.add_lesson(self.unit) self.lesson3.title = 'Test Lesson 3' class SkillGraphTests(BaseSkillMapTests): def test_add_skill(self): # Skill map is initially empty skill_graph = SkillGraph.load() self.assertEqual(0, len(skill_graph.skills)) # Add a single skill skill = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) self.assertEqual(1, len(skill_graph.skills)) # Retrieve the skill by id self.assertEqual(SKILL_NAME, skill.name) self.assertEqual(SKILL_DESC, skill.description) def test_add_skill_twice_is_rejected(self): skill_graph = SkillGraph.load() # Add a single skill skill = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) self.assertEqual(1, len(skill_graph.skills)) # Retrieve the skill by id and add it again with self.assertRaises(AssertionError): skill_graph.add(skill) def test_delete_skill(self): # Skill map is initially empty skill_graph = SkillGraph.load() self.assertEqual(0, len(skill_graph.skills)) # Add a single skill skill = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) self.assertEqual(1, len(skill_graph.skills)) # Delete the skill and expect empty skill_graph.delete(skill.id) self.assertEqual(0, len(skill_graph.skills)) def test_delete_skill_with_successors(self): skill_graph = SkillGraph.load() skill_1 = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) skill_2 = skill_graph.add(Skill.build(SKILL_NAME_2, SKILL_DESC_2)) # Skill 1 is a prerequisite for Skill 2 skill_graph.add_prerequisite(skill_2.id, skill_1.id) skill_graph.delete(skill_1.id) self.assertEqual(1, len(skill_graph.skills)) self.assertEqual(skill_2, skill_graph.skills[0]) self.assertEqual(0, len(skill_graph.prerequisites(skill_2.id))) def test_add_prerequisite(self): skill_graph = SkillGraph.load() skill_1 = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) skill_2 = skill_graph.add(Skill.build(SKILL_NAME_2, SKILL_DESC_2)) # Skill 1 is a prerequisite for Skill 2 skill_graph.add_prerequisite(skill_2.id, skill_1.id) skill_graph = SkillGraph.load() self.assertEqual(1, len(skill_graph.prerequisites(skill_2.id))) self.assertEqual( skill_1.id, skill_graph.prerequisites(skill_2.id)[0].id) self.assertEqual(1, len(skill_graph.successors(skill_1.id))) self.assertEqual( skill_2.id, skill_graph.successors(skill_1.id)[0].id) def test_add_missing_prerequisites_rejected(self): skill_graph = SkillGraph.load() with self.assertRaises(AssertionError): skill_graph.add_prerequisite('missing', 'also missing') skill_1 = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) with self.assertRaises(AssertionError): skill_graph.add_prerequisite('missing', skill_1.id) with self.assertRaises(AssertionError): skill_graph.add_prerequisite(skill_1.id, 'also missing') def test_add_loop_rejected(self): """Test that cannot add a skill with a length-1 cycle.""" skill_graph = SkillGraph.load() skill_1 = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) with self.assertRaises(AssertionError): skill_graph.add_prerequisite(skill_1.id, skill_1.id) def test_add_duplicate_prerequisites_rejected(self): skill_graph = SkillGraph.load() skill_1 = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) skill_2 = skill_graph.add(Skill.build(SKILL_NAME_2, SKILL_DESC_2)) skill_graph.add_prerequisite(skill_2.id, skill_1.id) with self.assertRaises(AssertionError): skill_graph.add_prerequisite(skill_2.id, skill_1.id) def test_delete_prerequisite(self): skill_graph = SkillGraph.load() skill_1 = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) skill_2 = skill_graph.add(Skill.build(SKILL_NAME_2, SKILL_DESC_2)) skill_3 = skill_graph.add(Skill.build(SKILL_NAME_3, SKILL_DESC_3)) # Skills 1 and 2 are prerequisites for Skill 3 skill_graph.add_prerequisite(skill_3.id, skill_1.id) skill_graph.add_prerequisite(skill_3.id, skill_2.id) skill_graph = SkillGraph.load() self.assertEqual(2, len(skill_graph.prerequisites(skill_3.id))) # Delete skill 1 as a prerequisite and expect that only skill 2 is a # prerequisite now skill_graph.delete_prerequisite(skill_3.id, skill_1.id) self.assertEqual(1, len(skill_graph.prerequisites(skill_3.id))) self.assertEqual( skill_2.id, skill_graph.prerequisites(skill_3.id)[0].id) def test_delete_missing_prerequisites_rejected(self): skill_graph = SkillGraph.load() with self.assertRaises(AssertionError): skill_graph.delete_prerequisite('missing', 'also missing') skill_1 = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) skill_2 = skill_graph.add(Skill.build(SKILL_NAME_2, SKILL_DESC_2)) with self.assertRaises(AssertionError): skill_graph.delete_prerequisite('missing', skill_1.id) with self.assertRaises(AssertionError): skill_graph.delete_prerequisite(skill_1.id, 'also missing') # Also reject deletion of a prerequisite if the skill exists but is not # currently a prerequisite with self.assertRaises(AssertionError): skill_graph.delete_prerequisite(skill_1.id, skill_2.id) def test_multiple_successors(self): skill_graph = SkillGraph.load() skill_1 = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) skill_2 = skill_graph.add(Skill.build(SKILL_NAME_2, SKILL_DESC_2)) skill_3 = skill_graph.add(Skill.build(SKILL_NAME_3, SKILL_DESC_3)) # Skills 2 and 3 are successors of Skill 1 skill_graph.add_prerequisite(skill_2.id, skill_1.id) skill_graph.add_prerequisite(skill_3.id, skill_1.id) skill_graph = SkillGraph.load() successor_ids = {s.id for s in skill_graph.successors(skill_1.id)} self.assertEqual({skill_2.id, skill_3.id}, successor_ids) class SkillMapTests(BaseSkillMapTests): def setUp(self): super(SkillMapTests, self).setUp() self.unit = self.course.add_unit() self.unit.title = 'Test Unit' self.lesson1 = self.course.add_lesson(self.unit) self.lesson1.title = 'Test Lesson 1' self.lesson2 = self.course.add_lesson(self.unit) self.lesson2.title = 'Test Lesson 2' self.lesson3 = self.course.add_lesson(self.unit) self.lesson3.title = 'Test Lesson 3' self.course.save() def tearDown(self): self.course.clear_current() super(SkillMapTests, self).tearDown() def test_topo_sort(self): self._build_sample_graph() skill_map = SkillMap.load(self.course) self.assertEqual(6, len(skill_map.skills())) # verify topological co-sets expected = { 0: set([self.sa.id, self.sb.id, self.sc.id]), 1: set([self.se.id, self.sd.id]), 2: set([self.sf.id])} for ind, co_set in enumerate(skill_map._topo_sort()): self.assertEqual(expected[ind], co_set) # verify sorting skills by lesson expected = ['a', 'b', 'd', 'c', 'e', 'f'] self.assertEqual( expected, [s.name for s in skill_map.skills(sort_by='lesson')]) # verify sorting skills by name expected = ['a', 'b', 'c', 'd', 'e', 'f'] self.assertEqual( expected, [s.name for s in skill_map.skills(sort_by='name')]) # verify sorting skills by prerequisites expected = ['a', 'b', 'c', 'd', 'e', 'f'] actual = [s.name for s in skill_map.skills(sort_by='prerequisites')] self.assertEqual(expected, actual) def test_get_lessons_for_skill(self): skill_graph = SkillGraph.load() skill_1 = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) skill_2 = skill_graph.add(Skill.build(SKILL_NAME_2, SKILL_DESC_2)) # lesson 1 has one skill self.lesson1.properties[LESSON_SKILL_LIST_KEY] = [skill_1.id] # lesson 2 has no skills # lesson 3 has both skills self.lesson3.properties[LESSON_SKILL_LIST_KEY] = [ skill_1.id, skill_2.id] self.course.save() skill_map = SkillMap.load(self.course) lessons = skill_map.get_lessons_for_skill(skill_1) self.assertEqual(2, len(lessons)) self.assertEqual(self.lesson1.lesson_id, lessons[0].lesson_id) self.assertEqual(self.lesson3.lesson_id, lessons[1].lesson_id) lessons = skill_map.get_lessons_for_skill(skill_2) self.assertEqual(1, len(lessons)) self.assertEqual(self.lesson3.lesson_id, lessons[0].lesson_id) def test_get_lessons_returns_empty_list_when_no_skills_assigned(self): skill_graph = SkillGraph.load() skill = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) skill_map = SkillMap.load(self.course) # look up lessons by skill id lessons = skill_map.get_lessons_for_skill(skill) self.assertIsNotNone(lessons) self.assertEqual(0, len(lessons)) # look up lessons by skill lessons = skill_map.get_lessons_for_skill(skill) self.assertIsNotNone(lessons) self.assertEqual(0, len(lessons)) def test_skill_map_request_cache_invalidation(self): # verify that skill graph updates invalidate the cached skill map skill_graph = SkillGraph.load() skill_map_1 = SkillMap.load(self.course) skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) skill_map_2 = SkillMap.load(self.course) self.assertEqual(1, len(skill_map_2.skills())) self.assertNotEqual(skill_map_1, skill_map_2) # verify that the cached skill map is served # when there are no skill graph updates skill_map_3 = SkillMap.load(self.course) self.assertEqual(skill_map_2, skill_map_3) class LocationListRestHandlerTests(BaseSkillMapTests): URL = 'rest/modules/skill_map/location_list' def test_refuses_list_to_non_admin(self): response = self.get(self.URL) self.assertEqual(200, response.status_int) body = transforms.loads(response.body) self.assertEqual(401, body['status']) self.assertEqual('Access denied.', body['message']) def test_deleivers_list_of_all_locations(self): unit = self.course.add_unit() unit.title = 'Test Unit' lesson1 = self.course.add_lesson(unit) lesson1.title = 'Test Lesson 1' lesson2 = self.course.add_lesson(unit) lesson2.title = 'Test Lesson 2' self.course.save() actions.login(ADMIN_EMAIL) response = self.get(self.URL) self.assertEqual(200, response.status_int) body = transforms.loads(response.body) self.assertEqual(200, body['status']) payload = transforms.loads(body['payload']) location_list = payload['location_list'] expected_location_list = [ { 'edit_href': 'dashboard?action=edit_lesson&key=2', 'sort_key': [1, 2], 'label': '1.1', 'href': 'unit?unit=1&lesson=2', 'key': 'lesson:2', 'lesson': 'Test Lesson 1', 'unit': 'Test Unit' }, { 'edit_href': 'dashboard?action=edit_lesson&key=3', 'sort_key': [1, 3], 'label': '1.2', 'href': 'unit?unit=1&lesson=3', 'key': 'lesson:3', 'lesson': 'Test Lesson 2', 'unit': 'Test Unit'}] self.assertEqual(expected_location_list, location_list) class SkillRestHandlerTests(BaseSkillMapTests): URL = 'rest/modules/skill_map/skill' XSRF_TOKEN = 'skill-handler' def _put( self, version=None, name=None, description=None, prerequisite_ids=None, xsrf_token=None, key=None): payload = { 'version': version, 'name': name, 'description': description} if prerequisite_ids: payload['prerequisites'] = [ {'id': pid} for pid in prerequisite_ids] request_dict = { 'key': key, 'xsrf_token': xsrf_token, 'payload': transforms.dumps(payload)} response = self.put( self.URL, {'request': transforms.dumps(request_dict)}) return transforms.loads(response.body) def test_rejected_if_not_authorized(self): # Bad XSRF_TOKEN response = self._put( version='1', name=SKILL_NAME, description=SKILL_DESC, xsrf_token='BAD XSRF TOKEN') self.assertEqual(403, response['status']) # Not logged in xsrf_token = crypto.XsrfTokenManager.create_xsrf_token(self.XSRF_TOKEN) response = self._put( version='1', name=SKILL_NAME, description=SKILL_DESC, xsrf_token=xsrf_token) self.assertEqual(401, response['status']) # Not admin actions.login('not-an-admin@foo.com') xsrf_token = crypto.XsrfTokenManager.create_xsrf_token(self.XSRF_TOKEN) response = self._put( version='1', name=SKILL_NAME, description=SKILL_DESC, xsrf_token=xsrf_token) self.assertEqual(401, response['status']) def test_create_skill(self): skill_graph = SkillGraph.load() self.assertEqual(0, len(skill_graph.skills)) actions.login(ADMIN_EMAIL) xsrf_token = crypto.XsrfTokenManager.create_xsrf_token(self.XSRF_TOKEN) response = self._put( version='1', name=SKILL_NAME, description=SKILL_DESC, xsrf_token=xsrf_token) self.assertEqual(200, response['status']) self.assertEqual('Saved.', response['message']) payload = transforms.loads(response['payload']) key = payload['key'] skill_graph = SkillGraph.load() self.assertEqual(1, len(skill_graph.skills)) skill = skill_graph.get(key) self.assertEqual(key, skill.id) self.assertEqual(SKILL_NAME, skill.name) self.assertEqual(SKILL_DESC, skill.description) def test_create_skill_with_prerequisites(self): skill_graph = SkillGraph.load() src_skill = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) # add skill with one prerequisite actions.login(ADMIN_EMAIL) xsrf_token = crypto.XsrfTokenManager.create_xsrf_token(self.XSRF_TOKEN) response = self._put( version='1', name=SKILL_NAME_2, description=SKILL_DESC_2, prerequisite_ids=[src_skill.id], xsrf_token=xsrf_token) self.assertEqual(200, response['status']) self.assertEqual('Saved.', response['message']) payload = transforms.loads(response['payload']) tgt_key = payload['key'] skill_graph = SkillGraph.load() self.assertEqual(2, len(skill_graph.skills)) prerequisites = skill_graph.prerequisites(tgt_key) self.assertEqual(1, len(prerequisites)) self.assertEqual(src_skill.id, prerequisites[0].id) tgt_skill = payload['skill'] self.assertEqual(SKILL_NAME_2, tgt_skill['name']) self.assertEqual(tgt_skill['description'], SKILL_DESC_2) self.assertEqual([], tgt_skill['locations']) self.assertEqual(1, len(tgt_skill['prerequisite_ids'])) def test_(self): skill_graph = SkillGraph.load() src_skill = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) tgt_skill = skill_graph.add(Skill.build(SKILL_NAME_2, SKILL_DESC_2)) # update prerequisites actions.login(ADMIN_EMAIL) xsrf_token = crypto.XsrfTokenManager.create_xsrf_token(self.XSRF_TOKEN) response = self._put( version='1', name=SKILL_NAME_3, description=SKILL_DESC_3, prerequisite_ids=[src_skill.id], xsrf_token=xsrf_token, key=tgt_skill.id) self.assertEqual(200, response['status']) self.assertEqual('Saved.', response['message']) payload = transforms.loads(response['payload']) tgt_key = payload['key'] skill_graph = SkillGraph.load() tgt_skill = skill_graph.get(tgt_key) self.assertEqual(2, len(skill_graph.skills)) prerequisites = skill_graph.prerequisites(tgt_key) self.assertEqual(1, len(prerequisites)) self.assertEqual(src_skill.id, prerequisites[0].id) self.assertEqual(tgt_skill.name, SKILL_NAME_3) self.assertEqual(tgt_skill.description, SKILL_DESC_3) def test_reject_update_with_duplicate_prerequisites(self): skill_graph = SkillGraph.load() src_skill = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) tgt_skill = skill_graph.add(Skill.build(SKILL_NAME_2, SKILL_DESC_2)) actions.login(ADMIN_EMAIL) xsrf_token = crypto.XsrfTokenManager.create_xsrf_token(self.XSRF_TOKEN) response = self._put( version='1', name=SKILL_NAME_3, description=SKILL_DESC_3, prerequisite_ids=[src_skill.id, src_skill.id], xsrf_token=xsrf_token, key=tgt_skill.id) self.assertEqual(412, response['status']) self.assertEqual('Prerequisites must be unique', response['message']) def test_reject_update_prerequisites_with_self_loop(self): skill_graph = SkillGraph.load() skill = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) actions.login(ADMIN_EMAIL) xsrf_token = crypto.XsrfTokenManager.create_xsrf_token(self.XSRF_TOKEN) response = self._put( version='1', name=skill.name, description=skill.description, prerequisite_ids=[skill.id], xsrf_token=xsrf_token, key=skill.id) self.assertEqual(412, response['status']) self.assertEqual( 'A skill cannot be its own prerequisite', response['message']) skill_graph = SkillGraph.load() skill = skill_graph.get(skill.id) self.assertEqual(set(), skill.prerequisite_ids) def test_get_skill(self): skill_graph = SkillGraph.load() skill_1 = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) actions.login(ADMIN_EMAIL) get_url = '%s?%s' % (self.URL, urllib.urlencode({'key': skill_1.id})) response = transforms.loads(self.get(get_url).body) self.assertEqual(200, response['status']) skill = transforms.loads(response['payload'])['skill'] self.assertEqual(skill_1.id, skill['id']) self.assertEqual(skill_1.name, skill['name']) self.assertEqual(skill_1.description, skill['description']) def test_get_skill_list(self): skill_graph = SkillGraph.load() assert skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) assert skill_graph.add(Skill.build(SKILL_NAME_2, SKILL_DESC_2)) assert skill_graph.add(Skill.build(SKILL_NAME_3, SKILL_DESC_3)) actions.login(ADMIN_EMAIL) response = transforms.loads(self.get(self.URL).body) self.assertEqual(200, response['status']) self.assertIn('xsrf_token', response) skill_list = transforms.loads(response['payload'])['skill_list'] self.assertEqual(3, len(skill_list)) # check that every skill has the following properties keys = ['id', 'name', 'description', 'prerequisite_ids', 'locations', 'sort_key', 'topo_sort_key'] for skill in skill_list: self.assertItemsEqual(keys, skill.keys()) # check that skills are sorted in lexicographic order skill_names = sorted([SKILL_NAME, SKILL_NAME_2, SKILL_NAME_3]) self.assertEqual(skill_names, [x['name'] for x in skill_list]) def test_get_skills_multiple_locations(self): """The skills are mapped to more than one lesson.""" skill_graph = SkillGraph.load() skill_1 = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) unit = self.course.add_unit() unit.title = 'Test Unit' lesson1 = self.course.add_lesson(unit) lesson1.title = 'Test Lesson 1' lesson2 = self.course.add_lesson(unit) lesson2.title = 'Test Lesson 2' self.course.save() lesson1.properties[LESSON_SKILL_LIST_KEY] = [skill_1.id] lesson2.properties[LESSON_SKILL_LIST_KEY] = [skill_1.id] self.course.save() actions.login(ADMIN_EMAIL) response = transforms.loads(self.get(self.URL).body) self.assertEqual(200, response['status']) skill_list = transforms.loads(response['payload'])['skill_list'] self.assertEqual(1, len(skill_list)) # All locations listed self.assertEqual(2, len(skill_list[0]['locations'])) def test_delete_skill(self): skill_graph = SkillGraph.load() skill = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) actions.login(ADMIN_EMAIL) xsrf_token = crypto.XsrfTokenManager.create_xsrf_token(self.XSRF_TOKEN) delete_url = '%s?%s' % ( self.URL, urllib.urlencode({ 'key': skill.id, 'xsrf_token': cgi.escape(xsrf_token) })) response = self.delete(delete_url) self.assertEquals(200, response.status_int) def test_delete_skill_with_lesson(self): # add a unit and a lesson to the course unit = self.course.add_unit() unit.title = 'Test Unit' lesson = self.course.add_lesson(unit) lesson.title = 'Test Lesson' self.course.save() # add one skill to the lesson skill_graph = SkillGraph.load() skill = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) lesson.properties[LESSON_SKILL_LIST_KEY] = [skill.id] self.course.update_lesson(lesson) self.course.save() skill_map = SkillMap.load(self.course) lessons = skill_map.get_lessons_for_skill(skill) self.assertEqual(1, len(lessons)) self.assertEqual('Test Lesson', lessons[0].title) actions.login(ADMIN_EMAIL) xsrf_token = crypto.XsrfTokenManager.create_xsrf_token(self.XSRF_TOKEN) delete_url = '%s?%s' % ( self.URL, urllib.urlencode({ 'key': skill.id, 'xsrf_token': cgi.escape(xsrf_token) })) response = self.delete(delete_url) self.assertEquals(200, response.status_int) course = courses.Course(None, self.course.app_context) skill_map = SkillMap.load(course) lessons = skill_map.get_lessons_for_skill(skill) self.assertEqual([], lessons) def test_delete_prerequisites(self): skill_graph = SkillGraph.load() src_skill = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) tgt_skill = skill_graph.add(Skill.build(SKILL_NAME_2, SKILL_DESC_2)) skill_graph.add_prerequisite(tgt_skill.id, src_skill.id) skill_graph = SkillGraph.load() self.assertEqual(1, len(skill_graph.prerequisites(tgt_skill.id))) # delete prerequisite actions.login(ADMIN_EMAIL) xsrf_token = crypto.XsrfTokenManager.create_xsrf_token(self.XSRF_TOKEN) response = self._put( version='1', name=tgt_skill.name, description=tgt_skill.description, prerequisite_ids=[], xsrf_token=xsrf_token, key=tgt_skill.id) self.assertEqual(200, response['status']) self.assertEqual('Saved.', response['message']) skill_graph = SkillGraph.load() prerequisites = skill_graph.prerequisites(tgt_skill.id) self.assertEqual(0, len(prerequisites)) class SkillMapHandlerTests(actions.TestBase): ADMIN_EMAIL = 'admin@foo.com' COURSE_NAME = 'skill_map_course' DASHBOARD_SKILL_MAP_URL = 'dashboard?action=skill_map' SKILL_MAP_URL = 'modules/skill_map?action=skill_map&tab=skills_table' GRAPH_URL = 'modules/skill_map?action=skill_map&tab=dependency_graph' def setUp(self): super(SkillMapHandlerTests, self).setUp() self.base = '/' + self.COURSE_NAME context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'Skill Map Course') self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME) self.course = courses.Course(None, context) self.unit = self.course.add_unit() self.unit.title = 'Unit 1' self.lesson = self.course.add_lesson(self.unit) self.lesson.title = 'Lesson 1' self.course.save() actions.login(self.ADMIN_EMAIL, is_admin=True) def tearDown(self): del sites.Registry.test_overrides[sites.GCB_COURSES_CONFIG.name] namespace_manager.set_namespace(self.old_namespace) super(SkillMapHandlerTests, self).tearDown() def test_redirect_to_skill_map_handler(self): response = self.get(self.DASHBOARD_SKILL_MAP_URL) self.assertEqual(302, response.status_int) response = self.get(response.location) self.assertEqual(200, response.status_int) def test_rejected_if_not_authorized(self): actions.login('student@foo.com') response = self.get(self.SKILL_MAP_URL) self.assertEqual(302, response.status_int) def test_dependency_graph_tab(self): response = self.get(self.GRAPH_URL) self.assertEqual(200, response.status_int) dom = self.parse_html_string(response.body) assert dom.find('.//div[@class="graph"]') def test_dependency_graph(self): skill_graph = SkillGraph.load() src_skill = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC)) tgt_skill = skill_graph.add(Skill.build( SKILL_NAME_2, SKILL_DESC_2, prerequisite_ids=[{'id': src_skill.id}])) response = self.get(self.GRAPH_URL) self.assertEqual(200, response.status_int) dom = self.parse_html_string(response.body) graph_div = dom.find('.//div[@class="graph"]') assert graph_div nodes = json.loads(graph_div.get('data-nodes')) self.assertEqual(2, len(nodes)) links = json.loads(graph_div.get('data-links')) self.assertEqual(1, len(links)) link = links[0] # The link points from the node to its prerequisite # because d3 dependo library follows the discrete math convention # for arrow direction if nodes[0]['id'] == tgt_skill.name: self.assertEqual(1, link['source']) self.assertEqual(0, link['target']) elif nodes[0]['id'] == src_skill.name: self.assertEqual(0, link['source']) self.assertEqual(1, link['target']) else: raise Exception('Unexpected skill name.') class StudentSkillViewWidgetTests(BaseSkillMapTests): def setUp(self): super(StudentSkillViewWidgetTests, self).setUp() actions.login(ADMIN_EMAIL) self.unit = self.course.add_unit() self.unit.title = 'Test Unit' self.unit.now_available = True self.lesson = self.course.add_lesson(self.unit) self.lesson.title = 'Test Lesson' self.lesson.now_available = True self.course.save() def _getWidget(self): url = 'unit?unit=%(unit)s&lesson=%(lesson)s' % { 'unit': self.unit.unit_id, 'lesson': self.lesson.lesson_id} dom = self.parse_html_string(self.get(url).body) self.assertEqual( 'Test Lesson', dom.find('.//h1[@class="gcb-lesson-title"]').text.strip()) return dom.find('.//div[@class="skill-panel"]') def test_skills_widget_supressed_by_course_settings(self): skill_graph = SkillGraph.load() sa = skill_graph.add(Skill.build('a', 'describe a')) sb = skill_graph.add(Skill.build('b', 'describe b')) self.lesson.properties[LESSON_SKILL_LIST_KEY] = [sa.id, sb.id] self.course.save() # Skill widget is not shown if supressed by course setting env = {'course': {'display_skill_widget': False}} with actions.OverriddenEnvironment(env): self.assertIsNone(self._getWidget()) # But the skill widget *is* shown if the course setting is True or is # unset self.assertIsNotNone(self._getWidget()) env = {'course': {'display_skill_widget': True}} with actions.OverriddenEnvironment(env): self.assertIsNotNone(self._getWidget()) def test_no_skills_in_lesson(self): self.assertIsNone(self._getWidget()) def test_skills_with_no_prerequisites_or_successors(self): # Expect skills shown and friendly messages for prerequ and successors skill_graph = SkillGraph.load() sa = skill_graph.add(Skill.build('a', 'describe a')) sb = skill_graph.add(Skill.build('b', 'describe b')) self.lesson.properties[LESSON_SKILL_LIST_KEY] = [sa.id, sb.id] self.course.save() widget = self._getWidget() skills_div, details_div, control_div = widget.findall('./*') actions.assert_contains( 'Taught in this lesson', skills_div.find('./span[@class="section-title"]').text) li_list = skills_div.findall('.//li[@class="skill"]') self.assertEqual(2, len(li_list)) actions.assert_contains('a', li_list[0].text) actions.assert_contains( 'describe a', li_list[0].attrib['data-skill-description']) actions.assert_contains('b', li_list[1].text) actions.assert_contains( 'describe b', li_list[1].attrib['data-skill-description']) details_xml = cElementTree.tostring(details_div) actions.assert_contains('doesn\'t have any prerequisites', details_xml) actions.assert_contains('isn\'t a prerequisite', details_xml) def test_skills_with_prerequisites_and_successors(self): # Set up lesson with two skills, B and C, where A is a prerequisite of B # and D is a successor of B. Expect to see A and D listed in the # 'depends on' and 'leads to' sections respectively skill_graph = SkillGraph.load() sa = skill_graph.add(Skill.build('a', 'describe a')) sb = skill_graph.add(Skill.build('b', 'describe b')) sc = skill_graph.add(Skill.build('c', 'describe c')) sd = skill_graph.add(Skill.build('d', 'describe d')) skill_graph.add_prerequisite(sb.id, sa.id) skill_graph.add_prerequisite(sd.id, sc.id) self.lesson.properties[LESSON_SKILL_LIST_KEY] = [sb.id, sc.id] self.course.save() widget = self._getWidget() # Check B and C are listed as skills in this lesson skills_in_lesson = widget.findall('./div[1]//li[@class="skill"]') self.assertEqual(2, len(skills_in_lesson)) actions.assert_contains('b', skills_in_lesson[0].text) actions.assert_contains('c', skills_in_lesson[1].text) # Skill A is listed in the "depends on" section depends_on = widget.findall('./div[2]/div[1]/ol/li') self.assertEqual(1, len(depends_on)) self.assertEqual(str(sa.id), depends_on[0].attrib['data-skill-id']) # Skill D is listed in the "leads to" section leads_to = widget.findall('./div[2]/div[2]/ol/li') self.assertEqual(1, len(leads_to)) self.assertEqual(str(sd.id), leads_to[0].attrib['data-skill-id']) # But if Skill A is also taught in this lesson, don't list it self.lesson.properties[LESSON_SKILL_LIST_KEY].append(sa.id) self.course.save() widget = self._getWidget() depends_on = widget.findall('./div[2]/div[1]/ol/li') self.assertEqual(0, len(depends_on)) # In fact even if skill A is also taught elsewhere, because it's taught # in this lesson, don't list it. other_lesson = self.course.add_lesson(self.unit) other_lesson.title = 'Other Lesson' other_lesson.now_available = True other_lesson.properties[LESSON_SKILL_LIST_KEY] = [sa.id] self.course.save() widget = self._getWidget() depends_on = widget.findall('./div[2]/div[1]/ol/li') self.assertEqual(0, len(depends_on)) def test_same_skill_prerequ_of_multiple_skills(self): # Set up one skill which is a prerequisite of two skills and expect it # to be shown only once on the "Depends on row" skill_graph = SkillGraph.load() sa = skill_graph.add(Skill.build('a', 'common prerequisite')) sb = skill_graph.add(Skill.build('b', 'depens on a')) sc = skill_graph.add(Skill.build('c', 'also depends on a')) skill_graph.add_prerequisite(sb.id, sa.id) skill_graph.add_prerequisite(sc.id, sa.id) self.lesson.properties[LESSON_SKILL_LIST_KEY] = [sb.id, sc.id] self.course.save() widget = self._getWidget() # Check B and C are listed as skills in this lesson skills_in_lesson = widget.findall('./div[1]//li[@class="skill"]') self.assertEqual(2, len(skills_in_lesson)) actions.assert_contains('b', skills_in_lesson[0].text) actions.assert_contains('c', skills_in_lesson[1].text) # Skill A is listed exactly once in the "depends on" section depends_on = widget.findall('./div[2]/div[1]/ol/li') self.assertEqual(1, len(depends_on)) self.assertEqual(str(sa.id), depends_on[0].attrib['data-skill-id']) def test_skills_cards_have_title_description_and_lesson_links(self): # The lesson contains Skill A which has Skill B as a follow-on. Skill B # is found in Lesson 2. Check that the skill card shown for Skill B in # Lesson 1 has correct information skill_graph = SkillGraph.load() sa = skill_graph.add(Skill.build('a', 'describe a')) sb = skill_graph.add(Skill.build('b', 'describe b')) skill_graph.add_prerequisite(sb.id, sa.id) self.lesson.properties[LESSON_SKILL_LIST_KEY] = [sa.id] lesson2 = self.course.add_lesson(self.unit) lesson2.title = 'Test Lesson 2' lesson2.now_available = True lesson2.properties[LESSON_SKILL_LIST_KEY] = [sb.id] self.course.save() widget = self._getWidget() leads_to = widget.findall('./div[2]/div[2]/ol/li') self.assertEqual(1, len(leads_to)) card = leads_to[0] name = card.find('.//div[@class="name"]').text description = card.find( './/div[@class="description"]/div[@class="content"]').text locations = card.findall('.//ol[@class="locations"]/li/a') self.assertEqual('b', name.strip()) self.assertEqual('describe b', description.strip()) self.assertEqual(1, len(locations)) self.assertEqual( '1.2 Test Lesson 2', ' '.join(locations[0].text.strip().split())) self.assertEqual( 'unit?unit=%(unit)s&lesson=%(lesson)s' % { 'unit': self.unit.unit_id, 'lesson': lesson2.lesson_id}, locations[0].attrib['href']) # Next, make the lesson unavailable lesson2.now_available = False self.course.save() # Except the subsequent skill does not show its lesson widget = self._getWidget() leads_to = widget.findall('./div[2]/div[2]/ol/li') card = leads_to[0] locations = card.findall('.//ol[@class="locations"]/li') self.assertEqual(1, len(locations)) self.assertEqual('Not taught', locations[0].text) class SkillMapAnalyticsTabTests(BaseSkillMapTests): """Tests the handlers for the tab Analytics > Skill Map""" TAB_URL = ('/{}/dashboard?action=analytics&tab=skill_map'.format( COURSE_NAME)) NON_ADMIN_EMAIL = 'noadmin@example.tests' def test_get_tab(self): """Performs a get call to the tab.""" actions.login(ADMIN_EMAIL, is_admin=True) response = self.get(self.TAB_URL) self.assertEqual(response.status_code, 200) def test_get_tab_no_admin(self): """Non admin users should not have access.""" actions.login(self.NON_ADMIN_EMAIL, is_admin=False) response = self.get(self.TAB_URL, expect_errors=True) self.assertEquals(302, response.status_int) class CountSkillCompletionsTests(BaseSkillMapTests): """Tests the result of the map reduce job CountSkillCompletions.""" def setUp(self): super(CountSkillCompletionsTests, self).setUp() actions.login(ADMIN_EMAIL, is_admin=True) self._create_skills() self._create_students() def _create_students(self): """Creates 4 StudentPropertyEntities with partial progress.""" def mktime(str_date): return time.mktime(time.strptime( str_date, CountSkillCompletion.DATE_FORMAT)) self.day1 = '2015-01-01' self.day2 = '2015-01-02' self.day3 = '2015-01-03' self.day4 = '2015-01-04' c = SkillCompletionTracker.COMPLETED p = SkillCompletionTracker.IN_PROGRESS # progress string for students students_progress = [ {self.skill1.id : {c: mktime(self.day2), p: mktime(self.day1)}, self.skill2.id : {c: mktime(self.day4), p: mktime(self.day1)}}, {self.skill1.id : {c: mktime(self.day2), p: mktime(self.day2)}, self.skill2.id : {p: mktime(self.day1)}}, {self.skill1.id : {c: mktime(self.day1)}}, {} # No progress ] for index, progress in enumerate(students_progress): student = models.Student(user_id=str(index)) student.put() comp = models.StudentPropertyEntity.create( student=student, property_name=SkillCompletionTracker.PROPERTY_KEY) comp.value = transforms.dumps(progress) comp.put() def _create_skills(self): """Creates 2 skills.""" skill_graph = SkillGraph.load() self.skill1 = skill_graph.add(Skill.build('a', '')) self.skill2 = skill_graph.add(Skill.build('b', '')) self.skill3 = skill_graph.add(Skill.build('c', '')) self.course.save() def run_generator_job(self): job = CountSkillCompletion(self.app_context) job.submit() self.execute_all_deferred_tasks() def test_job_aggregate_entities(self): """Tests the SkillCompletionAggregate entities created by the job.""" # This is testing: # - Skills completed without in progress state # - Days with no progress # - Skills with no progress # - Students with no progress self.run_generator_job() job = CountSkillCompletion(self.app_context).load() expected = { str(self.skill1.id): {self.day1: 1, self.day2: 3}, str(self.skill2.id): {self.day4: 1}, str(self.skill3.id): {} } # Check entities result = list(SkillCompletionAggregate.all().run()) self.assertEqual(3, len(result)) # One per skill for aggregate in result: skill_id = aggregate.key().name() self.assertEqual(expected[skill_id], transforms.loads(aggregate.aggregate)) def test_job_output(self): """Tests the output of the job for the SkillMapDataSource.""" self.run_generator_job() job = CountSkillCompletion(self.app_context).load() output = jobs.MapReduceJob.get_results(job) expected = [[str(self.skill1.id), self.skill1.name, 3, 0], [str(self.skill2.id), self.skill2.name, 1, 1], [str(self.skill3.id), self.skill3.name, 0, 0]] self.assertEqual(sorted(expected), sorted(output)) def test_build_additional_mapper_params(self): """The additional param in a dictionary mapping from skills to lessons. """ job = CountSkillCompletion(self.app_context) result = job.build_additional_mapper_params(self.app_context) expected = { self.skill1.id: job.pack_name(self.skill1.id, self.skill1.name), self.skill2.id: job.pack_name(self.skill2.id, self.skill2.name), self.skill3.id: job.pack_name(self.skill3.id, self.skill3.name) } self.assertEqual({'skills': expected}, result) class SkillAggregateRestHandlerTests(BaseSkillMapTests): """Tests for the class SkillAggregateRestHandler.""" URL = 'rest/modules/skill_map/skill_aggregate_count' XSRF_TOKEN = 'skill_aggregate' def _add_aggregates(self): self.day1 = '2015-01-01' self.day2 = '2015-01-02' self.day3 = '2015-01-03' self.day4 = '2015-01-04' self.skill_ids = range(1, 4) self.aggregates = { self.skill_ids[0]: {self.day1: 1, self.day2: 2}, self.skill_ids[1]: {self.day4: 1}, self.skill_ids[2]: {}, } for skill_id, aggregate in self.aggregates.iteritems(): SkillCompletionAggregate( key_name=str(skill_id), aggregate=transforms.dumps(aggregate)).put() def test_rejected_if_not_authorized(self): # Not logged in response = transforms.loads(self.get(self.URL).body) self.assertEqual(401, response['status']) # logged in but not admin actions.login('user.foo.com') response = transforms.loads(self.get(self.URL).body) self.assertEqual(401, response['status']) # logged in as admin actions.logout() actions.login(ADMIN_EMAIL) response = transforms.loads(self.get(self.URL).body) self.assertEqual(200, response['status']) def test_single_skill_request(self): """Asks for one skill information.""" self._add_aggregates() actions.login(ADMIN_EMAIL) get_url = '%s?%s' % (self.URL, urllib.urlencode({ 'ids': [self.skill_ids[0]]}, True)) response = self.get(get_url) self.assertEqual(200, response.status_int) payload = transforms.loads(response.body)['payload'] expected_header = ['Date', str(self.skill_ids[0])] expected_data = [[self.day1, 1], [self.day2, 2]] result = transforms.loads(payload) self.assertEqual(expected_header, result['column_headers']) self.assertEqual(len(expected_data), len(result['data'])) for row in expected_data: self.assertIn(row, result['data']) def test_multiple_skill_request(self): """Asks for more than one skill information.""" self._add_aggregates() actions.login(ADMIN_EMAIL) get_url = '%s?%s' % (self.URL, urllib.urlencode({ 'ids': self.skill_ids}, True)) response = self.get(get_url) self.assertEqual(200, response.status_int) payload = transforms.loads(response.body)['payload'] result = transforms.loads(payload) expected_header = ['Date'] + [str(skill_id) for skill_id in self.skill_ids] expected_data = [ [self.day1, 1, 0, 0], [self.day2, 2, 0, 0], [self.day4, 2, 1, 0] ] self.assertEqual(expected_header, result['column_headers']) self.assertEqual(len(expected_data), len(result['data'])) for row in expected_data: self.assertIn(row, result['data']) def test_no_skill_request(self): """Sends a request with no skills.""" actions.login(ADMIN_EMAIL) response = self.get(self.URL) self.assertEqual(200, response.status_int) payload = transforms.loads(response.body)['payload'] result = transforms.loads(payload) self.assertEqual(['Date'], result['column_headers']) self.assertEqual([], result['data']) def test_no_skill_aggregate(self): """Sends a request with a skill that does not have an object in db.""" actions.login(ADMIN_EMAIL) get_url = '%s?%s' % (self.URL, urllib.urlencode({ 'ids': [1]}, True)) response = self.get(get_url) self.assertEqual(200, response.status_int) payload = transforms.loads(response.body)['payload'] result = transforms.loads(payload) self.assertEqual(['Date'], result['column_headers']) self.assertEqual([], result['data']) def test_exceed_limit_request(self): """Exceeds the limit in the number of skills requested.""" actions.login(ADMIN_EMAIL) ids_list = list(range(SkillAggregateRestHandler.MAX_REQUEST_SIZE)) get_url = '%s?%s' % (self.URL, urllib.urlencode({ 'ids': ids_list}, True)) response = transforms.loads(self.get(get_url).body) self.assertEqual(412, response['status']) class SkillMapMetricTests(BaseSkillMapTests): """Tests for the functions in file skill_map_metrics""" def test_nxgraph(self): """The graph of SkillMapMetrics and the skill_map are equivalent.""" self._build_sample_graph() # Adding singleton sg = self.skill_graph.add(Skill.build('g', '')) skill_map = SkillMap.load(self.course) nxgraph = SkillMapMetrics(skill_map).nxgraph self.assertIsInstance(nxgraph, DiGraph) successors = skill_map.build_successors() # Check nodes self.assertEqual(len(nxgraph), len(successors)) for skill in successors: self.assertIn(skill, nxgraph.nodes(), msg='Node {} not found in nx graph.'.format(skill)) # Check edges original_edges = sum(len(dst) for dst in successors.values()) self.assertEqual(len(nxgraph.edges()), original_edges) for src, dst in nxgraph.edges_iter(): self.assertIn(src, successors) self.assertIn(dst, successors[src], msg='Extra {},{} edge in nx graph.'.format(src, dst)) def test_find_cycles_no_cycle(self): """The input is a directed graph with no cycles. Expected [].""" self._build_sample_graph() skill_map = SkillMap.load(self.course) self.assertEqual(SkillMapMetrics(skill_map).simple_cycles(), []) def test_find_cycles_one_cycle(self): """The input is a directed graph with only 1 cycle.""" self._build_sample_graph() # Adding cycle a -> d -> a self.skill_graph.add_prerequisite(self.sa.id, self.sd.id) skill_map = SkillMap.load(self.course) self.assertEqual(6, len(skill_map.skills())) successors = skill_map.build_successors() self.assertEqual( sorted(SkillMapMetrics(skill_map).simple_cycles()[0]), [self.sa.id, self.sd.id]) def test_find_cycles_multiple_cycles(self): """The input is a directed graph with two cycles.""" self._build_sample_graph() # Adding cycle a -> d -> a self.skill_graph.add_prerequisite(self.sa.id, self.sd.id) # Adding cycle g -> h -> g sg = self.skill_graph.add(Skill.build('g', '')) sh = self.skill_graph.add(Skill.build('h', '')) self.skill_graph.add_prerequisite(sg.id, sh.id) self.skill_graph.add_prerequisite(sh.id, sg.id) expected = [[self.sa.id, self.sd.id], [sg.id, sh.id]] skill_map = SkillMap.load(self.course) successors = skill_map.build_successors() result = SkillMapMetrics(skill_map).simple_cycles() self.assertEqual(len(result), len(expected)) for cycle in result: self.assertIn(sorted(cycle), expected) def test_find_cycles_not_conected(self): """The input is a directed graph whith an isolated scc.""" self._build_sample_graph() # Adding cycle g -> h -> g sg = self.skill_graph.add(Skill.build('g', '')) sh = self.skill_graph.add(Skill.build('h', '')) self.skill_graph.add_prerequisite(sg.id, sh.id) self.skill_graph.add_prerequisite(sh.id, sg.id) skill_map = SkillMap.load(self.course) expected0 = [sg.id, sh.id] successors = skill_map.build_successors() result = SkillMapMetrics(skill_map).simple_cycles() self.assertEqual(sorted(result[0]), expected0) def test_metrics_empty(self): """The input is an empty graph.""" skill_map = SkillMap.load(self.course) sm_metrics = SkillMapMetrics(skill_map) self.assertEqual(sm_metrics.simple_cycles(), []) self.assertEqual(sm_metrics.singletons(), []) self.assertEqual(sm_metrics.long_chains(), []) expected = {'cycles': [], 'singletons': [], 'long_chains': []} self.assertEqual(sm_metrics.diagnose(), expected) def test_find_singletons(self): """Singletons are components with only one node.""" self._build_sample_graph() # Adding singletons sg = self.skill_graph.add(Skill.build('g', '')) sh = self.skill_graph.add(Skill.build('h', '')) skill_map = SkillMap.load(self.course) result = SkillMapMetrics(skill_map).singletons() expected = [sg.id, sh.id] self.assertEqual(sorted(expected), sorted(result)) def test_find_long_chains(self): """Find all simple paths longer than a constant.""" # a --> d --> j g h --> i # b _/ c --> e --> f self._build_sample_graph() # Adding singleton sg = self.skill_graph.add(Skill.build('g', '')) # Adding short path sh = self.skill_graph.add(Skill.build('h', '')) si = self.skill_graph.add(Skill.build('i', '')) self.skill_graph.add_prerequisite(si.id, sh.id) # Making path longer sj = self.skill_graph.add(Skill.build('j', '')) self.skill_graph.add_prerequisite(sj.id, self.sd.id) skill_map = SkillMap.load(self.course) result = SkillMapMetrics(skill_map).long_chains(2) expected = [ [self.sa.id, self.sd.id, sj.id], [self.sb.id, self.sd.id, sj.id], [self.sc.id, self.se.id, self.sf.id] ] self.assertEqual(sorted(expected), sorted(result)) def test_find_long_chains_multiple(self): """Finds longest path when there is more than one path from A to B. """ # a -> b -> c -> ... x # \________________/ self.skill_graph = SkillGraph.load() old_skill = self.skill_graph.add(Skill.build('o', '')) last_skill = self.skill_graph.add(Skill.build('l', '')) self.skill_graph.add_prerequisite(last_skill.id, old_skill.id) chain_ids = [old_skill.id] for index in range(CHAINS_MIN_LENGTH): new_skill = self.skill_graph.add(Skill.build(str(index), '')) chain_ids.append(new_skill.id) self.skill_graph.add_prerequisite(new_skill.id, old_skill.id) old_skill = new_skill self.skill_graph.add_prerequisite(old_skill.id, last_skill.id) skill_map = SkillMap.load(self.course) result = SkillMapMetrics(skill_map).long_chains() self.assertEqual([chain_ids], result) def test_get_diagnose(self): """Checks the diagnose contains the required metrics. The function returns a dictionary with the simple cycles, singletons and long_chains. """ self._build_sample_graph() # Adding cycle a -> d -> a self.skill_graph.add_prerequisite(self.sa.id, self.sd.id) # Adding singleton sg = self.skill_graph.add(Skill.build('g', '')) skill_map = SkillMap.load(self.course) result = SkillMapMetrics(skill_map).diagnose() expected = { 'cycles': [[self.sd.id, self.sa.id]], 'singletons': [sg.id], 'long_chains': [] } self.assertEqual(result, expected) class SkillI18nTests(actions.TestBase): ADMIN_EMAIL = 'admin@foo.com' COURSE_NAME = 'skill_map_course' DASHBOARD_SKILL_MAP_URL = 'dashboard?action=skill_map' SKILL_MAP_URL = 'modules/skill_map?action=skill_map&tab=skills_table' def setUp(self): super(SkillI18nTests, self).setUp() self.base = '/' + self.COURSE_NAME context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'Skill Map Course') self.old_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace('ns_%s' % self.COURSE_NAME) self.course = courses.Course(None, context) self.unit = self.course.add_unit() self.unit.title = 'Unit 1' self.lesson = self.course.add_lesson(self.unit) self.lesson.title = 'Lesson 1' self.course.save() actions.login(self.ADMIN_EMAIL, is_admin=True) actions.update_course_config(self.COURSE_NAME, { 'extra_locales': [ {'locale': 'el', 'availability': 'available'}, {'locale': 'ru', 'availability': 'available'}] }) def tearDown(self): del sites.Registry.test_overrides[sites.GCB_COURSES_CONFIG.name] namespace_manager.set_namespace(self.old_namespace) courses.Course.ENVIRON_TEST_OVERRIDES.clear() super(SkillI18nTests, self).tearDown() def _put_payload(self, url, xsrf_name, key, payload): request_dict = { 'key': key, 'xsrf_token': ( crypto.XsrfTokenManager.create_xsrf_token(xsrf_name)), 'payload': transforms.dumps(payload) } response = transforms.loads(self.put( url, {'request': transforms.dumps(request_dict)}).body) self.assertEquals(200, response['status']) self.assertEquals('Saved.', response['message']) return response def _assert_progress(self, key, el_progress=None, ru_progress=None): progress_dto = i18n_dashboard.I18nProgressDAO.load(str(key)) self.assertIsNotNone(progress_dto) self.assertEquals(el_progress, progress_dto.get_progress('el')) self.assertEquals(ru_progress, progress_dto.get_progress('ru')) def test_on_skill_changed(self): # Make a skill with a weird name and weird description. skill = Skill(None, { 'name': 'x', 'description': 'y' }) skill_key = _SkillDao.save(skill) key = resource.Key(ResourceSkill.TYPE, skill_key) # Make a resource bundle corresponding to the skill, but with a # translation of the skill's description not matching the name # or description. bundle_key = i18n_dashboard.ResourceBundleKey.from_resource_key( key, 'el') bundle = i18n_dashboard.ResourceBundleDTO(str(bundle_key), { 'name': { 'type': 'string', 'source_value': '', 'data': [{ 'source_value': SKILL_NAME, 'target_value': SKILL_NAME.upper(), }] }, 'description': { 'type': 'text', 'source_value': '', 'data': [{ 'source_value': SKILL_DESC, 'target_value': SKILL_DESC.upper(), }] }, }) i18n_dashboard.ResourceBundleDAO.save(bundle) # Now, call the REST url to update the skill's name and description # to be something matching the current translated version. We should # now believe that the translation is current and up-to date. self._put_payload( 'rest/modules/skill_map/skill', SkillRestHandler.XSRF_TOKEN, skill_key, { 'version': SkillRestHandler.SCHEMA_VERSIONS[0], 'name': SKILL_NAME, 'description': SKILL_DESC, }) self.execute_all_deferred_tasks() self._assert_progress( key, el_progress=i18n_dashboard.I18nProgressDTO.DONE, ru_progress=i18n_dashboard.I18nProgressDTO.NOT_STARTED) # Again using the REST interface, change the native-language # description to something else. The translation should show as # being in-progress (we have something), but not up-to-date. self._put_payload( 'rest/modules/skill_map/skill', SkillRestHandler.XSRF_TOKEN, skill_key, { 'version': SkillRestHandler.SCHEMA_VERSIONS[0], 'name': SKILL_NAME, 'description': SKILL_DESC_2, }) self.execute_all_deferred_tasks() self._assert_progress( key, el_progress=i18n_dashboard.I18nProgressDTO.IN_PROGRESS, ru_progress=i18n_dashboard.I18nProgressDTO.NOT_STARTED) def test_skills_are_translated(self): skill = Skill(None, { 'name': SKILL_NAME, 'description': SKILL_DESC }) skill_key = _SkillDao.save(skill) key = resource.Key(ResourceSkill.TYPE, skill_key) bundle_key = i18n_dashboard.ResourceBundleKey.from_resource_key( key, 'el') bundle = i18n_dashboard.ResourceBundleDTO(str(bundle_key), { 'name': { 'type': 'string', 'source_value': '', 'data': [{ 'source_value': SKILL_NAME, 'target_value': SKILL_NAME.upper(), }] }, 'description': { 'type': 'text', 'source_value': '', 'data': [{ 'source_value': SKILL_DESC, 'target_value': SKILL_DESC.upper(), }] }, }) i18n_dashboard.ResourceBundleDAO.save(bundle) self.lesson.properties[LESSON_SKILL_LIST_KEY] = [skill_key] self.course.save() # Verify that we get the untranslated (lowercased) version when we # do not want to see the translated language. response = self.get('unit?unit=%s&lesson=%s' % (self.unit.unit_id, self.lesson.lesson_id)) dom = self.parse_html_string(response.body) skill_li = dom.find('.//li[@data-skill-description="%s"]' % skill.description) skill_text = (''.join(skill_li.itertext())).strip() self.assertEqual(skill.name, skill_text) # Set pref to see translated version prefs = models.StudentPreferencesDAO.load_or_create() prefs.locale = 'el' models.StudentPreferencesDAO.save(prefs) # And verify that we do get the translated (uppercase) version. response = self.get('unit?unit=%s&lesson=%s' % (self.unit.unit_id, self.lesson.lesson_id)) dom = self.parse_html_string(response.body) skill_li = dom.find('.//li[@data-skill-description="%s"]' % skill.description.upper()) skill_text = (''.join(skill_li.itertext())).strip() self.assertEqual(skill.name.upper(), skill_text) def test_skills_appear_on_i18n_dashboard(self): skill = Skill(None, { 'name': SKILL_NAME, 'description': SKILL_DESC }) _SkillDao.save(skill) skill = Skill(None, { 'name': SKILL_NAME_2, 'description': SKILL_DESC_2 }) _SkillDao.save(skill) response = self.get('dashboard?action=i18n_dashboard') dom = self.parse_html_string(response.body) table = dom.find('.//table[@class="i18n-progress-table"]') rows = table.findall('./tbody/tr') skills_row_index = -1 for index, row in enumerate(rows): td_text = (''.join(row.find('td').itertext())).strip() if td_text == 'Skills': skills_row_index = index break self.assertNotEqual(-1, skills_row_index, 'Must have a Skills section') self.assertEqual( SKILL_NAME_2, ''.join(rows[skills_row_index + 1].find('td').itertext()).strip(), 'Skill name 2 added second appears first due to sorting') self.assertEqual( SKILL_NAME, ''.join(rows[skills_row_index + 2].find('td').itertext()).strip(), 'Skill name added first appears second due to sorting') def _do_upload(self, contents): xsrf_token = crypto.XsrfTokenManager.create_xsrf_token( i18n_dashboard.TranslationUploadRestHandler.XSRF_TOKEN_NAME) response = self.post( '/%s%s' % (self.COURSE_NAME, i18n_dashboard.TranslationUploadRestHandler.URL), {'request': transforms.dumps({'xsrf_token': xsrf_token})}, upload_files=[('file', 'doesntmatter', contents)]) return response def _do_download(self, payload): request = { 'xsrf_token': crypto.XsrfTokenManager.create_xsrf_token( i18n_dashboard.TranslationDownloadRestHandler.XSRF_TOKEN_NAME), 'payload': transforms.dumps(payload), } response = self.post( '/%s%s' % (self.COURSE_NAME, i18n_dashboard.TranslationDownloadRestHandler.URL), {'request': transforms.dumps(request)}) return response def _parse_zip_response(self, response): download_zf = zipfile.ZipFile(cStringIO.StringIO(response.body), 'r') out_stream = StringIO.StringIO() out_stream.fp = out_stream for item in download_zf.infolist(): file_data = download_zf.read(item) catalog = pofile.read_po(cStringIO.StringIO(file_data)) yield catalog def test_export_skills(self): skill = Skill(None, { 'name': SKILL_NAME, 'description': SKILL_DESC }) skill_key = _SkillDao.save(skill) key = resource.Key(ResourceSkill.TYPE, skill_key) bundle_key = i18n_dashboard.ResourceBundleKey.from_resource_key( key, 'el') bundle = i18n_dashboard.ResourceBundleDTO(str(bundle_key), { 'name': { 'type': 'string', 'source_value': '', 'data': [{ 'source_value': SKILL_NAME, 'target_value': SKILL_NAME.upper(), }] }, 'description': { 'type': 'text', 'source_value': '', 'data': [{ 'source_value': SKILL_DESC, 'target_value': SKILL_DESC.upper(), }] }, }) i18n_dashboard.ResourceBundleDAO.save(bundle) response = self._do_download({ 'locales': [{'locale': 'el', 'checked': True}], 'export_what': 'all', }) found_skill_name = False found_skill_desc = False for catalog in self._parse_zip_response(response): for msg in catalog: if msg.id == SKILL_NAME: self.assertEquals(SKILL_NAME.upper(), msg.string) found_skill_name = True if msg.id == SKILL_DESC: self.assertEquals(SKILL_DESC.upper(), msg.string) found_skill_desc = True self.assertTrue(found_skill_name) self.assertTrue(found_skill_desc) def test_import_skills(self): skill = Skill(None, { 'name': SKILL_NAME, 'description': SKILL_DESC }) skill_key = _SkillDao.save(skill) key = resource.Key(ResourceSkill.TYPE, skill_key) bundle_key = i18n_dashboard.ResourceBundleKey.from_resource_key( key, 'el') bundle = i18n_dashboard.ResourceBundleDTO(str(bundle_key), { 'name': { 'type': 'string', 'source_value': '', 'data': [{ 'source_value': SKILL_NAME, 'target_value': SKILL_NAME.upper(), }] }, 'description': { 'type': 'text', 'source_value': '', 'data': [{ 'source_value': SKILL_DESC, 'target_value': SKILL_DESC.upper(), }] }, }) i18n_dashboard.ResourceBundleDAO.save(bundle) # Do download to force creation of progress entities. self._do_download({ 'locales': [{'locale': 'el', 'checked': True}], 'export_what': 'all', }) response = self._do_upload( '# <span class="">%s</span>\n' % SKILL_DESC + '#: GCB-1|name|string|skill:1:el:0\n' '#| msgid ""\n' + 'msgid "%s"\n' % SKILL_DESC + 'msgstr "%s"\n' % SKILL_DESC[::-1]) self.assertIn( '<response><status>200</status><message>Success.</message>', response.body) # Fetch the translation bundle and verify that the description has # been changed to the reversed-order string bundle = i18n_dashboard.ResourceBundleDAO.load(str(bundle_key)) self.assertEquals(bundle.dict['description']['data'][0]['target_value'], SKILL_DESC[::-1]) class SkillCompletionTrackerTests(BaseSkillMapTests): """Hanldes the access and modification of the skill progress.""" def _add_student_and_progress(self): # progress string for students student_progress = { self.sa.id: { SkillCompletionTracker.COMPLETED: time.time() - 100, SkillCompletionTracker.IN_PROGRESS: time.time() - 200 }, self.sb.id: { SkillCompletionTracker.IN_PROGRESS: time.time() }, } self.student = models.Student(user_id='1') self.student.put() self.progress = models.StudentPropertyEntity.create( student=self.student, property_name=SkillCompletionTracker.PROPERTY_KEY) self.progress.value = transforms.dumps(student_progress) self.progress.put() def _create_linear_progress(self): uid = self.unit.unit_id # progress string for students student_progress = { 'u.{}.l.{}'.format(uid, self.lesson1.lesson_id): 2, 'u.{}.l.{}'.format(uid, self.lesson2.lesson_id): 2 } student = models.Student(user_id='1') student.put() comp = UnitLessonCompletionTracker.get_or_create_progress( student) comp.value = transforms.dumps(student_progress) comp.put() def test_get_skill_progress(self): """Looks in the db for the progress of the skill.""" self._build_sample_graph() self._add_student_and_progress() tracker = SkillCompletionTracker() result = tracker.get_skills_progress( self.student, [self.sa.id, self.sb.id, self.sc.id]) self.assertEqual(SkillCompletionTracker.COMPLETED, result[self.sa.id][0]) self.assertEqual(SkillCompletionTracker.IN_PROGRESS, result[self.sb.id][0]) self.assertEqual(SkillCompletionTracker.NOT_ATTEMPTED, result[self.sc.id][0]) def test_get_non_existent_skill_progress(self): """Asks for the progress of a non existing StudentPropertyEntity.""" self._build_sample_graph() student = models.Student(user_id='1') tracker = SkillCompletionTracker() result = tracker.get_skills_progress(student, [self.sc.id]) self.assertEqual(SkillCompletionTracker.NOT_ATTEMPTED, result[self.sc.id][0]) def test_update_skill_progress(self): progress_value = {} skill = 1 start_time = time.time() completed = SkillCompletionTracker.COMPLETED SkillCompletionTracker.update_skill_progress(progress_value, skill, completed) end_time = time.time() # Repeat, the timestamp should not be affected. SkillCompletionTracker.update_skill_progress(progress_value, skill, completed) skill = str(skill) self.assertIn(skill, progress_value) self.assertIn(completed, progress_value[skill]) self.assertLessEqual(start_time, progress_value[skill][completed]) self.assertLessEqual(progress_value[skill][completed], end_time) def test_recalculate_progress(self): """Calculates the skill progress from the lessons.""" self._build_sample_graph() self._create_lessons() # 3 lessons in unit 1 self.student = models.Student(user_id='1') self._create_linear_progress() # Lesson 1 and 2 completed self.lesson1.properties[LESSON_SKILL_LIST_KEY] = [self.sa.id] self.lesson2.properties[LESSON_SKILL_LIST_KEY] = [self.sb.id] self.lesson3.properties[LESSON_SKILL_LIST_KEY] = [self.sa.id, self.sc.id] self.course.save() tracker = SkillCompletionTracker(self.course) lprogress_tracker = UnitLessonCompletionTracker(self.course) lprogress = lprogress_tracker.get_or_create_progress(self.student) expected = { self.sa: tracker.IN_PROGRESS, self.sb: tracker.COMPLETED, self.sc: tracker.NOT_ATTEMPTED } for skill, expected_progress in expected.iteritems(): self.assertEqual(expected_progress, tracker.recalculate_progress(lprogress_tracker, lprogress, skill)) def test_update_skills_to_completed(self): """Calculates the state from the linear progress.""" self._build_sample_graph() self._create_lessons() # 3 lessons in unit 1 self._add_student_and_progress() # sa completed, sb in progress self._create_linear_progress() # Lesson 1 and 2 completed self.lesson1.properties[LESSON_SKILL_LIST_KEY] = [self.sa.id, self.sb.id] self.course.save() start_time = time.time() tracker = SkillCompletionTracker(self.course) lprogress_tracker = UnitLessonCompletionTracker(self.course) lprogress = lprogress_tracker.get_or_create_progress(self.student) tracker.update_skills(self.student, lprogress, self.lesson1.lesson_id) # Nothing changes with sa sprogress = models.StudentPropertyEntity.get( self.student, SkillCompletionTracker.PROPERTY_KEY) progress_value = transforms.loads(sprogress.value) self.assertIn(tracker.COMPLETED, progress_value[str(self.sa.id)]) self.assertLessEqual( progress_value[str(self.sa.id)][tracker.COMPLETED], start_time) # Update in sb self.assertIn(tracker.COMPLETED, progress_value[str(self.sb.id)]) self.assertGreaterEqual( progress_value[str(self.sb.id)][tracker.COMPLETED], start_time) def test_update_recalculate_no_skill_map(self): self._build_sample_graph() self._create_lessons() # 3 lessons in unit 1 self._add_student_and_progress() # sa completed, sb in progress lprogress_tracker = UnitLessonCompletionTracker(self.course) lprogress = lprogress_tracker.get_or_create_progress(self.student) tracker = SkillCompletionTracker() # Just does not raise any error tracker.update_skills(self.student, lprogress, self.lesson1.lesson_id) tracker.recalculate_progress(lprogress_tracker, lprogress, self.sa)
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Functional tests for modules/i18n_dashboard/jobs.py.""" __author__ = [ 'johncox@google.com (John Cox)', ] import os import zipfile from modules.i18n_dashboard import jobs from tests.functional import modules_i18n_dashboard from tools.etl import etl from tools.etl import testing # Allow access to code under test. pylint: disable=protected-access class _JobTestBase( testing.EtlTestBase, modules_i18n_dashboard.CourseLocalizationTestBase): def setUp(self): super(_JobTestBase, self).setUp() self.filename = os.path.join(self.test_tempdir, 'filename') self.zipfile_name = self.filename + '.zip' def assert_dies_if_cannot_get_app_context_for_course_url_prefix( self, job_name, job_args=None): bad_course_url_prefix = '/bad' + self.url_prefix args = [ 'run', 'modules.i18n_dashboard.jobs.' + job_name, bad_course_url_prefix, 'myapp', 'localhost:8080'] if job_args: args.append(job_args) with self.assertRaises(SystemExit): etl.main( etl.create_args_parser().parse_args(args), environment_class=testing.FakeEnvironment) self.assertIn( 'Unable to find course with url prefix ' + bad_course_url_prefix, self.get_log()) def assert_ln_locale_in_course(self, response): self.assertEqual(200, response.status_int) self.assertIn('<th>ln</th>', response.body) def assert_ln_locale_not_in_course(self, response): self.assertEqual(200, response.status_int) self.assertNotIn('<th>ln</th>', response.body) def assert_zipfile_contains_only_ln_locale(self, filename): with zipfile.ZipFile(filename) as zf: files = zf.infolist() self.assertEqual( ['locale/ln/LC_MESSAGES/messages.po'], [f.filename for f in files]) def create_file(self, contents): with open(self.filename, 'w') as f: f.write(contents) def run_job(self, name, job_args=None): # Requires course at /first; use self._import_course(). args = ['run', name, '/first', 'myapp', 'localhost:8080'] if job_args: args.append(job_args) etl.main( etl.create_args_parser().parse_args(args), environment_class=testing.FakeEnvironment) def run_delete_job(self, job_args=None): self.run_job( 'modules.i18n_dashboard.jobs.DeleteTranslations', job_args=job_args) def run_download_job(self, job_args=None): if not job_args: job_args = '--job_args=' + self.zipfile_name self.run_job( 'modules.i18n_dashboard.jobs.DownloadTranslations', job_args=job_args) def run_translate_job(self, job_args=None): self.run_job( 'modules.i18n_dashboard.jobs.TranslateToReversedCase', job_args=job_args) def run_upload_job(self, job_args=None): if not job_args: job_args = '--job_args=' + self.zipfile_name self.run_job( 'modules.i18n_dashboard.jobs.UploadTranslations', job_args=job_args) class BaseJobTest(_JobTestBase): def test_file_does_not_exist_when_file_does_not_exist(self): jobs._BaseJob._check_file_does_not_exist(self.filename) def test_file_does_not_exist_dies_when_file_exists(self): with open(self.filename, 'w') as f: f.write('contents') with self.assertRaises(SystemExit): jobs._BaseJob._check_file_does_not_exist(self.filename) self.assertIn('File already exists', self.get_log()) def test_file_exists_when_file_exists(self): self.create_file('contents') jobs._BaseJob._check_file_exists(self.filename) def test_file_exists_dies_when_file_does_not_exist(self): with self.assertRaises(SystemExit): jobs._BaseJob._check_file_exists(self.filename) self.assertIn('File does not exist', self.get_log()) def test_get_app_context_or_die_gets_existing_app_context(self): self.assertEqual( self.url_prefix, jobs._BaseJob._get_app_context_or_die(self.url_prefix).slug) def test_get_app_context_or_die_dies_if_context_missing(self): with self.assertRaises(SystemExit): jobs._BaseJob._get_app_context_or_die('missing') self.assertIn( 'Unable to find course with url prefix missing', self.get_log()) def get_get_locales_returns_all_locales_if_no_requested_locales(self): self.assertEqual( ['all'], jobs._BaseJob._get_locales([], ['requested'], 'strip', 'prefix')) def test_get_locales_strips_default_locale(self): self.assertEqual( ['keep'], jobs._BaseJob._get_locales( [], ['strip', 'keep'], 'strip', 'prefix')) def test_get_locales_returns_sorted_locales_when_no_locales_missing(self): self.assertEqual( ['a', 'b'], jobs._BaseJob._get_locales( ['b', 'a'], ['b', 'a', 'strip'], 'strip', 'prefix')) def test_get_locales_dies_if_requested_locales_missing(self): with self.assertRaises(SystemExit): jobs._BaseJob._get_locales( ['missing'], ['first', 'second', 'strip'], 'strip', 'prefix') self.assertIn( 'Requested locale missing not found for course at prefix. Choices ' 'are: first, second', self.get_log()) class DeleteTranslationsTest(_JobTestBase): def test_dies_if_cannot_get_app_context_for_course_url_prefix(self): self.assert_dies_if_cannot_get_app_context_for_course_url_prefix( 'DeleteTranslations') def test_delete_all_locales(self): self._import_course() self.run_translate_job() response = self.get('first/dashboard?action=i18n_dashboard') self.assert_ln_locale_in_course(response) self.run_delete_job() response = self.get('first/dashboard?action=i18n_dashboard') self.assert_ln_locale_not_in_course(response) def test_delete_specific_locales(self): self._import_course() self.run_translate_job() response = self.get('first/dashboard?action=i18n_dashboard') self.assert_ln_locale_in_course(response) self.run_delete_job(job_args='--job_args=--locales=ln') response = self.get('first/dashboard?action=i18n_dashboard') self.assert_ln_locale_not_in_course(response) class DownloadTranslationsTest(_JobTestBase): def test_dies_if_cannot_get_app_context_for_course_url_prefix(self): self.assert_dies_if_cannot_get_app_context_for_course_url_prefix( 'DownloadTranslations', '--job_args=path') def test_dies_if_path_already_exists(self): self.create_file('contents') args = [ 'run', 'modules.i18n_dashboard.jobs.DownloadTranslations', self.url_prefix, 'myapp', 'localhost:8080', '--job_args=%s' % self.filename] with self.assertRaises(SystemExit): etl.main( etl.create_args_parser().parse_args(args), environment_class=testing.FakeEnvironment) self.assertIn('File already exists', self.get_log()) def test_download_of_course_with_no_translations_dies(self): args = [ 'run', 'modules.i18n_dashboard.jobs.DownloadTranslations', self.url_prefix, 'myapp', 'localhost:8080', '--job_args=%s' % self.zipfile_name] with self.assertRaises(SystemExit): etl.main( etl.create_args_parser().parse_args(args), environment_class=testing.FakeEnvironment) self.assertIn( 'No translations found for course at %s; exiting' % self.url_prefix, self.get_log()) def test_download_all_locales(self): self._import_course() self.run_translate_job() response = self.get('first/dashboard?action=i18n_dashboard') self.assert_ln_locale_in_course(response) self.run_download_job() self.assert_zipfile_contains_only_ln_locale(self.zipfile_name) def test_download_specific_locales(self): self._import_course() self.run_translate_job() response = self.get('first/dashboard?action=i18n_dashboard') self.assert_ln_locale_in_course(response) self.run_download_job('--job_args=%s --locales=ln' % self.zipfile_name) self.assert_zipfile_contains_only_ln_locale(self.zipfile_name) class TranslateToReversedCaseTest(_JobTestBase): def test_dies_if_cannot_get_app_context_for_course_url_prefix(self): self.assert_dies_if_cannot_get_app_context_for_course_url_prefix( 'TranslateToReversedCase') class UploadTranslationsTest(_JobTestBase): def create_zip_file(self, contents): with zipfile.ZipFile(self.zipfile_name, 'w') as zf: zf.writestr('filename', contents) def extract_zipfile(self): extracted = [] with zipfile.ZipFile(self.zipfile_name) as zf: for zipinfo in zf.infolist(): path = os.path.join(self.test_tempdir, zipinfo.filename) os.makedirs(os.path.dirname(path)) with open(path, 'w') as f: fromzip = zf.open(zipinfo.filename) f.write(fromzip.read()) extracted.append(path) return extracted def test_dies_if_path_does_not_exist(self): args = [ 'run', 'modules.i18n_dashboard.jobs.UploadTranslations', self.url_prefix, 'myapp', 'localhost:8080', '--job_args=%s' % self.zipfile_name] with self.assertRaises(SystemExit): etl.main( etl.create_args_parser().parse_args(args), environment_class=testing.FakeEnvironment) self.assertIn('File does not exist', self.get_log()) def test_dies_if_path_has_bad_file_extension(self): args = [ 'run', 'modules.i18n_dashboard.jobs.UploadTranslations', self.url_prefix, 'myapp', 'localhost:8080', '--job_args=%s' % self.zipfile_name + '.bad'] with self.assertRaises(SystemExit): etl.main( etl.create_args_parser().parse_args(args), environment_class=testing.FakeEnvironment) self.assertIn('Invalid file extension: ".bad"', self.get_log()) def test_dies_if_cannot_get_app_context_for_course_url_prefix(self): self.create_zip_file('contents') args = [ 'run', 'modules.i18n_dashboard.jobs.UploadTranslations', '/bad' + self.url_prefix, 'myapp', 'localhost:8080', '--job_args=%s' % self.zipfile_name] with self.assertRaises(SystemExit): etl.main( etl.create_args_parser().parse_args(args), environment_class=testing.FakeEnvironment) self.assertIn( 'Unable to find course with url prefix', self.get_log()) def test_processes_pofile(self): self._import_course() self.run_translate_job() response = self.get('first/dashboard?action=i18n_dashboard') self.assert_ln_locale_in_course(response) self.run_download_job() self.assert_zipfile_contains_only_ln_locale(self.zipfile_name) self.run_delete_job() response = self.get('first/dashboard?action=i18n_dashboard') self.assert_ln_locale_not_in_course(response) for po_file in self.extract_zipfile(): self.run_upload_job('--job_args=' + po_file) response = self.get('first/dashboard?action=i18n_dashboard') self.assert_ln_locale_in_course(response) def test_processes_zipfile(self): self._import_course() self.run_translate_job() response = self.get('first/dashboard?action=i18n_dashboard') self.assert_ln_locale_in_course(response) self.run_download_job() self.assert_zipfile_contains_only_ln_locale(self.zipfile_name) self.run_delete_job() response = self.get('first/dashboard?action=i18n_dashboard') self.assert_ln_locale_not_in_course(response) self.run_upload_job() response = self.get('first/dashboard?action=i18n_dashboard') self.assert_ln_locale_in_course(response) class RoundTripTest(_JobTestBase): """Tests translate -> download -> delete -> upload.""" def test_round_trip(self): self._import_course() response = self.get('first/dashboard?action=i18n_dashboard') self.assert_ln_locale_not_in_course(response) self.run_translate_job() response = self.get('first/dashboard?action=i18n_dashboard') self.assert_ln_locale_in_course(response) self.run_download_job() self.assert_zipfile_contains_only_ln_locale(self.zipfile_name) self.run_delete_job() response = self.get('first/dashboard?action=i18n_dashboard') self.assert_ln_locale_not_in_course(response) self.run_upload_job() response = self.get('first/dashboard?action=i18n_dashboard') self.assert_ln_locale_in_course(response)
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the math module.""" __author__ = ['Gun Pinyo (gunpinyo@google.com)', 'Neema Kotonya (neemak@google.com)'] from models import courses from tests.functional import actions COURSE_NAME = 'math_tag_test_course' ADMIN_EMAIL = 'user@test.com' MATHJAX_SCRIPT = """<script src="/modules/math/MathJax/MathJax.js?config=\ TeX-AMS-MML_HTMLorMML">""" LATEX_SCRIPT = """<script type="math/tex">x^2+2x+1</script>""" class MathTagTests(actions.TestBase): """Tests for the math content tag.""" def setUp(self): super(MathTagTests, self).setUp() actions.login(ADMIN_EMAIL, is_admin=True) self.base = '/' + COURSE_NAME test_course = actions.simple_add_course(COURSE_NAME, ADMIN_EMAIL, 'Test Course') self.course = courses.Course(None, test_course) math_unit = self.course.add_unit() math_unit.title = 'math_test_unit' no_math_unit = self.course.add_unit() no_math_unit.title = 'no_math_test_unit' self.math_unit_id = math_unit.unit_id self.no_math_unit_id = no_math_unit.unit_id no_math_lesson = self.course.add_lesson(no_math_unit) no_math_lesson.title = 'Lesson without any mathematical formula.' no_math_lesson.objectives = 'This lesson does not contain a math tag.' math_lesson = self.course.add_lesson(math_unit) math_lesson.title = 'First lesson with mathematical formula' math_lesson.objectives = ( '<gcb-math input_type="TeX" instanceid="X99HibNGBIX4">' 'x^2+2x+1' '</gcb-math><br>') self.course.save() def _search_element_lesson_body(self, search_element, assert_function, unit_id): """Base method for test_math_not_loaded() and test_math_loaded().""" for lesson in self.course.get_lessons(unit_id): response = self.get('unit?unit=%s&lesson=%s' % (unit_id, lesson.lesson_id)) assert_function(search_element, response.body) def test_mathjax_library_not_loaded_when_no_math_tag_present(self): self._search_element_lesson_body(MATHJAX_SCRIPT, actions.assert_does_not_contain, self.no_math_unit_id) def test_mathjax_library_is_loaded_when_math_tag_present(self): self._search_element_lesson_body(MATHJAX_SCRIPT, actions.assert_contains , self.math_unit_id) def test_same_formula_body(self): self._search_element_lesson_body(LATEX_SCRIPT, actions.assert_contains, self.math_unit_id)
Python
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # @author: psimakov@google.com (Pavel Simakov) """A collection of actions for testing Course Builder pages.""" import cgi import functools import logging import os import re import urllib from xml.etree import cElementTree import html5lib import appengine_config from controllers import sites from controllers import utils import main from models import config from models import courses from models import custom_modules from models import transforms from models import vfs from tests import suite from google.appengine.api import memcache from google.appengine.api import namespace_manager from google.appengine.api import users # All URLs referred to from all the pages. UNIQUE_URLS_FOUND = {} BASE_HOOK_POINTS = [ '<!-- base.before_head_tag_ends -->', '<!-- base.after_body_tag_begins -->', '<!-- base.after_navbar_begins -->', '<!-- base.before_navbar_ends -->', '<!-- base.after_top_content_ends -->', '<!-- base.after_main_content_ends -->', '<!-- base.before_body_tag_ends -->'] UNIT_HOOK_POINTS = [ '<!-- unit.after_leftnav_begins -->', '<!-- unit.before_leftnav_ends -->', '<!-- unit.after_content_begins -->', '<!-- unit.before_content_ends -->'] PREVIEW_HOOK_POINTS = [ '<!-- preview.after_top_content_ends -->', '<!-- preview.after_main_content_ends -->'] class MockAppContext(object): def __init__(self, environ=None, namespace=None, slug=None): self.environ = environ or {} self.namespace = namespace if namespace is not None else 'namespace' self.slug = slug if slug is not None else 'slug' self.fs = vfs.AbstractFileSystem( vfs.LocalReadOnlyFileSystem(logical_home_folder='/')) def get_environ(self): return self.environ def get_namespace_name(self): return self.namespace def get_slug(self): return self.slug class MockHandler(object): def __init__(self, app_context=None, base_href=None): self.app_context = app_context or MockAppContext() self.base_href = base_href or 'http://mycourse.appspot.com/' def get_base_href(self, unused_handler): return self.base_href + self.app_context.slug + '/' class ShouldHaveFailedByNow(Exception): """Special exception raised when a prior method did not raise.""" pass class OverriddenEnvironment(object): """Override the course environment from course.yaml with values in a dict. Usage: Use the class in a with statement as follows: with OverridenEnvironment({'course': {'browsable': True}}): # calls to Course.get_environ will return a dictionary # in which the original value of course/browsable has been # shadowed. """ def __init__(self, new_env): self._old_get_environ = courses.Course.get_environ self._new_env = new_env def _get_environ(self, app_context): return courses.deep_dict_merge( self._new_env, self._old_get_environ(app_context)) def __enter__(self): courses.Course.get_environ = self._get_environ def __exit__(self, *unused_exception_info): courses.Course.get_environ = self._old_get_environ return False class OverriddenConfig(object): """Override a ConfigProperty value within a scope. Usage: def test_welcome_page(self): with OverriddenConfig(sites.GCB_COURSES_CONFIG.name, ''): .... test content needing to believe there are no courses.... """ def __init__(self, name, value): self._name = name self._value = value self._had_prev_value = False self._prev_value = None def __enter__(self): self._had_prev_value = self._name in config.Registry.test_overrides self._prev_value = config.Registry.test_overrides.get(self._name) config.Registry.test_overrides[self._name] = self._value def __exit__(self, *unused_exception_info): if not self._had_prev_value: del config.Registry.test_overrides[self._name] else: config.Registry.test_overrides[self._name] = self._prev_value class TestBase(suite.AppEngineTestBase): """Contains methods common to all functional tests.""" last_request_url = None def getApp(self): main.debug = True sites.ApplicationRequestHandler.bind(main.namespaced_routes) return main.app def assert_default_namespace(self): ns = namespace_manager.get_namespace() if ns != appengine_config.DEFAULT_NAMESPACE_NAME: raise Exception('Expected default namespace, found: %s' % ns) def get_auto_deploy(self): return True def setUp(self): super(TestBase, self).setUp() memcache.flush_all() sites.ApplicationContext.clear_per_process_cache() self.auto_deploy = sites.ApplicationContext.AUTO_DEPLOY_DEFAULT_COURSE sites.ApplicationContext.AUTO_DEPLOY_DEFAULT_COURSE = ( self.get_auto_deploy()) self.supports_editing = False self.assert_default_namespace() self.namespace = '' self.base = '/' # Reload all properties now to flush the values modified in other tests. config.Registry.get_overrides(True) def tearDown(self): self.assert_default_namespace() sites.ApplicationContext.AUTO_DEPLOY_DEFAULT_COURSE = self.auto_deploy super(TestBase, self).tearDown() def canonicalize(self, href, response=None): """Create absolute URL using <base> if defined, self.base otherwise.""" if href.startswith('/') or utils.ApplicationHandler.is_absolute(href): pass else: base = self.base if response: match = re.search( r'<base href=[\'"]?([^\'" >]+)', response.body) if match and not href.startswith('/'): base = match.groups()[0] if not base.endswith('/'): base += '/' href = '%s%s' % (base, href) self.audit_url(href) return href def audit_url(self, url): """Record for audit purposes the URL we encountered.""" UNIQUE_URLS_FOUND[url] = True def hook_response(self, response): """Modify response.goto() to compute URL using <base>, if defined.""" if response.status_int == 200: self.check_response_hrefs(response) self.last_request_url = self.canonicalize(response.request.path) gotox = response.goto def new_goto(href, method='get', **args): return gotox(self.canonicalize(href), method, **args) response.goto = new_goto return response def check_response_hrefs(self, response): """Check response page URLs are properly formatted/canonicalized.""" hrefs = re.findall(r'href=[\'"]?([^\'" >]+)', response.body) srcs = re.findall(r'src=[\'"]?([^\'" >]+)', response.body) for url in hrefs + srcs: # We expect all internal URLs to be relative: 'asset/css/main.css', # and use <base> tag. All others URLs must be whitelisted below. if url.startswith('/'): absolute = url.startswith('//') root = url == '/' canonical = url.startswith(self.base) allowed = self.url_allowed(url) if not (absolute or root or canonical or allowed): raise Exception('Invalid reference \'%s\' in:\n%s' % ( url, response.body)) self.audit_url(self.canonicalize(url, response=response)) def url_allowed(self, url): """Check whether a URL should be allowed as a href in the response.""" if url.startswith('/_ah/'): return True global_routes = [] for module in custom_modules.Registry.registered_modules.values(): for route, unused_handler in module.global_routes: global_routes.append(route) if any(re.match(route, url) for route in global_routes): return True return False def parse_html_string(self, html_str): """Parse the given HTML string to a XML DOM tree. Args: html_str: string. The HTML document to be parsed. Returns: An ElementTree representation of the DOM. """ parser = html5lib.HTMLParser( tree=html5lib.treebuilders.getTreeBuilder('etree', cElementTree), namespaceHTMLElements=False) return parser.parse(html_str) def execute_all_deferred_tasks(self, queue_name='default', iteration_limit=None): """Executes all pending deferred tasks.""" # Outer loop here because some tasks (esp. map/reduce) will enqueue # more tasks as part of their operation. tasks_executed = 0 while iteration_limit is None or iteration_limit > 0: tasks = self.taskq.GetTasks(queue_name) if not tasks: break for task in tasks: old_namespace = namespace_manager.get_namespace() try: self.task_dispatcher.dispatch_task(task) tasks_executed += 1 finally: if sites.has_path_info(): sites.unset_path_info() namespace_manager.set_namespace(old_namespace) if iteration_limit: iteration_limit -= 1 return tasks_executed def get(self, url, previous_response=None, **kwargs): url = self.canonicalize(url, response=previous_response) logging.info('HTTP Get: %s', url) response = self.testapp.get(url, **kwargs) return self.hook_response(response) def post(self, url, params, expect_errors=False, upload_files=None): url = self.canonicalize(url) logging.info('HTTP Post: %s', url) response = self.testapp.post(url, params, expect_errors=expect_errors, upload_files=upload_files) return self.hook_response(response) def put(self, url, params, expect_errors=False): url = self.canonicalize(url) logging.info('HTTP Put: %s', url) response = self.testapp.put(url, params, expect_errors=expect_errors) return self.hook_response(response) def delete(self, url, expect_errors=False): url = self.canonicalize(url) logging.info('HTTP Delete: %s', url) response = self.testapp.delete(url, expect_errors=expect_errors) return self.hook_response(response) def click(self, response, name, expect_errors=False): links = self.parse_html_string(response.body).findall('.//a') for link in links: if link.text and link.text.strip() == name: return self.get(link.get('href'), response, expect_errors=expect_errors) complaint = 'No link with text "%s" found on page.\n' % name for link in links: if link.text: complaint += 'Possible link text: "%s"\n' % link.text.strip() raise ValueError(complaint) def submit(self, form, previous_response=None): logging.info('Form submit: %s', form) form.action = self.canonicalize(form.action, previous_response) response = form.submit() return self.hook_response(response) class ExportTestBase(TestBase): """Base test class for classes that implement export functionality. If your entities.BaseEntity class implements a custom for_export or safe_key, you probably want to test them with this TestCase. """ def assert_blacklisted_properties_removed(self, original_model, exported): for prop in original_model._get_export_blacklist(): self.assertFalse(hasattr(exported, prop)) def transform(self, value): return 'transformed_' + value def assert_equals(actual, expected): if expected != actual: raise Exception('Expected \'%s\', does not match actual \'%s\'.' % (expected, actual)) def to_unicode(text): """Converts text to Unicode if is not Unicode already.""" if not isinstance(text, unicode): return unicode(text, 'utf-8') return text def assert_contains(needle, haystack, collapse_whitespace=False): needle = to_unicode(needle) haystack = to_unicode(haystack) if collapse_whitespace: haystack = ' '.join(haystack.replace('\n', ' ').split()) if needle not in haystack: raise Exception('Can\'t find \'%s\' in \'%s\'.' % (needle, haystack)) def assert_contains_all_of(needles, haystack): haystack = to_unicode(haystack) for needle in needles: needle = to_unicode(needle) if needle not in haystack: raise Exception( 'Can\'t find \'%s\' in \'%s\'.' % (needle, haystack)) def assert_does_not_contain(needle, haystack, collapse_whitespace=False): needle = to_unicode(needle) haystack = to_unicode(haystack) if collapse_whitespace: haystack = ' '.join(haystack.replace('\n', ' ').split()) if needle in haystack: raise Exception('Found \'%s\' in \'%s\'.' % (needle, haystack)) def assert_contains_none_of(needles, haystack): haystack = to_unicode(haystack) for needle in needles: needle = to_unicode(needle) if needle in haystack: raise Exception('Found \'%s\' in \'%s\'.' % (needle, haystack)) def assert_none_fail(browser, callbacks): """Invokes all callbacks and expects each one not to fail.""" for callback in callbacks: callback(browser) def assert_at_least_one_succeeds(callbacks): """Invokes all callbacks and expects at least one to succeed.""" for callback in callbacks: try: callback() return True except Exception: # pylint: disable=broad-except pass raise Exception('All callbacks failed.') def assert_all_fail(browser, callbacks): """Invokes all callbacks and expects each one to fail.""" for callback in callbacks: try: callback(browser) raise ShouldHaveFailedByNow( 'Expected to fail: %s().' % callback.__name__) except ShouldHaveFailedByNow as e: raise e except Exception: # pylint: disable=broad-except pass def get_form_by_action(response, action): """Gets a form give an action string or returns None.""" form = None try: form = next( form for form in response.forms.values() if form.action == action) except StopIteration: pass return form def login(email, is_admin=False): os.environ['USER_EMAIL'] = email os.environ['USER_ID'] = email is_admin_value = '0' if is_admin: is_admin_value = '1' os.environ['USER_IS_ADMIN'] = is_admin_value def get_current_user_email(): email = os.environ['USER_EMAIL'] if not email: raise Exception('No current user.') return email def logout(): del os.environ['USER_EMAIL'] del os.environ['USER_ID'] del os.environ['USER_IS_ADMIN'] def in_course(course, url): if not course: return url return '%s/%s' % (course, url) def register(browser, name, course=None): """Registers a new student with the given name.""" response = view_registration(browser, course) register_form = get_form_by_action(response, 'register') register_form.set('form01', name) response = browser.submit(register_form, response) assert_equals(response.status_int, 302) assert_contains( 'course#registration_confirmation', response.headers['location']) check_profile(browser, name, course) return response def check_profile(browser, name, course=None): response = view_my_profile(browser, course) assert_contains('Email', response.body) assert_contains(cgi.escape(name), response.body) assert_contains(get_current_user_email(), response.body) return response def view_registration(browser, course=None): response = browser.get(in_course(course, 'register')) check_personalization(browser, response) assert_contains('What is your name?', response.body) assert_contains_all_of([ '<!-- reg_form.additional_registration_fields -->'], response.body) return response def register_with_additional_fields(browser, name, data2, data3): """Registers a new student with customized registration form.""" response = browser.get('/') assert_equals(response.status_int, 302) response = view_registration(browser) register_form = get_form_by_action(response, 'register') register_form.set('form01', name) register_form.set('form02', data2) register_form.set('form03', data3) response = browser.submit(register_form) assert_equals(response.status_int, 302) assert_contains( 'course#registration_confirmation', response.headers['location']) check_profile(browser, name) def check_logout_link(response_body): assert_contains(get_current_user_email(), response_body) def check_login_link(response_body): assert_contains('Login', response_body) def check_personalization(browser, response): """Checks that the login/logout text is correct.""" sites.set_path_info(browser.last_request_url) app_context = sites.get_course_for_current_request() sites.unset_path_info() browsable = app_context.get_environ()['course']['browsable'] if browsable: callbacks = [ functools.partial(check_login_link, response.body), functools.partial(check_logout_link, response.body) ] assert_at_least_one_succeeds(callbacks) else: check_logout_link(response.body) def view_preview(browser): """Views /preview page.""" response = browser.get('preview') assert_contains(' the stakes are high.', response.body) assert_contains( '<li class=\'\'><p class="gcb-top-content"> ' '<span class="gcb-progress-none"></span> ' 'Pre-course assessment </p> </li>', response.body, collapse_whitespace=True) assert_contains_none_of(UNIT_HOOK_POINTS, response.body) assert_contains_all_of(PREVIEW_HOOK_POINTS, response.body) return response def view_course(browser): """Views /course page.""" response = browser.get('course') assert_contains(' the stakes are high.', response.body) assert_contains('<a href="assessment?name=Pre">Pre-course assessment</a>', response.body) check_personalization(browser, response) assert_contains_all_of(BASE_HOOK_POINTS, response.body) assert_contains_none_of(UNIT_HOOK_POINTS, response.body) assert_contains_none_of(PREVIEW_HOOK_POINTS, response.body) return response def view_unit(browser): """Views /unit page.""" response = browser.get('unit?unit=1&lesson=1') assert_contains('Unit 1 - Introduction', response.body) assert_contains('1.3 How search works', response.body) assert_contains('1.6 Finding text on a web page', response.body) assert_contains('https://www.youtube.com/embed/1ppwmxidyIE', response.body) check_personalization(browser, response) assert_contains_all_of(BASE_HOOK_POINTS, response.body) assert_contains_all_of(UNIT_HOOK_POINTS, response.body) assert_contains_none_of(PREVIEW_HOOK_POINTS, response.body) return response def view_activity(browser): response = browser.get('activity?unit=1&lesson=2') assert_contains('<script src="assets/js/activity-1.2.js"></script>', response.body) check_personalization(browser, response) return response def get_activity(browser, unit_id, lesson_id, args): """Retrieve the activity page for a given unit and lesson id.""" response = browser.get('activity?unit=%s&lesson=%s' % (unit_id, lesson_id)) assert_equals(response.status_int, 200) assert_contains( '<script src="assets/js/activity-%s.%s.js"></script>' % (unit_id, lesson_id), response.body) assert_contains('assets/lib/activity-generic-1.3.js', response.body) js_response = browser.get('assets/lib/activity-generic-1.3.js') assert_equals(js_response.status_int, 200) # Extract XSRF token from the page. match = re.search(r'eventXsrfToken = [\']([^\']+)', response.body) assert match xsrf_token = match.group(1) args['xsrf_token'] = xsrf_token return response, args def attempt_activity(browser, unit_id, lesson_id, index, answer, correct): """Attempts an activity in a given unit and lesson.""" response, args = get_activity(browser, unit_id, lesson_id, {}) # Prepare activity submission event. args['source'] = 'attempt-activity' args['payload'] = { 'index': index, 'type': 'activity-choice', 'value': answer, 'correct': correct } args['payload']['location'] = ( 'http://localhost:8080/activity?unit=%s&lesson=%s' % (unit_id, lesson_id)) args['payload'] = transforms.dumps(args['payload']) # Submit the request to the backend. response = browser.post('rest/events?%s' % urllib.urlencode( {'request': transforms.dumps(args)}), {}) assert_equals(response.status_int, 200) assert not response.body def view_announcements(browser): response = browser.get('announcements') assert_equals(response.status_int, 200) return response def view_my_profile(browser, course=None): response = browser.get(in_course(course, 'student/home')) assert_contains('Date enrolled', response.body) check_personalization(browser, response) return response def view_forum(browser): response = browser.get('forum') assert_contains('document.getElementById("forum_embed").src =', response.body) check_personalization(browser, response) return response def view_assessments(browser): for name in ['Pre', 'Mid', 'Fin']: response = browser.get('assessment?name=%s' % name) assert 'assets/js/assessment-%s.js' % name in response.body assert_equals(response.status_int, 200) check_personalization(browser, response) def submit_assessment(browser, unit_id, args, presubmit_checks=True): """Submits an assessment.""" course = None for app_context in sites.get_all_courses(): if app_context.get_slug() == browser.base: course = courses.Course(None, app_context=app_context) break assert course is not None, 'browser.base must match a course' if course.version == courses.COURSE_MODEL_VERSION_1_3: parent = course.get_parent_unit(unit_id) if parent is not None: response = browser.get( 'unit?unit=%s&assessment=%s' % (parent.unit_id, unit_id)) else: response = browser.get('assessment?name=%s' % unit_id) elif course.version == courses.COURSE_MODEL_VERSION_1_2: response = browser.get('assessment?name=%s' % unit_id) if presubmit_checks: assert_contains( '<script src="assets/js/assessment-%s.js"></script>' % unit_id, response.body) js_response = browser.get('assets/js/assessment-%s.js' % unit_id) assert_equals(js_response.status_int, 200) # Extract XSRF token from the page. match = re.search(r'assessmentXsrfToken = [\']([^\']+)', response.body) assert match xsrf_token = match.group(1) args['xsrf_token'] = xsrf_token response = browser.post('answer', args) assert_equals(response.status_int, 200) return response def request_new_review(browser, unit_id, expected_status_code=302): """Requests a new assignment to review.""" response = browser.get('reviewdashboard?unit=%s' % unit_id) assert_contains('Assignments for your review', response.body) # Extract XSRF token from the page. match = re.search( r'<input type="hidden" name="xsrf_token"\s* value="([^"]*)">', response.body) assert match xsrf_token = match.group(1) args = {'xsrf_token': xsrf_token} expect_errors = (expected_status_code not in [200, 302]) response = browser.post( 'reviewdashboard?unit=%s' % unit_id, args, expect_errors=expect_errors) assert_equals(response.status_int, expected_status_code) if expected_status_code == 302: assert_equals(response.status_int, expected_status_code) assert_contains( 'review?unit=%s' % unit_id, response.location) response = browser.get(response.location) assert_contains('Assignment to review', response.body) return response def view_review(browser, unit_id, review_step_key, expected_status_code=200): """View a review page.""" response = browser.get( 'review?unit=%s&key=%s' % (unit_id, review_step_key), expect_errors=(expected_status_code != 200)) assert_equals(response.status_int, expected_status_code) if expected_status_code == 200: assert_contains('Assignment to review', response.body) return response def submit_review( browser, unit_id, review_step_key, args, presubmit_checks=True): """Submits a review.""" response = browser.get( 'review?unit=%s&key=%s' % (unit_id, review_step_key)) if presubmit_checks: assert_contains( '<script src="assets/js/review-%s.js"></script>' % unit_id, response.body) js_response = browser.get('assets/js/review-%s.js' % unit_id) assert_equals(js_response.status_int, 200) # Extract XSRF token from the page. match = re.search(r'assessmentXsrfToken = [\']([^\']+)', response.body) assert match xsrf_token = match.group(1) args['xsrf_token'] = xsrf_token args['key'] = review_step_key args['unit_id'] = unit_id response = browser.post('review', args) assert_equals(response.status_int, 200) return response def add_reviewer(browser, unit_id, reviewee_email, reviewer_email): """Adds a reviewer to a submission.""" url_params = { 'action': 'edit_assignment', 'reviewee_id': reviewee_email, 'unit_id': unit_id, } response = browser.get('/dashboard?%s' % urllib.urlencode(url_params)) # Extract XSRF token from the page. match = re.search( r'<input type="hidden" name="xsrf_token"\s* value="([^"]*)">', response.body) assert match xsrf_token = match.group(1) args = { 'xsrf_token': xsrf_token, 'reviewer_id': reviewer_email, 'reviewee_id': reviewee_email, 'unit_id': unit_id, } response = browser.post('/dashboard?action=add_reviewer', args) return response def change_name(browser, new_name): """Change the name of a student.""" response = browser.get('student/home') edit_form = get_form_by_action(response, 'student/editstudent') edit_form.set('name', new_name) response = browser.submit(edit_form) assert_equals(response.status_int, 302) check_profile(browser, new_name) def unregister(browser, course=None): """Unregister a student.""" if course: response = browser.get('/%s/student/home' % course) else: response = browser.get('student/home') response = browser.click(response, 'Unenroll') assert_contains('to unenroll from', response.body) unregister_form = get_form_by_action(response, 'student/unenroll') browser.submit(unregister_form, response) class Permissions(object): """Defines who can see what.""" @classmethod def get_browsable_pages(cls): """Returns all pages that can be accessed by a logged-out user.""" return [view_announcements, view_forum, view_course, view_unit, view_assessments, view_activity] @classmethod def get_nonbrowsable_pages(cls): """Returns all non-browsable pages.""" return [view_preview, view_my_profile, view_registration] @classmethod def get_logged_out_allowed_pages(cls): """Returns all pages that a logged-out user can see.""" return [view_announcements, view_preview] @classmethod def get_logged_out_denied_pages(cls): """Returns all pages that a logged-out user can't see.""" return [view_forum, view_course, view_assessments, view_unit, view_activity, view_my_profile, view_registration] @classmethod def get_enrolled_student_allowed_pages(cls): """Returns all pages that a logged-in, enrolled student can see.""" return [view_announcements, view_forum, view_course, view_assessments, view_unit, view_activity, view_my_profile] @classmethod def get_enrolled_student_denied_pages(cls): """Returns all pages that a logged-in, enrolled student can't see.""" return [view_registration, view_preview] @classmethod def get_unenrolled_student_allowed_pages(cls): """Returns all pages that a logged-in, unenrolled student can see.""" return [view_announcements, view_registration, view_preview] @classmethod def get_unenrolled_student_denied_pages(cls): """Returns all pages that a logged-in, unenrolled student can't see.""" pages = Permissions.get_enrolled_student_allowed_pages() for allowed in Permissions.get_unenrolled_student_allowed_pages(): if allowed in pages: pages.remove(allowed) return pages @classmethod def assert_can_browse(cls, browser): """Check that pages for a browsing user are visible.""" assert_none_fail(browser, Permissions.get_browsable_pages()) assert_all_fail(browser, Permissions.get_nonbrowsable_pages()) @classmethod def assert_logged_out(cls, browser): """Check that only pages for a logged-out user are visible.""" assert_none_fail(browser, Permissions.get_logged_out_allowed_pages()) assert_all_fail(browser, Permissions.get_logged_out_denied_pages()) @classmethod def assert_enrolled(cls, browser): """Check that only pages for an enrolled student are visible.""" assert_none_fail( browser, Permissions.get_enrolled_student_allowed_pages()) assert_all_fail( browser, Permissions.get_enrolled_student_denied_pages()) @classmethod def assert_unenrolled(cls, browser): """Check that only pages for an unenrolled student are visible.""" assert_none_fail( browser, Permissions.get_unenrolled_student_allowed_pages()) assert_all_fail( browser, Permissions.get_unenrolled_student_denied_pages()) def update_course_config(name, settings): """Merge settings into the saved course.yaml configuration. Args: name: Name of the course. E.g., 'my_test_course'. settings: A nested dict of name/value settings. Names for items here can be found in modules/dashboard/course_settings.py in create_course_registry. See below in simple_add_course() for an example. Returns: Context object for the modified course. """ site_type = 'course' namespace = 'ns_%s' % name slug = '/%s' % name rule = '%s:%s::%s' % (site_type, slug, namespace) context = sites.get_all_courses(rule)[0] environ = courses.deep_dict_merge(settings, courses.Course.get_environ(context)) course = courses.Course(handler=None, app_context=context) course.save_settings(environ) course_config = config.Registry.test_overrides.get( sites.GCB_COURSES_CONFIG.name, 'course:/:/') if rule not in course_config: course_config = '%s, %s' % (rule, course_config) sites.setup_courses(course_config) return context def update_course_config_as_admin(name, admin_email, settings): """Log in as admin and merge settings into course.yaml.""" prev_user = users.get_current_user() if not prev_user: login(admin_email, is_admin=True) elif prev_user.email() != admin_email: logout() login(admin_email, is_admin=True) ret = update_course_config(name, settings) if not prev_user: logout() elif prev_user and prev_user.email() != admin_email: logout() login(prev_user.email()) return ret def simple_add_course(name, admin_email, title): """Convenience wrapper to add an active course.""" return update_course_config_as_admin( name, admin_email, { 'course': { 'title': title, 'admin_user_emails': admin_email, 'now_available': True, 'browsable': True, }, })
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Functional tests for models/jobs.py.""" __author__ = [ 'mgainer@google.com (Mike Gainer)', ] from common.utils import Namespace from models import jobs from models import transforms from tests.functional import actions from google.appengine.ext import db TEST_NAMESPACE = 'test' TEST_DATA = {'bunny_names': ['flopsy', 'mopsy', 'cottontail']} TEST_DURATION = 123 TEST_BAD_DATA = {'wolf_actions': ['huff', 'puff', 'blow your house down']} TEST_BAD_DURATION = 4 class MockAppContext(object): def __init__(self, namespace): self._namespace = namespace def get_namespace_name(self): return self._namespace class TestJob(jobs.DurableJobBase): def __init__(self, namespace): super(TestJob, self).__init__(MockAppContext(namespace)) def force_start_job(self, sequence_num): with Namespace(self._namespace): db.run_in_transaction( jobs.DurableJobEntity._start_job, self._job_name, sequence_num) def force_complete_job(self, sequence_num, data, duration): data = transforms.dumps(data) with Namespace(self._namespace): db.run_in_transaction( jobs.DurableJobEntity._complete_job, self._job_name, sequence_num, data, duration) def force_fail_job(self, sequence_num, data, duration): data = transforms.dumps(data) with Namespace(self._namespace): db.run_in_transaction( jobs.DurableJobEntity._fail_job, self._job_name, sequence_num, data, duration) def get_output(self): return transforms.loads(self.load().output) class JobOperationsTest(actions.TestBase): """Validate operation of job behaviors.""" def setUp(self): super(JobOperationsTest, self).setUp() self.test_job = TestJob(TEST_NAMESPACE) # --------------------------------------------------------------------- # Tests with no item in datastore def test_load_finds_none(self): self.assertIsNone(self.test_job.load()) def test_cancel_finds_none(self): self.assertIsNone(self.test_job.cancel()) def test_not_active(self): self.assertFalse(self.test_job.is_active()) # --------------------------------------------------------------------- # Normal operation w/ no admin intervention def test_submit_enqueues_job(self): self.assertFalse(self.test_job.is_active()) self.test_job.submit() self.assertTrue(self.test_job.is_active()) self.assertEquals(jobs.STATUS_CODE_QUEUED, self.test_job.load().status_code) def test_start_starts_job(self): self.assertFalse(self.test_job.is_active()) sequence_num = self.test_job.submit() self.test_job.force_start_job(sequence_num) self.assertTrue(self.test_job.is_active()) self.assertEquals(jobs.STATUS_CODE_STARTED, self.test_job.load().status_code) def test_complete_job_saves_result(self): self._test_saves_result(self.test_job.force_complete_job, jobs.STATUS_CODE_COMPLETED) def test_fail_job_saves_result(self): self._test_saves_result(self.test_job.force_fail_job, jobs.STATUS_CODE_FAILED) def _test_saves_result(self, func, expected_status): self.assertFalse(self.test_job.is_active()) sequence_num = self.test_job.submit() self.test_job.force_start_job(sequence_num) self.assertIsNone(self.test_job.load().output) func(sequence_num, TEST_DATA, TEST_DURATION) self.assertFalse(self.test_job.is_active()) self.assertEquals(expected_status, self.test_job.load().status_code) self.assertEquals(TEST_DATA, self.test_job.get_output()) self.assertEquals(TEST_DURATION, self.test_job.load().execution_time_sec) def test_submit_does_not_restart_running_job(self): sequence_num = self.test_job.submit() self.test_job.force_start_job(sequence_num) next_seq = self.test_job.submit() self.assertEquals(next_seq, -1) # Check status is still STARTED, not QUEUED, which it would be # if we'd started the job anew. self.assertEquals(jobs.STATUS_CODE_STARTED, self.test_job.load().status_code) # -------------------------------------------------------------------- # Cancelling jobs def test_cancel_kills_queued_job(self): self.assertFalse(self.test_job.is_active()) self.test_job.submit() self.test_job.cancel() self.assertFalse(self.test_job.is_active()) self.assertIn('Canceled by default', self.test_job.load().output) self.assertEquals(jobs.STATUS_CODE_FAILED, self.test_job.load().status_code) def test_cancel_kills_started_job(self): self.assertFalse(self.test_job.is_active()) sequence_num = self.test_job.submit() self.test_job.force_start_job(sequence_num) self.test_job.cancel() self.assertFalse(self.test_job.is_active()) self.assertEquals(jobs.STATUS_CODE_FAILED, self.test_job.load().status_code) def test_cancel_does_not_kill_completed_job(self): sequence_num = self.test_job.submit() self.test_job.force_start_job(sequence_num) self.test_job.force_complete_job(sequence_num, TEST_DATA, TEST_DURATION) self.assertFalse(self.test_job.is_active()) self.test_job.cancel() self.assertEquals(jobs.STATUS_CODE_COMPLETED, self.test_job.load().status_code) def test_killed_job_can_still_complete(self): self._killed_job_can_still_record_results( self.test_job.force_complete_job, jobs.STATUS_CODE_COMPLETED) def test_killed_job_can_still_fail(self): self._killed_job_can_still_record_results( self.test_job.force_fail_job, jobs.STATUS_CODE_FAILED) def _killed_job_can_still_record_results(self, func, expected_status): sequence_num = self.test_job.submit() self.test_job.force_start_job(sequence_num) self.test_job.cancel() self.assertIn('Canceled by default', self.test_job.load().output) self.assertEquals(jobs.STATUS_CODE_FAILED, self.test_job.load().status_code) func(sequence_num, TEST_DATA, TEST_DURATION) self.assertEquals(expected_status, self.test_job.load().status_code) self.assertEquals(TEST_DATA, self.test_job.get_output()) self.assertEquals(TEST_DURATION, self.test_job.load().execution_time_sec) # -------------------------------------------------------------------- # Results from older runs are ignored, even if a seemingly-hung job # later completes or fails. def test_kill_and_restart_job_old_job_completes(self): self._test_kill_and_restart(self.test_job.force_complete_job) def test_kill_and_restart_job_old_job_fails(self): self._test_kill_and_restart(self.test_job.force_fail_job) def _test_kill_and_restart(self, func): sequence_num = self.test_job.submit() self.test_job.force_start_job(sequence_num) self.test_job.cancel() sequence_num_2 = self.test_job.submit() self.assertEquals(sequence_num_2, sequence_num + 1) self.test_job.force_start_job(sequence_num_2) self.test_job.force_complete_job(sequence_num_2, TEST_DATA, TEST_DURATION) # Now try to complete the (long-running) first try. # Results from previous run should not overwrite more-recent. func(sequence_num, TEST_BAD_DATA, TEST_BAD_DURATION) self.assertEquals(TEST_DATA, self.test_job.get_output()) self.assertEquals(TEST_DURATION, self.test_job.load().execution_time_sec)
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Verify operation of custom tags from core_tags module.""" __author__ = 'Mike Gainer (mgainer@google.com)' import os import StringIO import appengine_config from controllers import sites from models import config from models import courses from models import models from models import transforms from modules.core_tags import core_tags from tests.functional import actions COURSE_NAME = 'test_course' COURSE_TITLE = 'Test Course' ADMIN_EMAIL = 'test@example.com' PRE_INCLUDE = 'XXX' POST_INCLUDE = 'YYY' HTML_DIR = os.path.join(appengine_config.BUNDLE_ROOT, 'assets/html') HTML_FILE = 'test.html' HTML_PATH = os.path.join(HTML_DIR, HTML_FILE) GCB_INCLUDE = (PRE_INCLUDE + '<gcb-include path="/assets/html/%s" ' + 'instanceid="uODxjWHTxxIC"></gcb-include>' + POST_INCLUDE) LESSON_URL = '/test_course/unit?unit=1&lesson=2' class GoogleDriveTestBase(actions.TestBase): def tearDown(self): config.Registry.test_overrides = {} super(GoogleDriveTestBase, self).tearDown() def assert_404_response_with_empty_body(self, response): self.assertEqual(404, response.status_code) self.assertEqual('', response.body) def disable_courses_can_use_google_apis(self): config.Registry.test_overrides[ courses.COURSES_CAN_USE_GOOGLE_APIS.name] = False def enable_courses_can_use_google_apis(self): config.Registry.test_overrides[ courses.COURSES_CAN_USE_GOOGLE_APIS.name] = True def get_env(self, api_key=None, client_id=None): result = { courses._CONFIG_KEY_PART_COURSE: { courses._CONFIG_KEY_PART_GOOGLE: {} } } google_config = result.get( courses._CONFIG_KEY_PART_COURSE ).get( courses._CONFIG_KEY_PART_GOOGLE) if api_key is not None: google_config[courses._CONFIG_KEY_PART_API_KEY] = api_key if client_id is not None: google_config[courses._CONFIG_KEY_PART_CLIENT_ID] = client_id return result class RuntimeTest(GoogleDriveTestBase): def setUp(self): super(RuntimeTest, self).setUp() self.app_context = sites.get_all_courses()[0] self.api_key = 'api_key_value' self.client_id = 'client_id_value' self.email = 'admin@example.com' def tearDown(self): config.Registry.test_overrides = {} super(RuntimeTest, self).tearDown() def test_can_edit_false_if_user_is_not_logged_in(self): self.assertFalse(core_tags._Runtime(self.app_context).can_edit()) def test_can_edit_false_if_user_is_not_admin(self): actions.login(self.email, is_admin=False) self.assertFalse(core_tags._Runtime(self.app_context).can_edit()) def test_can_edit_true_if_user_is_admin(self): actions.login(self.email, is_admin=True) runtime = core_tags._Runtime(self.app_context) self.assertTrue(runtime.can_edit()) def test_configured_false_when_courses_cannot_use_google_apis(self): with actions.OverriddenEnvironment(self.get_env( api_key=self.api_key, client_id=self.client_id)): self.assertFalse(core_tags._Runtime(self.app_context).configured()) def test_configured_false_when_api_key_empty(self): self.enable_courses_can_use_google_apis() with actions.OverriddenEnvironment(self.get_env( client_id=self.client_id)): self.assertFalse(core_tags._Runtime(self.app_context).configured()) def test_configured_false_when_client_id_empty(self): self.enable_courses_can_use_google_apis() with actions.OverriddenEnvironment(self.get_env( api_key=self.api_key)): self.assertFalse(core_tags._Runtime(self.app_context).configured()) def test_configured_true_when_enabled_and_api_key_and_client_id_set(self): self.enable_courses_can_use_google_apis() with actions.OverriddenEnvironment(self.get_env( api_key=self.api_key, client_id=self.client_id)): self.assertTrue(core_tags._Runtime(self.app_context).configured()) def test_courses_cannot_use_google_apis_by_default(self): self.assertFalse( core_tags._Runtime(self.app_context).courses_can_use_google_apis()) def test_courses_can_use_google_apis_with_override(self): self.enable_courses_can_use_google_apis() self.assertTrue( core_tags._Runtime(self.app_context).courses_can_use_google_apis()) def test_get_api_key_returns_empty_string_when_not_set(self): self.assertEqual('', core_tags._Runtime(self.app_context).get_api_key()) def test_get_api_key_returns_expected_value_when_set(self): with actions.OverriddenEnvironment(self.get_env(api_key=self.api_key)): self.assertEqual( self.api_key, core_tags._Runtime(self.app_context).get_api_key()) def test_get_client_id_returns_empty_string_when_not_set(self): self.assertEqual( '', core_tags._Runtime(self.app_context).get_client_id()) def test_get_client_id_returns_expected_value_when_set(self): with actions.OverriddenEnvironment(self.get_env( client_id=self.client_id)): self.assertEqual( self.client_id, core_tags._Runtime(self.app_context).get_client_id()) class GoogleDriveRESTHandlerTest(GoogleDriveTestBase): def setUp(self): super(GoogleDriveRESTHandlerTest, self).setUp() self.content_type = 'text/html' self.contents = 'contents_value' self.document_id = 'document_id_value' self.type_id = 'type_id_value' self.xsrf_token = core_tags.GoogleDriveRESTHandler.get_xsrf_token() self.uid = models.ContentChunkDAO.make_uid( self.type_id, self.document_id) self.enable_courses_can_use_google_apis() def assert_response(self, code, body_needle, response): from_json = transforms.loads(response.body) self.assertEqual(200, response.status_code) self.assertEqual(code, from_json['status']) self.assertIn(body_needle, from_json['message']) def assert_200_response(self, response): self.assert_response(200, 'Success.', response) def assert_400_response_type_id_not_set(self, response): self.assert_response(400, 'type_id not set', response) def assert_400_response_no_item_chosen(self, response): self.assert_response(400, 'no Google Drive item chosen', response) def assert_403_response(self, response): self.assert_response(403, 'Bad XSRF token', response) def assert_500_response(self, body_needle, response): self.assert_response(500, body_needle, response) def _get_payload(self, body): return transforms.loads(body) def _make_params(self, params): return {'request': transforms.dumps(params)} def test_put_returns_200_and_creates_new_entity(self): params = self._make_params({ 'contents': self.contents, 'document_id': self.document_id, 'type_id': self.type_id, 'xsrf_token': self.xsrf_token, }) response = self.testapp.put( core_tags._GOOGLE_DRIVE_TAG_PATH, params=params) matches = models.ContentChunkDAO.get_by_uid(self.uid) created = matches[0] self.assert_200_response(response) self.assertEqual(1, len(matches)) self.assertEqual(self.contents, created.contents) self.assertEqual(self.document_id, created.resource_id) self.assertEqual(self.type_id, created.type_id) def test_put_returns_200_and_updates_existing_entity(self): models.ContentChunkDAO.save(models.ContentChunkDTO({ 'content_type': 'old_' + self.content_type, 'contents': 'old_' + self.contents, 'resource_id': self.document_id, 'type_id': self.type_id, })) params = self._make_params({ 'contents': self.contents, 'document_id': self.document_id, 'type_id': self.type_id, 'xsrf_token': self.xsrf_token, }) old_dto = models.ContentChunkDAO.get_by_uid(self.uid)[0] self.assertEqual('old_' + self.contents, old_dto.contents) self.assertEqual('old_' + self.content_type, old_dto.content_type) response = self.testapp.put( core_tags._GOOGLE_DRIVE_TAG_PATH, params=params) matches = models.ContentChunkDAO.get_by_uid(self.uid) created = matches[0] self.assert_200_response(response) self.assertEqual(1, len(matches)) self.assertEqual(self.contents, created.contents) self.assertEqual(self.document_id, created.resource_id) self.assertEqual(self.type_id, created.type_id) def test_put_returns_400_if_contents_not_set(self): params = self._make_params({ 'document_id': self.document_id, 'type_id': self.type_id, 'xsrf_token': self.xsrf_token, }) response = self.testapp.put( core_tags._GOOGLE_DRIVE_TAG_PATH, expect_errors=True, params=params) self.assert_400_response_no_item_chosen(response) def test_put_returns_400_if_document_id_not_set(self): params = self._make_params({ 'contents': self.contents, 'type_id': self.type_id, 'xsrf_token': self.xsrf_token, }) response = self.testapp.put( core_tags._GOOGLE_DRIVE_TAG_PATH, expect_errors=True, params=params) self.assert_400_response_no_item_chosen(response) def test_put_returns_400_if_type_id_not_set(self): params = self._make_params({ 'contents': self.contents, 'document_id': self.document_id, 'xsrf_token': self.xsrf_token, }) response = self.testapp.put( core_tags._GOOGLE_DRIVE_TAG_PATH, expect_errors=True, params=params) self.assert_400_response_type_id_not_set(response) def test_put_returns_403_if_xsrf_token_invalid(self): params = self._make_params({ 'xsrf_token': 'bad_' + self.xsrf_token, }) response = self.testapp.put( core_tags._GOOGLE_DRIVE_TAG_PATH, expect_errors=True, params=params) self.assert_403_response(response) def test_get_returns_404_if_courses_cannot_use_google_apis(self): self.disable_courses_can_use_google_apis() params = self._make_params({ 'contents': self.contents, 'document_id': self.document_id, 'type_id': self.type_id, 'xsrf_token': self.xsrf_token, }) response = self.testapp.put( core_tags._GOOGLE_DRIVE_TAG_PATH, expect_errors=True, params=params) self.assert_404_response_with_empty_body(response) def test_put_returns_500_if_save_throws(self): def throw( unused_self, unused_contents, unused_type_id, unused_document_id): raise ValueError('save failed') self.swap( core_tags.GoogleDriveRESTHandler, '_save_content_chunk', throw) params = self._make_params({ 'contents': self.contents, 'document_id': self.document_id, 'type_id': self.type_id, 'xsrf_token': self.xsrf_token, }) response = self.testapp.put( core_tags._GOOGLE_DRIVE_TAG_PATH, expect_errors=True, params=params) self.assert_500_response('save failed', response) class GoogleDriveTagRendererTest(GoogleDriveTestBase): def setUp(self): super(GoogleDriveTagRendererTest, self).setUp() self.contents = 'contents_value' self.resource_id = 'resource_id_value' self.type_id = 'type_id_value' dto = models.ContentChunkDTO({ 'content_type': 'text/html', 'contents': self.contents, 'resource_id': self.resource_id, 'type_id': self.type_id, }) self.uid = models.ContentChunkDAO.make_uid( self.type_id, self.resource_id) models.ContentChunkDAO.save(dto) self.dto = models.ContentChunkDAO.get_by_uid(self.uid) self.enable_courses_can_use_google_apis() def assert_response(self, code, body_needle, response): self.assertEqual(code, response.status_code) self.assertIn(body_needle, response.body) def assert_200_response(self, body_needle, response): self.assert_response(200, body_needle, response) def assert_400_response(self, response): self.assert_response(400, 'Bad request', response) def assert_404_response(self, response): self.assert_response(404, 'Content chunk not found', response) def test_get_returns_200_if_content_chunk_found(self): response = self.testapp.get( core_tags._GOOGLE_DRIVE_TAG_RENDERER_PATH, params={ 'resource_id': self.resource_id, 'type_id': self.type_id, }) self.assert_200_response(self.contents, response) def test_get_returns_200_with_first_chunk_if_multiple_matches(self): models.ContentChunkDAO.save(models.ContentChunkDTO({ 'content_type': 'text/html', 'contents': 'other contents', 'resource_id': self.resource_id, 'type_id': self.type_id, })) response = self.testapp.get( core_tags._GOOGLE_DRIVE_TAG_RENDERER_PATH, params={ 'resource_id': self.resource_id, 'type_id': self.type_id, }) self.assertEqual(2, len(models.ContentChunkDAO.get_by_uid(self.uid))) self.assert_200_response(self.contents, response) def test_get_returns_400_if_resource_id_missing(self): response = self.testapp.get( core_tags._GOOGLE_DRIVE_TAG_RENDERER_PATH, expect_errors=True, params={'type_id': self.type_id}) self.assert_400_response(response) def test_get_returns_400_if_type_id_missing(self): response = self.testapp.get( core_tags._GOOGLE_DRIVE_TAG_RENDERER_PATH, expect_errors=True, params={'resource_id': self.resource_id}) self.assert_400_response(response) def test_get_returns_404_if_content_chunk_not_found(self): response = self.testapp.get( core_tags._GOOGLE_DRIVE_TAG_RENDERER_PATH, expect_errors=True, params={ 'type_id': 'other_' + self.type_id, 'resource_id': 'other_' + self.resource_id, }) self.assert_404_response(response) def test_get_returns_404_if_courses_cannot_use_google_apis(self): self.disable_courses_can_use_google_apis() response = self.testapp.get( core_tags._GOOGLE_DRIVE_TAG_RENDERER_PATH, expect_errors=True, params={ 'type_id': 'other_' + self.type_id, 'resource_id': 'other_' + self.resource_id, }) self.assert_404_response_with_empty_body(response) class TagsMarkdown(actions.TestBase): def test_markdown(self): self.context = actions.simple_add_course(COURSE_NAME, ADMIN_EMAIL, COURSE_TITLE) self.course = courses.Course(None, self.context) self.unit = self.course.add_unit() self.unit.title = 'The Unit' self.unit.now_available = True self.lesson = self.course.add_lesson(self.unit) self.lesson.title = 'The Lesson' self.lesson.now_available = True self.lesson.objectives = ''' Welcome to Markdown! <gcb-markdown instanceid="BHpNAOMuLdMn"> # This is an H1 ## This is an H2 This is [an example](http://example.com/ &quot;Title&quot;) inline link. [This link](http://example.net/) has no title attribute. Text attributes *italic*, **bold**, `monospace`. Shopping list: * apples * oranges * pears Numbered list: 1. apples 2. oranges 3. pears </gcb-markdown><br>''' self.course.save() response = self.get(LESSON_URL) self.assertIn('<h1>This is an H1</h1>', response.body) self.assertIn('<h2>This is an H2</h2>', response.body) self.assertIn( '<p><a href="http://example.net/">This link</a> ' 'has no title attribute.</p>', response.body) self.assertIn('<em>italic</em>', response.body) self.assertIn('<strong>bold</strong>', response.body) self.assertIn('<code>monospace</code>', response.body) self.assertIn('<li>apples</li>', response.body) self.assertIn('<li>oranges</li>', response.body) self.assertIn('<ul>\n<li>apples</li>', response.body) self.assertIn('<ol>\n<li>apples</li>', response.body) self.assertIn( '<p>This is <a href="http://example.com/" title="Title">' 'an example</a> inline link.</p>', response.body) class TagsInclude(actions.TestBase): def setUp(self): super(TagsInclude, self).setUp() self.context = actions.simple_add_course(COURSE_NAME, ADMIN_EMAIL, COURSE_TITLE) self.course = courses.Course(None, self.context) self.unit = self.course.add_unit() self.unit.title = 'The Unit' self.unit.now_available = True self.lesson = self.course.add_lesson(self.unit) self.lesson.title = 'The Lesson' self.lesson.now_available = True self.lesson.objectives = GCB_INCLUDE % HTML_FILE self.course.save() def tearDown(self): self.context.fs.delete(HTML_PATH) def _set_content(self, content): self.context.fs.put(HTML_PATH, StringIO.StringIO(content)) def _expect_content(self, expected, response): expected = '%s<div>%s</div>%s' % (PRE_INCLUDE, expected, POST_INCLUDE) self.assertIn(expected, response.body) def test_missing_file_gives_error(self): self.lesson.objectives = GCB_INCLUDE % 'no_such_file.html' self.course.save() response = self.get(LESSON_URL) self.assertIn('Invalid HTML tag: no_such_file.html', response.body) def test_file_from_actual_filesystem(self): # Note: This has the potential to cause a test flake: Adding an # actual file to the filesystem and then removing it may cause # ETL tests to complain - they saw the file, then failed to copy # it because it went away. simple_content = 'Fiery the angels fell' if not os.path.isdir(HTML_DIR): os.mkdir(HTML_DIR) with open(HTML_PATH, 'w') as fp: fp.write(simple_content) response = self.get(LESSON_URL) os.unlink(HTML_PATH) self._expect_content(simple_content, response) def test_simple(self): simple_content = 'Deep thunder rolled around their shores' self._set_content(simple_content) response = self.get(LESSON_URL) self._expect_content(simple_content, response) def test_content_containing_tags(self): content = '<h1>This is a test</h1><p>This is only a test.</p>' self._set_content(content) response = self.get(LESSON_URL) self._expect_content(content, response) def test_jinja_base_path(self): content = '{{ base_path }}' self._set_content(content) response = self.get(LESSON_URL) self._expect_content('assets/html', response) def test_jinja_course_base(self): content = '{{ gcb_course_base }}' self._set_content(content) response = self.get(LESSON_URL) self._expect_content('http://localhost/test_course/', response) def test_jinja_course_title(self): content = '{{ course_info.course.title }}' self._set_content(content) response = self.get(LESSON_URL) self._expect_content('Test Course', response) def test_inclusion(self): content = 'Hello, World!' sub_path = os.path.join( appengine_config.BUNDLE_ROOT, HTML_DIR, 'sub.html') self.context.fs.put(sub_path, StringIO.StringIO(content)) self._set_content('{% include "sub.html" %}') try: response = self.get(LESSON_URL) self._expect_content(content, response) finally: self.context.fs.delete(sub_path)
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests verifying progress in units.""" __author__ = 'Mike Gainer (mgainer@google.com)' import re from common import crypto from common.utils import Namespace from controllers import utils from models import config from models import courses from models import models from tests.functional import actions COURSE_NAME = 'percent_completion' NAMESPACE = 'ns_%s' % COURSE_NAME COURSE_TITLE = 'Percent Completion' ADMIN_EMAIL = 'admin@foo.com' BASE_URL = '/' + COURSE_NAME STUDENT_EMAIL = 'foo@foo.com' class ProgressPercent(actions.TestBase): def setUp(self): super(ProgressPercent, self).setUp() context = actions.simple_add_course( COURSE_NAME, ADMIN_EMAIL, COURSE_TITLE) self.course = courses.Course(None, context) self.unit = self.course.add_unit() self.unit.title = 'No Lessons' self.unit.now_available = True self.lesson_one = self.course.add_lesson(self.unit) self.lesson_one.title = 'Lesson One' self.lesson_one.objectives = 'body of lesson' self.lesson_one.now_available = True self.lesson_two = self.course.add_lesson(self.unit) self.lesson_two.title = 'Lesson Two' self.lesson_two.objectives = 'body of lesson' self.lesson_two.now_available = True self.lesson_three = self.course.add_lesson(self.unit) self.lesson_three.title = 'Lesson Three' self.lesson_three.objectives = 'body of lesson' self.lesson_three.now_available = True self.assessment_one = self.course.add_assessment() self.assessment_one.title = 'Assessment One' self.assessment_one.html_content = 'assessment one content' self.assessment_one.now_available = True self.assessment_two = self.course.add_assessment() self.assessment_two.title = 'Assessment Two' self.assessment_two.html_content = 'assessment two content' self.assessment_two.now_available = True self.course.save() actions.login(STUDENT_EMAIL) actions.register(self, STUDENT_EMAIL, COURSE_NAME) config.Registry.test_overrides[ utils.CAN_PERSIST_ACTIVITY_EVENTS.name] = True self.tracker = self.course.get_progress_tracker() with Namespace(NAMESPACE): self.student = models.Student.get_by_email(STUDENT_EMAIL) def _get_unit_page(self, unit): return self.get(BASE_URL + '/unit?unit=' + str(unit.unit_id)) def _click_button(self, class_name, response): matches = re.search( r'<div class="%s">\s*<a href="([^"]*)"' % class_name, response.body) url = matches.group(1).replace('&amp;', '&') return self.get(url, response) def _click_next_button(self, response): return self._click_button('gcb-next-button', response) def _post_assessment(self, assessment_id, score): return self.post(BASE_URL + '/answer', { 'xsrf_token': crypto.XsrfTokenManager.create_xsrf_token( 'assessment-post'), 'assessment_type': assessment_id, 'score': score}) def test_progress_no_pre_assessment(self): # Zero progress when no unit actions taken. with Namespace(NAMESPACE): self.assertEquals(0.0, self.tracker.get_unit_percent_complete( self.student)[self.unit.unit_id]) # Progress is counted when navigating _on to_ lesson. response = self._get_unit_page(self.unit) with Namespace(NAMESPACE): self.assertEquals(0.333, self.tracker.get_unit_percent_complete( self.student)[self.unit.unit_id]) # Navigate to next lesson. Verify rounding to 3 decimal places. response = self._click_next_button(response) with Namespace(NAMESPACE): self.assertEquals(0.667, self.tracker.get_unit_percent_complete( self.student)[self.unit.unit_id]) # Navigate to next lesson. response = self._click_next_button(response) with Namespace(NAMESPACE): self.assertEquals(1.000, self.tracker.get_unit_percent_complete( self.student)[self.unit.unit_id]) def test_progress_pre_assessment_unsubmitted(self): self.unit.pre_assessment = self.assessment_one.unit_id self.unit.post_assessment = self.assessment_two.unit_id self.course.save() # Zero progress when no unit actions taken. with Namespace(NAMESPACE): self.assertEquals(0.0, self.tracker.get_unit_percent_complete( self.student)[self.unit.unit_id]) # Zero progress when navigate to pre-assessment response = self._get_unit_page(self.unit) with Namespace(NAMESPACE): self.assertEquals(0.000, self.tracker.get_unit_percent_complete( self.student)[self.unit.unit_id]) # Progress is counted when navigating _on to_ lesson. response = self._click_next_button(response) with Namespace(NAMESPACE): self.assertEquals(0.333, self.tracker.get_unit_percent_complete( self.student)[self.unit.unit_id]) # Navigate to next lesson. Verify rounding to 3 decimal places. response = self._click_next_button(response) with Namespace(NAMESPACE): self.assertEquals(0.667, self.tracker.get_unit_percent_complete( self.student)[self.unit.unit_id]) # Navigate to next lesson. response = self._click_next_button(response) with Namespace(NAMESPACE): self.assertEquals(1.000, self.tracker.get_unit_percent_complete( self.student)[self.unit.unit_id]) # Navigate to post-assessment does not change completion response = self._click_next_button(response) with Namespace(NAMESPACE): self.assertEquals(1.000, self.tracker.get_unit_percent_complete( self.student)[self.unit.unit_id]) def test_progress_pre_assessment_submitted_but_wrong(self): self.unit.pre_assessment = self.assessment_one.unit_id self.unit.post_assessment = self.assessment_two.unit_id self.course.save() self._get_unit_page(self.unit) response = self._post_assessment(self.assessment_one.unit_id, '99') # Reload student; assessment scores are cached in student. with Namespace(NAMESPACE): self.student = models.Student.get_by_email(STUDENT_EMAIL) # Zero progress because posting the assessment did not score 100%. with Namespace(NAMESPACE): self.assertEquals(0.000, self.tracker.get_unit_percent_complete( self.student)[self.unit.unit_id]) # Still zero progress when take redirect to assessment confirmation. response = response.follow() with Namespace(NAMESPACE): self.assertEquals(0.000, self.tracker.get_unit_percent_complete( self.student)[self.unit.unit_id]) # But have 33% progress when following the link to the 1st lesson response = self._click_next_button(response) with Namespace(NAMESPACE): self.assertEquals(0.333, self.tracker.get_unit_percent_complete( self.student)[self.unit.unit_id]) def test_progress_pre_assessment_submitted_and_fully_correct(self): self.unit.pre_assessment = self.assessment_one.unit_id self.unit.post_assessment = self.assessment_two.unit_id self.course.save() self._get_unit_page(self.unit) response = self._post_assessment(self.assessment_one.unit_id, '100') # Reload student; assessment scores are cached in student. with Namespace(NAMESPACE): self.student = models.Student.get_by_email(STUDENT_EMAIL) # 100% progress because pre-assessment was 100% correct. with Namespace(NAMESPACE): self.assertEquals(1.000, self.tracker.get_unit_percent_complete( self.student)[self.unit.unit_id]) # Still 100% after navigating onto a lesson response = response.follow() with Namespace(NAMESPACE): self.assertEquals(1.000, self.tracker.get_unit_percent_complete( self.student)[self.unit.unit_id])
Python
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for modules/search/.""" __author__ = 'Ellis Michael (emichael@google.com)' import datetime import logging import re import urllib import actions from common import utils as common_utils from controllers import sites from models import courses from models import resources_display from models import custom_modules from models import models from models import transforms from modules.announcements import announcements from modules.i18n_dashboard.i18n_dashboard import ResourceBundleDAO from modules.i18n_dashboard.i18n_dashboard import ResourceBundleDTO from modules.i18n_dashboard.i18n_dashboard import ResourceBundleKey from modules.search import search from tests.unit import modules_search as search_unit_test from google.appengine.api import namespace_manager class SearchTest(search_unit_test.SearchTestBase): """Tests the search module.""" @classmethod def enable_module(cls): custom_modules.Registry.registered_modules[ search.MODULE_NAME].enable() assert search.custom_module.enabled @classmethod def get_xsrf_token(cls, body, form_name): match = re.search(form_name + r'.+[\n\r].+value="([^"]+)"', body) assert match return match.group(1) def index_test_course(self): email = 'admin@google.com' actions.login(email, is_admin=True) response = self.get('/test/dashboard?action=search') index_token = self.get_xsrf_token(response.body, 'gcb-index-course') response = self.post('/test/dashboard?action=index_course', {'xsrf_token': index_token}) self.execute_all_deferred_tasks() def setUp(self): super(SearchTest, self).setUp() self.enable_module() self.logged_error = '' def error_report(string, *args, **unused_kwargs): self.logged_error = string % args self.error_report = error_report def test_module_enabled(self): email = 'admin@google.com' actions.login(email, is_admin=True) response = self.get('course') self.assertIn('gcb-search-box', response.body) response = self.get('/search?query=lorem') self.assertEqual(response.status_code, 200) response = self.get('dashboard?action=search') self.assertIn('Google &gt; Dashboard &gt; Search', response.body) self.assertIn('Index Course', response.body) self.assertIn('Clear Index', response.body) def test_indexing_and_clearing_buttons(self): email = 'admin@google.com' actions.login(email, is_admin=True) response = self.get('dashboard?action=search') index_token = self.get_xsrf_token(response.body, 'gcb-index-course') clear_token = self.get_xsrf_token(response.body, 'gcb-clear-index') response = self.post('dashboard?action=index_course', {'xsrf_token': index_token}) self.assertEqual(response.status_int, 302) response = self.post('dashboard?action=clear_index', {'xsrf_token': clear_token}) self.assertEqual(response.status_int, 302) response = self.post('dashboard?action=index_course', {}, expect_errors=True) assert response.status_int == 403 response = self.post('dashboard?action=clear_index', {}, expect_errors=True) assert response.status_int == 403 def test_index_search_clear(self): email = 'admin@google.com' actions.login(email, is_admin=True) response = self.get('dashboard?action=search') index_token = self.get_xsrf_token(response.body, 'gcb-index-course') clear_token = self.get_xsrf_token(response.body, 'gcb-clear-index') response = self.post('dashboard?action=index_course', {'xsrf_token': index_token}) self.execute_all_deferred_tasks() # weather is a term found in the Power Searching Course and should not # be in the HTML returned by the patched urlfetch in SearchTestBase response = self.get('search?query=weather') self.assertNotIn('gcb-search-result', response.body) # This term should be present as it is in the dummy content. response = self.get('search?query=cogito%20ergo%20sum') self.assertIn('gcb-search-result', response.body) response = self.post('dashboard?action=clear_index', {'xsrf_token': clear_token}) self.execute_all_deferred_tasks() # After the index is cleared, it shouldn't match anything response = self.get('search?query=cogito%20ergo%20sum') self.assertNotIn('gcb-search-result', response.body) def test_bad_search(self): email = 'user@google.com' actions.login(email, is_admin=False) # %3A is a colon, and searching for only punctuation will cause App # Engine's search to throw an error that should be handled response = self.get('search?query=%3A') self.assertEqual(response.status_int, 200) self.assertIn('gcb-search-info', response.body) def test_errors_not_displayed_to_user(self): exception_code = '0xDEADBEEF' def bad_fetch(*unused_vargs, **unused_kwargs): raise Exception(exception_code) self.swap(search, 'fetch', bad_fetch) self.swap(logging, 'error', self.error_report) response = self.get('search?query=cogito') self.assertEqual(response.status_int, 200) self.assertIn('unavailable', response.body) self.assertNotIn('gcb-search-result', response.body) self.assertIn('gcb-search-info', response.body) self.assertIn(exception_code, self.logged_error) def test_unicode_pages(self): sites.setup_courses('course:/test::ns_test, course:/:/') course = courses.Course(None, app_context=sites.get_all_courses()[0]) unit = course.add_unit() unit.now_available = True lesson_a = course.add_lesson(unit) lesson_a.notes = search_unit_test.UNICODE_PAGE_URL lesson_a.now_available = True course.update_unit(unit) course.save() self.index_test_course() self.swap(logging, 'error', self.error_report) response = self.get('/test/search?query=paradox') self.assertEqual('', self.logged_error) self.assertNotIn('unavailable', response.body) self.assertIn('gcb-search-result', response.body) def test_external_links(self): sites.setup_courses('course:/test::ns_test, course:/:/') course = courses.Course(None, app_context=sites.get_all_courses()[0]) unit = course.add_unit() unit.now_available = True lesson_a = course.add_lesson(unit) lesson_a.notes = search_unit_test.VALID_PAGE_URL objectives_link = 'http://objectiveslink.null/' lesson_a.objectives = '<a href="%s"></a><a href="%s"></a>' % ( search_unit_test.LINKED_PAGE_URL, objectives_link) lesson_a.now_available = True course.update_unit(unit) course.save() self.index_test_course() response = self.get('/test/search?query=What%20hath%20God%20wrought') self.assertIn('gcb-search-result', response.body) response = self.get('/test/search?query=Cogito') self.assertIn('gcb-search-result', response.body) self.assertIn(search_unit_test.VALID_PAGE_URL, response.body) self.assertIn(objectives_link, response.body) self.assertNotIn(search_unit_test.PDF_URL, response.body) # If this test fails, indexing will crawl the entire web response = self.get('/test/search?query=ABORT') self.assertNotIn('gcb-search-result', response.body) self.assertNotIn(search_unit_test.SECOND_LINK_PAGE_URL, response.body) def test_youtube(self): sites.setup_courses('course:/test::ns_test, course:/:/') default_namespace = namespace_manager.get_namespace() try: namespace_manager.set_namespace('ns_test') course = courses.Course(None, app_context=sites.get_all_courses()[0]) unit = course.add_unit() unit.now_available = True lesson_a = course.add_lesson(unit) lesson_a.video = 'portal' lesson_a.now_available = True lesson_b = course.add_lesson(unit) lesson_b.objectives = '<gcb-youtube videoid="glados">' lesson_b.now_available = True course.update_unit(unit) course.save() entity = announcements.AnnouncementEntity() entity.html = '<gcb-youtube videoid="aperature">' entity.title = 'Sample Announcement' entity.date = datetime.datetime.now().date() entity.is_draft = False entity.put() self.index_test_course() response = self.get('/test/search?query=apple') self.assertIn('gcb-search-result', response.body) self.assertIn('start=3.14', response.body) self.assertIn('v=portal', response.body) self.assertIn('v=glados', response.body) self.assertIn('v=aperature', response.body) self.assertIn('lemon', response.body) self.assertIn('Medicus Quis', response.body) self.assertIn('- YouTube', response.body) self.assertIn('http://thumbnail.null', response.body) # Test to make sure empty notes field doesn't cause a urlfetch response = self.get('/test/search?query=cogito') self.assertNotIn('gcb-search-result', response.body) finally: namespace_manager.set_namespace(default_namespace) def _add_announcement(self, form_settings): response = actions.view_announcements(self) add_form = response.forms['gcb-add-announcement'] response = self.submit(add_form).follow() match = re.search(r'\'([^\']+rest/announcements/item\?key=([^\']+))', response.body) url = match.group(1) key = match.group(2) response = self.get(url) json_dict = transforms.loads(response.body) payload_dict = transforms.loads(json_dict['payload']) payload_dict.update(form_settings) request = {} request['key'] = key request['payload'] = transforms.dumps(payload_dict) request['xsrf_token'] = json_dict['xsrf_token'] response = self.put('rest/announcements/item?%s' % urllib.urlencode( {'request': transforms.dumps(request)}), {}) def test_announcements(self): email = 'admin@google.com' actions.login(email, is_admin=True) self._add_announcement({ 'title': 'My Test Title', 'date': '2015/02/03', 'is_draft': False, 'send_email': False, 'html': 'Four score and seven years ago, our founding fathers' }) self._add_announcement({ 'title': 'My Test Title', 'date': '2015/02/03', 'is_draft': True, 'send_email': False, 'html': 'Standing beneath this serene sky, overlooking these', }) response = self.get('dashboard?action=search') index_token = self.get_xsrf_token(response.body, 'gcb-index-course') response = self.post('dashboard?action=index_course', {'xsrf_token': index_token}) self.execute_all_deferred_tasks() # This matches an announcement in the Power Searching course response = self.get( 'search?query=Four%20score%20seven%20years') self.assertIn('gcb-search-result', response.body) self.assertIn('announcements#', response.body) # The draft announcement in Power Searching should not be indexed response = self.get('search?query=Standing%20beneath%20serene') self.assertNotIn('gcb-search-result', response.body) self.assertNotIn('announcements#', response.body) def test_private_units_and_lessons(self): sites.setup_courses('course:/test::ns_test, course:/:/') course = courses.Course(None, app_context=sites.get_all_courses()[0]) unit1 = course.add_unit() lesson11 = course.add_lesson(unit1) lesson11.notes = search_unit_test.VALID_PAGE_URL lesson11.objectives = search_unit_test.VALID_PAGE lesson11.video = 'portal' unit2 = course.add_unit() lesson21 = course.add_lesson(unit2) lesson21.notes = search_unit_test.VALID_PAGE_URL lesson21.objectives = search_unit_test.VALID_PAGE lesson21.video = 'portal' unit1.now_available = True lesson11.now_available = False course.update_unit(unit1) unit2.now_available = False lesson21.now_available = True course.update_unit(unit2) course.save() self.index_test_course() response = self.get('/test/search?query=cogito%20ergo%20sum') self.assertNotIn('gcb-search-result', response.body) response = self.get('/test/search?query=apple') self.assertNotIn('gcb-search-result', response.body) self.assertNotIn('v=portal', response.body) def test_tracked_lessons(self): context = actions.simple_add_course('test', 'admin@google.com', 'Test Course') course = courses.Course(None, context) actions.login('admin@google.com') actions.register(self, 'Some Admin', 'test') with common_utils.Namespace('ns_test'): foo_id = models.LabelDAO.save(models.LabelDTO( None, {'title': 'Foo', 'descripton': 'foo', 'type': models.LabelDTO.LABEL_TYPE_COURSE_TRACK})) bar_id = models.LabelDAO.save(models.LabelDTO( None, {'title': 'Bar', 'descripton': 'bar', 'type': models.LabelDTO.LABEL_TYPE_COURSE_TRACK})) unit1 = course.add_unit() unit1.now_available = True unit1.labels = str(foo_id) lesson11 = course.add_lesson(unit1) lesson11.objectives = 'common plugh <gcb-youtube videoid="glados">' lesson11.now_available = True lesson11.notes = search_unit_test.VALID_PAGE_URL lesson11.video = 'portal' course.update_unit(unit1) unit2 = course.add_unit() unit2.now_available = True unit1.labels = str(bar_id) lesson21 = course.add_lesson(unit2) lesson21.objectives = 'common plover' lesson21.now_available = True course.update_unit(unit2) course.save() self.index_test_course() # Registered, un-tracked student sees all. response = self.get('/test/search?query=common') self.assertIn('common', response.body) self.assertIn('plugh', response.body) self.assertIn('plover', response.body) response = self.get('/test/search?query=link') # Do see followed links self.assertIn('Partial', response.body) self.assertIn('Absolute', response.body) response = self.get('/test/search?query=lemon') # Do see video refs self.assertIn('v=glados', response.body) # Student with tracks sees filtered view. with common_utils.Namespace('ns_test'): models.Student.set_labels_for_current(str(foo_id)) response = self.get('/test/search?query=common') self.assertIn('common', response.body) self.assertNotIn('plugh', response.body) self.assertIn('plover', response.body) response = self.get('/test/search?query=link') # Links are filtered self.assertNotIn('Partial', response.body) self.assertNotIn('Absolute', response.body) response = self.get('/test/search?query=lemon') # Don't see video refs self.assertNotIn('v=glados', response.body) def test_localized_search(self): def _text(elt): return ''.join(elt.itertext()) dogs_page = """ <html> <body> A page about dogs. </body> </html>""" dogs_link = 'http://dogs.null/' self.pages[dogs_link + '$'] = (dogs_page, 'text/html') dogs_page_fr = """ <html> <body> A page about French dogs. </body> </html>""" dogs_link_fr = 'http://dogs_fr.null/' self.pages[dogs_link_fr + '$'] = (dogs_page_fr, 'text/html') self.base = '/test' context = actions.simple_add_course( 'test', 'admin@google.com', 'Test Course') course = courses.Course(None, context) actions.login('admin@google.com') actions.register(self, 'Some Admin') unit = course.add_unit() unit.now_available = True lesson = course.add_lesson(unit) lesson.objectives = 'A lesson about <a href="%s">dogs</a>' % dogs_link lesson.now_available = True course.save() lesson_bundle = { 'objectives': { 'type': 'html', 'source_value': ( 'A lesson about <a href="%s">dogs</a>' % dogs_link), 'data': [{ 'source_value': ( 'A lesson about <a#1 href="%s">dogs</a#1>' % dogs_link), 'target_value': ( 'A lesson about French <a#1 href="%s">' 'dogs</a#1>' % dogs_link_fr)}] } } lesson_key_fr = ResourceBundleKey( resources_display.ResourceLesson.TYPE, lesson.lesson_id, 'fr') with common_utils.Namespace('ns_test'): ResourceBundleDAO.save( ResourceBundleDTO(str(lesson_key_fr), lesson_bundle)) extra_locales = [{'locale': 'fr', 'availability': 'available'}] with actions.OverriddenEnvironment({'extra_locales': extra_locales}): self.index_test_course() dom = self.parse_html_string(self.get('search?query=dogs').body) snippets = dom.findall('.//div[@class="gcb-search-result-snippet"]') self.assertEquals(2, len(snippets)) # Expect no French hits self.assertIn('page about dogs', _text(snippets[0])) self.assertIn('lesson about dogs', _text(snippets[1])) # Switch locale to 'fr' with common_utils.Namespace('ns_test'): prefs = models.StudentPreferencesDAO.load_or_create() prefs.locale = 'fr' models.StudentPreferencesDAO.save(prefs) dom = self.parse_html_string(self.get('search?query=dogs').body) snippets = dom.findall('.//div[@class="gcb-search-result-snippet"]') self.assertEquals(2, len(snippets)) # Expect no Engish hits self.assertIn('page about French dogs', _text(snippets[0])) self.assertIn('lesson about French dogs', _text(snippets[1]))
Python
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Functional tests for modules/upload/upload.py.""" __author__ = [ 'johncox@google.com (John Cox)', ] import os from controllers import utils from models import models from models import student_work from modules.upload import upload from tests.functional import actions from google.appengine.ext import db class TextFileUploadHandlerTestCase(actions.TestBase): """Tests for TextFileUploadHandler.""" def setUp(self): super(TextFileUploadHandlerTestCase, self).setUp() self.contents = 'contents' self.email = 'user@example.com' self.headers = {'referer': 'http://localhost/path?query=value#fragment'} self.unit_id = '1' self.user_id = '2' self.student = models.Student( is_enrolled=True, key_name=self.email, user_id=self.user_id) self.student.put() self.xsrf_token = utils.XsrfTokenManager.create_xsrf_token( upload._XSRF_TOKEN_NAME) def configure_environ_for_current_user(self): os.environ['USER_EMAIL'] = self.email os.environ['USER_ID'] = self.user_id def get_submission(self, student_key, unit_id): return db.get(student_work.Submission.get_key(unit_id, student_key)) def test_bad_xsrf_token_returns_400(self): response = self.testapp.post( upload._POST_ACTION_SUFFIX, {'form_xsrf_token': 'bad'}, self.headers, expect_errors=True) self.assertEqual(400, response.status_int) def test_creates_new_submission(self): self.configure_environ_for_current_user() user_xsrf_token = utils.XsrfTokenManager.create_xsrf_token( upload._XSRF_TOKEN_NAME) params = { 'contents': self.contents, 'form_xsrf_token': user_xsrf_token, 'unit_id': self.unit_id, } self.assertIsNone(self.get_submission(self.student.key(), self.user_id)) response = self.testapp.post( upload._POST_ACTION_SUFFIX, params, self.headers) self.assertEqual(200, response.status_int) submissions = student_work.Submission.all().fetch(2) self.assertEqual(1, len(submissions)) self.assertEqual(u'"%s"' % self.contents, submissions[0].contents) def test_empty_contents_returns_400(self): self.configure_environ_for_current_user() user_xsrf_token = utils.XsrfTokenManager.create_xsrf_token( upload._XSRF_TOKEN_NAME) params = { 'contents': '', 'form_xsrf_token': user_xsrf_token, 'unit_id': self.unit_id, } response = self.testapp.post( upload._POST_ACTION_SUFFIX, params, self.headers, expect_errors=True) self.assertEqual(400, response.status_int) def test_missing_contents_returns_400(self): self.configure_environ_for_current_user() user_xsrf_token = utils.XsrfTokenManager.create_xsrf_token( upload._XSRF_TOKEN_NAME) params = { 'form_xsrf_token': user_xsrf_token, 'unit_id': self.unit_id, } response = self.testapp.post( upload._POST_ACTION_SUFFIX, params, self.headers, expect_errors=True) self.assertEqual(400, response.status_int) def test_missing_student_returns_403(self): response = self.testapp.post( upload._POST_ACTION_SUFFIX, {'form_xsrf_token': self.xsrf_token}, self.headers, expect_errors=True) self.assertEqual(403, response.status_int) def test_missing_xsrf_token_returns_400(self): response = self.testapp.post( upload._POST_ACTION_SUFFIX, {}, self.headers, expect_errors=True) self.assertEqual(400, response.status_int) def test_updates_existing_submission(self): self.configure_environ_for_current_user() user_xsrf_token = utils.XsrfTokenManager.create_xsrf_token( upload._XSRF_TOKEN_NAME) params = { 'contents': 'old', 'form_xsrf_token': user_xsrf_token, 'unit_id': self.unit_id, } self.assertIsNone(self.get_submission(self.student.key(), self.user_id)) response = self.testapp.post( upload._POST_ACTION_SUFFIX, params, self.headers) self.assertEqual(200, response.status_int) params['contents'] = self.contents response = self.testapp.post( upload._POST_ACTION_SUFFIX, params, self.headers) self.assertEqual(200, response.status_int) submissions = student_work.Submission.all().fetch(2) self.assertEqual(1, len(submissions)) self.assertEqual(u'"%s"' % self.contents, submissions[0].contents) def test_unsavable_contents_returns_400(self): self.configure_environ_for_current_user() user_xsrf_token = utils.XsrfTokenManager.create_xsrf_token( upload._XSRF_TOKEN_NAME) params = { # Entity size = contents + other data, so 1MB here will overlfow. 'contents': 'a' * 1024 * 1024, 'form_xsrf_token': user_xsrf_token, 'unit_id': self.unit_id, } response = self.testapp.post( upload._POST_ACTION_SUFFIX, params, self.headers, expect_errors=True) self.assertEqual(400, response.status_int)
Python
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Course Builder test suite. This script runs all functional and units test in the Course Builder project. Here is how to use the script: - if you don't have pip, install it using 'sudo apt-get install python-pip' - install WebTest using: 'sudo pip install WebTest' - make sure your PYTHONPATH contains: google_appengine, google_appengine/lib/jinja2-2.6, google_appengine/lib/webapp2-2.5.1 and the 'coursebuilder' directory itself - invoke this test suite from the command line: # Automatically find and run all Python tests in tests/*. python tests/suite.py --pattern test*.py # Run test method baz in unittest.TestCase Bar found in tests/foo.py. python tests/suite.py --test_class_name tests.foo.Bar.baz - review the output to make sure there are no errors or warnings Good luck! """ __author__ = 'Sean Lip' import argparse import logging import os import shutil import signal import socket import stat import subprocess import sys import time import unittest import task_queue import webtest import appengine_config from tools.etl import etl from google.appengine.api.search import simple_search_stub from google.appengine.datastore import datastore_stub_util from google.appengine.ext import testbed _PARSER = argparse.ArgumentParser() _PARSER.add_argument( '--pattern', default='*.py', help='shell pattern for discovering files containing tests', type=str) _PARSER.add_argument( '--test_class_name', help='optional dotted module name of the test(s) to run', type=str) _PARSER.add_argument( '--integration_server_start_cmd', help='script to start an external CB server', type=str) # Base filesystem location for test data. if 'COURSEBUILDER_RESOURCES' in os.environ: TEST_DATA_BASE = os.path.join( os.environ['COURSEBUILDER_RESOURCES'], 'test-data/') else: TEST_DATA_BASE = os.path.join( os.environ['HOME'], 'coursebuilder_resources/test-data/') def empty_environ(): os.environ['AUTH_DOMAIN'] = 'example.com' os.environ['SERVER_NAME'] = 'localhost' os.environ['HTTP_HOST'] = 'localhost' os.environ['SERVER_PORT'] = '8080' os.environ['USER_EMAIL'] = '' os.environ['USER_ID'] = '' os.environ['DEFAULT_VERSION_HOSTNAME'] = ( os.environ['HTTP_HOST'] + ':' + os.environ['SERVER_PORT']) def iterate_tests(test_suite_or_case): """Iterate through all of the test cases in 'test_suite_or_case'.""" try: suite = iter(test_suite_or_case) except TypeError: yield test_suite_or_case else: for test in suite: for subtest in iterate_tests(test): yield subtest class TestBase(unittest.TestCase): """Base class for all Course Builder tests.""" REQUIRES_INTEGRATION_SERVER = 'REQUIRES_INTEGRATION_SERVER' REQUIRES_TESTING_MODULES = 'REQUIRES_TESTING_MODULES' INTEGRATION_SERVER_BASE_URL = 'http://localhost:8081' ADMIN_SERVER_BASE_URL = 'http://localhost:8000' STOP_AFTER_FIRST_FAILURE = False HAS_PENDING_FAILURE = False def setUp(self): if TestBase.STOP_AFTER_FIRST_FAILURE: assert not TestBase.HAS_PENDING_FAILURE super(TestBase, self).setUp() # e.g. TEST_DATA_BASE/tests/functional/tests/MyTestCase. self.test_tempdir = os.path.join( TEST_DATA_BASE, self.__class__.__module__.replace('.', os.sep), self.__class__.__name__) self.reset_filesystem() self._originals = {} # Map of object -> {symbol_string: original_value} def run(self, result=None): if not result: result = self.defaultTestResult() super(TestBase, self).run(result) if not result.wasSuccessful(): TestBase.HAS_PENDING_FAILURE = True def tearDown(self): self._unswap_all() self.reset_filesystem(remove_only=True) super(TestBase, self).tearDown() def reset_filesystem(self, remove_only=False): if os.path.exists(self.test_tempdir): shutil.rmtree(self.test_tempdir) if not remove_only: os.makedirs(self.test_tempdir) def swap(self, source, symbol, new): # pylint: disable=invalid-name """Swaps out source.symbol for a new value. Allows swapping of members and methods: myobject.foo = 'original_foo' self.swap(myobject, 'foo', 'bar') self.assertEqual('bar', myobject.foo) myobject.baz() # -> 'original_baz' self.swap(myobject, 'baz', lambda: 'quux') self.assertEqual('quux', myobject.bar()) Swaps are automatically undone in tearDown(). Args: source: object. The source object to swap from. symbol: string. The name of the symbol to swap. new: object. The new value to swap in. """ if source not in self._originals: self._originals[source] = {} if not self._originals[source].get(symbol, None): self._originals[source][symbol] = getattr(source, symbol) setattr(source, symbol, new) def _unswap_all(self): for source, symbol_to_value in self._originals.iteritems(): for symbol, value in symbol_to_value.iteritems(): setattr(source, symbol, value) def shortDescription(self): """Additional information logged during unittest invocation.""" # Suppress default logging of docstrings. Instead log name/status only. return None class FunctionalTestBase(TestBase): """Base class for functional tests.""" class AppEngineTestBase(FunctionalTestBase): """Base class for tests that require App Engine services.""" def getApp(self): """Returns the main application to be tested.""" raise Exception('Not implemented.') def setUp(self): super(AppEngineTestBase, self).setUp() empty_environ() # setup an app to be tested self.testapp = webtest.TestApp(self.getApp()) self.testbed = testbed.Testbed() self.testbed.activate() # configure datastore policy to emulate instantaneously and globally # consistent HRD; we also patch dev_appserver in main.py to run under # the same policy policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy( probability=1) # declare any relevant App Engine service stubs here self.testbed.init_user_stub() self.testbed.init_memcache_stub() self.testbed.init_datastore_v3_stub(consistency_policy=policy) self.testbed.init_taskqueue_stub() self.taskq = self.testbed.get_stub(testbed.TASKQUEUE_SERVICE_NAME) self.testbed.init_urlfetch_stub() self.testbed.init_files_stub() self.testbed.init_blobstore_stub() self.testbed.init_mail_stub() # TODO(emichael): Fix this when an official stub is created self.testbed._register_stub( 'search', simple_search_stub.SearchServiceStub()) self.task_dispatcher = task_queue.TaskQueueHandlerDispatcher( self.testapp, self.taskq) def tearDown(self): self.testbed.deactivate() super(AppEngineTestBase, self).tearDown() def get_mail_stub(self): return self.testbed.get_stub(testbed.MAIL_SERVICE_NAME) def create_test_suite(parsed_args): """Loads all requested test suites. By default, loads all unittest.TestCases found under the project root's tests/ directory. Args: parsed_args: argparse.Namespace. Processed command-line arguments. Returns: unittest.TestSuite. The test suite populated with all tests to run. """ loader = unittest.TestLoader() if parsed_args.test_class_name: return loader.loadTestsFromName(parsed_args.test_class_name) else: return loader.discover( os.path.dirname(__file__), pattern=parsed_args.pattern) def ensure_port_available(port_number): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: s.bind(('localhost', port_number)) except socket.error, ex: logging.error( '''========================================================== Failed to bind to port %d. This probably means another CourseBuilder server is already running. Be sure to shut down any manually started servers before running tests. ==========================================================''', port_number) raise ex s.close() def start_integration_server(integration_server_start_cmd, modules): if modules: _fn = os.path.join(appengine_config.BUNDLE_ROOT, 'custom.yaml') _st = os.stat(_fn) os.chmod(_fn, _st.st_mode | stat.S_IWUSR) fp = open(_fn, 'w') fp.writelines([ 'env_variables:\n', ' GCB_REGISTERED_MODULES_CUSTOM:\n']) fp.writelines([' %s\n' % module.__name__ for module in modules]) fp.close() logging.info('Starting external server: %s', integration_server_start_cmd) server = subprocess.Popen(integration_server_start_cmd) time.sleep(3) # Wait for server to start up return server def stop_integration_server(server, modules): server.kill() # dev_appserver.py itself. # The new dev appserver starts a _python_runtime.py process that isn't # captured by start_integration_server and so doesn't get killed. Until it's # done, our tests will never complete so we kill it manually. (stdout, unused_stderr) = subprocess.Popen( ['pgrep', '-f', '_python_runtime.py'], stdout=subprocess.PIPE ).communicate() # If tests are killed partway through, runtimes can build up; send kill # signals to all of them, JIC. pids = [int(pid.strip()) for pid in stdout.split('\n') if pid.strip()] for pid in pids: os.kill(pid, signal.SIGKILL) if modules: fp = open( os.path.join(appengine_config.BUNDLE_ROOT, 'custom.yaml'), 'w') fp.writelines([ '# Add configuration for your application here to avoid\n' '# potential merge conflicts with new releases of the main\n' '# app.yaml file. Modules registered here should support the\n' '# standard CourseBuilder module config. (Specifically, the\n' '# imported Python module should provide a method\n' '# "register_module()", taking no parameters and returning a\n' '# models.custom_modules.Module instance.\n' '#\n' 'env_variables:\n' '# GCB_REGISTERED_MODULES_CUSTOM:\n' '# modules.my_extension_module\n' '# my_extension.modules.widgets\n' '# my_extension.modules.blivets\n' ]) fp.close() def fix_sys_path(): """Fix the sys.path to include GAE extra paths.""" import dev_appserver # pylint: disable=C6204 # dev_appserver.fix_sys_path() prepends GAE paths to sys.path and hides # our classes like 'tests' behind other modules that have 'tests'. # Here, unlike dev_appserver, we append the path instead of prepending it, # so that our classes come first. sys.path += dev_appserver.EXTRA_PATHS[:] # This is to work around an issue with the __import__ builtin. The # problem seems to be that if the sys.path list contains an item that # partially matches a package name to import, __import__ will get # confused, and report an error message (which removes the first path # element from the module it's complaining about, which does not help # efforts to diagnose the problem at all). # # The specific case where this causes an issue is between # $COURSEBUILDER_HOME/tests/internal and $COURSEBUILDER_HOME/internal # Since the former exists, __import__ will ignore the second, and so # things like .../internal/experimental/autoregister/autoregister # cannot be loaded. # # To address this issue, we ensure that COURSEBUILDER_HOME is on sys.path # before anything else, and do it before appengine_config's module # importation starts running. (And we have to do it here, because if we # try to do this within appengine_config, AppEngine will throw an error) if appengine_config.BUNDLE_ROOT in sys.path: sys.path.remove(appengine_config.BUNDLE_ROOT) sys.path.insert(0, appengine_config.BUNDLE_ROOT) def main(): """Starts in-process server and runs all test cases in this module.""" fix_sys_path() etl._set_env_vars_from_app_yaml() parsed_args = _PARSER.parse_args() test_suite = create_test_suite(parsed_args) all_tags = {} for test in iterate_tests(test_suite): if hasattr(test, 'TAGS'): for tag in test.TAGS: if isinstance(test.TAGS[tag], set) and tag in all_tags: all_tags[tag].update(test.TAGS[tag]) else: all_tags[tag] = test.TAGS[tag] server = None if TestBase.REQUIRES_INTEGRATION_SERVER in all_tags: ensure_port_available(8081) ensure_port_available(8000) server = start_integration_server( parsed_args.integration_server_start_cmd, all_tags.get(TestBase.REQUIRES_TESTING_MODULES, set())) result = unittest.TextTestRunner(verbosity=2).run(test_suite) if server: stop_integration_server( server, all_tags.get(TestBase.REQUIRES_TESTING_MODULES, set())) if result.errors or result.failures: raise Exception( 'Test suite failed: %s errors, %s failures of ' ' %s tests run.' % ( len(result.errors), len(result.failures), result.testsRun)) import tests.functional.actions as actions count = len(actions.UNIQUE_URLS_FOUND.keys()) result.stream.writeln('INFO: Unique URLs found: %s' % count) result.stream.writeln('INFO: All %s tests PASSED!' % result.testsRun) if __name__ == '__main__': appengine_config.gcb_force_default_encoding('ascii') main()
Python
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test the autoregister module.""" import os os.environ['GCB_REGISTERED_MODULES_CUSTOM'] = ( 'internal.experimental.autoregister.autoregister') from common import crypto from models import courses from tests.functional import actions from internal.experimental.autoregister import autoregister class AutoregisterTests(actions.TestBase): COURSE_NAME = 'autoregister_course' ADMIN_EMAIL = 'admin@foo.com' STUDENT_EMAIL = 'student@foo.com' REDIRECT_URL = 'http://disney.com' COURSE_URL = '/%s/course' % COURSE_NAME PREVIEW_URL = '/%s/preview' % COURSE_NAME REGISTER_URL = '/%s/register' % COURSE_NAME AUTOREGISTER_URL = '/%s/autoregister' % COURSE_NAME UNENROLL_URL = '/%s/student/unenroll' % COURSE_NAME def setUp(self): super(AutoregisterTests, self).setUp() self.context = actions.simple_add_course( self.COURSE_NAME, self.ADMIN_EMAIL, 'Autoregister Course') course = courses.Course(None, app_context=self.context) self.unit = course.add_unit() self.unit.now_available = True self.lesson = course.add_lesson(self.unit) self.lesson.now_available = True course.save() actions.login(self.ADMIN_EMAIL) actions.update_course_config( self.COURSE_NAME, { 'course': { 'now_available': True, 'browsable': False, }, autoregister.AUTOREGISTER_SETTINGS_SCHEMA_SECTION: { autoregister.REDIRECT_URL: self.REDIRECT_URL, autoregister.AUTOREGISTER_ENABLED: True, } }) actions.login(self.STUDENT_EMAIL) def test_redirect(self): # Partly, we're testing that the redirect does, in fact, redirect. We # are also demonstrating that unless some other circumstances change, # loading the default course URL will cause a redirect. We want to # have this property so as to be able to not have to re-verify this # for all of the test cases for the non-redirect exceptions. response = self.get(self.COURSE_URL) self.assertEqual(301, response.status_int) self.assertEqual(self.REDIRECT_URL, response.location) def test_redirect_mid_course_url(self): lesson_url = '/%s/unit?unit=%s&lesson=%s' % ( self.COURSE_NAME, self.unit.unit_id, self.lesson.lesson_id) response = self.get(lesson_url) self.assertEqual(301, response.status_int) self.assertEqual(self.REDIRECT_URL, response.location) def test_direct_registration_redirects(self): # We also want attempts to directly register to fail; this pushes # students to register with GLearn first and then get redirected to # the autoregister URL. response = self.get(self.REGISTER_URL) self.assertEqual(301, response.status_int) self.assertEqual(self.REDIRECT_URL, response.location) def test_page_unavailable_when_course_not_public(self): actions.update_course_config(self.COURSE_NAME, {'course': {'now_available': False}}) response = self.get(self.COURSE_URL, expect_errors=True) self.assertEqual(404, response.status_int) def test_no_redirect_when_course_is_browsable(self): actions.update_course_config(self.COURSE_NAME, {'course': {'browsable': True}}) response = self.get(self.COURSE_URL) self.assertEqual(200, response.status_int) def test_no_redirect_when_admin(self): # Here, we do a GET for the /preview url. (If instead we had hit the # /course url, we'd have been redirected to /preview because the # course is only browseable, and that would look like a bug) actions.login(self.ADMIN_EMAIL) response = self.get(self.PREVIEW_URL) self.assertEqual(200, response.status_int) def test_no_redirect_when_autoregister_disabled(self): actions.update_course_config( self.COURSE_NAME, { autoregister.AUTOREGISTER_SETTINGS_SCHEMA_SECTION: { autoregister.AUTOREGISTER_ENABLED: False, } }) response = self.get(self.PREVIEW_URL) self.assertEqual(200, response.status_int) def test_autoregister_and_unenroll(self): # Unregistered student gets redirected. response = self.get(self.COURSE_URL) self.assertEqual(301, response.status_int) self.assertEqual(self.REDIRECT_URL, response.location) response = self.get(self.AUTOREGISTER_URL) self.assertEqual(302, response.status_int) self.assertEqual('http://localhost' + self.COURSE_URL, response.location) response = self.get(self.COURSE_URL) self.assertEqual(200, response.status_int) self.post(self.UNENROLL_URL, { 'xsrf_token': crypto.XsrfTokenManager.create_xsrf_token( 'student-unenroll') }) response = self.get(self.COURSE_URL) self.assertEqual(301, response.status_int) self.assertEqual(self.REDIRECT_URL, response.location)
Python
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Set of converters between db models, Python and JSON dictionaries, etc.""" __author__ = 'Pavel Simakov (psimakov@google.com)' import datetime import itertools import json from StringIO import StringIO import types import urlparse from xml.etree import ElementTree import transforms_constants import yaml from google.appengine.api import datastore_types from google.appengine.ext import db # Leave tombstones pointing to moved functions # pylint: disable=unused-import,g-bad-import-order from entity_transforms import dict_to_entity from entity_transforms import entity_to_dict from entity_transforms import get_schema_for_entity ISO_8601_DATE_FORMAT = '%Y-%m-%d' ISO_8601_DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ' _LEGACY_DATE_FORMAT = '%Y/%m/%d' _JSON_DATE_FORMATS = [ ISO_8601_DATE_FORMAT, _LEGACY_DATE_FORMAT, ] _JSON_DATETIME_FORMATS = [ ISO_8601_DATETIME_FORMAT ] + [ ''.join(parts) for parts in itertools.product( # Permutations of reasonably-expected permitted variations on ISO-8601. # The first item in each tuple indicates the preferred choice. _JSON_DATE_FORMATS, ('T', ' '), ('%H:%M:%S', '%H:%M'), ('.%f', ',%f', ''), # US/Euro decimal separator ('Z', ''), # Be explicit about Zulu timezone. Blank implies local. ) ] JSON_TYPES = ['string', 'date', 'datetime', 'text', 'html', 'boolean', 'integer', 'number', 'array', 'object', 'timestamp'] # Prefix to add to all JSON responses to guard against XSSI. Must be kept in # sync with modules/oeditor/oeditor.html. JSON_XSSI_PREFIX = ")]}'\n" # Modules can extends the range of objects which can be JSON serialized by # adding custom JSON encoder functions to this list. The function will be called # with a single argument which is an object to be encoded. If the encoding # function wants to encode this object, it should return a serializable # representation of the object, or return None otherwise. The first function # that can encode the object wins, so modules should not override the encodings # of standard type (list, string, number, etc. CUSTOM_JSON_ENCODERS = [] def dict_to_json(source_dict, unused_schema): """Converts Python dictionary into JSON dictionary using schema.""" output = {} for key, value in source_dict.items(): if value is None or isinstance(value, transforms_constants.SIMPLE_TYPES): output[key] = value elif isinstance(value, datastore_types.Key): output[key] = str(value) elif isinstance(value, datetime.datetime): output[key] = value.strftime(ISO_8601_DATETIME_FORMAT) elif isinstance(value, datetime.date): output[key] = value.strftime(ISO_8601_DATE_FORMAT) elif isinstance(value, db.GeoPt): output[key] = {'lat': value.lat, 'lon': value.lon} else: raise ValueError( 'Failed to encode key \'%s\' with value \'%s\'.' % (key, value)) return output def validate_object_matches_json_schema(obj, schema, path='', complaints=None): """Check whether the given object matches a schema. When building up a dict of contents which is supposed to match a declared schema, human error often creeps in; it is easy to neglect to cast a number to a floating point number, or an object ID to a string. This function verifies the presence, type, and format of fields. Note that it is not effective to verify sub-components that are scalars or arrays, due to the way field names are (or rather, are not) stored in the JSON schema layout. Args: obj: A dict containing contents that should match the given schema schema: A dict describing a schema, as obtained from FieldRegistry.get_json_schema_dict(). This parameter can also be the 'properties' member of a JSON schema dict, as that sub-item is commonly used in the REST data source subsystem. path: Do not pass a value for this; it is used for internal recursion. complaints: Either leave this blank or pass in an empty list. If blank, the list of complaints is available as the return value. If nonblank, the list of complaints will be appended to this list. Either is fine, depending on your preferred style. Returns: Array of verbose complaint strings. If array is blank, object validated without error. """ def is_valid_url(obj): url = urlparse.urlparse(obj) return url.scheme and url.netloc def is_valid_date(obj): try: datetime.datetime.strptime(obj, ISO_8601_DATE_FORMAT) return True except ValueError: return False def is_valid_datetime(obj): try: datetime.datetime.strptime(obj, ISO_8601_DATETIME_FORMAT) return True except ValueError: return False if complaints is None: complaints = [] if 'properties' in schema or isinstance(obj, dict): if not path: if 'id' in schema: path = schema['id'] else: path = '(root)' if obj is None: pass elif not isinstance(obj, dict): complaints.append('Expected a dict at %s, but had %s' % ( path, type(obj))) else: if 'properties' in schema: schema = schema['properties'] for name, sub_schema in schema.iteritems(): validate_object_matches_json_schema( obj.get(name), sub_schema, path + '.' + name, complaints) for name in obj: if name not in schema: complaints.append('Unexpected member "%s" in %s' % ( name, path)) elif 'items' in schema: if 'items' in schema['items']: complaints.append('Unsupported: array-of-array at ' + path) if obj is None: pass elif not isinstance(obj, (list, tuple)): complaints.append('Expected a list or tuple at %s, but had %s' % ( path, type(obj))) else: for index, item in enumerate(obj): item_path = path + '[%d]' % index if item is None: complaints.append('Found None at %s' % item_path) else: validate_object_matches_json_schema( item, schema['items'], item_path, complaints) else: if obj is None: if not schema.get('optional'): complaints.append('Missing mandatory value at ' + path) else: expected_type = None validator = None if schema['type'] in ('string', 'text', 'html', 'file'): expected_type = basestring elif schema['type'] == 'url': expected_type = basestring validator = is_valid_url elif schema['type'] in ('integer', 'timestamp'): expected_type = int elif schema['type'] in 'number': expected_type = float elif schema['type'] in 'boolean': expected_type = bool elif schema['type'] == 'date': expected_type = basestring validator = is_valid_date elif schema['type'] == 'datetime': expected_type = basestring validator = is_valid_datetime if expected_type: if not isinstance(obj, expected_type): complaints.append( 'Expected %s at %s, but instead had %s' % ( expected_type, path, type(obj))) elif validator and not validator(obj): complaints.append( 'Value "%s" is not well-formed according to %s' % ( str(obj), validator.__name__)) else: complaints.append( 'Unrecognized schema scalar type "%s" at %s' % ( schema['type'], path)) return complaints def dumps(*args, **kwargs): """Wrapper around json.dumps. No additional behavior; present here so this module is a drop-in replacement for json.dumps|loads. Clients should never use json.dumps|loads directly. See usage docs at http://docs.python.org/2/library/json.html. Args: *args: positional arguments delegated to json.dumps. **kwargs: keyword arguments delegated to json.dumps. Returns: string. The converted JSON. """ def set_encoder(obj): if isinstance(obj, set): return list(obj) return None def string_escape(in_str): # Defend against XSS by escaping <, > and non-ASCII chars out = StringIO() for c in in_str.decode('utf8'): char_val = ord(c) if char_val > 0x7f or c == '<' or c == '>': out.write('\\u%04X' % char_val) else: out.write(c) return out.getvalue() class CustomJSONEncoder(json.JSONEncoder): def default(self, obj): for f in CUSTOM_JSON_ENCODERS + [set_encoder]: value = f(obj) if value is not None: return value return super(CustomJSONEncoder, self).default(obj) if 'cls' not in kwargs: kwargs['cls'] = CustomJSONEncoder return string_escape(json.dumps(*args, **kwargs)) def loads(s, prefix=JSON_XSSI_PREFIX, strict=True, **kwargs): """Wrapper around json.loads that handles XSSI-protected responses. To prevent XSSI we insert a prefix before our JSON responses during server- side rendering. This loads() removes the prefix and should always be used in place of json.loads. See usage docs at http://docs.python.org/2/library/json.html. Args: s: str or unicode. JSON contents to convert. prefix: string. The XSSI prefix we remove before conversion. strict: boolean. If True use JSON parser, if False - YAML. YAML parser allows parsing of malformed JSON text, which has trailing commas and can't be parsed by the normal JSON parser. **kwargs: keyword arguments delegated to json.loads. Returns: object. Python object reconstituted from the given JSON string. """ if s.startswith(prefix): s = s.lstrip(prefix) if strict: return json.loads(s, **kwargs) else: return yaml.safe_load(s, **kwargs) def _json_to_datetime(value, date_only=False): DNMF = 'does not match format' if date_only: formats = _JSON_DATE_FORMATS else: formats = _JSON_DATETIME_FORMATS exception = None for format_str in formats: try: value = datetime.datetime.strptime(value, format_str) if date_only: value = value.date() return value except ValueError as e: # Save first exception so as to preserve the error message that # describes the most-preferred format, unless the new error # message is something other than "does-not-match-format", (and # the old one is) in which case save that, because anything other # than DNMF is more useful/informative. if not exception or (DNMF not in str(e) and DNMF in str(exception)): exception = e # We cannot get here without an exception. # The linter thinks we might still have 'None', but is mistaken. # pylint: disable=raising-bad-type raise exception def json_to_dict(source_dict, schema, permit_none_values=False): """Converts JSON dictionary into Python dictionary using schema.""" def convert_bool(value, key): if isinstance(value, types.NoneType): return False elif isinstance(value, bool): return value elif isinstance(value, basestring): value = value.lower() if value == 'true': return True elif value == 'false': return False raise ValueError('Bad boolean value for %s: %s' % (key, value)) output = {} for key, attr in schema['properties'].items(): # Skip schema elements that don't exist in source. if key not in source_dict: is_optional = convert_bool(attr.get('optional'), 'optional') if not is_optional: raise ValueError('Missing required attribute: %s' % key) continue # Reifying from database may provide "null", which translates to # None. As long as the field is optional (checked above), set # value to None directly (skipping conversions below). if permit_none_values and source_dict[key] is None: output[key] = None continue attr_type = attr['type'] if attr_type not in JSON_TYPES: raise ValueError('Unsupported JSON type: %s' % attr_type) if attr_type == 'object': output[key] = json_to_dict(source_dict[key], attr) elif attr_type == 'datetime' or attr_type == 'date': output[key] = _json_to_datetime(source_dict[key], attr_type == 'date') elif attr_type == 'number': output[key] = float(source_dict[key]) elif attr_type in ('integer', 'timestamp'): output[key] = int(source_dict[key]) if source_dict[key] else 0 elif attr_type == 'boolean': output[key] = convert_bool(source_dict[key], key) elif attr_type == 'array': subschema = attr['items'] array = [] for item in source_dict[key]: array.append(json_to_dict(item, subschema)) output[key] = array else: output[key] = source_dict[key] return output def string_to_value(string, value_type): """Converts string representation to a value.""" if value_type == str: if not string: return '' else: return string elif value_type == bool: if string == '1' or string == 'True' or string == 1: return True else: return False elif value_type == int or value_type == long: if not string: return 0 else: return long(string) else: raise ValueError('Unknown type: %s' % value_type) def value_to_string(value, value_type): """Converts value to a string representation.""" if value_type == str: return value elif value_type == bool: if value: return 'True' else: return 'False' elif value_type == int or value_type == long: return str(value) else: raise ValueError('Unknown type: %s' % value_type) def dict_to_instance(adict, instance, defaults=None): """Populates instance attributes using data dictionary.""" for key, unused_value in instance.__dict__.iteritems(): if not key.startswith('_'): if key in adict: setattr(instance, key, adict[key]) elif defaults and key in defaults: setattr(instance, key, defaults[key]) else: raise KeyError(key) def instance_to_dict(instance): """Populates data dictionary from instance attrs.""" adict = {} for key, unused_value in instance.__dict__.iteritems(): if not key.startswith('_'): adict[key] = getattr(instance, key) return adict def send_json_response( handler, status_code, message, payload_dict=None, xsrf_token=None): """Formats and sends out a JSON REST response envelope and body.""" handler.response.headers[ 'Content-Type'] = 'application/javascript; charset=utf-8' handler.response.headers['X-Content-Type-Options'] = 'nosniff' handler.response.headers['Content-Disposition'] = 'attachment' response = {} response['status'] = status_code response['message'] = message if payload_dict: response['payload'] = dumps(payload_dict) if xsrf_token: response['xsrf_token'] = xsrf_token handler.response.write(JSON_XSSI_PREFIX + dumps(response)) def send_file_upload_response( handler, status_code, message, payload_dict=None): """Formats and sends out a response to a file upload request. Args: handler: the request handler. status_code: int. The HTTP status code for the response. message: str. The text of the message. payload_dict: dict. A optional dict of extra data. """ handler.response.headers['Content-Type'] = 'text/xml' handler.response.headers['X-Content-Type-Options'] = 'nosniff' response_elt = ElementTree.Element('response') status_elt = ElementTree.Element('status') status_elt.text = str(status_code) response_elt.append(status_elt) message_elt = ElementTree.Element('message') message_elt.text = message response_elt.append(message_elt) if payload_dict: payload_elt = ElementTree.Element('payload') payload_elt.text = dumps(payload_dict) response_elt.append(payload_elt) handler.response.write(ElementTree.tostring(response_elt, encoding='utf-8')) class JsonFile(object): """A streaming file-ish interface for JSON content. Usage: writer = JsonFile('path') writer.open('w') writer.write(json_serializable_python_object) # We serialize for you. writer.write(another_json_serializable_python_object) writer.close() # Must close before read. reader = JsonFile('path') reader.open('r') # Only 'r' and 'w' are supported. for entity in reader: do_something_with(entity) # We deserialize back to Python for you. self.reader.reset() # Reset read pointer to head. contents = self.reader.read() # Returns {'rows': [...]}. for entity in contents['rows']: do_something_with(entity) # Again, deserialized back to Python. reader.close() with syntax is not supported. Cannot be used inside the App Engine container where the filesystem is read-only. Internally, each call to write will take a Python object, serialize it, and write the contents as one line to the json file. On __iter__ we deserialize one line at a time, generator-style, to avoid OOM unless serialization/de- serialization of one object exhausts memory. """ # When writing to files use \n instead of os.linesep; see # http://docs.python.org/2/library/os.html. _LINE_TEMPLATE = ',\n %s' _MODE_READ = 'r' _MODE_WRITE = 'w' _MODES = frozenset([_MODE_READ, _MODE_WRITE]) _PREFIX = '{"rows": [' _SUFFIX = ']}\n' # make sure output is new-line terminated def __init__(self, path): self._first = True self._file = None self._path = path def __iter__(self): assert self._file return self def close(self): """Closes the file; must close before read.""" assert self._file if not self._file.closed: # Like file, allow multiple close calls. if self.mode == self._MODE_WRITE: self._file.write('\n' + self._SUFFIX) self._file.close() @property def mode(self): """Returns the mode the file was opened in.""" assert self._file return self._file.mode @property def name(self): """Returns string name of the file.""" assert self._file return self._file.name def next(self): """Retrieves the next line and deserializes it into a Python object.""" assert self._file line = self._file.readline() if line.startswith(self._PREFIX): line = self._file.readline() if line.endswith(self._SUFFIX): raise StopIteration() line = line.strip() if line.endswith(','): line = line[:-1] return loads(line) def open(self, mode): """Opens the file in the given mode string ('r, 'w' only).""" assert not self._file assert mode in self._MODES self._file = open(self._path, mode) if self.mode == self._MODE_WRITE: self._file.write(self._PREFIX) def read(self): """Reads the file into a single Python object; may exhaust memory. Returns: dict. Format: {'rows': [...]} where the value is a list of de- serialized objects passed to write. """ assert self._file return loads(self._file.read()) def reset(self): """Resets file's position to head.""" assert self._file self._file.seek(0) def write(self, python_object): """Writes serialized JSON representation of python_object to file. Args: python_object: object. Contents to write. Must be JSON-serializable. Raises: ValueError: if python_object cannot be JSON-serialized. """ assert self._file template = self._LINE_TEMPLATE if self._first: template = template[1:] self._first = False self._file.write(template % dumps(python_object)) def convert_dict_to_xml(element, python_object): if isinstance(python_object, dict): for key, value in dict.items(python_object): dict_element = ElementTree.Element(key) element.append(dict_element) convert_dict_to_xml(dict_element, value) elif isinstance(python_object, list): list_element = ElementTree.Element('list') element.append(list_element) for item in python_object: item_element = ElementTree.Element('item') list_element.append(item_element) convert_dict_to_xml(item_element, item) else: try: loaded_python_object = loads(python_object) convert_dict_to_xml(element, loaded_python_object) except: # pylint: disable=bare-except element.text = unicode(python_object) return def convert_json_rows_file_to_xml(json_fn, xml_fn): """To XML converter for JSON files created by JsonFile writer. Usage: convert_json_rows_file_to_xml('Student.json', 'Student.xml') Args: json_fn: filename of the JSON file (readable with JsonFile) to import. xml_fn: filename of the target XML file to export. The dict and list objects are unwrapped; all other types are converted to Unicode strings. """ json_file = JsonFile(json_fn) json_file.open('r') xml_file = open(xml_fn, 'w') xml_file.write('<rows>') for line in json_file: root = ElementTree.Element('row') convert_dict_to_xml(root, line) xml_file.write(ElementTree.tostring(root, encoding='utf-8')) xml_file.write('\n') xml_file.write('</rows>') xml_file.close() def nested_lists_as_string_to_dict(stringified_list_of_lists): """Convert list of 2-item name/value lists to dict. This is for converting Student.additional_fields. When creating a Student, the raw HTML form content is just added to additional_fields without first converting into a dict. Thus we have a very dict-like thing which is actually expressed as a stringified list-of-lists. E.g., '[["age", "27"], ["gender", "female"], ["course_goal", "dabble"]] Args: stringified_list_of_lists: String as example above Returns: dict version of the list-of-key/value 2-tuples """ if not isinstance(stringified_list_of_lists, basestring): return None try: items = json.loads(stringified_list_of_lists) if not isinstance(items, list): return None for item in items: if not isinstance(item, list): return False if len(item) != 2: return False if not isinstance(item[0], basestring): return False return {item[0]: item[1] for item in items} except ValueError: return None def dict_to_nested_lists_as_string(d): """Convert a dict to stringified list-of-2-tuples format.""" return json.dumps([[a, b] for a, b in d.items()])
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Constants shared between transforms.py and entity_transforms.py.""" __author__ = 'Mike Gainer (mgainer@google.com)' SIMPLE_TYPES = (int, long, float, bool, dict, basestring, list)
Python
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Common classes and methods for managing long running jobs.""" __author__ = 'Pavel Simakov (psimakov@google.com)' import ast import datetime import logging import time import traceback import urllib import entities from mapreduce import base_handler from mapreduce import input_readers from mapreduce import mapreduce_pipeline from mapreduce.lib.pipeline import pipeline import transforms from common.utils import Namespace from google.appengine import runtime from google.appengine.api import users from google.appengine.ext import db from google.appengine.ext import deferred # A job can be in one of these states. STATUS_CODE_QUEUED = 0 STATUS_CODE_STARTED = 1 STATUS_CODE_COMPLETED = 2 STATUS_CODE_FAILED = 3 STATUS_CODE_DESCRIPTION = { STATUS_CODE_QUEUED: 'Queued', STATUS_CODE_STARTED: 'Started', STATUS_CODE_COMPLETED: 'Completed', STATUS_CODE_FAILED: 'Failed', } # The methods in DurableJobEntity are module-level protected # pylint: disable=protected-access class DurableJobBase(object): """A class that represents a deferred durable job at runtime.""" xg_on = db.create_transaction_options(xg=True) @staticmethod def get_description(): """Briefly describe the nature and purpose of your job type. This is used in the display code of analytics to complete sentences like "<description> statistics have not been calculated yet". Don't capitalize; captialization will be automatically performed where <description> appears at the start of a sentence or in a section title. """ raise NotImplementedError( 'Leaf classes inheriting from DurableJobBase should provide a ' 'brief description of their nature and purpose. E.g., ' '"student ranking"') def __init__(self, app_context): self._app_context = app_context self._namespace = app_context.get_namespace_name() self._job_name = 'job-%s-%s' % ( self.__class__.__name__, self._namespace) def submit(self): if self.is_active(): return -1 with Namespace(self._namespace): if not self._pre_transaction_setup(): return -1 return db.run_in_transaction_options(self.xg_on, self.non_transactional_submit) def non_transactional_submit(self): with Namespace(self._namespace): return DurableJobEntity._create_job(self._job_name) def load(self): """Loads the last known state of this job from the datastore.""" with Namespace(self._namespace): return DurableJobEntity._get_by_name(self._job_name) def cancel(self): job = self.load() if job and not job.has_finished: user = users.get_current_user() message = 'Canceled by %s at %s' % ( user.nickname() if user else 'default', datetime.datetime.now().strftime('%Y-%m-%d, %H:%M UTC')) duration = int((datetime.datetime.now() - job.updated_on) .total_seconds()) with Namespace(self._namespace): # Do work specific to job type outside of our transaction self._cancel_queued_work(job, message) # Update our job record return db.run_in_transaction(self._mark_job_canceled, job, message, duration) return job def _cancel_queued_work(self, unused_job, unused_message): """Override in subclasses to do cancel work outside transaction.""" pass def _mark_job_canceled(self, job, message, duration): DurableJobEntity._fail_job( self._job_name, job.sequence_num, message, duration) def is_active(self): job = self.load() return job and not job.has_finished def _pre_transaction_setup(self): return True # All is well. class DurableJob(DurableJobBase): def run(self): """Override this method to provide actual business logic.""" def main(self, sequence_num): """Main method of the deferred task.""" with Namespace(self._namespace): logging.info('Job started: %s w/ sequence number %d', self._job_name, sequence_num) time_started = time.time() try: db.run_in_transaction(DurableJobEntity._start_job, self._job_name, sequence_num) result = self.run() db.run_in_transaction(DurableJobEntity._complete_job, self._job_name, sequence_num, transforms.dumps(result), long(time.time() - time_started)) logging.info('Job completed: %s', self._job_name) except (Exception, runtime.DeadlineExceededError) as e: logging.error(traceback.format_exc()) logging.error('Job failed: %s\n%s', self._job_name, e) db.run_in_transaction(DurableJobEntity._fail_job, self._job_name, sequence_num, traceback.format_exc(), long(time.time() - time_started)) raise deferred.PermanentTaskFailure(e) def non_transactional_submit(self): sequence_num = super(DurableJob, self).non_transactional_submit() deferred.defer(self.main, sequence_num) return sequence_num class MapReduceJobPipeline(base_handler.PipelineBase): def run(self, job_name, sequence_num, kwargs, namespace): time_started = time.time() with Namespace(namespace): db.run_in_transaction( DurableJobEntity._start_job, job_name, sequence_num, MapReduceJob.build_output(self.root_pipeline_id, [])) output = yield mapreduce_pipeline.MapreducePipeline(**kwargs) yield StoreMapReduceResults(job_name, sequence_num, time_started, namespace, output) def finalized(self): pass # Suppress default Pipeline behavior of sending email. class StoreMapReduceResults(base_handler.PipelineBase): def run(self, job_name, sequence_num, time_started, namespace, output): results = [] # TODO(mgainer): Notice errors earlier in pipeline, and mark job # as failed in that case as well. try: iterator = input_readers.RecordsReader(output, 0) for item in iterator: # Map/reduce puts reducer output into blobstore files as a # string obtained via "str(result)". Use AST as a safe # alternative to eval() to get the Python object back. results.append(ast.literal_eval(item)) time_completed = time.time() with Namespace(namespace): db.run_in_transaction( DurableJobEntity._complete_job, job_name, sequence_num, MapReduceJob.build_output(self.root_pipeline_id, results), long(time_completed - time_started)) # Don't know what exceptions are currently, or will be in future, # thrown from Map/Reduce or Pipeline libraries; these are under # active development. # # pylint: disable=broad-except except Exception, ex: time_completed = time.time() with Namespace(namespace): db.run_in_transaction( DurableJobEntity._fail_job, job_name, sequence_num, MapReduceJob.build_output(self.root_pipeline_id, results, str(ex)), long(time_completed - time_started)) class MapReduceJob(DurableJobBase): # The 'output' field in the DurableJobEntity representing a MapReduceJob # is a map with the following keys: # # _OUTPUT_KEY_ROOT_PIPELINE_ID # Holds a string representing the ID of the MapReduceJobPipeline # as known to the mapreduce/lib/pipeline internals. This is used # to generate URLs pointing at the pipeline support UI for detailed # inspection of pipeline action. # # _OUTPUT_KEY_RESULTS # Holds a list of individual results. The result items will be of # whatever type is 'yield'-ed from the 'reduce' method (see below). # # _OUTPUT_KEY_ERROR # Stringified error message in the event that something has gone wrong # with the job. Present and relevant only if job status is # STATUS_CODE_FAILED. _OUTPUT_KEY_ROOT_PIPELINE_ID = 'root_pipeline_id' _OUTPUT_KEY_RESULTS = 'results' _OUTPUT_KEY_ERROR = 'error' @staticmethod def build_output(root_pipeline_id, results_list, error=None): return transforms.dumps({ MapReduceJob._OUTPUT_KEY_ROOT_PIPELINE_ID: root_pipeline_id, MapReduceJob._OUTPUT_KEY_RESULTS: results_list, MapReduceJob._OUTPUT_KEY_ERROR: error, }) @staticmethod def get_status_url(job, namespace, xsrf_token): if not job.output: return None content = transforms.loads(job.output) pipeline_id = content[MapReduceJob._OUTPUT_KEY_ROOT_PIPELINE_ID] return ('/mapreduce/ui/pipeline/status?' + urllib.urlencode({'root': pipeline_id, 'namespace': namespace, 'xsrf_token': xsrf_token})) @staticmethod def get_root_pipeline_id(job): if not job or not job.output: return None content = transforms.loads(job.output) return content[MapReduceJob._OUTPUT_KEY_ROOT_PIPELINE_ID] @staticmethod def has_status_url(job): if not job.output: return False return MapReduceJob._OUTPUT_KEY_ROOT_PIPELINE_ID in job.output @staticmethod def get_results(job): if not job.output: return None content = transforms.loads(job.output) return content[MapReduceJob._OUTPUT_KEY_RESULTS] @staticmethod def get_error_message(job): if not job.output: return None content = transforms.loads(job.output) return content[MapReduceJob._OUTPUT_KEY_ERROR] def entity_class(self): """Return a reference to the class for the DB/NDB type to map over.""" raise NotImplementedError('Classes derived from MapReduceJob must ' 'implement entity_class()') @staticmethod def map(item): """Implements the map function. Must be declared @staticmethod. Args: item: The parameter passed to this function is a single element of the type given by entity_class(). This function may <em>yield</em> as many times as appropriate (including zero) to return key/value 2-tuples. E.g., for calculating student scores from a packed block of course events, this function would take as input the packed block. It would iterate over the events, 'yield'-ing for those events that respresent items counting towards the grade. E.g., yield (event.student, event.data['score']) """ raise NotImplementedError('Classes derived from MapReduceJob must ' 'implement map as a @staticmethod.') @staticmethod def reduce(key, values): """Implements the reduce function. Must be declared @staticmethod. This function should <em>yield</em> whatever it likes; the recommended thing to do is emit entities. All emitted outputs from all reducers will be collected in an array and set into the output value for the job, so don't pick anything humongous. If you need humongous, instead persist out your humongous stuff and return a reference (and deal with doing the dereference to load content in the FooHandler class in analytics.py) Args: key: A key value as emitted from the map() function, above. values: A list of all values from all mappers that were tagged with the given key. This code can assume that it is the only process handling values for this key. AFAICT, it can also assume that it will be called exactly once for each key with all of the output, but this may not be a safe assumption; needs to be verified. """ raise NotImplementedError('Classes derived from MapReduceJob must ' 'implement map as a @staticmethod.') @staticmethod def combine(unused_key, values, previously_combined_values): """Optional. Performs reduce task on mappers to minimize shuffling. After the map() function, each job-host has a chunk of yield()-ed results, often for the same key. Rather than send all of those separate results over to the appropriate reducer task, it would be nice to be able to pre-combine these items within the mapper job, so as to minimize the amount of data that needs to be shuffled and piped out to reducers. If your reduce step is strictly aggregative in nature (specifically, if the reduce: 1.) does not need to have the entire universe of mapped-values for the same key in order to operate correctly 2.) can meaningfully combine partial results into another partial result, which can itself later be combined (either in another collect() call, or in the final reduce() call) then you're OK to implement this function. NOTE that since this function can't make up any new keys, the framework expects the yield() from this function to yield only a single combined value, not a key/value pair. See the example below in AbstractCountingMapReduceJob. """ raise NotImplementedError('Classes derived from MapReduceJob may ' 'optionally implement combine() as a static ' 'method.') def build_additional_mapper_params(self, unused_app_context): """Build a dict of additional parameters to make available to mappers. The map/reduce framework permits an arbitrary dict of plain-old-data items to be passed along and made available to mapper jobs. This is very useful if you have a small-ish (10s of K) amount of data that is needed as a lookup table or similar when the mapper is running, and which is expensive to re-calculate within each mapper job. To make use of this, override this function and return a dict. This will be merged with the mapper_params. Note that you cannot override the reserved items already in mapper_params: - 'entity_kind' - The name of the DB entity class mapped over - 'namespace' - The namespace in which mappers operate. To access this extra data, you need to: from mapreduce import context class MyMapReduceClass(jobs.MapReduceJob): def build_additional_mapper_params(self, app_context): .... set up values to be conveyed to mappers ... return { 'foo': foo, .... } @staticmethod def map(item): mapper_params = context.get().mapreduce_spec.mapper.params foo = mapper_params['foo'] .... yield(...) Args: unused_app_context: Caller provides namespaced context for subclass implementation of this function. Returns: A dict of name/value pairs that should be made available to map jobs. """ return {} def _pre_transaction_setup(self): """Hack to allow use of DB before we are formally in a txn.""" self.mapper_params = self.build_additional_mapper_params( self._app_context) return True def non_transactional_submit(self): if self.is_active(): return -1 sequence_num = super(MapReduceJob, self).non_transactional_submit() entity_class_type = self.entity_class() entity_class_name = '%s.%s' % (entity_class_type.__module__, entity_class_type.__name__) # Build config parameters to make available to map framework # and individual mapper jobs. Overwrite important parameters # so derived class cannot mistakenly set them. self.mapper_params.update({ 'entity_kind': entity_class_name, 'namespace': self._namespace, }) kwargs = { 'job_name': self._job_name, 'mapper_spec': '%s.%s.map' % ( self.__class__.__module__, self.__class__.__name__), 'reducer_spec': '%s.%s.reduce' % ( self.__class__.__module__, self.__class__.__name__), 'input_reader_spec': 'mapreduce.input_readers.DatastoreInputReader', 'output_writer_spec': 'mapreduce.output_writers.BlobstoreRecordsOutputWriter', 'mapper_params': self.mapper_params, 'reducer_params': self.mapper_params, } if (getattr(self.__class__, 'combine') != getattr(MapReduceJob, 'combine')): kwargs['combiner_spec'] = '%s.%s.combine' % ( self.__class__.__module__, self.__class__.__name__) mr_pipeline = MapReduceJobPipeline(self._job_name, sequence_num, kwargs, self._namespace) mr_pipeline.start(base_path='/mapreduce/worker/pipeline') return sequence_num def _cancel_queued_work(self, job, message): root_pipeline_id = MapReduceJob.get_root_pipeline_id(job) if root_pipeline_id: p = pipeline.Pipeline.from_id(root_pipeline_id) if p: p.abort(message) def _mark_job_canceled(self, job, message, duration): DurableJobEntity._fail_job( self._job_name, job.sequence_num, MapReduceJob.build_output(None, None, message), duration) def mark_cleaned_up(self): job = self.load() # If the job has already finished, then the cleanup is a # no-op; we are just reclaiming transient state. However, if # our DurableJobEntity still thinks the job is running and it # is actually not, then mark the status message to indicate # the cleanup. if job and not job.has_finished: duration = int((datetime.datetime.utcnow() - job.updated_on) .total_seconds()) with Namespace(self._namespace): return db.run_in_transaction( self._mark_job_canceled, job, 'Job has not completed; assumed to have failed after %s' % str(datetime.timedelta(seconds=duration)), duration) return job class AbstractCountingMapReduceJob(MapReduceJob): """Provide common functionality for map/reduce jobs that just count. This class provides a common implementation of combine() and reduce() so that a map/reduce task that is only concerned with counting the number of occurrences of something can be more terse. E.g., if we want to get a total of the number of students with the same first name, we only need to write: class NameCounter(jobs.AbstractCountingMapReduceJob): @staticmethod def get_description(): return "count names" def entity_class(): return models.Student @staticmethod def map(student): return (student.name.split()[0], 1) The output of this job will be an array of 2-tuples consisting of the name and the total number of students with that same first name. """ @staticmethod def combine(unused_key, values, previously_combined_outputs=None): total = sum([int(value) for value in values]) if previously_combined_outputs is not None: total += sum([int(value) for value in previously_combined_outputs]) yield total @staticmethod def reduce(key, values): total = sum(int(value) for value in values) yield (key, total) class DurableJobEntity(entities.BaseEntity): """A class that represents a persistent database entity of durable job.""" updated_on = db.DateTimeProperty(indexed=True) execution_time_sec = db.IntegerProperty(indexed=False) status_code = db.IntegerProperty(indexed=False) output = db.TextProperty(indexed=False) sequence_num = db.IntegerProperty(indexed=False) @classmethod def _get_by_name(cls, name): return DurableJobEntity.get_by_key_name(name) @classmethod def _update(cls, name, sequence_num, status_code, output, execution_time_sec): """Updates job state in a datastore.""" assert db.is_in_transaction() job = DurableJobEntity._get_by_name(name) if not job: logging.error('Job was not started or was deleted: %s', name) return if job.sequence_num != sequence_num: logging.warning( 'Request to update status code to %d ' % status_code + 'for sequence number %d ' % sequence_num + 'but job is already on run %d' % job.sequence_num) return job.updated_on = datetime.datetime.now() job.execution_time_sec = execution_time_sec job.status_code = status_code if output: job.output = output job.put() @classmethod def _create_job(cls, name): """Creates new or reset a state of existing job in a datastore.""" assert db.is_in_transaction() job = DurableJobEntity._get_by_name(name) if not job: job = DurableJobEntity(key_name=name) job.updated_on = datetime.datetime.now() job.execution_time_sec = 0 job.status_code = STATUS_CODE_QUEUED job.output = None if not job.sequence_num: job.sequence_num = 1 else: job.sequence_num += 1 job.put() return job.sequence_num @classmethod def _start_job(cls, name, sequence_num, output=None): return cls._update(name, sequence_num, STATUS_CODE_STARTED, output, 0) @classmethod def _complete_job(cls, name, sequence_num, output, execution_time_sec): return cls._update(name, sequence_num, STATUS_CODE_COMPLETED, output, execution_time_sec) @classmethod def _fail_job(cls, name, sequence_num, output, execution_time_sec): return cls._update(name, sequence_num, STATUS_CODE_FAILED, output, execution_time_sec) @property def has_finished(self): return self.status_code in [STATUS_CODE_COMPLETED, STATUS_CODE_FAILED]
Python
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Models and helper utilities for the review workflow.""" __author__ = [ 'johncox@google.com (John Cox)', 'sll@google.com (Sean Lip)', ] import entities import transforms import models from google.appengine.ext import db class KeyProperty(db.StringProperty): """A property that stores a datastore key. App Engine's db.ReferenceProperty is dangerous because accessing a ReferenceProperty on a model instance implicitly causes an RPC. We always want to know about and be in control of our RPCs, so we use this property instead, store a key, and manually make datastore calls when necessary. This is analogous to the approach ndb takes, and it also allows us to do validation against a key's kind (see __init__). Keys are stored as indexed strings internally. Usage: class Foo(db.Model): pass class Bar(db.Model): foo_key = KeyProperty(kind=Foo) # Validates key is of kind 'Foo'. foo_key = Foo().put() bar = Bar(foo_key=foo_key) bar_key = bar.put() foo = db.get(bar.foo_key) """ def __init__(self, *args, **kwargs): """Constructs a new KeyProperty. Args: *args: positional arguments passed to superclass. **kwargs: keyword arguments passed to superclass. Additionally may contain kind, which if passed will be a string used to validate key kind. If omitted, any kind is considered valid. """ kind = kwargs.pop('kind', None) super(KeyProperty, self).__init__(*args, **kwargs) self._kind = kind def validate(self, value): """Validates passed db.Key value, validating kind passed to ctor.""" super(KeyProperty, self).validate(str(value)) if value is None: # Nones are valid iff they pass the parent validator. return value if not isinstance(value, db.Key): raise db.BadValueError( 'Value must be of type db.Key; got %s' % type(value)) if self._kind and value.kind() != self._kind: raise db.BadValueError( 'Key must be of kind %s; was %s' % (self._kind, value.kind())) return value # For many classes we define both a _DomainObject subclass and a db.Model. # When possible it is best to use the domain object, since db.Model carries with # it the datastore API and allows clients to bypass business logic by making # direct datastore calls. class BaseEntity(entities.BaseEntity): """Abstract base entity for models related to reviews.""" @classmethod def key_name(cls): """Returns a key_name for use with cls's constructor.""" raise NotImplementedError @classmethod def _split_key(cls, key_name): """Takes a key_name and returns its components.""" # '(a:b:(c:d:(e:f:g)):h)' -> ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']. return key_name.replace('(', '').replace(')', '').split(':') class Review(BaseEntity): """Datastore model for a student review of a Submission.""" # Contents of the student's review. Max size is 1MB. contents = db.TextProperty() # Key of the student whose work is being reviewed. reviewee_key = KeyProperty(kind=models.Student.kind()) # Key of the Student who wrote this review. reviewer_key = KeyProperty(kind=models.Student.kind()) # Identifier of the unit this review is a part of. unit_id = db.StringProperty(required=True) def __init__(self, *args, **kwargs): """Constructs a new Review.""" assert not kwargs.get('key_name'), ( 'Setting key_name manually is not supported') reviewee_key = kwargs.get('reviewee_key') reviewer_key = kwargs.get('reviewer_key') unit_id = kwargs.get('unit_id') assert reviewee_key, 'Missing required property: reviewee_key' assert reviewer_key, 'Missing required property: reviewer_key' assert unit_id, 'Missing required_property: unit_id' kwargs['key_name'] = self.key_name(unit_id, reviewee_key, reviewer_key) super(Review, self).__init__(*args, **kwargs) @classmethod def key_name(cls, unit_id, reviewee_key, reviewer_key): """Creates a key_name string for datastore operations. In order to work with the review subsystem, entities must have a key name populated from this method. Args: unit_id: string. The id of the unit this review belongs to. reviewee_key: db.Key of models.models.Student. The student whose work is being reviewed. reviewer_key: db.Key of models.models.Student. The author of this the review. Returns: String. """ return '(review:%s:%s:%s)' % (unit_id, reviewee_key, reviewer_key) @classmethod def safe_key(cls, db_key, transform_fn): _, unit_id, reviewee_key_str, reviewer_key_str = cls._split_key( db_key.name()) reviewee_key = db.Key(encoded=reviewee_key_str) reviewer_key = db.Key(encoded=reviewer_key_str) safe_reviewee_key = models.Student.safe_key(reviewee_key, transform_fn) safe_reviewer_key = models.Student.safe_key(reviewer_key, transform_fn) return db.Key.from_path( cls.kind(), cls.key_name(unit_id, safe_reviewee_key, safe_reviewer_key)) def for_export(self, transform_fn): model = super(Review, self).for_export(transform_fn) model.reviewee_key = models.Student.safe_key( model.reviewee_key, transform_fn) model.reviewer_key = models.Student.safe_key( model.reviewer_key, transform_fn) return model class Submission(BaseEntity): """Datastore model for a student work submission.""" # Contents of the student submission. Max size is 1MB. contents = db.TextProperty() # Key of the Student who wrote this submission. reviewee_key = KeyProperty(kind=models.Student.kind()) # Identifier of the unit this review is a part of. unit_id = db.StringProperty(required=True) def __init__(self, *args, **kwargs): """Constructs a new Submission.""" assert not kwargs.get('key_name'), ( 'Setting key_name manually is not supported') reviewee_key = kwargs.get('reviewee_key') unit_id = kwargs.get('unit_id') assert reviewee_key, 'Missing required property: reviewee_key' assert unit_id, 'Missing required_property: unit_id' kwargs['key_name'] = self.key_name(unit_id, reviewee_key) super(Submission, self).__init__(*args, **kwargs) @classmethod def _get_student_key(cls, value): return db.Key.from_path(models.Student.kind(), value) @classmethod def key_name(cls, unit_id, reviewee_key): """Creates a key_name string for datastore operations. In order to work with the review subsystem, entities must have a key name populated from this method. Args: unit_id: string. The id of the unit this submission belongs to. reviewee_key: db.Key of models.models.Student. The author of the the submission. Returns: String. """ return '(submission:%s:%s)' % (unit_id, reviewee_key.id_or_name()) @classmethod def get_key(cls, unit_id, reviewee_key): """Returns a db.Key for a submission.""" return db.Key.from_path( cls.kind(), cls.key_name(unit_id, reviewee_key)) @classmethod def safe_key(cls, db_key, transform_fn): _, unit_id, student_key_str = cls._split_key(db_key.name()) student_key = db.Key.from_path(models.Student.kind(), student_key_str) safe_student_key = models.Student.safe_key(student_key, transform_fn) return db.Key.from_path( cls.kind(), cls.key_name(unit_id, safe_student_key)) @classmethod def write(cls, unit_id, reviewee_key, contents): """Updates or creates a student submission, and returns the key. Args: unit_id: string. The id of the unit this submission belongs to. reviewee_key: db.Key of models.models.Student. The author of the submission. contents: object. The contents of the submission, as a Python object. This will be JSON-transformed before it is stored. Returns: db.Key of Submission. """ return cls( unit_id=str(unit_id), reviewee_key=reviewee_key, contents=transforms.dumps(contents) ).put() @classmethod def get_contents(cls, unit_id, reviewee_key): """Returns the de-JSONified contents of a submission.""" submission_key = cls.get_key(unit_id, reviewee_key) return cls.get_contents_by_key(submission_key) @classmethod def get_contents_by_key(cls, submission_key): """Returns the contents of a submission, given a db.Key.""" submission = entities.get(submission_key) return transforms.loads(submission.contents) if submission else None def for_export(self, transform_fn): model = super(Submission, self).for_export(transform_fn) model.reviewee_key = models.Student.safe_key( model.reviewee_key, transform_fn) return model class StudentWorkUtils(object): """A utility class for processing student work objects.""" @classmethod def get_answer_list(cls, submission): """Compiles a list of the student's answers from a submission.""" if not submission: return [] answer_list = [] for item in submission: # Check that the indices within the submission are valid. assert item['index'] == len(answer_list) answer_list.append(item['value']) return answer_list
Python
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Common classes and methods for managing persistent entities.""" __author__ = 'Pavel Simakov (psimakov@google.com)' from counters import PerfCounter import transforms from google.appengine.ext import db # datastore performance counters DB_QUERY = PerfCounter( 'gcb-models-db-query', 'A number of times a query()/all() was executed on a datastore.') DB_GET = PerfCounter( 'gcb-models-db-get', 'A number of times an object was fetched from datastore.') DB_PUT = PerfCounter( 'gcb-models-db-put', 'A number of times an object was put into datastore.') DB_DELETE = PerfCounter( 'gcb-models-db-delete', 'A number of times an object was deleted from datastore.') # String. Name of the safe key property used for data export. SAFE_KEY_NAME = 'safe_key' def delete(keys): """Wrapper around db.delete that counts entities we attempted to get.""" DB_DELETE.inc(increment=_count(keys)) return db.delete(keys) def get(keys): """Wrapper around db.get that counts entities we attempted to get.""" DB_GET.inc(increment=_count(keys)) return db.get(keys) def put(keys): """Wrapper around db.put that counts entities we attempted to put.""" DB_PUT.inc(increment=_count(keys)) return db.put(keys) def _count(keys): # App engine accepts key or list of key; count entities found. return len(keys) if isinstance(keys, (list, tuple)) else 1 class ExportEntity(db.Expando): """An entity instantiated, but never saved; for data export only. Will not work with the webapp. """ def __init__(self, *args, **kwargs): assert kwargs.get(SAFE_KEY_NAME) super(ExportEntity, self).__init__(*args, **kwargs) def get(self): raise NotImplementedError def put(self): raise NotImplementedError class BaseEntity(db.Model): """A common class to all datastore entities.""" # List of db.Property, or string. This lists the properties on this # model that should be purged before export via tools/etl.py because they # contain private information about a user. If a property is internally # structured, the name may identify sub-components to remove. E.g., # for a record of type Student, you might specify: # _PROPERTY_EXPORT_BLACKLIST = [ # name, # A db.Property in Student # 'additional_fields.gender', # A named sub-element # 'additional_fields.age', # ditto. # ] # This syntax permits non-PII fields (e.g. 'additional_fields.course_goal') # to remain present. It is harmless to name items that are not present; # this permits backward compatibility with older versions of DB entities. # # For fields that must be transformed rather than purged, see # BaseEntity.for_export(). _PROPERTY_EXPORT_BLACKLIST = [] @classmethod def all(cls, **kwds): DB_QUERY.inc() return super(BaseEntity, cls).all(**kwds) @classmethod def get(cls, keys): DB_GET.inc() return super(BaseEntity, cls).get(keys) @classmethod def get_by_key_name(cls, key_names): DB_GET.inc() return super(BaseEntity, cls).get_by_key_name(key_names) @classmethod def safe_key(cls, db_key, unused_transform_fn): """Creates a copy of db_key that is safe for export. Keys may contain sensitive user data, like the user_id of a users.User. This method takes a db_key for an entity that is the same kind as cls. It returns a new instance of a key for that same kind with any sensitive data irreversibly transformed. The suggested irreversible transformation is cls.hash. The transformation must take a value and a client-defined secret. It must be deterministic and nonreversible. Args: db_key: db.Key of the same kind as cls. Key containing original values. unused_transform_fn: function that takes a single argument castable to string and returns a transformed string of that user data that is safe for export. If no user data is sensitive, the identity transform should be used. Used in subclass implementations. Returns: db.Key of the same kind as cls with sensitive data irreversibly transformed. """ assert cls.kind() == db_key.kind() return db_key @classmethod def _get_export_blacklist(cls): """Collapses all _PROPERTY_EXPORT_BLACKLISTs in the class hierarchy.""" blacklist = [] for klass in cls.__mro__: if hasattr(klass, '_PROPERTY_EXPORT_BLACKLIST'): # Treat as module-protected. # pylint: disable=protected-access blacklist.extend(klass._PROPERTY_EXPORT_BLACKLIST) for index, item in enumerate(blacklist): if isinstance(item, db.Property): blacklist[index] = item.name elif isinstance(item, basestring): pass else: raise ValueError( 'Blacklist entries must be either a db.Property ' + 'or a string. The entry "%s" is neither. ' % str(item)) return sorted(set(blacklist)) def put(self): DB_PUT.inc() return super(BaseEntity, self).put() def delete(self): DB_DELETE.inc() super(BaseEntity, self).delete() def _properties_for_export(self, transform_fn): """Creates an ExportEntity populated from this entity instance. This method is called during export via tools/etl.py to make an entity instance safe for export via tools/etl.py when --privacy is passed. For this to obtain, 1) Properties that need to be purged must be deleted from the instance. Subclasses can set these fields in _PROPERTY_EXPORT_BLACKLIST. 2) Properties that need to be transformed should be modified in subclass implementations. In particular, properties with customizable JSON contents often need to be handled this way. Args: transform_fn: function that takes a single argument castable to string and returns a transformed string of that user data that is safe for export. If no user data is sensitive, the identity transform should be used. Raises: ValueError: if the _PROPERTY_EXPORT_BLACKLIST contains anything other than db.Property references or strings. Returns: EventEntity populated with the fields from self, plus a new field called 'safe_key', containing a string representation of the value returned by cls.safe_key(). """ properties = {} # key is a reserved property and cannot be mutated; write to safe_key # instead, but refuse to handle entities that set safe_key themselves. # TODO(johncox): reserve safe_key so it cannot be used in the first # place? assert SAFE_KEY_NAME not in self.properties().iterkeys() properties[SAFE_KEY_NAME] = self.safe_key(self.key(), transform_fn) for name, prop in self.properties().items(): if isinstance(prop, db.ReferenceProperty): referent = getattr(self, name) if referent: unsafe_key = referent.key() safe_key = referent.safe_key(unsafe_key, transform_fn) properties[name] = str(safe_key) else: properties[name] = getattr(self, name) return properties def for_export(self, transform_fn): properties = self._properties_for_export(transform_fn) # Blacklist may contain db.Property, or names as strings. If string, # the name may be a dotted list of containers. This is useful for # redacting sub-items. E.g., for the type Student, # specifying 'additional_items.name' would remove the PII item for # the student's name, but not affect additional_items['goal'], # (the student's goal for the course), which is not PII. for item in self._get_export_blacklist(): self._remove_named_component(item, properties) return ExportEntity(**properties) def for_export_unsafe(self): """Get properties for entity ignoring blacklist, and without encryption. Using this function is strongly discouraged. The only situation in which this function is merited is for the export of data for analysis, where that analysis: - Requires PII (e.g., gender, age, detailed locale, income level, etc.) - Will be aggregated such that individuals' PII is not retained - Subject to a data retention policy with a maximum age. In particular, the Data Pump will not infrequently need to send per-Student data. This will often contain user-supplied PII in the 'additional_fields' member. This function permits the use of BigQuery for analyses not shipped with base CourseBuilder. (Note that BigQuery permits specification of a maximum data retention period, and the Data Pump sets this age by default to 30 days. This is overridable, but only on individual requests) Returns: An ExportEntity (db.Expando) containing the entity's properties. """ properties = self._properties_for_export(lambda x: x) return ExportEntity(**properties) @classmethod def _remove_named_component(cls, spec, container): name, tail = spec.split('.', 1) if '.' in spec else (spec, None) if isinstance(container, dict) and name in container: if tail: tmp_dict = transforms.nested_lists_as_string_to_dict( container[name]) if tmp_dict: cls._remove_named_component(tail, tmp_dict) container[name] = transforms.dict_to_nested_lists_as_string( tmp_dict) else: cls._remove_named_component(tail, container[name]) else: del container[name]
Python
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Manages performance counters of an application and/or its modules.""" __author__ = 'Pavel Simakov (psimakov@google.com)' def incr_counter_global_value(unused_name, unused_delta): """Hook method for global aggregation.""" pass def get_counter_global_value(unused_name): """Hook method for global aggregation.""" return None class PerfCounter(object): """A generic, in-process integer counter.""" def __init__(self, name, doc_string): self._name = name self._doc_string = doc_string self._value = 0 Registry.registered[self.name] = self def _clear(self): """Resets value for tests.""" self._value = 0 def inc( self, increment=1, context=None): # pylint: disable=unused-argument """Increments value by a given increment.""" self._value += increment incr_counter_global_value(self.name, increment) def poll_value(self): """Override this method to return the desired value directly.""" return None @property def name(self): return self._name @property def doc_string(self): return self._doc_string @property def value(self): """Value for this process only.""" value = self.poll_value() if value: return value return self._value @property def global_value(self): """Value aggregated across all processes.""" return get_counter_global_value(self.name) class Registry(object): """Holds all registered counters.""" registered = {} @classmethod def _clear_all(cls): """Clears all counters for tests.""" for counter in cls.registered.values(): counter._clear() # pylint: disable=protected-access
Python
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Core data model classes.""" __author__ = 'Pavel Simakov (psimakov@google.com)' import collections import copy import logging import os import sys import time from config import ConfigProperty import counters from counters import PerfCounter from entities import BaseEntity import jinja2 import services import transforms import appengine_config from common import caching from common import utils as common_utils from google.appengine.api import memcache from google.appengine.api import namespace_manager from google.appengine.api import users from google.appengine.ext import db # We want to use memcache for both objects that exist and do not exist in the # datastore. If object exists we cache its instance, if object does not exist # we cache this object below. NO_OBJECT = {} # The default amount of time to cache the items for in memcache. DEFAULT_CACHE_TTL_SECS = 60 * 5 # https://developers.google.com/appengine/docs/python/memcache/#Python_Limits MEMCACHE_MAX = (1000 * 1000 - 96 - 250) MEMCACHE_MULTI_MAX = 32 * 1000 * 1000 # Global memcache controls. CAN_USE_MEMCACHE = ConfigProperty( 'gcb_can_use_memcache', bool, ( 'Whether or not to cache various objects in memcache. For production ' 'this value should be on to enable maximum performance. For ' 'development this value should be off so you can see your changes to ' 'course content instantaneously.'), appengine_config.PRODUCTION_MODE) # performance counters CACHE_PUT = PerfCounter( 'gcb-models-cache-put', 'A number of times an object was put into memcache.') CACHE_PUT_TOO_BIG = PerfCounter( 'gcb-models-cache-put-too-big', 'Number of times an object was too big to put in memcache.') CACHE_HIT = PerfCounter( 'gcb-models-cache-hit', 'A number of times an object was found in memcache.') CACHE_MISS = PerfCounter( 'gcb-models-cache-miss', 'A number of times an object was not found in memcache.') CACHE_DELETE = PerfCounter( 'gcb-models-cache-delete', 'A number of times an object was deleted from memcache.') # performance counters for in-process cache CACHE_PUT_LOCAL = PerfCounter( 'gcb-models-cache-put-local', 'A number of times an object was put into local memcache.') CACHE_HIT_LOCAL = PerfCounter( 'gcb-models-cache-hit-local', 'A number of times an object was found in local memcache.') CACHE_MISS_LOCAL = PerfCounter( 'gcb-models-cache-miss-local', 'A number of times an object was not found in local memcache.') # Intent for sending welcome notifications. WELCOME_NOTIFICATION_INTENT = 'welcome' class MemcacheManager(object): """Class that consolidates all memcache operations.""" _LOCAL_CACHE = None _IS_READONLY = False _READONLY_REENTRY_COUNT = 0 _READONLY_APP_CONTEXT = None @classmethod def _is_same_app_context_if_set(cls): if cls._READONLY_APP_CONTEXT is None: return True from controllers import sites app_context = sites.get_course_for_current_request() return cls._READONLY_APP_CONTEXT == app_context @classmethod def _assert_true_clear_cache_and_raise_if_not(cls, value_to_assert, msg): if not value_to_assert: cls.clear_readonly_cache() raise AssertionError(msg) @classmethod def _fs_begin_readonly(cls): from controllers import sites cls._READONLY_APP_CONTEXT = sites.get_course_for_current_request() if cls._READONLY_APP_CONTEXT: cls._READONLY_APP_CONTEXT.fs.begin_readonly() @classmethod def _fs_end_readonly(cls): if cls._READONLY_APP_CONTEXT: cls._READONLY_APP_CONTEXT.fs.end_readonly() cls._READONLY_APP_CONTEXT = None @classmethod def begin_readonly(cls): cls._assert_true_clear_cache_and_raise_if_not( cls._READONLY_REENTRY_COUNT >= 0, 'Re-entry counter is < 0.') cls._assert_true_clear_cache_and_raise_if_not( cls._is_same_app_context_if_set(), 'Unable to switch app_context.') if cls._READONLY_REENTRY_COUNT == 0: appengine_config.log_appstats_event( 'MemcacheManager.begin_readonly') cls._IS_READONLY = True cls._LOCAL_CACHE = {} cls._fs_begin_readonly() cls._READONLY_REENTRY_COUNT += 1 @classmethod def end_readonly(cls): cls._assert_true_clear_cache_and_raise_if_not( cls._READONLY_REENTRY_COUNT > 0, 'Re-entry counter <= 0.') cls._assert_true_clear_cache_and_raise_if_not( cls._is_same_app_context_if_set(), 'Unable to switch app_context.') cls._READONLY_REENTRY_COUNT -= 1 if cls._READONLY_REENTRY_COUNT == 0: cls._fs_end_readonly() cls._IS_READONLY = False cls._LOCAL_CACHE = None cls._READONLY_APP_CONTEXT = None appengine_config.log_appstats_event('MemcacheManager.end_readonly') @classmethod def clear_readonly_cache(cls): cls._LOCAL_CACHE = None cls._IS_READONLY = False cls._READONLY_REENTRY_COUNT = 0 if cls._READONLY_APP_CONTEXT and ( cls._READONLY_APP_CONTEXT.fs.is_in_readonly): cls._READONLY_APP_CONTEXT.fs.end_readonly() cls._READONLY_APP_CONTEXT = None @classmethod def _local_cache_get(cls, key, namespace): if cls._IS_READONLY: assert cls._is_same_app_context_if_set() _dict = cls._LOCAL_CACHE.get(namespace) if not _dict: _dict = {} cls._LOCAL_CACHE[namespace] = _dict if key in _dict: CACHE_HIT_LOCAL.inc() value = _dict[key] return True, value else: CACHE_MISS_LOCAL.inc() return False, None @classmethod def _local_cache_put(cls, key, namespace, value): if cls._IS_READONLY: assert cls._is_same_app_context_if_set() _dict = cls._LOCAL_CACHE.get(namespace) if not _dict: _dict = {} cls._LOCAL_CACHE[namespace] = _dict _dict[key] = value CACHE_PUT_LOCAL.inc() @classmethod def _local_cache_get_multi(cls, keys, namespace): if cls._IS_READONLY: assert cls._is_same_app_context_if_set() values = [] for key in keys: is_cached, value = cls._local_cache_get(key, namespace) if not is_cached: return False, [] else: values.append(value) return True, values return False, [] @classmethod def _local_cache_put_multi(cls, values, namespace): if cls._IS_READONLY: assert cls._is_same_app_context_if_set() for key, value in values.items(): cls._local_cache_put(key, namespace, value) @classmethod def get_namespace(cls): """Look up namespace from namespace_manager or use default.""" namespace = namespace_manager.get_namespace() if namespace: return namespace return appengine_config.DEFAULT_NAMESPACE_NAME @classmethod def _get_namespace(cls, namespace): if namespace is not None: return namespace return cls.get_namespace() @classmethod def get(cls, key, namespace=None): """Gets an item from memcache if memcache is enabled.""" if not CAN_USE_MEMCACHE.value: return None _namespace = cls._get_namespace(namespace) is_cached, value = cls._local_cache_get(key, _namespace) if is_cached: return copy.deepcopy(value) value = memcache.get(key, namespace=_namespace) # We store some objects in memcache that don't evaluate to True, but are # real objects, '{}' for example. Count a cache miss only in a case when # an object is None. if value is not None: CACHE_HIT.inc() else: CACHE_MISS.inc(context=key) cls._local_cache_put(key, _namespace, value) return copy.deepcopy(value) @classmethod def get_multi(cls, keys, namespace=None): """Gets a set of items from memcache if memcache is enabled.""" if not CAN_USE_MEMCACHE.value: return {} _namespace = cls._get_namespace(namespace) is_cached, values = cls._local_cache_get_multi(keys, _namespace) if is_cached: return values values = memcache.get_multi(keys, namespace=_namespace) for key, value in values.items(): if value is not None: CACHE_HIT.inc() else: logging.info('Cache miss, key: %s. %s', key, Exception()) CACHE_MISS.inc(context=key) cls._local_cache_put_multi(values, _namespace) return values @classmethod def set(cls, key, value, ttl=DEFAULT_CACHE_TTL_SECS, namespace=None): """Sets an item in memcache if memcache is enabled.""" # Ensure subsequent mods to value do not affect the cached copy. value = copy.deepcopy(value) try: if CAN_USE_MEMCACHE.value: size = sys.getsizeof(value) if size > MEMCACHE_MAX: CACHE_PUT_TOO_BIG.inc() else: CACHE_PUT.inc() _namespace = cls._get_namespace(namespace) memcache.set(key, value, ttl, namespace=_namespace) cls._local_cache_put(key, _namespace, value) except: # pylint: disable=bare-except logging.exception( 'Failed to set: %s, %s', key, cls._get_namespace(namespace)) return None @classmethod def set_multi(cls, mapping, ttl=DEFAULT_CACHE_TTL_SECS, namespace=None): """Sets a dict of items in memcache if memcache is enabled.""" try: if CAN_USE_MEMCACHE.value: if not mapping: return size = sum([ sys.getsizeof(key) + sys.getsizeof(value) for key, value in mapping.items()]) if size > MEMCACHE_MULTI_MAX: CACHE_PUT_TOO_BIG.inc() else: CACHE_PUT.inc() _namespace = cls._get_namespace(namespace) memcache.set_multi(mapping, time=ttl, namespace=_namespace) cls._local_cache_put_multi(mapping, _namespace) except: # pylint: disable=bare-except logging.exception( 'Failed to set_multi: %s, %s', mapping, cls._get_namespace(namespace)) return None @classmethod def delete(cls, key, namespace=None): """Deletes an item from memcache if memcache is enabled.""" assert not cls._IS_READONLY if CAN_USE_MEMCACHE.value: CACHE_DELETE.inc() memcache.delete(key, namespace=cls._get_namespace(namespace)) @classmethod def delete_multi(cls, key_list, namespace=None): """Deletes a list of items from memcache if memcache is enabled.""" assert not cls._IS_READONLY if CAN_USE_MEMCACHE.value: CACHE_DELETE.inc(increment=len(key_list)) memcache.delete_multi( key_list, namespace=cls._get_namespace(namespace)) @classmethod def incr(cls, key, delta, namespace=None): """Incr an item in memcache if memcache is enabled.""" if CAN_USE_MEMCACHE.value: memcache.incr( key, delta, namespace=cls._get_namespace(namespace), initial_value=0) CAN_AGGREGATE_COUNTERS = ConfigProperty( 'gcb_can_aggregate_counters', bool, 'Whether or not to aggregate and record counter values in memcache. ' 'This allows you to see counter values aggregated across all frontend ' 'application instances. Without recording, you only see counter values ' 'for one frontend instance you are connected to right now. Enabling ' 'aggregation improves quality of performance metrics, but adds a small ' 'amount of latency to all your requests.', default_value=False) def incr_counter_global_value(name, delta): if CAN_AGGREGATE_COUNTERS.value: MemcacheManager.incr( 'counter:' + name, delta, namespace=appengine_config.DEFAULT_NAMESPACE_NAME) def get_counter_global_value(name): if CAN_AGGREGATE_COUNTERS.value: return MemcacheManager.get( 'counter:' + name, namespace=appengine_config.DEFAULT_NAMESPACE_NAME) else: return None counters.get_counter_global_value = get_counter_global_value counters.incr_counter_global_value = incr_counter_global_value # Whether to record tag events in a database. CAN_SHARE_STUDENT_PROFILE = ConfigProperty( 'gcb_can_share_student_profile', bool, ( 'Whether or not to share student profile between different courses.'), False) class CollisionError(Exception): """Exception raised to show that a collision in a namespace has occurred.""" class ValidationError(Exception): """Exception raised to show that a validation failed.""" class ContentChunkEntity(BaseEntity): """Defines storage for ContentChunk, a blob of opaque content to display.""" _PROPERTY_EXPORT_BLACKLIST = [] # No PII in ContentChunks. # A string that gives the type of the content chunk. At the data layer we # make no restrictions on the values that can be used here -- we only # require that a type is given. The type here may be independent of any # notion of Content-Type in an HTTP header. content_type = db.StringProperty(required=True) # UTC last modification timestamp. last_modified = db.DateTimeProperty(auto_now=True, required=True) # Whether or not the chunk supports custom tags. If True, the renderer may # be extended to parse and render those tags at display time (this is a stub # for future functionality that does not exist yet). If False, the contents # of the chunk will be rendered verbatim. supports_custom_tags = db.BooleanProperty(default=False) # Optional identifier for the chunk in the system it was sourced from. # Format is type_id:resource_id where type_id is an identifier that maps to # an external system and resource_id is the identifier for a resource within # that system (e.g. 'drive:1234' or 'web:http://example.com/index.html'). # Exact values are up to the caller, but if either type_id or resource_id is # given, both must be, they must both be truthy, and type_id cannot contain # ':'. Max size is 500B, enforced by datastore. uid = db.StringProperty(indexed=True) # Payload of the chunk. Max size is 1MB, enforced by datastore. contents = db.TextProperty() class ContentChunkDAO(object): """Data access object for ContentChunks.""" @classmethod def delete(cls, entity_id): """Deletes ContentChunkEntity for datastore id int; returns None.""" memcache_key = cls._get_memcache_key(entity_id) entity = ContentChunkEntity.get_by_id(entity_id) if entity: db.delete(entity) MemcacheManager.delete(memcache_key) @classmethod def get(cls, entity_id): """Gets ContentChunkEntityDTO or None from given datastore id int.""" if entity_id is None: return memcache_key = cls._get_memcache_key(entity_id) found = MemcacheManager.get(memcache_key) if found == NO_OBJECT: return None elif found: return found else: result = None cache_value = NO_OBJECT entity = ContentChunkEntity.get_by_id(entity_id) if entity: result = cls._make_dto(entity) cache_value = result MemcacheManager.set(memcache_key, cache_value) return result @classmethod def get_by_uid(cls, uid): """Gets list of DTOs for all entities with given uid string.""" results = ContentChunkEntity.all().filter( ContentChunkEntity.uid.name, uid ).fetch(1000) return sorted( [cls._make_dto(result) for result in results], key=lambda dto: dto.id) @classmethod def make_uid(cls, type_id, resource_id): """Makes a uid string (or None) from the given strings (or Nones).""" if type_id is None and resource_id is None: return None assert type_id and resource_id and ':' not in type_id return '%s:%s' % (type_id, resource_id) @classmethod def save(cls, dto): """Saves contents of a DTO and returns the key of the saved entity. Handles both creating new and updating existing entities. If the id of the passed DTO is found, the entity will be updated. Note that this method does not refetch the saved entity from the datastore after put since this is impossible in a transaction. This means the last_modified date we put in the cache skews from the actual saved value by however long put took. This is expected datastore behavior; we do not at present have a use case for perfect accuracy in this value for our getters. Args: dto: ContentChunkDTO. last_modified will be ignored. Returns: db.Key of saved ContentChunkEntity. """ if dto.id is None: entity = ContentChunkEntity(content_type=dto.content_type) else: entity = ContentChunkEntity.get_by_id(dto.id) if entity is None: entity = ContentChunkEntity(content_type=dto.content_type) entity.contents = dto.contents entity.supports_custom_tags = dto.supports_custom_tags entity.uid = cls.make_uid(dto.type_id, dto.resource_id) entity.put() MemcacheManager.set( cls._get_memcache_key(entity.key().id()), cls._make_dto(entity)) return entity.key() @classmethod def _get_memcache_key(cls, entity_id): assert entity_id is not None return '(%s:%s)' % (ContentChunkEntity.kind(), entity_id) @classmethod def _make_dto(cls, entity): type_id, resource_id = cls._split_uid(entity.uid) return ContentChunkDTO({ 'content_type': entity.content_type, 'contents': entity.contents, 'id': entity.key().id(), 'last_modified': entity.last_modified, 'resource_id': resource_id, 'supports_custom_tags': entity.supports_custom_tags, 'type_id': type_id, }) @classmethod def _split_uid(cls, uid): resource_id = None type_id = None if uid is not None: assert ':' in uid type_id, resource_id = uid.split(':', 1) assert type_id and resource_id return type_id, resource_id class ContentChunkDTO(object): """Data transfer object for ContentChunks.""" def __init__(self, entity_dict): self.content_type = entity_dict.get('content_type') self.contents = entity_dict.get('contents') self.id = entity_dict.get('id') self.last_modified = entity_dict.get('last_modified') self.resource_id = entity_dict.get('resource_id') self.supports_custom_tags = entity_dict.get('supports_custom_tags') self.type_id = entity_dict.get('type_id') def __eq__(self, other): return ( isinstance(other, ContentChunkDTO) and self.content_type == other.content_type and self.contents == other.contents and self.id == other.id and self.last_modified == other.last_modified and self.resource_id == other.resource_id and self.supports_custom_tags == other.supports_custom_tags and self.type_id == other.type_id) class PersonalProfile(BaseEntity): """Personal information not specific to any course instance.""" email = db.StringProperty(indexed=False) legal_name = db.StringProperty(indexed=False) nick_name = db.StringProperty(indexed=False) date_of_birth = db.DateProperty(indexed=False) enrollment_info = db.TextProperty() course_info = db.TextProperty() _PROPERTY_EXPORT_BLACKLIST = [email, legal_name, nick_name, date_of_birth] @property def user_id(self): return self.key().name() @classmethod def safe_key(cls, db_key, transform_fn): return db.Key.from_path(cls.kind(), transform_fn(db_key.name())) class PersonalProfileDTO(object): """DTO for PersonalProfile.""" def __init__(self, personal_profile=None): self.enrollment_info = '{}' self.course_info = '{}' if personal_profile: self.user_id = personal_profile.user_id self.email = personal_profile.email self.legal_name = personal_profile.legal_name self.nick_name = personal_profile.nick_name self.date_of_birth = personal_profile.date_of_birth self.enrollment_info = personal_profile.enrollment_info self.course_info = personal_profile.course_info class StudentProfileDAO(object): """All access and mutation methods for PersonalProfile and Student.""" TARGET_NAMESPACE = appengine_config.DEFAULT_NAMESPACE_NAME # Each hook is called back after update() has completed without raising # an exception. Arguments are: # profile: The PersonalProfile object for the user # student: The Student object for the user # Subsequent arguments are identical to the arguments list to the update() # call. Not documented here so as to not get out-of-date. # The return value from hooks is discarded. Since these hooks run # after update() has succeeded, they should run as best-effort, rather # than raising exceptions. UPDATE_POST_HOOKS = [] # Each hook is called back after _add_new_student_for_current_user has # completed without raising an exception. Arguments are: # student: The Student object for the user. # The return value from hooks is discarded. Since these hooks run # after update() has succeeded, they should run as best-effort, rather # than raising exceptions. ADD_STUDENT_POST_HOOKS = [] @classmethod def _memcache_key(cls, key): """Makes a memcache key from primary key.""" return 'entity:personal-profile:%s' % key @classmethod def _get_profile_by_user_id(cls, user_id): """Loads profile given a user_id and returns Entity object.""" old_namespace = namespace_manager.get_namespace() try: namespace_manager.set_namespace(cls.TARGET_NAMESPACE) profile = MemcacheManager.get( cls._memcache_key(user_id), namespace=cls.TARGET_NAMESPACE) if profile == NO_OBJECT: return None if profile: return profile profile = PersonalProfile.get_by_key_name(user_id) MemcacheManager.set( cls._memcache_key(user_id), profile if profile else NO_OBJECT, namespace=cls.TARGET_NAMESPACE) return profile finally: namespace_manager.set_namespace(old_namespace) @classmethod def _add_new_profile(cls, user_id, email): """Adds new profile for a user_id and returns Entity object.""" if not CAN_SHARE_STUDENT_PROFILE.value: return None old_namespace = namespace_manager.get_namespace() try: namespace_manager.set_namespace(cls.TARGET_NAMESPACE) profile = PersonalProfile(key_name=user_id) profile.email = email profile.enrollment_info = '{}' profile.put() return profile finally: namespace_manager.set_namespace(old_namespace) @classmethod def _update_global_profile_attributes( cls, profile, email=None, legal_name=None, nick_name=None, date_of_birth=None, is_enrolled=None, final_grade=None, course_info=None): """Modifies various attributes of Student's Global Profile.""" # TODO(psimakov): update of email does not work for student if email is not None: profile.email = email if legal_name is not None: profile.legal_name = legal_name if nick_name is not None: profile.nick_name = nick_name if date_of_birth is not None: profile.date_of_birth = date_of_birth if not (is_enrolled is None and final_grade is None and course_info is None): # Defer to avoid circular import. from controllers import sites course = sites.get_course_for_current_request() course_namespace = course.get_namespace_name() if is_enrolled is not None: enrollment_dict = transforms.loads(profile.enrollment_info) enrollment_dict[course_namespace] = is_enrolled profile.enrollment_info = transforms.dumps(enrollment_dict) if final_grade is not None or course_info is not None: course_info_dict = {} if profile.course_info: course_info_dict = transforms.loads(profile.course_info) if course_namespace in course_info_dict.keys(): info = course_info_dict[course_namespace] else: info = {} if final_grade: info['final_grade'] = final_grade if course_info: info['info'] = course_info course_info_dict[course_namespace] = info profile.course_info = transforms.dumps(course_info_dict) @classmethod def _update_course_profile_attributes( cls, student, nick_name=None, is_enrolled=None, labels=None): """Modifies various attributes of Student's Course Profile.""" if nick_name is not None: student.name = nick_name if is_enrolled is not None: student.is_enrolled = is_enrolled if labels is not None: student.labels = labels @classmethod def _update_attributes( cls, profile, student, email=None, legal_name=None, nick_name=None, date_of_birth=None, is_enrolled=None, final_grade=None, course_info=None, labels=None): """Modifies various attributes of Student and Profile.""" if profile: cls._update_global_profile_attributes( profile, email=email, legal_name=legal_name, nick_name=nick_name, date_of_birth=date_of_birth, is_enrolled=is_enrolled, final_grade=final_grade, course_info=course_info) if student: cls._update_course_profile_attributes( student, nick_name=nick_name, is_enrolled=is_enrolled, labels=labels) @classmethod def _put_profile(cls, profile): """Does a put() on profile objects.""" if not profile: return profile.put() MemcacheManager.delete( cls._memcache_key(profile.user_id), namespace=cls.TARGET_NAMESPACE) @classmethod def get_profile_by_user_id(cls, user_id): """Loads profile given a user_id and returns DTO object.""" profile = cls._get_profile_by_user_id(user_id) if profile: return PersonalProfileDTO(personal_profile=profile) return None @classmethod def add_new_profile(cls, user_id, email): return cls._add_new_profile(user_id, email) @classmethod def add_new_student_for_current_user( cls, nick_name, additional_fields, handler, labels=None): user = users.get_current_user() student_by_uid = Student.get_student_by_user_id(user.user_id()) is_valid_student = (student_by_uid is None or student_by_uid.user_id == user.user_id()) assert is_valid_student, ( 'Student\'s email and user id do not match.') student = cls._add_new_student_for_current_user( user.user_id(), user.email(), nick_name, additional_fields, labels) try: cls._send_welcome_notification(handler, student) except Exception, e: # On purpose. pylint: disable=broad-except logging.error( 'Unable to send welcome notification; error was: ' + str(e)) @classmethod def _add_new_student_for_current_user( cls, user_id, email, nick_name, additional_fields, labels=None): student = cls._add_new_student_for_current_user_in_txn( user_id, email, nick_name, additional_fields, labels) common_utils.run_hooks(cls.ADD_STUDENT_POST_HOOKS, student) return student @classmethod @db.transactional(xg=True) def _add_new_student_for_current_user_in_txn( cls, user_id, email, nick_name, additional_fields, labels=None): """Create new or re-enroll old student.""" # create profile if does not exist profile = cls._get_profile_by_user_id(user_id) if not profile: profile = cls._add_new_profile(user_id, email) # create new student or re-enroll existing student = Student.get_by_email(email) if not student: # TODO(psimakov): we must move to user_id as a key student = Student(key_name=email) # update profile cls._update_attributes( profile, student, nick_name=nick_name, is_enrolled=True, labels=labels) # update student student.user_id = user_id student.additional_fields = additional_fields # put both cls._put_profile(profile) student.put() return student @classmethod def _send_welcome_notification(cls, handler, student): if not cls._can_send_welcome_notifications(handler): return if services.unsubscribe.has_unsubscribed(student.email): return course_settings = handler.app_context.get_environ()['course'] course_title = course_settings['title'] sender = cls._get_welcome_notifications_sender(handler) assert sender, 'Must set welcome_notifications_sender in course.yaml' context = { 'student_name': student.name, 'course_title': course_title, 'course_url': handler.get_base_href(handler), 'unsubscribe_url': services.unsubscribe.get_unsubscribe_url( handler, student.email) } if course_settings.get('welcome_notifications_subject'): subject = jinja2.Template(unicode( course_settings['welcome_notifications_subject'] )).render(context) else: subject = 'Welcome to ' + course_title if course_settings.get('welcome_notifications_body'): body = jinja2.Template(unicode( course_settings['welcome_notifications_body'] )).render(context) else: jinja_environment = handler.app_context.fs.get_jinja_environ( [os.path.join( appengine_config.BUNDLE_ROOT, 'views', 'notifications')], autoescape=False) body = jinja_environment.get_template('welcome.txt').render(context) services.notifications.send_async( student.email, sender, WELCOME_NOTIFICATION_INTENT, body, subject, audit_trail=context, ) @classmethod def _can_send_welcome_notifications(cls, handler): return ( services.notifications.enabled() and services.unsubscribe.enabled() and cls._get_send_welcome_notifications(handler)) @classmethod def _get_send_welcome_notifications(cls, handler): return handler.app_context.get_environ().get( 'course', {} ).get('send_welcome_notifications', False) @classmethod def _get_welcome_notifications_sender(cls, handler): return handler.app_context.get_environ().get( 'course', {} ).get('welcome_notifications_sender') @classmethod def get_enrolled_student_by_email_for(cls, email, app_context): """Returns student for a specific course.""" old_namespace = namespace_manager.get_namespace() try: namespace_manager.set_namespace(app_context.get_namespace_name()) return Student.get_enrolled_student_by_email(email) finally: namespace_manager.set_namespace(old_namespace) @classmethod def update( cls, user_id, email, legal_name=None, nick_name=None, date_of_birth=None, is_enrolled=None, final_grade=None, course_info=None, labels=None, profile_only=False): profile, student = cls._update_in_txn( user_id, email, legal_name, nick_name, date_of_birth, is_enrolled, final_grade, course_info, labels, profile_only) common_utils.run_hooks( cls.UPDATE_POST_HOOKS, profile, student, user_id, email, legal_name, nick_name, date_of_birth, is_enrolled, final_grade, course_info, labels, profile_only) @classmethod @db.transactional(xg=True) def _update_in_txn( cls, user_id, email, legal_name=None, nick_name=None, date_of_birth=None, is_enrolled=None, final_grade=None, course_info=None, labels=None, profile_only=False): """Updates a student and/or their global profile.""" student = None if not profile_only: student = Student.get_by_email(email) if not student: raise Exception('Unable to find student for: %s' % user_id) profile = cls._get_profile_by_user_id(user_id) if not profile: profile = cls.add_new_profile(user_id, email) cls._update_attributes( profile, student, email=email, legal_name=legal_name, nick_name=nick_name, date_of_birth=date_of_birth, is_enrolled=is_enrolled, final_grade=final_grade, course_info=course_info, labels=labels) cls._put_profile(profile) if not profile_only: student.put() return profile, student class Student(BaseEntity): """Student data specific to a course instance.""" enrolled_on = db.DateTimeProperty(auto_now_add=True, indexed=True) user_id = db.StringProperty(indexed=True) name = db.StringProperty(indexed=False) additional_fields = db.TextProperty(indexed=False) is_enrolled = db.BooleanProperty(indexed=False) # Each of the following is a string representation of a JSON dict. scores = db.TextProperty(indexed=False) labels = db.StringProperty(indexed=False) _PROPERTY_EXPORT_BLACKLIST = [ additional_fields, # Suppress all additional_fields items. # Convenience items if not all additional_fields should be suppressed: #'additional_fields.xsrf_token', # Not PII, but also not useful. #'additional_fields.form01', # User's name on registration form. name] @classmethod def safe_key(cls, db_key, transform_fn): return db.Key.from_path(cls.kind(), transform_fn(db_key.id_or_name())) def for_export(self, transform_fn): """Creates an ExportEntity populated from this entity instance.""" assert not hasattr(self, 'key_by_user_id') model = super(Student, self).for_export(transform_fn) model.user_id = transform_fn(self.user_id) # Add a version of the key that always uses the user_id for the name # component. This can be used to establish relationships between objects # where the student key used was created via get_key(). In general, # this means clients will join exports on this field, not the field made # from safe_key(). model.key_by_user_id = self.get_key(transform_fn=transform_fn) return model @property def is_transient(self): return False @property def email(self): return self.key().name() @property def profile(self): return StudentProfileDAO.get_profile_by_user_id(self.user_id) @classmethod def _memcache_key(cls, key): """Makes a memcache key from primary key.""" return 'entity:student:%s' % key def put(self): """Do the normal put() and also add the object to memcache.""" result = super(Student, self).put() MemcacheManager.set(self._memcache_key(self.key().name()), self) return result def delete(self): """Do the normal delete() and also remove the object from memcache.""" super(Student, self).delete() MemcacheManager.delete(self._memcache_key(self.key().name())) @classmethod def add_new_student_for_current_user( cls, nick_name, additional_fields, handler, labels=None): StudentProfileDAO.add_new_student_for_current_user( nick_name, additional_fields, handler, labels) @classmethod def get_by_email(cls, email): return Student.get_by_key_name(email.encode('utf8')) @classmethod def get_enrolled_student_by_email(cls, email): """Returns enrolled student or None.""" student = MemcacheManager.get(cls._memcache_key(email)) if NO_OBJECT == student: return None if not student: student = Student.get_by_email(email) if student: MemcacheManager.set(cls._memcache_key(email), student) else: MemcacheManager.set(cls._memcache_key(email), NO_OBJECT) if student and student.is_enrolled: return student else: return None @classmethod def _get_user_and_student(cls): """Loads user and student and asserts both are present.""" user = users.get_current_user() if not user: raise Exception('No current user.') student = Student.get_by_email(user.email()) if not student: raise Exception('Student instance corresponding to user %s not ' 'found.' % user.email()) return user, student @classmethod def rename_current(cls, new_name): """Gives student a new name.""" _, student = cls._get_user_and_student() StudentProfileDAO.update( student.user_id, student.email, nick_name=new_name) @classmethod def set_enrollment_status_for_current(cls, is_enrolled): """Changes student enrollment status.""" _, student = cls._get_user_and_student() StudentProfileDAO.update( student.user_id, student.email, is_enrolled=is_enrolled) @classmethod def set_labels_for_current(cls, labels): """Set labels for tracks on the student.""" _, student = cls._get_user_and_student() StudentProfileDAO.update( student.user_id, student.email, labels=labels) def get_key(self, transform_fn=None): """Gets a version of the key that uses user_id for the key name.""" if not self.user_id: raise Exception('Student instance has no user_id set.') user_id = transform_fn(self.user_id) if transform_fn else self.user_id return db.Key.from_path(Student.kind(), user_id) @classmethod def get_student_by_user_id(cls, user_id): students = cls.all().filter(cls.user_id.name, user_id).fetch(limit=2) if len(students) == 2: raise Exception( 'There is more than one student with user_id %s' % user_id) return students[0] if students else None def has_same_key_as(self, key): """Checks if the key of the student and the given key are equal.""" return key == self.get_key() def get_labels_of_type(self, label_type): if not self.labels: return set() label_ids = LabelDAO.get_set_of_ids_of_type(label_type) return set([int(label) for label in common_utils.text_to_list(self.labels) if int(label) in label_ids]) class TransientStudent(object): """A transient student (i.e. a user who hasn't logged in or registered).""" @property def is_transient(self): return True @property def is_enrolled(self): return False class EventEntity(BaseEntity): """Generic events. Each event has a 'source' that defines a place in a code where the event was recorded. Each event has a 'user_id' to represent an actor who triggered the event. The event 'data' is a JSON object, the format of which is defined elsewhere and depends on the type of the event. """ recorded_on = db.DateTimeProperty(auto_now_add=True, indexed=True) source = db.StringProperty(indexed=False) user_id = db.StringProperty(indexed=False) # Each of the following is a string representation of a JSON dict. data = db.TextProperty(indexed=False) @classmethod def record(cls, source, user, data): """Records new event into a datastore.""" event = cls() event.source = source event.user_id = user.user_id() event.data = data event.put() def for_export(self, transform_fn): model = super(EventEntity, self).for_export(transform_fn) model.user_id = transform_fn(self.user_id) return model class StudentAnswersEntity(BaseEntity): """Student answers to the assessments.""" updated_on = db.DateTimeProperty(indexed=True) # Each of the following is a string representation of a JSON dict. data = db.TextProperty(indexed=False) @classmethod def safe_key(cls, db_key, transform_fn): return db.Key.from_path(cls.kind(), transform_fn(db_key.id_or_name())) class StudentPropertyEntity(BaseEntity): """A property of a student, keyed by the string STUDENT_ID-PROPERTY_NAME.""" updated_on = db.DateTimeProperty(indexed=True) name = db.StringProperty() # Each of the following is a string representation of a JSON dict. value = db.TextProperty() @classmethod def _memcache_key(cls, key): """Makes a memcache key from primary key.""" return 'entity:student_property:%s' % key @classmethod def create_key(cls, student_id, property_name): return '%s-%s' % (student_id, property_name) @classmethod def create(cls, student, property_name): return cls( key_name=cls.create_key(student.user_id, property_name), name=property_name) @classmethod def safe_key(cls, db_key, transform_fn): user_id, name = db_key.name().split('-', 1) return db.Key.from_path( cls.kind(), '%s-%s' % (transform_fn(user_id), name)) def put(self): """Do the normal put() and also add the object to memcache.""" result = super(StudentPropertyEntity, self).put() MemcacheManager.set(self._memcache_key(self.key().name()), self) return result def delete(self): """Do the normal delete() and also remove the object from memcache.""" super(StudentPropertyEntity, self).delete() MemcacheManager.delete(self._memcache_key(self.key().name())) @classmethod def get(cls, student, property_name): """Loads student property.""" key = cls.create_key(student.user_id, property_name) value = MemcacheManager.get(cls._memcache_key(key)) if NO_OBJECT == value: return None if not value: value = cls.get_by_key_name(key) if value: MemcacheManager.set(cls._memcache_key(key), value) else: MemcacheManager.set(cls._memcache_key(key), NO_OBJECT) return value class BaseJsonDao(object): """Base DAO class for entities storing their data in a single JSON blob.""" class EntityKeyTypeId(object): @classmethod def get_entity_by_key(cls, entity_class, key): return entity_class.get_by_id(int(key)) @classmethod def new_entity(cls, entity_class, unused_key): return entity_class() # ID auto-generated when entity is put(). class EntityKeyTypeName(object): @classmethod def get_entity_by_key(cls, entity_class, key): return entity_class.get_by_key_name(key) @classmethod def new_entity(cls, entity_class, key_name): return entity_class(key_name=key_name) @classmethod def _memcache_key(cls, obj_id): """Makes a memcache key from datastore id.""" # Keeping case-sensitivity in kind() because Foo(object) != foo(object). return '(entity:%s:%s)' % (cls.ENTITY.kind(), obj_id) @classmethod def _memcache_all_key(cls): """Makes a memcache key for caching get_all().""" # Keeping case-sensitivity in kind() because Foo(object) != foo(object). return '(entity-get-all:%s)' % cls.ENTITY.kind() @classmethod def get_all_mapped(cls): # try to get from memcache entities = MemcacheManager.get(cls._memcache_all_key()) if entities is not None and entities != NO_OBJECT: cls._maybe_apply_post_load_hooks(entities.itervalues()) return entities # get from datastore result = {dto.id: dto for dto in cls.get_all_iter()} # put into memcache result_to_cache = NO_OBJECT if result: result_to_cache = result MemcacheManager.set(cls._memcache_all_key(), result_to_cache) cls._maybe_apply_post_load_hooks(result.itervalues()) return result @classmethod def get_all(cls): return cls.get_all_mapped().values() @classmethod def get_all_iter(cls): """Return a generator that will produce all DTOs of a given type. Yields: A DTO for each row in the Entity type's table. """ prev_cursor = None any_records = True while any_records: any_records = False query = cls.ENTITY.all().with_cursor(prev_cursor) for entity in query.run(): any_records = True yield cls.DTO(entity.key().id_or_name(), transforms.loads(entity.data)) prev_cursor = query.cursor() @classmethod def _maybe_apply_post_load_hooks(cls, dto_list): """Run any post-load processing hooks. Modules may insert post-load processing hooks (e.g. for i18n translation) into the list POST_LOAD_HOOKS defined on the DAO class. If the class has this list and any hook functions are present, they are passed the list of DTO's for in-place processing. Args: dto_list: list of DTO objects """ if hasattr(cls, 'POST_LOAD_HOOKS'): for hook in cls.POST_LOAD_HOOKS: hook(dto_list) @classmethod def _maybe_apply_post_save_hooks(cls, dto_and_id_list): """Run any post-save processing hooks. Modules may insert post-save processing hooks (e.g. for i18n translation) into the list POST_SAVE_HOOKS defined on the DAO class. If the class has this list and any hook functions are present, they are passed the list of DTO's for in-place processing. Args: dto_and_id_list: list of pairs of (id, DTO) objects """ dto_list = [ cls.DTO(dto_id, orig_dto.dict) for dto_id, orig_dto in dto_and_id_list] if hasattr(cls, 'POST_SAVE_HOOKS'): common_utils.run_hooks(cls.POST_SAVE_HOOKS, dto_list) @classmethod def _load_entity(cls, obj_id): if not obj_id: return None memcache_key = cls._memcache_key(obj_id) entity = MemcacheManager.get(memcache_key) if NO_OBJECT == entity: return None if not entity: entity = cls.ENTITY_KEY_TYPE.get_entity_by_key(cls.ENTITY, obj_id) if entity: MemcacheManager.set(memcache_key, entity) else: MemcacheManager.set(memcache_key, NO_OBJECT) return entity @classmethod def load(cls, obj_id): entity = cls._load_entity(obj_id) if entity: dto = cls.DTO(obj_id, transforms.loads(entity.data)) cls._maybe_apply_post_load_hooks([dto]) return dto else: return None @classmethod @appengine_config.timeandlog('Models.bulk_load') def bulk_load(cls, obj_id_list): # fetch from memcache memcache_keys = [cls._memcache_key(obj_id) for obj_id in obj_id_list] memcache_entities = MemcacheManager.get_multi(memcache_keys) # fetch missing from datastore both_keys = zip(obj_id_list, memcache_keys) datastore_keys = [ obj_id for obj_id, memcache_key in both_keys if memcache_key not in memcache_entities] if datastore_keys: datastore_entities = dict(zip( datastore_keys, db.get([ db.Key.from_path(cls.ENTITY.kind(), obj_id) for obj_id in datastore_keys]))) else: datastore_entities = {} # weave the results together ret = [] memcache_update = {} dtos_for_post_hooks = [] for obj_id, memcache_key in both_keys: entity = datastore_entities.get(obj_id) if entity is not None: dto = cls.DTO(obj_id, transforms.loads(entity.data)) ret.append(dto) dtos_for_post_hooks.append(dto) memcache_update[memcache_key] = entity elif memcache_key not in memcache_entities: ret.append(None) memcache_update[memcache_key] = NO_OBJECT else: entity = memcache_entities[memcache_key] if NO_OBJECT == entity: ret.append(None) else: ret.append(cls.DTO(obj_id, transforms.loads(entity.data))) # run hooks cls._maybe_apply_post_load_hooks(dtos_for_post_hooks) # put into memcache if datastore_entities: MemcacheManager.set_multi(memcache_update) return ret @classmethod def _create_if_necessary(cls, dto): entity = cls._load_entity(dto.id) if not entity: entity = cls.ENTITY_KEY_TYPE.new_entity(cls.ENTITY, dto.id) entity.data = transforms.dumps(dto.dict) return entity @classmethod def before_put(cls, dto, entity): pass @classmethod def save(cls, dto): entity = cls._create_if_necessary(dto) cls.before_put(dto, entity) entity.put() MemcacheManager.delete(cls._memcache_all_key()) id_or_name = entity.key().id_or_name() MemcacheManager.set(cls._memcache_key(id_or_name), entity) cls._maybe_apply_post_save_hooks([(id_or_name, dto)]) return id_or_name @classmethod def save_all(cls, dtos): """Performs a block persist of a list of DTO's.""" entities = [] for dto in dtos: entity = cls._create_if_necessary(dto) entities.append(entity) cls.before_put(dto, entity) keys = db.put(entities) MemcacheManager.delete(cls._memcache_all_key()) for key, entity in zip(keys, entities): MemcacheManager.set(cls._memcache_key(key.id_or_name()), entity) id_or_name_list = [key.id_or_name() for key in keys] cls._maybe_apply_post_save_hooks(zip(id_or_name_list, dtos)) return id_or_name_list @classmethod def delete(cls, dto): entity = cls._load_entity(dto.id) entity.delete() MemcacheManager.delete(cls._memcache_all_key()) MemcacheManager.delete(cls._memcache_key(entity.key().id_or_name())) @classmethod def clone(cls, dto): return cls.DTO(None, copy.deepcopy(dto.dict)) class LastModfiedJsonDao(BaseJsonDao): """Base DAO that updates the last_modified field of entities on every save. DTOs managed by this DAO must have a settable field last_modified defined. """ @classmethod def save(cls, dto): dto.last_modified = time.time() return super(LastModfiedJsonDao, cls).save(dto) @classmethod def save_all(cls, dtos): for dto in dtos: dto.last_modified = time.time() return super(LastModfiedJsonDao, cls).save_all(dtos) class QuestionEntity(BaseEntity): """An object representing a top-level question.""" data = db.TextProperty(indexed=False) class QuestionDTO(object): """DTO for question entities.""" MULTIPLE_CHOICE = 0 SHORT_ANSWER = 1 def __init__(self, the_id, the_dict): self.id = the_id self.dict = the_dict @property def type(self): return self.dict.get('type') @type.setter def type(self, value): self.dict['type'] = value @property def description(self): return self.dict.get('description') or '' @description.setter def description(self, value): self.dict['description'] = value @property def last_modified(self): return self.dict.get('last_modified') or '' @last_modified.setter def last_modified(self, value): self.dict['last_modified'] = value class QuestionDAO(LastModfiedJsonDao): VERSION = '1.5' DTO = QuestionDTO ENTITY = QuestionEntity ENTITY_KEY_TYPE = BaseJsonDao.EntityKeyTypeId # Enable other modules to add post-load transformations POST_LOAD_HOOKS = [] # Enable other modules to add post-save transformations POST_SAVE_HOOKS = [] @classmethod def used_by(cls, question_id): """Returns the question groups using a question. Args: question_id: int. Identifier of the question we're testing. Returns: List of question groups. The list of all question groups that use the given question. """ # O(num_question_groups), but deserialization of 1 large group takes # ~1ms so practically speaking latency is OK for the admin console. matches = [] for group in QuestionGroupDAO.get_all(): # Add the group the same amount of times as it contains the question matches.extend([group] * ( [long(x) for x in group.question_ids].count(long(question_id)) )) return matches @classmethod def create_question(cls, question_dict, question_type): question = cls.DTO(None, question_dict) question.type = question_type return cls.save(question) @classmethod def get_questions_descriptions(cls): return set([q.description for q in cls.get_all()]) @classmethod def validate_unique_description(cls, description): if description in cls.get_questions_descriptions(): raise CollisionError( 'Non-unique question description: %s' % description) return None class QuestionImporter(object): """Helper class for converting ver. 1.2 questoins to ver. 1.3 ones.""" @classmethod def _gen_description(cls, unit, lesson_title, question_number): return ( 'Imported from unit "%s", lesson "%s" (question #%s)' % ( unit.title, lesson_title, question_number)) @classmethod def import_freetext(cls, question, description, task): QuestionDAO.validate_unique_description(description) try: response = question.get('correctAnswerRegex') # Regex /.*/ is added as a guard for questions with no answer. response = response.value if response else '/.*/' return { 'version': QuestionDAO.VERSION, 'description': description, 'question': task, 'hint': question['showAnswerOutput'], 'graders': [{ 'score': 1.0, 'matcher': 'regex', 'response': response, 'feedback': question.get('correctAnswerOutput', '') }], 'defaultFeedback': question.get('incorrectAnswerOutput', '')} except KeyError as e: raise ValidationError('Invalid question: %s, %s' % (description, e)) @classmethod def import_question( cls, question, unit, lesson_title, question_number, task): question_type = question['questionType'] task = ''.join(task) description = cls._gen_description(unit, lesson_title, question_number) if question_type == 'multiple choice': question_dict = cls.import_multiple_choice( question, description, task) qid = QuestionDAO.create_question( question_dict, QuestionDAO.DTO.MULTIPLE_CHOICE) elif question_type == 'freetext': question_dict = cls.import_freetext(question, description, task) qid = QuestionDAO.create_question( question_dict, QuestionDTO.SHORT_ANSWER) elif question_type == 'multiple choice group': question_group_dict = cls.import_multiple_choice_group( question, description, unit, lesson_title, question_number, task) qid = QuestionGroupDAO.create_question_group(question_group_dict) else: raise ValueError('Unknown question type: %s' % question_type) return (qid, common_utils.generate_instance_id()) @classmethod def import_multiple_choice(cls, question, description, task): QuestionDAO.validate_unique_description(description) task = ''.join(task) if task else '' return { 'version': QuestionDAO.VERSION, 'description': description, 'question': task, 'multiple_selections': False, 'choices': [ { 'text': choice[0], 'score': 1.0 if choice[1].value else 0.0, 'feedback': choice[2] } for choice in question['choices']]} @classmethod def import_multiple_choice_group( cls, group, description, unit, lesson_title, question_number, task): """Import a 'multiple choice group' as a question group.""" QuestionGroupDAO.validate_unique_description(description) question_group_dict = { 'version': QuestionDAO.VERSION, 'description': description, 'introduction': task} question_list = [] for index, question in enumerate(group['questionsList']): description = ( 'Imported from unit "%s", lesson "%s" (question #%s, part #%s)' % (unit.title, lesson_title, question_number, index + 1)) question_dict = cls.import_multiple_choice_group_question( question, description) question = QuestionDTO(None, question_dict) question.type = QuestionDTO.MULTIPLE_CHOICE question_list.append(question) qid_list = QuestionDAO.save_all(question_list) question_group_dict['items'] = [{ 'question': str(quid), 'weight': 1.0} for quid in qid_list] return question_group_dict @classmethod def import_multiple_choice_group_question(cls, orig_question, description): """Import the questions from a group as individual questions.""" QuestionDAO.validate_unique_description(description) # TODO(jorr): Handle allCorrectOutput and someCorrectOutput correct_index = orig_question['correctIndex'] multiple_selections = not isinstance(correct_index, int) if multiple_selections: partial = 1.0 / len(correct_index) choices = [{ 'text': text, 'score': partial if i in correct_index else -1.0 } for i, text in enumerate(orig_question['choices'])] else: choices = [{ 'text': text, 'score': 1.0 if i == correct_index else 0.0 } for i, text in enumerate(orig_question['choices'])] return { 'version': QuestionDAO.VERSION, 'description': description, 'question': orig_question.get('questionHTML') or '', 'multiple_selections': multiple_selections, 'choices': choices} @classmethod def build_short_answer_question_dict(cls, question_html, matcher, response): return { 'version': QuestionDAO.VERSION, 'question': question_html or '', 'graders': [{ 'score': 1.0, 'matcher': matcher, 'response': response, }] } @classmethod def build_multiple_choice_question_dict(cls, question): """Assemble the dict for a multiple choice question.""" question_dict = { 'version': QuestionDAO.VERSION, 'question': question.get('questionHTML') or '', 'multiple_selections': False } choices = [] for choice in question.get('choices'): if isinstance(choice, basestring): text = choice score = 0.0 else: text = choice.value score = 1.0 choices.append({ 'text': text, 'score': score }) question_dict['choices'] = choices return question_dict @classmethod def import_assessment_question(cls, question): if 'questionHTML' in question: question['questionHTML'] = question['questionHTML'].decode( 'string-escape') # Convert a single question into a QuestioDTO. if 'choices' in question: q_dict = cls.build_multiple_choice_question_dict( question) question_type = QuestionDTO.MULTIPLE_CHOICE elif 'correctAnswerNumeric' in question: q_dict = cls.build_short_answer_question_dict( question.get('questionHTML'), 'numeric', question.get('correctAnswerNumeric')) question_type = QuestionDTO.SHORT_ANSWER elif 'correctAnswerString' in question: q_dict = cls.build_short_answer_question_dict( question.get('questionHTML'), 'case_insensitive', question.get('correctAnswerString')) question_type = QuestionDTO.SHORT_ANSWER elif 'correctAnswerRegex' in question: q_dict = cls.build_short_answer_question_dict( question.get('questionHTML'), 'regex', question.get('correctAnswerRegex').value) question_type = QuestionDTO.SHORT_ANSWER else: raise ValueError('Unknown question type') question_dto = QuestionDTO(None, q_dict) question_dto.type = question_type return question_dto @classmethod def build_question_dtos(cls, assessment_dict, template, unit, errors): """Convert the assessment into a list of QuestionDTO's.""" descriptions = QuestionDAO.get_questions_descriptions() question_dtos = [] try: for i, q in enumerate(assessment_dict['questionsList']): description = template % (unit.title, (i + 1)) if description in descriptions: raise CollisionError( 'Non-unique question description: %s' % description) question_dto = cls.import_assessment_question(q) question_dto.dict['description'] = description question_dtos.append(question_dto) except CollisionError: errors.append( 'This assessment has already been imported. Remove ' 'duplicate questions from the question bank in ' 'order to re-import: %s.' % description) return None except Exception as ex: # pylint: disable=broad-except errors.append('Unable to convert: %s' % ex) return None return question_dtos class QuestionGroupEntity(BaseEntity): """An object representing a question group in the datastore.""" data = db.TextProperty(indexed=False) class QuestionGroupDTO(object): """Data transfer object for question groups.""" def __init__(self, the_id, the_dict): self.id = the_id self.dict = the_dict @property def description(self): return self.dict.get('description') or '' @property def introduction(self): return self.dict.get('introduction') or '' @property def question_ids(self): return [item['question'] for item in self.dict.get('items', [])] @property def items(self): return copy.deepcopy(self.dict.get('items', [])) def add_question(self, question_id, weight): self.dict['items'].append({'question': question_id, 'weight': weight}) @property def last_modified(self): return self.dict.get('last_modified') or '' @last_modified.setter def last_modified(self, value): self.dict['last_modified'] = value class QuestionGroupDAO(LastModfiedJsonDao): DTO = QuestionGroupDTO ENTITY = QuestionGroupEntity ENTITY_KEY_TYPE = BaseJsonDao.EntityKeyTypeId # Enable other modules to add post-load transformations POST_LOAD_HOOKS = [] # Enable other modules to add post-save transformations POST_SAVE_HOOKS = [] @classmethod def get_question_groups_descriptions(cls): return set([g.description for g in cls.get_all()]) @classmethod def create_question_group(cls, question_group_dict): question_group = QuestionGroupDTO(None, question_group_dict) return cls.save(question_group) @classmethod def validate_unique_description(cls, description): if description in cls.get_question_groups_descriptions(): raise CollisionError( 'Non-unique question group description: %s' % description) class LabelEntity(BaseEntity): """A class representing labels that can be applied to Student, Unit, etc.""" data = db.TextProperty(indexed=False) MEMCACHE_KEY = 'labels' _PROPERTY_EXPORT_BLACKLIST = [] # No PII in labels. def put(self): """Save the content to the datastore. To support caching the list of all labels, we must invalidate the cache on any change to any label. Returns: Value of entity as modified by put() (i.e., key setting) """ result = super(LabelEntity, self).put() MemcacheManager.delete(self.MEMCACHE_KEY) return result def delete(self): """Remove a label from the datastore. To support caching the list of all labels, we must invalidate the cache on any change to any label. """ super(LabelEntity, self).delete() MemcacheManager.delete(self.MEMCACHE_KEY) class LabelDTO(object): LABEL_TYPE_GENERAL = 0 LABEL_TYPE_COURSE_TRACK = 1 LABEL_TYPE_LOCALE = 2 # ... etc. # If you are extending CourseBuilder, please consider picking # a number at 1,000 or over to avoid any potential conflicts # with types added by the CourseBuilder team in future releases. # Provide consistent naming and labeling for admin UI elements. LabelType = collections.namedtuple( 'LabelType', ['type', 'name', 'title', 'menu_order']) USER_EDITABLE_LABEL_TYPES = [ LabelType(LABEL_TYPE_GENERAL, 'general', 'General', 0), LabelType(LABEL_TYPE_COURSE_TRACK, 'course_track', 'Course Track', 1), ] SYSTEM_EDITABLE_LABEL_TYPES = [ LabelType(LABEL_TYPE_LOCALE, 'locale', 'Locale', 2), ] LABEL_TYPES = USER_EDITABLE_LABEL_TYPES + SYSTEM_EDITABLE_LABEL_TYPES def __init__(self, the_id, the_dict): self.id = the_id self.dict = the_dict # UI layer takes care of sanity-checks. @property def title(self): return self.dict.get('title', '') @property def description(self): return self.dict.get('description', '') @property def type(self): return self.dict.get('type', self.LABEL_TYPE_GENERAL) class LabelManager(caching.RequestScopedSingleton): """Class that manages optimized loading of I18N data from datastore.""" def __init__(self): self._key_to_label = None def _preload(self): self._key_to_label = {} for row in LabelDAO.get_all_iter(): self._key_to_label[row.id] = row def _get_all(self): if self._key_to_label is None: self._preload() return self._key_to_label.values() @classmethod def get_all(cls): # pylint: disable=protected-access return cls.instance()._get_all() class LabelDAO(BaseJsonDao): DTO = LabelDTO ENTITY = LabelEntity ENTITY_KEY_TYPE = BaseJsonDao.EntityKeyTypeId @classmethod def get_all(cls): items = LabelManager.get_all() order = {lt.type: lt.menu_order for lt in LabelDTO.LABEL_TYPES} return sorted(items, key=lambda l: (order[l.type], l.title)) @classmethod def get_all_of_type(cls, label_type): return [label for label in cls.get_all() if label.type == label_type] @classmethod def get_set_of_ids_of_type(cls, label_type): return set([label.id for label in cls.get_all_of_type(label_type)]) @classmethod def _apply_locale_labels_to_locale(cls, locale, items): """Filter out items not matching locale labels and current locale.""" if locale: id_to_label = {} for label in LabelDAO.get_all_of_type( LabelDTO.LABEL_TYPE_LOCALE): id_to_label[int(label.id)] = label for item in list(items): item_matches = set([int(label_id) for label_id in common_utils.text_to_list(item.labels) if int(label_id) in id_to_label.keys()]) found = False for item_match in item_matches: label = id_to_label[item_match] if id_to_label and label and label.title == locale: found = True if id_to_label and item_matches and not found: items.remove(item) return items @classmethod def apply_course_track_labels_to_student_labels( cls, course, student, items): MemcacheManager.begin_readonly() try: items = cls._apply_labels_to_student_labels( LabelDTO.LABEL_TYPE_COURSE_TRACK, student, items) if course.get_course_setting('can_student_change_locale'): return cls._apply_locale_labels_to_locale( course.app_context.get_current_locale(), items) else: return cls._apply_labels_to_student_labels( LabelDTO.LABEL_TYPE_LOCALE, student, items) finally: MemcacheManager.end_readonly() @classmethod def _apply_labels_to_student_labels(cls, label_type, student, items): """Filter out items whose labels don't match those on the student. If the student has no labels, all items are taken. Similarly, if a item has no labels, it is included. Args: label_type: a label types to consider. student: the logged-in Student matching the user for this request. items: a list of item instances, each having 'labels' attribute. Returns: A list of item instances whose labels match those on the student. """ label_ids = LabelDAO.get_set_of_ids_of_type(label_type) if student and not student.is_transient: student_matches = student.get_labels_of_type(label_type) for item in list(items): item_matches = set([int(label_id) for label_id in common_utils.text_to_list(item.labels) if int(label_id) in label_ids]) if (student_matches and item_matches and student_matches.isdisjoint(item_matches)): items.remove(item) return items class StudentPreferencesEntity(BaseEntity): """A class representing an individual's preferences for a course. Note that here, we are using "Student" in the broadest sense possible: some human associated with a course. This basically means that we want to support preferences that are relevant to a student's view of a course, as well as a course administrator's preferences. These will be saved in the same object but will be edited in different editors, appropriate to the scope of the particular field in the DTO. For example, show_hooks and show_jinja_context are edited in the Dashboard, in modules/dashboard/admin_preferences_editor.py while locale is set by an Ajax widget in base.html. Note that this type is indexed by "name" -- the key is the same as that of the user.get_current_user().user_id(), which is a string. This type is course-specific, so it must be accessed within a namespaced context. """ data = db.TextProperty(indexed=False) @classmethod def safe_key(cls, db_key, transform_fn): return db.Key.from_path(cls.kind(), transform_fn(db_key.name())) class StudentPreferencesDTO(object): def __init__(self, the_id, the_dict): self.id = the_id self.dict = the_dict @property def show_hooks(self): """Show controls to permit editing of HTML inclusions (hook points). On course pages, there are various locations (hook points) at which HTML content is inserted. Turn this setting on to see those locations with controls that permit an admin to edit that HTML, and off to see the content as a student would. Returns: True when admin wants to see edit controls, False when he doesn't. """ return self.dict.get('show_hooks', True) @show_hooks.setter def show_hooks(self, value): self.dict['show_hooks'] = value @property def show_jinja_context(self): """Do/don't show dump of Jinja context on bottom of pages.""" return self.dict.get('show_jinja_context', False) @show_jinja_context.setter def show_jinja_context(self, value): self.dict['show_jinja_context'] = value @property def locale(self): return self.dict.get('locale') @locale.setter def locale(self, value): self.dict['locale'] = value # Save the most recently visited course page so we can redirect there # when student revisits the (presumably bookmarked) base URL. @property def last_location(self): return self.dict.get('last_location') @last_location.setter def last_location(self, value): self.dict['last_location'] = value class StudentPreferencesDAO(BaseJsonDao): DTO = StudentPreferencesDTO ENTITY = StudentPreferencesEntity ENTITY_KEY_TYPE = BaseJsonDao.EntityKeyTypeName CURRENT_VERSION = '1.0' @classmethod def load_or_create(cls): user = users.get_current_user() if not user: return None user_id = user.user_id() prefs = cls.load(user_id) if not prefs: prefs = StudentPreferencesDTO( user_id, { 'version': cls.CURRENT_VERSION, 'show_hooks': False, 'show_jinja_context': False }) cls.save(prefs) return prefs class RoleEntity(BaseEntity): data = db.TextProperty(indexed=False) class RoleDTO(object): """Data transfer object for roles.""" def __init__(self, the_id, the_dict): self.id = the_id self.dict = the_dict @property def name(self): return self.dict.get('name', '') @property def description(self): return self.dict.get('description', '') @property def users(self): return self.dict.get('users', []) @property def permissions(self): return self.dict.get('permissions', {}) class RoleDAO(BaseJsonDao): DTO = RoleDTO ENTITY = RoleEntity ENTITY_KEY_TYPE = BaseJsonDao.EntityKeyTypeId
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module providing visualizations display as HTML/JS.""" __author__ = 'Mike Gainer (mgainer@google.com)' from common import safe_dom from controllers import utils from models import data_sources from models import jobs from models import transforms from models.analytics import utils as analytics_utils from modules.mapreduce import mapreduce_module def _generate_display_html(template_renderer, xsrf, app_context, visualizations): # Package-protected: pylint: disable=protected-access # First, load jobs for all generators required for an visualization. # Jobs may directly contain small results, just hold references to # larger results, or both. any_generator_not_running = False data_source_jobs = {} for generator_class in analytics_utils._generators_for_visualizations( visualizations): job = generator_class(app_context).load() data_source_jobs[generator_class] = job if not job or job.has_finished: any_generator_not_running = True # Generate HTML section for each visualization. html_sections = [] for v in visualizations: html_sections.extend(_generate_visualization_section( template_renderer, xsrf, app_context, v, data_source_jobs)) # Generate JS to pull contents of data-sources up to page and feed it # to visualization functions. html_sections.extend(_generate_data_source_script(template_renderer, visualizations, xsrf)) # Generate page content names_of_visualizations_with_generators = [] for visualization in visualizations: if analytics_utils._generators_for_visualizations([visualization]): names_of_visualizations_with_generators.append(visualization.name) rest_sources = [] has_pagination = False # True if any data_source has chunk size > 0 for rdsc in analytics_utils._rest_data_source_classes(visualizations): rest_sources.append({ 'name': rdsc.get_name(), 'title': rdsc.get_title(), 'chunk_size': rdsc.get_default_chunk_size(), }) has_pagination = has_pagination or rdsc.get_default_chunk_size() return template_renderer.render( None, 'models/analytics/display.html', { 'sections': html_sections, 'any_generator_not_running': any_generator_not_running, 'xsrf_token_run': xsrf.create_xsrf_token('run_visualizations'), 'visualizations': names_of_visualizations_with_generators, 'rest_sources': rest_sources, 'r': template_renderer.get_current_url(), 'has_pagination': has_pagination }) def _generate_visualization_section(template_renderer, xsrf, app_context, visualization, data_source_jobs): html_sections = [] # Collect statuses of generators and build a display messages for each. generator_status_messages = [] any_generator_still_running = False all_generators_completed_ok = True for generator_class in visualization.generator_classes: job = data_source_jobs[generator_class] if job is None: all_generators_completed_ok = False elif job.status_code != jobs.STATUS_CODE_COMPLETED: all_generators_completed_ok = False if not job.has_finished: any_generator_still_running = True generator_status_messages.append( get_generator_status_message(generator_class, job).append( get_pipeline_link(xsrf, app_context, generator_class, job))) # <h3> title block. html_sections.append(safe_dom.Element('h3').add_text(visualization.title)) html_sections.append(safe_dom.Element('br')) # Boilerplate content for each visualization's required generators html_sections.append(template_renderer.render( None, 'models/analytics/common_footer.html', { 'visualization': visualization.name, 'any_generator_still_running': any_generator_still_running, 'status_messages': generator_status_messages, 'xsrf_token_run': xsrf.create_xsrf_token('run_visualizations'), 'xsrf_token_cancel': xsrf.create_xsrf_token( 'cancel_visualizations'), 'r': template_renderer.get_current_url(), })) # If this source wants to generate inline values for its template, # and all generators that this source depends are complete (or zero # generators are depended on) then-and-only-then allow the source # to generate template values if all_generators_completed_ok: template_values = {'visualization': visualization.name} for source_class in visualization.data_source_classes: if issubclass(source_class, data_sources.SynchronousQuery): required_generator_classes = ( source_class.required_generators()) synchronous_query_jobs = [] for generator_class in required_generator_classes: synchronous_query_jobs.append( data_source_jobs[generator_class]) source_class.fill_values(app_context, template_values, *synchronous_query_jobs) html_sections.append(template_renderer.render( visualization, visualization.template_name, template_values)) return html_sections def get_generator_status_message(generator_class, job): message = safe_dom.NodeList() generator_description = generator_class.get_description() if job is None: message.append(safe_dom.Text( 'Statistics for %s have not been calculated yet' % generator_description)) elif job.status_code == jobs.STATUS_CODE_COMPLETED: message.append(safe_dom.Text( 'Statistics for %s were last updated at %s in about %s sec.' % ( generator_description, job.updated_on.strftime(utils.HUMAN_READABLE_DATETIME_FORMAT), job.execution_time_sec))) elif job.status_code == jobs.STATUS_CODE_FAILED: message.append(safe_dom.Text( 'There was an error updating %s ' % generator_description + 'statistics. Error msg:')) message.append(safe_dom.Element('br')) if issubclass(generator_class, jobs.MapReduceJob): error_message = jobs.MapReduceJob.get_error_message(job) else: error_message = job.output message.append(safe_dom.Element('blockquote').add_child( safe_dom.Element('pre').add_text(error_message))) else: message.append(safe_dom.Text( 'Job for %s statistics started at %s and is running now.' % ( generator_description, job.updated_on.strftime(utils.HUMAN_READABLE_DATETIME_FORMAT)))) return message def get_pipeline_link(xsrf, app_context, generator_class, job): ret = safe_dom.NodeList() if (not issubclass(generator_class, jobs.MapReduceJob) or # Don't give access to the pipeline details UI unless someone # has actively intended to provide access. The UI allows you to # kill jobs, and we don't want naive users stumbling around in # there without adult supervision. not mapreduce_module.GCB_ENABLE_MAPREDUCE_DETAIL_ACCESS.value or # Status URL may not be available immediately after job is launched; # pipeline setup is done w/ 'yield', and happens a bit later. not job or not jobs.MapReduceJob.has_status_url(job)): return ret if job.has_finished: link_text = 'View completed job run details' else: link_text = 'Check status of job' status_url = jobs.MapReduceJob.get_status_url( job, app_context.get_namespace_name(), xsrf.create_xsrf_token(mapreduce_module.XSRF_ACTION_NAME)) ret.append(safe_dom.Text(' ')) ret.append(safe_dom.A(status_url, target='_blank').add_text(link_text)) return ret def _generate_data_source_script(template_renderer, visualizations, xsrf): # Build list of {visualization name, [depended-upon data source names]} display_visualizations = {} for v in visualizations: rest_sources = [rsc.get_name() for rsc in v.rest_data_source_classes] if rest_sources: display_visualizations[v.name] = { 'callback_name': v.name, 'restSources': rest_sources, 'restSourcesNotYetSeen': { rest_source: True for rest_source in rest_sources}} if not display_visualizations: return [] # Build list of {data source name, [dependent visualization names]} display_rest_sources = {} # pylint: disable=protected-access for rdsc in analytics_utils._rest_data_source_classes(visualizations): v_names = [] for v in visualizations: if rdsc in v.rest_data_source_classes: v_names.append(v.name) display_rest_sources[rdsc.get_name()] = { 'currentPage': -1, 'pages': [], 'crossfilterDimensions': [], 'sourceContext': None, 'visualizations': v_names} env = { 'href': template_renderer.get_base_href(), 'visualizations': display_visualizations, 'restSources': display_rest_sources, 'dataSourceToken': data_sources.utils.generate_data_source_token(xsrf), } return [template_renderer.render( None, 'models/analytics/rest_visualizations.html', {'env': transforms.dumps(env)})]
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utility functions common to analytics module.""" __author__ = 'Mike Gainer (mgainer@google.com)' import os import sys import appengine_config def _generators_for_visualizations(visualizations): ret = set() for visualization in visualizations: ret.update(visualization.generator_classes) return ret def _rest_data_source_classes(visualizations): ret = set() for visualization in visualizations: ret.update(visualization.rest_data_source_classes) return ret def _get_template_dir_names(visualization=None): """Find directories where the template for this visualization can be found. Always includes the CourseBuilder base install directory and the directory for the analytics module. Args: visualization: If the visualization is non-blank, we will also include the directories of all of the data sources and generators specified for that visualization. This behavior permits simple naming of templates as just their base names, as long as they are in the same directory as the code that provides their content. Returns: Array of directories in which to seek a template. Note that the CourseBuilder root directory is always listed first so that fully qualified paths (e.g. "modules/my_new_module/my_template.html") will always work.) """ # Always add root of CB install first, to permit disambiguation of # same-named files by specifying full path. Note that here, we're # using CODE_ROOT, not BUNDLE_ROOT - the latter refers to course # content, and the former to the supporting code. ret = [ appengine_config.CODE_ROOT, os.path.join(appengine_config.CODE_ROOT, 'modules', 'visualizations')] if visualization: # Add back path to source/generator classes, minus the .py file # in which the handler class exists. for source_class in visualization.data_source_classes: ret.append(os.path.join(appengine_config.CODE_ROOT, os.path.dirname( sys.modules[source_class.__module__].__file__))) for generator_class in visualization.generator_classes: ret.append(os.path.join(appengine_config.CODE_ROOT, os.path.dirname( sys.modules[generator_class.__module__].__file__))) return ret
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module providing public analytics interfaces.""" __author__ = 'Mike Gainer (mgainer@google.com)' import os import re import jinja2 import appengine_config from controllers import sites from controllers import utils as controllers_utils from models.analytics import display from models.analytics import utils as analytics_utils from models import data_sources by_name = {} class Visualization(object): def __init__(self, name, title, html_template_name, data_source_classes=None): """Establish a new visualization. Args: name: Valid Javascript identifier to be used for this visualization when generating scripts via templates. title: Section title for visualization on the Dashboard -> Analytics page. html_template_name: Name of a file which contains a Jinja template which will be used to generate a chart or graph for the visualization. This can be specified as a path relative to the CB installation root (e.g. 'modules/my_new_module/my_visualization.html'), or relative to any of the data sources or generators used for the visualization (meaning you can just use the name of the HTML file without any path components if it's in the same directory). data_source_classes: An optional array of data source classes. This should contain only classes inheriting from data_sources.base_types._DataSource. Raises: ValueError: when any of - name is already registered as an visualization - name is not a valid JavaScript identifier. - a data source class is not registered with the data_sources module. """ if name and not re.match('^[_0-9a-z]+$', name): raise ValueError( 'name "%s" must contain only lowercase letters, ' % name + 'numbers or underscore characters') if name in by_name: raise ValueError( 'Visualization %s is already registered' % name) data_source_classes = data_source_classes or [] for data_source_class in data_source_classes: if not data_sources.Registry.is_registered(data_source_class): raise ValueError( 'All data source classes used in visualizations must be ' 'registered in models.data_sources.Registry; ' '"%s" is not registered.' % data_source_class.__name__) self._name = name self._title = title self._template_name = html_template_name self._data_source_classes = data_source_classes by_name[name] = self @property def name(self): return self._name @property def title(self): return self._title @property def template_name(self): return self._template_name @property def generator_classes(self): ret = set() for source_class in self.data_source_classes: ret.update(source_class.required_generators()) return ret @property def data_source_classes(self): return set(self._data_source_classes) @property def rest_data_source_classes(self): return set([c for c in self._data_source_classes if issubclass(c, data_sources.AbstractRestDataSource)]) class _TemplateRenderer(object): """Insulate display code from knowing about handlers and Jinja. This abstraction makes unit testing simpler, as well as decouples the display code from being directly dependent on web-request handler types. """ def __init__(self, handler): self._handler = handler def render(self, visualization, template_name, template_values): return jinja2.utils.Markup( self._handler.get_template( template_name, # pylint: disable=protected-access analytics_utils._get_template_dir_names(visualization) ).render(template_values, autoescape=True)) def get_base_href(self): return controllers_utils.ApplicationHandler.get_base_href(self._handler) def get_current_url(self): return self._handler.request.url def generate_display_html(handler, xsrf_creator, visualizations): """Generate sections of HTML representing each visualization. This generates multiple small HTML sections which are intended for inclusion as-is into a larger display (specifically, the dashboard page showing visualizations). The HTML will likely contain JavaScript elements that induce callbacks from the page to the REST service providing JSON data. Args: handler: Must be derived from controllers.utils.ApplicationHandler. Used to load HTML templates and to establish page context for learning the course to which to restrict data loading. xsrf_creator: Thing which can create XSRF tokens by exposing a create_token(token_name) method. Normally, set this to common.crypto.XsrfTokenManager. Unit tests use a bogus creator to avoid DB requirement. Returns: An array of HTML sections. This will consist of SafeDom elements and the result of HTML template expansion. """ # pylint: disable=protected-access return display._generate_display_html( _TemplateRenderer(handler), xsrf_creator, handler.app_context, visualizations) class AnalyticsHandler(controllers_utils.ReflectiveRequestHandler, controllers_utils.ApplicationHandler): default_action = 'run_visualization' get_actions = [] post_actions = ['run_visualizations', 'cancel_visualizations'] def _get_generator_classes(self): # pylint: disable=protected-access return analytics_utils._generators_for_visualizations( [by_name[name] for name in self.request.get_all('visualization')]) def post_run_visualizations(self): for generator_class in self._get_generator_classes(): generator_class(self.app_context).submit() self.redirect(str(self.request.get('r'))) def post_cancel_visualizations(self): for generator_class in self._get_generator_classes(): generator_class(self.app_context).cancel() self.redirect(str(self.request.get('r'))) def get_namespaced_handlers(): return [('/analytics', AnalyticsHandler)] def get_global_handlers(): # https://github.com/dc-js # # "Multi-Dimensional charting built to work natively with # crossfilter rendered with d3.js" dc_handler = sites.make_zip_handler(os.path.join( appengine_config.BUNDLE_ROOT, 'lib', 'dc.js-1.6.0.zip')) # https://github.com/square/crossfilter # # "Crossfilter is a JavaScript library for exploring large # multivariate datasets in the browser. Crossfilter supports # extremely fast (<30ms) interaction with coordinated views, even # with datasets containing a million or more records; we built it # to power analytics for Square Register, allowing merchants to # slice and dice their payment history fluidly." crossfilter_handler = sites.make_zip_handler(os.path.join( appengine_config.BUNDLE_ROOT, 'lib', 'crossfilter-1.3.7.zip')) # http://d3js.org/ # # "D3.js is a JavaScript library for manipulating documents based # on data. D3 helps you bring data to life using HTML, SVG and # CSS. D3's emphasis on web standards gives you the full # capabilities of modern browsers without tying yourself to a # proprietary framework, combining powerful visualization # components and a data-driven approach to DOM manipulation." d3_handler = sites.make_zip_handler(os.path.join( appengine_config.BUNDLE_ROOT, 'lib', 'd3-3.4.3.zip')) # Restrict files served from full zip package to minimum needed return [ ('/static/crossfilter-1.3.7/(crossfilter-1.3.7/crossfilter.min.js)', crossfilter_handler), ('/static/d3-3.4.3/(d3.min.js)', d3_handler), ('/static/dc.js-1.6.0/(dc.js-1.6.0/dc.js)', dc_handler), ('/static/dc.js-1.6.0/(dc.js-1.6.0/dc.min.js)', dc_handler), ('/static/dc.js-1.6.0/(dc.js-1.6.0/dc.min.js.map)', dc_handler), ('/static/dc.js-1.6.0/(dc.js-1.6.0/dc.css)', dc_handler), ]
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Messages used in the models.""" __author__ = 'Boris Roussev (borislavr@google.com)' from common import safe_dom PEER_MATCHER_NAME = 'Peer' ASSESSMENT_CONTENT_DESCRIPTION = safe_dom.assemble_text_message(""" Assessment questions and answers (JavaScript format). """, 'https://code.google.com/p/course-builder/wiki/CreateAssessments') ASSESSMENT_DETAILS_DESCRIPTION = safe_dom.assemble_text_message(""" Properties and restrictions of your assessment. """, 'https://code.google.com/p/course-builder/wiki/PeerReview') DUE_DATE_FORMAT_DESCRIPTION = safe_dom.assemble_text_message(""" Should be formatted as YYYY-MM-DD hh:mm (e.g. 1997-07-16 19:20) and be specified in the UTC timezone.""", None) REVIEWER_FEEDBACK_FORM_DESCRIPTION = safe_dom.assemble_text_message(""" Review form questions and answers (JavaScript format). """, 'https://code.google.com/p/course-builder/wiki/PeerReview') REVIEW_DUE_DATE_FORMAT_DESCRIPTION = safe_dom.assemble_text_message(""" Should be formatted as YYYY-MM-DD hh:mm (e.g. 1997-07-16 19:20) and be specified in the UTC timezone. """, 'https://code.google.com/p/course-builder/wiki/PeerReview') REVIEW_MIN_COUNT_DESCRIPTION = safe_dom.assemble_text_message( None, 'https://code.google.com/p/course-builder/wiki/PeerReview') REVIEW_TIMEOUT_IN_MINUTES = safe_dom.assemble_text_message(""" This value should be specified in minutes. """, 'https://code.google.com/p/course-builder/wiki/PeerReview') LESSON_VIDEO_ID_DESCRIPTION = """ Provide a YouTube video ID to embed a video. """ LESSON_SCORED_DESCRIPTION = """ Whether questions in this lesson will be scored (summative) or only provide textual feedback (formative). """ LESSON_OBJECTIVES_DESCRIPTION = """ The lesson body is displayed to students above the video in the default template. """ LESSON_NOTES_DESCRIPTION = """ Provide a URL that points to the notes for this lesson (if applicable). These notes can be accessed by clicking on the 'Text Version' button on the lesson page. """ LESSON_AUTO_INDEX_DESCRIPTION = """ Assign a sequential number to this lesson automatically. """ LESSON_ACTIVITY_TITLE_DESCRIPTION = """ This appears above your activity. """ LESSON_ACTIVITY_LISTED_DESCRIPTION = """ Whether the activity should be viewable as a stand-alone item in the unit index. """ LESSON_ACTIVITY_DESCRIPTION = safe_dom.assemble_text_message(""" Note: Activities defined in the "Activity" area are deprecated, please use the "Lesson Body" area instead. Old-style activities are automatically converted during "Import Course". """, ('https://code.google.com/p/course-builder/wiki/CreateActivities' '#Writing_activities')) LESSON_MANUAL_PROGRESS_DESCRIPTION = """ When set, the manual progress REST API permits users to manually mark a unit or lesson as complete, overriding the automatic progress tracking. """ QUESTION_DESCRIPTION = 'Shown when selecting questions for quizzes, etc.' INCORRECT_ANSWER_FEEDBACK = """ Shown when the student response does not match any of the possible answers. """ INPUT_FIELD_HEIGHT_DESCRIPTION = """ Height of the input field, measured in rows. """ INPUT_FIELD_WIDTH_DESCRIPTION = """ Width of the input field, measured in columns. """ LINK_EDITOR_URL_DESCRIPTION = """ Links to external sites must start with 'http' or https'. """
Python
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utility for Sending notifications.""" __author__ = 'Abhinav Khandelwal (abhinavk@google.com)' from google.appengine.api import mail from google.appengine.api import users class EmailManager(object): """Notification Manager. Sends emails out.""" def __init__(self, course): self._course = course self._user = users.get_current_user() def send_mail(self, subject, body, reciever): """send email.""" message = mail.EmailMessage() message.sender = self._user.email() message.to = self._user.email() message.bcc = reciever message.subject = subject message.html = body message.send() return True def send_announcement(self, subject, body): """Send an announcement to course announcement list.""" announce_email = self._course.get_course_announcement_list_email() if announce_email: return self.send_mail(subject, body, announce_email) return False
Python
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Manages mapping of users to roles and roles to privileges.""" __author__ = 'Pavel Simakov (psimakov@google.com)' import collections import config from common import utils from models import MemcacheManager from models import RoleDAO from google.appengine.api import users GCB_ADMIN_LIST = config.ConfigProperty( 'gcb_admin_user_emails', str, ( 'A list of email addresses for super-admin users. ' 'WARNING! Super-admin users have the highest level of access to your ' 'Google App Engine instance and to all data about all courses and ' 'students within that instance. Be very careful when modifying this ' 'property. ' 'Syntax: Entries may be separated with any combination of ' 'tabs, spaces, commas, or newlines. Existing values using "[" and ' '"]" around email addresses continues to be supported. ' 'Regular expressions are not supported.'), '', multiline=True) KEY_COURSE = 'course' KEY_ADMIN_USER_EMAILS = 'admin_user_emails' GCB_WHITELISTED_USERS = config.ConfigProperty( 'gcb_user_whitelist', str, ( 'A list of email addresses of users allowed access to courses. ' 'If this is blank, site-wide user whitelisting is disabled. ' 'Access to courses is also implicitly granted to super admins and ' 'course admins, so you need not repeat those names here. ' 'Course-specific whitelists trump this list - if a course has a ' 'non-blank whitelist, this one is ignored. ' 'Syntax: Entries may be separated with any combination of ' 'tabs, spaces, commas, or newlines. Existing values using "[" and ' '"]" around email addresses continues to be supported. ' 'Regular expressions are not supported.'), '', multiline=True) Permission = collections.namedtuple('Permission', ['name', 'description']) class Roles(object): """A class that provides information about user roles.""" # Maps module names to callbacks which generate permissions. # See register_permissions for the structure of the callbacks. _REGISTERED_PERMISSIONS = collections.OrderedDict() memcache_key = 'roles.Roles.users_to_permissions_map' @classmethod def is_direct_super_admin(cls): """Checks if current user is a super admin, without delegation.""" return users.get_current_user() and users.is_current_user_admin() @classmethod def is_super_admin(cls): """Checks if current user is a super admin, possibly via delegation.""" if cls.is_direct_super_admin(): return True return cls._user_email_in(users.get_current_user(), GCB_ADMIN_LIST.value) @classmethod def is_course_admin(cls, app_context): """Checks if a user is a course admin, possibly via delegation.""" if cls.is_super_admin(): return True if KEY_COURSE in app_context.get_environ(): environ = app_context.get_environ()[KEY_COURSE] if KEY_ADMIN_USER_EMAILS in environ: allowed = environ[KEY_ADMIN_USER_EMAILS] user = users.get_current_user() if allowed and cls._user_email_in(user, allowed): return True return False @classmethod def is_user_whitelisted(cls, app_context): user = users.get_current_user() global_whitelist = GCB_WHITELISTED_USERS.value.strip() course_whitelist = app_context.whitelist.strip() # Most-specific whitelist used if present. if course_whitelist: return cls._user_email_in(user, course_whitelist) # Global whitelist if no course whitelist elif global_whitelist: return cls._user_email_in(user, global_whitelist) # Lastly, no whitelist = no restrictions else: return True @classmethod def _user_email_in(cls, user, text): return user and user.email() in utils.text_to_list( text, utils.BACKWARD_COMPATIBLE_SPLITTER) @classmethod def update_permissions_map(cls): """Puts a dictionary mapping users to permissions in memcache. A dictionary is constructed, using roles information from the datastore, mapping user emails to dictionaries that map module names to sets of permissions. Returns: The created dictionary. """ permissions_map = {} for role in RoleDAO.get_all(): for user in role.users: user_permissions = permissions_map.setdefault(user, {}) for (module_name, permissions) in role.permissions.iteritems(): module_permissions = user_permissions.setdefault( module_name, set()) module_permissions.update(permissions) MemcacheManager.set(cls.memcache_key, permissions_map) return permissions_map @classmethod def _load_permissions_map(cls): """Loads the permissions map from Memcache or creates it if needed.""" permissions_map = MemcacheManager.get(cls.memcache_key) if not permissions_map: permissions_map = cls.update_permissions_map() return permissions_map @classmethod def is_user_allowed(cls, app_context, module, permission): """Check whether the current user is assigned a certain permission. Args: app_context: sites.ApplicationContext of the relevant course module: module object that registered the permission. permission: string specifying the permission. Returns: boolean indicating whether the current user is allowed to perform the action associated with the permission. """ if cls.is_course_admin(app_context): return True if not module or not permission or not users.get_current_user(): return False permissions_map = cls._load_permissions_map() user_permissions = permissions_map.get( users.get_current_user().email(), {}) return permission in user_permissions.get(module.name, set()) @classmethod def register_permissions(cls, module, callback_function): """Registers a callback function that generates permissions. A callback should return an iteratable of permissions of the type Permission(permission_name, permission_description) Example: Module 'module-werewolf' registers permissions 'can_howl' and 'can_hunt' by defining a function callback_werewolf returning: [ Permission('can_howl', 'Can howl to the moon'), Permission('can_hunt', 'Can hunt for sheep') ] In order to register these permissions the module calls register_permissions(module, callback_werewolf) with the module whose module.name is 'module-werewolf'. Args: module: module object that registers the permissions. callback_function: a function accepting ApplicationContext as sole argument and returning a list of permissions. """ assert module is not None assert module.name assert module not in cls._REGISTERED_PERMISSIONS cls._REGISTERED_PERMISSIONS[module] = callback_function @classmethod def unregister_permissions(cls, module): del cls._REGISTERED_PERMISSIONS[module] @classmethod def get_modules(cls): return cls._REGISTERED_PERMISSIONS.iterkeys() @classmethod def get_permissions(cls): return cls._REGISTERED_PERMISSIONS.iteritems()
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Set of converters between db models, Python and JSON dictionaries, etc.""" __author__ = 'Mike Gainer (mgainer@google.com)' import base64 import datetime import entities import transforms_constants from common import schema_fields from google.appengine.api import datastore_types from google.appengine.ext import db # TODO(johncox): Regularize the simple and complex types named both here # and in transforms.json_to_dict() so that we have a well-defined consistent # set of types for which we can do conversions and generate schemas. PYTHON_TYPE_TO_JSON_TYPE = { basestring: 'string', datetime.date: 'date', datetime.datetime: 'datetime', int: 'integer', float: 'number', bool: 'boolean', datastore_types.Text: 'text', } SUPPORTED_TYPES = ( datastore_types.Key, datetime.date, datetime.datetime, db.GeoPt, ) def _get_schema_field(property_type): name = property_type.name if property_type.data_type == list: # Shallow evaluation here is OK; Python DB API does not permit # array-of-array; when declaring a ListProperty, the item type # must be a Type instance (and thus cannot be a class, and thus # cannot be a Property class) item_type = schema_fields.SchemaField( name=name + ':item', label=name + ':item', optional=True, property_type=PYTHON_TYPE_TO_JSON_TYPE[ property_type.item_type]) ret = schema_fields.FieldArray( name=name, label=name, description=property_type.verbose_name, item_type=item_type) else: type_name = PYTHON_TYPE_TO_JSON_TYPE.get(property_type.data_type) if not type_name: if issubclass(property_type.data_type, entities.BaseEntity): type_name = 'string' else: raise ValueError('Unsupported entity type for schema: %s' % str(property_type.data_type)) ret = schema_fields.SchemaField( name=name, label=name, property_type=type_name, description=property_type.verbose_name, optional=not property_type.required) return ret def get_schema_for_entity(clazz): """Get schema matching entity returned by BaseEntity.for_export().""" assert issubclass(clazz, entities.BaseEntity) # Must have blacklist. # Treating as module-protected. pylint: disable=protected-access return _get_schema_for_entity(clazz, clazz._get_export_blacklist()) def get_schema_for_entity_unsafe(clazz): """Get schema matching entity returned by BaseEntity.for_export_unsafe().""" return _get_schema_for_entity(clazz, {}) def _get_schema_for_entity(clazz, suppressed): available_properties = clazz.properties() registry = schema_fields.FieldRegistry(clazz.__name__) for property_type in available_properties.values(): if property_type.name not in suppressed: registry.add_property(_get_schema_field(property_type)) return registry def string_to_key(s): """Reify key from serialized version, discarding namespace and appid.""" key_with_namespace_and_appid = db.Key(encoded=s) return db.Key.from_path(*key_with_namespace_and_appid.to_path()) def entity_to_dict(entity, force_utf_8_encoding=False): """Puts model object attributes into a Python dictionary.""" output = {} for_export = isinstance(entity, entities.ExportEntity) properties = entity.properties() if for_export: for name in entity.instance_properties(): properties[name] = getattr(entity, name) for key, prop in properties.iteritems(): value = getattr(entity, key) if (value is None or isinstance(value, transforms_constants.SIMPLE_TYPES) or isinstance(value, SUPPORTED_TYPES)): output[key] = value # some values are raw bytes; force utf-8 or base64 encoding if force_utf_8_encoding and isinstance(value, basestring): try: output[key] = value.encode('utf-8') except UnicodeDecodeError: output[key] = { 'type': 'binary', 'encoding': 'base64', 'content': base64.urlsafe_b64encode(value)} elif isinstance(prop, db.ReferenceProperty): output[key] = str(value.key()) else: raise ValueError('Failed to encode: %s' % prop) # explicitly add entity key as a 'string' attribute output['key'] = str(entity.safe_key) if for_export else str(entity.key()) if for_export: output.pop('safe_key') return output def dict_to_entity(entity, source_dict): """Sets model object attributes from a Python dictionary.""" properties = entity.properties() for key, value in source_dict.items(): if (value and key in properties and isinstance(properties[key], db.ReferenceProperty)): setattr(entity, key, string_to_key(value)) elif (value is None or isinstance(value, transforms_constants.SIMPLE_TYPES) or isinstance(value, SUPPORTED_TYPES)): setattr(entity, key, value) else: raise ValueError('Failed to set value "%s" for %s' % (value, key)) return entity def json_dict_to_entity_initialization_dict(entity_class, source_dict): """Sets model object attributes from a Python dictionary.""" properties = entity_class.properties() ret = {} for key, value in source_dict.items(): if (value and key in properties and isinstance(properties[key], db.ReferenceProperty)): ret[key] = string_to_key(value) elif (value is None or isinstance(value, transforms_constants.SIMPLE_TYPES) or isinstance(value, SUPPORTED_TYPES)): ret[key] = value else: raise ValueError('Failed to set value "%s" for %s' % (value, key)) return ret
Python
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Common classes and methods for managing Courses.""" __author__ = 'Pavel Simakov (psimakov@google.com)' import collections import copy from datetime import datetime import logging import os import pickle import re import sys import threading import config import custom_units import messages import progress import review import transforms import utils import vfs import yaml import appengine_config from common import locales from common import safe_dom from common import schema_fields from common import utils as common_utils import common.tags from common.utils import Namespace import models from models import MemcacheManager from models import QuestionImporter from tools import verify from google.appengine.api import namespace_manager from google.appengine.ext import db COURSE_MODEL_VERSION_1_2 = '1.2' COURSE_MODEL_VERSION_1_3 = '1.3' DEFAULT_FETCH_LIMIT = 100 # all entities of these types are copies from source to target during course # import COURSE_CONTENT_ENTITIES = frozenset([ models.QuestionEntity, models.QuestionGroupEntity, models.LabelEntity, models.RoleEntity]) # add your custom entities here during module registration; they will also be # copied from source to target during course import ADDITIONAL_ENTITIES_FOR_COURSE_IMPORT = set() # 1.4 assessments are JavaScript files ASSESSMENT_MODEL_VERSION_1_4 = '1.4' # 1.5 assessments are HTML text, with embedded question tags ASSESSMENT_MODEL_VERSION_1_5 = '1.5' SUPPORTED_ASSESSMENT_MODEL_VERSIONS = frozenset( [ASSESSMENT_MODEL_VERSION_1_4, ASSESSMENT_MODEL_VERSION_1_5]) ALLOWED_MATCHERS_NAMES = {review.PEER_MATCHER: messages.PEER_MATCHER_NAME} # Date format string for validating input in ISO 8601 format without a # timezone. All such strings are assumed to refer to UTC datetimes. # Example: '2013-03-21 13:00' ISO_8601_DATE_FORMAT = '%Y-%m-%d %H:%M' # Whether or not individual courses are allowed to use Google APIs. COURSES_CAN_USE_GOOGLE_APIS = config.ConfigProperty( 'gcb_courses_can_use_google_apis', bool, ( 'Whether or not courses can use Google APIs. If True, individual ' 'courses must also be configured with API keys, etc., in order to ' 'actually make API calls'), False) # The config key part under which course info lives. _CONFIG_KEY_PART_COURSE = 'course' # The config key part under which google info lives. _CONFIG_KEY_PART_GOOGLE = 'google' # The config key part under which the api key is stored. _CONFIG_KEY_PART_API_KEY = 'api_key' # The config key part under which the client id is stored. _CONFIG_KEY_PART_CLIENT_ID = 'client_id' # The key in course.yaml under which the Google API key lives. CONFIG_KEY_GOOGLE_API_KEY = '%s:%s:%s' % ( _CONFIG_KEY_PART_COURSE, _CONFIG_KEY_PART_GOOGLE, _CONFIG_KEY_PART_API_KEY) # The key in course.yaml under which the Google client id lives. CONFIG_KEY_GOOGLE_CLIENT_ID = '%s:%s:%s' % ( _CONFIG_KEY_PART_COURSE, _CONFIG_KEY_PART_GOOGLE, _CONFIG_KEY_PART_CLIENT_ID) def deep_dict_merge(*args): """Merges default and real value dictionaries recursively.""" if len(args) > 2: return deep_dict_merge(args[0], deep_dict_merge(*(args[1:]))) real_values_dict = args[0] default_values_dict = args[1] def _deep_merge(real_values, default_values): """Updates real with default values recursively.""" # Recursively merge dictionaries. for key, value in real_values.items(): default_value = default_values.get(key) if (default_value and isinstance( value, dict) and isinstance(default_value, dict)): _deep_merge(value, default_value) # Copy over other values. for key, value in default_values.items(): if key not in real_values: real_values[key] = value result = {} if real_values_dict: result = copy.deepcopy(real_values_dict) _deep_merge(result, default_values_dict) return result # The template dict for all courses yaml_path = os.path.join(appengine_config.BUNDLE_ROOT, 'course_template.yaml') with open(yaml_path) as course_template_yaml: COURSE_TEMPLATE_DICT = yaml.safe_load( course_template_yaml.read().decode('utf-8')) # Here are the defaults for a new course. DEFAULT_COURSE_YAML_DICT = { 'course': { 'title': 'UNTITLED COURSE', 'locale': 'en_US', 'main_image': {}, 'browsable': True, 'now_available': False}, 'html_hooks': {}, 'preview': {}, 'unit': {}, 'reg_form': { 'can_register': True, 'whitelist': '', 'additional_registration_fields': '', } } # Here are the defaults for an existing course. DEFAULT_EXISTING_COURSE_YAML_DICT = deep_dict_merge( {'course': { 'now_available': True}}, DEFAULT_COURSE_YAML_DICT) # Here is the default course.yaml for a new course. EMPTY_COURSE_YAML = u"""# my new course.yaml course: title: 'New Course by %s' now_available: False """ # Here are the default assessment weights corresponding to the sample course. DEFAULT_LEGACY_ASSESSMENT_WEIGHTS = {'Pre': 0, 'Mid': 30, 'Fin': 70} # Indicates that an assessment is graded automatically. AUTO_GRADER = 'auto' # Indicates that an assessment is graded by a human. HUMAN_GRADER = 'human' # Allowed graders. ALLOWED_GRADERS = [AUTO_GRADER, HUMAN_GRADER] # Keys in unit.workflow (when it is converted to a dict). GRADER_KEY = 'grader' MATCHER_KEY = 'matcher' SUBMISSION_DUE_DATE_KEY = 'submission_due_date' REVIEW_DUE_DATE_KEY = 'review_due_date' REVIEW_MIN_COUNT_KEY = 'review_min_count' REVIEW_WINDOW_MINS_KEY = 'review_window_mins' DEFAULT_REVIEW_MIN_COUNT = 2 DEFAULT_REVIEW_WINDOW_MINS = 60 # Keys specific to human-graded assessments. HUMAN_GRADED_ASSESSMENT_KEY_LIST = [ MATCHER_KEY, REVIEW_MIN_COUNT_KEY, REVIEW_WINDOW_MINS_KEY, SUBMISSION_DUE_DATE_KEY, REVIEW_DUE_DATE_KEY ] # The name for the peer review assessment used in the sample v1.2 CSV file. # This is here so that a peer review assessment example is available when # Course Builder loads with the sample course. However, in general, peer # review assessments should only be specified in Course Builder v1.4 or # later (via the web interface). LEGACY_REVIEW_ASSESSMENT = 'ReviewAssessmentExample' # This value is the default workflow for assessment grading, DEFAULT_AUTO_GRADER_WORKFLOW = yaml.safe_dump({ GRADER_KEY: AUTO_GRADER }, default_flow_style=False) # This value is meant to be used only for the human-reviewed assessments in the # sample v1.2 Power Searching course. LEGACY_HUMAN_GRADER_WORKFLOW = yaml.safe_dump({ GRADER_KEY: HUMAN_GRADER, MATCHER_KEY: review.PEER_MATCHER, SUBMISSION_DUE_DATE_KEY: '2099-03-14 12:00', REVIEW_DUE_DATE_KEY: '2099-03-21 12:00', REVIEW_MIN_COUNT_KEY: DEFAULT_REVIEW_MIN_COUNT, REVIEW_WINDOW_MINS_KEY: DEFAULT_REVIEW_WINDOW_MINS, }, default_flow_style=False) def copy_attributes(source, target, converter): """Copies source object attributes into a target using a converter.""" for source_name, value in converter.items(): if value: target_name = value[0] target_type = value[1] setattr( target, target_name, target_type(getattr(source, source_name))) def load_csv_course(app_context): """Loads course data from the CSV files.""" logging.info('Initializing datastore from CSV files.') unit_file = os.path.join(app_context.get_data_home(), 'unit.csv') lesson_file = os.path.join(app_context.get_data_home(), 'lesson.csv') # Check files exist. if (not app_context.fs.isfile(unit_file) or not app_context.fs.isfile(lesson_file)): return None, None unit_stream = app_context.fs.open(unit_file) lesson_stream = app_context.fs.open(lesson_file) # Verify CSV file integrity. units = verify.read_objects_from_csv_stream( unit_stream, verify.UNITS_HEADER, verify.Unit) lessons = verify.read_objects_from_csv_stream( lesson_stream, verify.LESSONS_HEADER, verify.Lesson) verifier = verify.Verifier() verifier.verify_unit_fields(units) verifier.verify_lesson_fields(lessons) verifier.verify_unit_lesson_relationships(units, lessons) assert verifier.errors == 0 assert verifier.warnings == 0 # Load data from CSV files into a datastore. units = verify.read_objects_from_csv_stream( app_context.fs.open(unit_file), verify.UNITS_HEADER, Unit12, converter=verify.UNIT_CSV_TO_DB_CONVERTER) lessons = verify.read_objects_from_csv_stream( app_context.fs.open(lesson_file), verify.LESSONS_HEADER, Lesson12, converter=verify.LESSON_CSV_TO_DB_CONVERTER) return units, lessons def index_units_and_lessons(course): """Index all 'U' type units and their lessons. Indexes are 1-based.""" unit_index = 1 for unit in course.get_units(): if verify.UNIT_TYPE_UNIT == unit.type: unit._index = unit_index # pylint: disable=protected-access unit_index += 1 lesson_index = 1 for lesson in course.get_lessons(unit.unit_id): if lesson.auto_index: lesson._index = ( # pylint: disable=protected-access lesson_index) lesson_index += 1 def has_at_least_one_old_style_assessment(course): assessments = course.get_assessment_list() return any(a.is_old_style_assessment(course) for a in assessments) def has_only_new_style_assessments(course): return not has_at_least_one_old_style_assessment(course) def has_at_least_one_old_style_activity(course): for unit in course.get_units(): for lesson in course.get_lessons(unit.unit_id): if lesson.activity: fn = os.path.join( course.app_context.get_home(), course.get_activity_filename( unit.unit_id, lesson.lesson_id)) if course.app_context.fs.isfile(fn): return True return False def has_only_new_style_activities(course): return not has_at_least_one_old_style_activity(course) class AbstractCachedObject(object): """Abstract serializable versioned object that can stored in memcache.""" @classmethod def _max_size(cls): # By default, max out at one cache record. return models.MEMCACHE_MAX @classmethod def _make_keys(cls): # The course content files may change between deployment. To avoid # reading old cached values by the new version of the application we # add deployment version to the key. Now each version of the # application can put/get its own version of the course and the # deployment. # Generate the maximum number of cache shard keys indicated by the max # allowed size of the derived type. Not all of these will necessarily # be used, but the number of shards is typically very small (max of 4) # so pre-generating these is not a big burden. num_shards = ( (cls._max_size() + models.MEMCACHE_MAX - 1) // models.MEMCACHE_MAX) return [ 'course:model:pickle:%s:%s:%d' % ( cls.VERSION, os.environ.get('CURRENT_VERSION_ID'), shard) for shard in xrange(num_shards)] @classmethod def new_memento(cls): """Creates new empty memento instance; must be pickle serializable.""" raise Exception('Not implemented') @classmethod def instance_from_memento(cls, unused_app_context, unused_memento): """Creates instance from serializable memento.""" raise Exception('Not implemented') @classmethod def memento_from_instance(cls, unused_instance): """Creates serializable memento from instance.""" raise Exception('Not implemented') @classmethod def load(cls, app_context): """Loads instance from memcache; does not fail on errors.""" shard_keys = cls._make_keys() shard_contents = {} try: shard_0 = MemcacheManager.get( shard_keys[0], namespace=app_context.get_namespace_name()) if not shard_0: return None num_shards = ord(shard_0[0]) shard_contents[shard_keys[0]] = shard_0[1:] if num_shards > 1: shard_contents.update(MemcacheManager.get_multi( shard_keys[1:], namespace=app_context.get_namespace_name())) if len(shard_contents) != num_shards: return None data = [] for shard_key in sorted(shard_contents.keys()): data.append(shard_contents[shard_key]) memento = cls.new_memento() memento.deserialize(''.join(data)) return cls.instance_from_memento(app_context, memento) except Exception as e: # pylint: disable=broad-except logging.error( 'Failed to load object \'%s\' from memcache. %s', shard_keys, e) return None @classmethod def save(cls, app_context, instance): """Saves instance to memcache.""" # If item to cache is too large, clear the old cached value for this # item, and don't send the new, too-large item to cache. data_bytes = cls.memento_from_instance(instance).serialize() num_shards_required = (len(data_bytes) // models.MEMCACHE_MAX) + 1 data_bytes = chr(num_shards_required) + data_bytes if len(data_bytes) > cls._max_size(): logging.warning( 'Not sending %d bytes for %s to Memcache; this is more ' 'than the maximum limit of %d bytes.', len(data_bytes), cls.__name__, cls._max_size()) cls.delete(app_context) return mapping = {} shard_keys = cls._make_keys() i = 0 while i < num_shards_required: mapping[shard_keys[i]] = data_bytes[i * models.MEMCACHE_MAX: (i + 1) * models.MEMCACHE_MAX] i += 1 MemcacheManager.set_multi( mapping, namespace=app_context.get_namespace_name()) @classmethod def delete(cls, app_context): """Deletes instance from memcache.""" MemcacheManager.delete_multi( cls._make_keys(), namespace=app_context.get_namespace_name()) def serialize(self): """Saves instance to a pickle representation.""" return pickle.dumps(self.__dict__) def deserialize(self, binary_data): """Loads instance from a pickle representation.""" adict = pickle.loads(binary_data) if self.version != adict.get('version'): raise Exception('Expected version %s, found %s.' % ( self.version, adict.get('version'))) self.__dict__.update(adict) class Unit12(object): """An object to represent a Unit, Assessment or Link (version 1.2).""" def __init__(self): self.unit_id = '' # primary key self.type = '' self.title = '' self.release_date = '' self.now_available = False # Units of 'U' types have 1-based index. An index is automatically # computed. self._index = None @property def href(self): assert verify.UNIT_TYPE_LINK == self.type return self.unit_id @property def index(self): assert verify.UNIT_TYPE_UNIT == self.type return self._index @property def workflow_yaml(self): """Returns the workflow as a YAML text string.""" assert self.is_assessment() if self.unit_id == LEGACY_REVIEW_ASSESSMENT: return LEGACY_HUMAN_GRADER_WORKFLOW else: return DEFAULT_AUTO_GRADER_WORKFLOW @property def workflow(self): """Returns the workflow as an object.""" return Workflow(self.workflow_yaml) @property def pre_assessment(self): return None @property def post_assessment(self): return None @property def labels(self): return None @property def show_contents_on_one_page(self): return False @property def manual_progress(self): return False @property def description(self): return None @property def unit_header(self): return None @property def unit_footer(self): return None def is_assessment(self): return verify.UNIT_TYPE_ASSESSMENT == self.type def is_old_style_assessment(self, unused_course): return self.is_assessment() def needs_human_grader(self): return self.workflow.get_grader() == HUMAN_GRADER def is_custom_unit(self): return None class Lesson12(object): """An object to represent a Lesson (version 1.2).""" def __init__(self): self.lesson_id = 0 # primary key self.unit_id = 0 # unit.unit_id of parent self.title = '' self.scored = False self.objectives = '' self.video = '' self.notes = '' self.duration = '' self.activity = '' self.activity_title = '' self.activity_listed = True # Lessons have 1-based index inside the unit they belong to. An index # is automatically computed. self._auto_index = True self._index = None @property def now_available(self): return True @property def auto_index(self): return self._auto_index @property def index(self): return self._index @property def has_activity(self): return self.activity != '' @property def manual_progress(self): return False class CachedCourse12(AbstractCachedObject): """A representation of a Course12 optimized for storing in memcache.""" VERSION = COURSE_MODEL_VERSION_1_2 def __init__(self, units=None, lessons=None, unit_id_to_lessons=None): self.version = self.VERSION self.units = units self.lessons = lessons self.unit_id_to_lessons = unit_id_to_lessons @classmethod def new_memento(cls): return CachedCourse12() @classmethod def instance_from_memento(cls, app_context, memento): return CourseModel12( app_context, units=memento.units, lessons=memento.lessons, unit_id_to_lessons=memento.unit_id_to_lessons) @classmethod def memento_from_instance(cls, course): return CachedCourse12( units=course.units, lessons=course.lessons, unit_id_to_lessons=course.unit_id_to_lessons) class CourseModel12(object): """A course defined in terms of CSV files (version 1.2).""" VERSION = COURSE_MODEL_VERSION_1_2 @classmethod def load(cls, app_context): """Loads course data into a model.""" course = CachedCourse12.load(app_context) if not course: units, lessons = load_csv_course(app_context) if units and lessons: course = CourseModel12(app_context, units, lessons) if course: CachedCourse12.save(app_context, course) return course @classmethod def _make_unit_id_to_lessons_lookup_dict(cls, lessons): """Creates an index of unit.unit_id to unit.lessons.""" unit_id_to_lessons = {} for lesson in lessons: key = str(lesson.unit_id) if key not in unit_id_to_lessons: unit_id_to_lessons[key] = [] unit_id_to_lessons[key].append(lesson) return unit_id_to_lessons def __init__( self, app_context, units=None, lessons=None, unit_id_to_lessons=None): self._app_context = app_context self._units = [] self._lessons = [] self._unit_id_to_lessons = {} if units: self._units = units if lessons: self._lessons = lessons if unit_id_to_lessons: self._unit_id_to_lessons = unit_id_to_lessons else: self._unit_id_to_lessons = ( self._make_unit_id_to_lessons_lookup_dict(self._lessons)) index_units_and_lessons(self) @property def app_context(self): return self._app_context @property def units(self): return self._units @property def lessons(self): return self._lessons @property def unit_id_to_lessons(self): return self._unit_id_to_lessons def get_units(self): return self._units[:] def get_assessments(self): return [x for x in self.get_units() if x.is_assessment()] def get_lessons(self, unit_id): return self._unit_id_to_lessons.get(str(unit_id), []) def find_unit_by_id(self, unit_id): """Finds a unit given its id.""" for unit in self._units: if str(unit.unit_id) == str(unit_id): return unit return None def get_parent_unit(self, unused_unit_id): return None # This model does not support any kind of unit relations def get_review_filename(self, unit_id): """Returns the review filename from unit id.""" return 'assets/js/review-%s.js' % unit_id def get_assessment_filename(self, unit_id): """Returns assessment base filename.""" unit = self.find_unit_by_id(unit_id) assert unit and unit.is_assessment() return 'assets/js/assessment-%s.js' % unit.unit_id def _get_assessment_as_dict(self, filename): """Returns the Python dict representation of an assessment file.""" root_name = 'assessment' content = self._app_context.fs.impl.get(os.path.join( self._app_context.get_home(), filename)).read() content, noverify_text = verify.convert_javascript_to_python( content, root_name) return verify.evaluate_python_expression_from_text( content, root_name, verify.Assessment().scope, noverify_text) def get_assessment_content(self, unit): """Returns the schema for an assessment as a Python dict.""" return self._get_assessment_as_dict( self.get_assessment_filename(unit.unit_id)) def get_review_content(self, unit): """Returns the schema for a review form as a Python dict.""" return self._get_assessment_as_dict( self.get_review_filename(unit.unit_id)) def get_assessment_model_version(self, unused_unit): return ASSESSMENT_MODEL_VERSION_1_4 def get_activity_filename(self, unit_id, lesson_id): """Returns activity base filename.""" return 'assets/js/activity-%s.%s.js' % (unit_id, lesson_id) def find_lesson_by_id(self, unit, lesson_id): """Finds a lesson given its id (or 1-based index in this model).""" index = int(lesson_id) - 1 return self.get_lessons(unit.unit_id)[index] def to_json(self): """Creates JSON representation of this instance.""" adict = copy.deepcopy(self) del adict._app_context return transforms.dumps( adict, indent=4, sort_keys=True, default=lambda o: o.__dict__) class Unit13(object): """An object to represent a Unit, Assessment or Link (version 1.3).""" DEFAULT_VALUES = { 'workflow_yaml': DEFAULT_AUTO_GRADER_WORKFLOW, 'html_content': '', 'html_check_answers': False, 'html_review_form': '', 'properties': {}, 'labels': '', 'pre_assessment': None, 'post_assessment': None, 'show_contents_on_one_page': False, 'manual_progress': False, 'description': None, 'unit_header': None, 'unit_footer': None, 'custom_unit_type': None, } def __init__(self): self.unit_id = 0 # primary key self.type = '' self.title = '' self.release_date = '' self.now_available = False # custom properties self.properties = {} # Units of 'U' types have 1-based index. An index is automatically # computed. self._index = None # Only valid for the unit.type == verify.UNIT_TYPE_LINK. self.href = None # Only valid for the unit.type == verify.UNIT_TYPE_ASSESSMENT. self.weight = 1 # Only valid for the unit.type == verify.UNIT_TYPE_ASSESSMENT. self.html_content = None self.html_check_answers = False self.html_review_form = None # Only valid for the unit.type == verify.UNIT_TYPE_ASSESSMENT. self.workflow_yaml = DEFAULT_AUTO_GRADER_WORKFLOW # Valid for all values of unit.type self.labels = None # Support the appearance of assessments as being part of # units. Only valid for UNIT_TYPE_UNIT. # TODO(psimakov): Decide if/when we need a more general # hierarchical-container strategy, and if so, when? self.pre_assessment = None self.post_assessment = None # Whether to show all content in the unit on a single HTML # page, or display assessments/lessons/activities on separate pages. self.show_contents_on_one_page = False # When manual_progress is set, the user may manually mark a Unit # as completed. This does not apply to assessments or links. # Units marked for manual completion are also marked as complete # when all of their contained content is marked complete (either # manually or normally). self.manual_progress = False # Brief text (25 words or fewer) describing unit/assessment/link # for display in summaries. self.description = None # Only valid for unit_type == verify.UNIT_TYPE_UNIT. Shown # at top/bottom of page for units displayed all on one page, # or on same page above(below) first(last) unit element for # units displaying contained elements on separate pages. self.unit_header = None self.unit_footer = None # TODO(mgainer): Similarly for unit-specific header/footer # for each contained element within a unit, when unit shows # its elements on separate pages. # If this is a custom unit. We use this field to identify the type of # custom unit. self.custom_unit_type = None @property def index(self): assert verify.UNIT_TYPE_UNIT == self.type return self._index @property def workflow(self): """Returns the workflow as an object.""" assert self.is_assessment() or self.is_custom_unit() workflow = Workflow(self.workflow_yaml) return workflow @property def custom_unit_url(self): if hasattr(self, '_custom_unit_url'): return self._custom_unit_url return None def set_custom_unit_url(self, url): self._custom_unit_url = url def is_assessment(self): return verify.UNIT_TYPE_ASSESSMENT == self.type def is_custom_unit(self): return verify.UNIT_TYPE_CUSTOM == self.type def is_old_style_assessment(self, course): content = self.html_content if content: content = content.strip() if self.is_assessment() and not content: fn = os.path.join( course.app_context.get_home(), course.get_assessment_filename(self.unit_id)) if course.app_context.fs.isfile(fn): return True return False def needs_human_grader(self): return self.workflow.get_grader() == HUMAN_GRADER def scored(self): """Is this unit used for scoring. This does not take into account of lessons contained in the unit.""" if self.is_assessment(): return True if self.is_custom_unit(): cu = custom_units.UnitTypeRegistry.get(self.custom_unit_type) return cu and cu.is_graded return False class Lesson13(object): """An object to represent a Lesson (version 1.3).""" DEFAULT_VALUES = { 'activity_listed': True, 'scored': False, 'properties': {}, 'auto_index': True, 'manual_progress': False} def __init__(self): self.lesson_id = 0 # primary key self.unit_id = 0 # unit.unit_id of parent self.title = '' self.scored = False self.objectives = '' self.video = '' self.notes = '' self.duration = '' self.now_available = False self.has_activity = False self.activity_title = '' self.activity_listed = True # custom properties self.properties = {} # Lessons have 1-based index inside the unit they belong to. An index # is automatically computed. self.auto_index = True self._index = None # When manual_progress is set, the user must take an affirmative UI # action to mark the lesson as completed. If not set, a lesson is # considered completed the first time it is shown to the student. self.manual_progress = False @property def index(self): return self._index @property def activity(self): """A symbolic name to old attribute.""" return self.has_activity class PersistentCourse13(object): """A representation of a Course13 optimized for persistence.""" COURSES_FILENAME = 'data/course.json' def __init__(self, next_id=None, units=None, lessons=None): self.version = CourseModel13.VERSION self.next_id = next_id self.units = units self.lessons = lessons def to_dict(self): """Saves object attributes into a dict.""" result = {} result['version'] = str(self.version) result['next_id'] = int(self.next_id) units = [] for unit in self.units: units.append(transforms.instance_to_dict(unit)) result['units'] = units lessons = [] for lesson in self.lessons: lessons.append(transforms.instance_to_dict(lesson)) result['lessons'] = lessons return result def _from_dict(self, adict): """Loads instance attributes from the dict.""" self.next_id = int(adict.get('next_id')) self.units = [] unit_dicts = adict.get('units') if unit_dicts: for unit_dict in unit_dicts: unit = Unit13() transforms.dict_to_instance( unit_dict, unit, defaults=Unit13.DEFAULT_VALUES) self.units.append(unit) self.lessons = [] lesson_dicts = adict.get('lessons') if lesson_dicts: for lesson_dict in lesson_dicts: lesson = Lesson13() transforms.dict_to_instance( lesson_dict, lesson, defaults=Lesson13.DEFAULT_VALUES) self.lessons.append(lesson) @classmethod def save(cls, app_context, course): """Saves course to datastore.""" persistent = PersistentCourse13( next_id=course.next_id, units=course.units, lessons=course.lessons) fs = app_context.fs.impl filename = fs.physical_to_logical(cls.COURSES_FILENAME) app_context.fs.put(filename, vfs.FileStreamWrapped( None, persistent.serialize())) @classmethod def load(cls, app_context): """Loads course from datastore.""" fs = app_context.fs.impl filename = fs.physical_to_logical(cls.COURSES_FILENAME) stream = app_context.fs.open(filename) if stream: persistent = PersistentCourse13() persistent.deserialize(stream.read()) return CourseModel13( app_context, next_id=persistent.next_id, units=persistent.units, lessons=persistent.lessons) return None def serialize(self): """Saves instance to a JSON representation.""" adict = self.to_dict() json_text = transforms.dumps(adict) return json_text.encode('utf-8') def deserialize(self, binary_data): """Loads instance from a JSON representation.""" json_text = binary_data.decode('utf-8') adict = transforms.loads(json_text) if self.version != adict.get('version'): raise Exception('Expected version %s, found %s.' % ( self.version, adict.get('version'))) self._from_dict(adict) class CachedCourse13(AbstractCachedObject): """A representation of a Course13 optimized for storing in memcache.""" VERSION = COURSE_MODEL_VERSION_1_3 def __init__( self, next_id=None, units=None, lessons=None, unit_id_to_lesson_ids=None): self.version = self.VERSION self.next_id = next_id self.units = units self.lessons = lessons # This is almost the same as PersistentCourse13 above, but it also # stores additional indexes used for performance optimizations. There # is no need to persist these indexes in durable storage, but it is # nice to have them in memcache. self.unit_id_to_lesson_ids = unit_id_to_lesson_ids @classmethod def _max_size(cls): # Cap at approximately 4M to avoid 1M single-cache-element limit, # which is too small for larger courses. return models.MEMCACHE_MAX * 4 @classmethod def new_memento(cls): return CachedCourse13() @classmethod def instance_from_memento(cls, app_context, memento): return CourseModel13( app_context, next_id=memento.next_id, units=memento.units, lessons=memento.lessons, unit_id_to_lesson_ids=memento.unit_id_to_lesson_ids) @classmethod def memento_from_instance(cls, course): return CachedCourse13( next_id=course.next_id, units=course.units, lessons=course.lessons, unit_id_to_lesson_ids=course.unit_id_to_lesson_ids) class CourseModel13(object): """A course defined in terms of objects (version 1.3).""" VERSION = COURSE_MODEL_VERSION_1_3 @classmethod def load(cls, app_context): """Loads course from memcache or persistence.""" course = CachedCourse13.load(app_context) if not course: course = PersistentCourse13.load(app_context) if course: CachedCourse13.save(app_context, course) return course @classmethod def _make_unit_id_to_lessons_lookup_dict(cls, lessons): """Creates an index of unit.unit_id to unit.lessons.""" unit_id_to_lesson_ids = {} for lesson in lessons: key = str(lesson.unit_id) if key not in unit_id_to_lesson_ids: unit_id_to_lesson_ids[key] = [] unit_id_to_lesson_ids[key].append(str(lesson.lesson_id)) return unit_id_to_lesson_ids def __init__( self, app_context, next_id=None, units=None, lessons=None, unit_id_to_lesson_ids=None): # Init default values. self._app_context = app_context self._next_id = 1 # a counter for creating sequential entity ids self._units = [] self._lessons = [] self._unit_id_to_lesson_ids = {} # These array keep dirty object in current transaction. self._dirty_units = [] self._dirty_lessons = [] self._deleted_units = [] self._deleted_lessons = [] # Set provided values. if next_id: self._next_id = next_id if units: self._units = units if lessons: self._lessons = lessons if unit_id_to_lesson_ids: self._unit_id_to_lesson_ids = unit_id_to_lesson_ids else: self._index() @property def app_context(self): return self._app_context @property def next_id(self): return self._next_id @property def units(self): return self._units @property def lessons(self): return self._lessons @property def unit_id_to_lesson_ids(self): return self._unit_id_to_lesson_ids def _get_next_id(self): """Allocates next id in sequence.""" next_id = self._next_id self._next_id += 1 return next_id def _index(self): """Indexes units and lessons.""" self._unit_id_to_lesson_ids = self._make_unit_id_to_lessons_lookup_dict( self._lessons) index_units_and_lessons(self) def get_file_content(self, filename): fs = self.app_context.fs path = fs.impl.physical_to_logical(filename) if fs.isfile(path): return fs.get(path) return None def set_file_content(self, filename, content, metadata_only=None, is_draft=None): fs = self.app_context.fs path = fs.impl.physical_to_logical(filename) fs.put(path, content, metadata_only=metadata_only, is_draft=is_draft) def delete_file(self, filename): fs = self.app_context.fs path = fs.impl.physical_to_logical(filename) if fs.isfile(path): fs.delete(path) return True return False def is_dirty(self): """Checks if course object has been modified and needs to be saved.""" return self._dirty_units or self._dirty_lessons def _flush_deleted_objects(self): """Delete files owned by deleted objects.""" # TODO(psimakov): handle similarly add_unit() and set_assessment() # To delete an activity/assessment one must look up its filename. This # requires a valid unit/lesson. If unit was deleted it's no longer # found in _units, same for lesson. So we temporarily install deleted # unit/lesson array instead of actual. We also temporarily empty # so _unit_id_to_lesson_ids is not accidentally used. This is a hack, # and we will improve it as object model gets more complex, but for # now it works fine. units = self._units lessons = self._lessons unit_id_to_lesson_ids = self._unit_id_to_lesson_ids try: self._units = self._deleted_units self._lessons = self._deleted_lessons self._unit_id_to_lesson_ids = None # Delete owned assessments. for unit in self._deleted_units: if unit.is_assessment(): self._delete_assessment(unit) elif unit.is_custom_unit(): cu = custom_units.UnitTypeRegistry.get( unit.custom_unit_type) if cu: cu.delete_unit(self, unit) # Delete owned activities. for lesson in self._deleted_lessons: if lesson.has_activity: self._delete_activity(lesson) finally: self._units = units self._lessons = lessons self._unit_id_to_lesson_ids = unit_id_to_lesson_ids def _validate_settings_content(self, content): yaml.safe_load(content) def invalidate_cached_course_settings(self): """Clear settings cached locally in-process and globally in memcache.""" keys = [ Course.make_locale_environ_key(locale) for locale in [None] + self.app_context.get_all_locales()] models.MemcacheManager.delete_multi( keys, namespace=self.app_context.get_namespace_name()) self._app_context.clear_per_request_cache() def save_settings(self, course_settings): content = yaml.safe_dump(course_settings) try: self._validate_settings_content(content) except yaml.YAMLError as e: # pylint: disable=W0703 logging.error('Failed to validate course settings: %s.', str(e)) return False content_stream = vfs.string_to_stream(unicode(content)) # Store settings. self.set_file_content('/course.yaml', content_stream) self.invalidate_cached_course_settings() return True def _update_dirty_objects(self): """Update files owned by course.""" fs = self.app_context.fs # Update state of owned assessments. for unit in self._dirty_units: unit = self.find_unit_by_id(unit.unit_id) if not unit or verify.UNIT_TYPE_ASSESSMENT != unit.type: continue filename = self.get_assessment_filename(unit.unit_id) path = fs.impl.physical_to_logical(filename) if fs.isfile(path): self.set_file_content( filename, None, metadata_only=True, is_draft=not unit.now_available) # Update state of owned activities. for lesson in self._dirty_lessons: lesson = self.find_lesson_by_id(None, lesson.lesson_id) if not lesson or not lesson.has_activity: continue path = fs.impl.physical_to_logical( self.get_activity_filename(None, lesson.lesson_id)) if fs.isfile(path): fs.put( path, None, metadata_only=True, is_draft=not lesson.now_available) def save(self): """Saves course to datastore and memcache.""" self._flush_deleted_objects() self._update_dirty_objects() self._dirty_units = [] self._dirty_lessons = [] self._deleted_units = [] self._deleted_lessons = [] self._index() PersistentCourse13.save(self._app_context, self) CachedCourse13.delete(self._app_context) def get_units(self): return self._units[:] def get_assessments(self): return [x for x in self.get_units() if x.is_assessment()] def get_lessons(self, unit_id): lesson_ids = self._unit_id_to_lesson_ids.get(str(unit_id)) lessons = [] if lesson_ids: for lesson_id in lesson_ids: lessons.append(self.find_lesson_by_id(None, lesson_id)) return lessons def get_assessment_filename(self, unit_id): """Returns assessment base filename.""" unit = self.find_unit_by_id(unit_id) assert unit and unit.is_assessment() return 'assets/js/assessment-%s.js' % unit.unit_id def get_review_filename(self, unit_id): """Returns the review filename from unit id.""" unit = self.find_unit_by_id(unit_id) assert unit and unit.is_assessment() return 'assets/js/review-%s.js' % unit.unit_id def get_activity_filename(self, unused_unit_id, lesson_id): """Returns activity base filename.""" lesson = self.find_lesson_by_id(None, lesson_id) assert lesson if lesson.has_activity: return 'assets/js/activity-%s.js' % lesson_id return None def find_unit_by_id(self, unit_id): """Finds a unit given its id.""" for unit in self._units: if str(unit.unit_id) == str(unit_id): return unit return None def find_lesson_by_id(self, unused_unit, lesson_id): """Finds a lesson given its id.""" for lesson in self._lessons: if str(lesson.lesson_id) == str(lesson_id): return lesson return None def get_parent_unit(self, unit_id): # See if the unit is an assessment being used as a pre/post # unit lesson. for unit in self.get_units(): if (str(unit.pre_assessment) == str(unit_id) or str(unit.post_assessment) == str(unit_id)): return unit # Nope, no other kinds of parentage; no parent. return None def add_unit(self, unit_type, title, custom_unit_type=None): """Adds a brand new unit.""" assert unit_type in verify.UNIT_TYPES if verify.UNIT_TYPE_CUSTOM == unit_type: assert custom_unit_type else: assert not custom_unit_type unit = Unit13() unit.type = unit_type unit.unit_id = self._get_next_id() unit.title = title unit.now_available = False if verify.UNIT_TYPE_CUSTOM == unit_type: unit.custom_unit_type = custom_unit_type self._units.append(unit) self._index() self._dirty_units.append(unit) return unit def add_lesson(self, unit, title): """Adds brand new lesson to a unit.""" unit = self.find_unit_by_id(unit.unit_id) assert unit lesson = Lesson13() lesson.lesson_id = self._get_next_id() lesson.unit_id = unit.unit_id lesson.title = title lesson.now_available = False self._lessons.append(lesson) self._index() self._dirty_lessons.append(lesson) return lesson def move_lesson_to(self, lesson, unit): """Moves a lesson to another unit.""" unit = self.find_unit_by_id(unit.unit_id) assert unit assert verify.UNIT_TYPE_UNIT == unit.type lesson = self.find_lesson_by_id(None, lesson.lesson_id) assert lesson lesson.unit_id = unit.unit_id self._index() return lesson def _delete_activity(self, lesson): """Deletes activity.""" filename = self._app_context.fs.impl.physical_to_logical( self.get_activity_filename(None, lesson.lesson_id)) if self.app_context.fs.isfile(filename): self.app_context.fs.delete(filename) return True return False def _delete_assessment(self, unit): """Deletes assessment.""" files_deleted_count = 0 filenames = [ self._app_context.fs.impl.physical_to_logical( self.get_assessment_filename(unit.unit_id)), self._app_context.fs.impl.physical_to_logical( self.get_review_filename(unit.unit_id))] for filename in filenames: if self.app_context.fs.isfile(filename): self.app_context.fs.delete(filename) files_deleted_count += 1 return bool(files_deleted_count) def delete_all(self): """Deletes all course files.""" for entity in self._app_context.fs.impl.list( appengine_config.BUNDLE_ROOT): self._app_context.fs.impl.delete(entity) assert not self._app_context.fs.impl.list(appengine_config.BUNDLE_ROOT) CachedCourse13.delete(self._app_context) def delete_lesson(self, lesson): """Delete a lesson.""" lesson = self.find_lesson_by_id(None, lesson.lesson_id) if not lesson: return False self._lessons.remove(lesson) self._index() self._deleted_lessons.append(lesson) self._dirty_lessons.append(lesson) return True def delete_unit(self, unit): """Deletes a unit.""" unit = self.find_unit_by_id(unit.unit_id) if not unit: return False for lesson in self.get_lessons(unit.unit_id): self.delete_lesson(lesson) parent = self.get_parent_unit(unit.unit_id) if parent: if parent.pre_assessment == unit.unit_id: parent.pre_assessment = None if parent.post_assessment == unit.unit_id: parent.post_assessment = None self._dirty_units.append(parent) self._units.remove(unit) self._index() self._deleted_units.append(unit) self._dirty_units.append(unit) return True def update_unit(self, unit): """Updates an existing unit.""" existing_unit = self.find_unit_by_id(unit.unit_id) if not existing_unit: return False existing_unit.title = unit.title existing_unit.release_date = unit.release_date existing_unit.now_available = unit.now_available existing_unit.labels = unit.labels existing_unit.pre_assessment = unit.pre_assessment existing_unit.post_assessment = unit.post_assessment existing_unit.show_contents_on_one_page = unit.show_contents_on_one_page existing_unit.manual_progress = unit.manual_progress existing_unit.description = unit.description existing_unit.unit_header = unit.unit_header existing_unit.unit_footer = unit.unit_footer existing_unit.properties = unit.properties existing_unit.custom_unit_type = unit.custom_unit_type if verify.UNIT_TYPE_LINK == existing_unit.type: existing_unit.href = unit.href if existing_unit.is_assessment() or existing_unit.is_custom_unit(): existing_unit.weight = unit.weight existing_unit.html_content = unit.html_content existing_unit.html_check_answers = unit.html_check_answers existing_unit.html_review_form = unit.html_review_form existing_unit.workflow_yaml = unit.workflow_yaml self._dirty_units.append(existing_unit) return existing_unit def update_lesson(self, lesson): """Updates an existing lesson.""" existing_lesson = self.find_lesson_by_id( lesson.unit_id, lesson.lesson_id) if not existing_lesson: return False existing_lesson.title = lesson.title existing_lesson.unit_id = lesson.unit_id existing_lesson.scored = lesson.scored existing_lesson.objectives = lesson.objectives existing_lesson.video = lesson.video existing_lesson.notes = lesson.notes existing_lesson.duration = lesson.duration existing_lesson.now_available = lesson.now_available existing_lesson.has_actvity = lesson.has_activity existing_lesson.activity_title = lesson.activity_title existing_lesson.activity_listed = lesson.activity_listed existing_lesson.properties = lesson.properties existing_lesson.auto_index = lesson.auto_index existing_lesson.manual_progress = lesson.manual_progress self._index() self._dirty_lessons.append(existing_lesson) return existing_lesson def reorder_units(self, order_data): """Reorder the units and lessons based on the order data given. Args: order_data: list of dict. Format is The order_data is in the following format: [ {'id': 0, 'lessons': [{'id': 0}, {'id': 1}, {'id': 2}]}, {'id': 1}, {'id': 2, 'lessons': [{'id': 0}, {'id': 1}]} ... ] """ reordered_units = [] unit_ids = set() for unit_data in order_data: unit_id = unit_data['id'] unit = self.find_unit_by_id(unit_id) assert unit reordered_units.append(self.find_unit_by_id(unit_id)) unit_ids.add(unit_id) assert len(unit_ids) == len(self._units) self._units = reordered_units reordered_lessons = [] lesson_ids = set() for unit_data in order_data: unit_id = unit_data['id'] unit = self.find_unit_by_id(unit_id) assert unit if verify.UNIT_TYPE_UNIT != unit.type: continue for lesson_data in unit_data['lessons']: lesson_id = lesson_data['id'] lesson = self.find_lesson_by_id(None, lesson_id) lesson.unit_id = unit_id reordered_lessons.append(lesson) lesson_ids.add((unit_id, lesson_id)) assert len(lesson_ids) == len(self._lessons) self._lessons = reordered_lessons self._index() def _get_file_content_as_dict(self, filename): """Gets the content of an assessment file as a Python dict.""" path = self._app_context.fs.impl.physical_to_logical(filename) root_name = 'assessment' file_content = self.app_context.fs.get(path) content, noverify_text = verify.convert_javascript_to_python( file_content, root_name) return verify.evaluate_python_expression_from_text( content, root_name, verify.Assessment().scope, noverify_text) def get_assessment_content(self, unit): """Returns the schema for an assessment as a Python dict.""" return self._get_file_content_as_dict( self.get_assessment_filename(unit.unit_id)) def get_review_content(self, unit): """Returns the schema for a review form as a Python dict.""" return self._get_file_content_as_dict( self.get_review_filename(unit.unit_id)) def get_assessment_model_version(self, unit): filename = self.get_assessment_filename(unit.unit_id) path = self._app_context.fs.impl.physical_to_logical(filename) if self.app_context.fs.isfile(path): return ASSESSMENT_MODEL_VERSION_1_4 else: return ASSESSMENT_MODEL_VERSION_1_5 def set_assessment_file_content( self, unit, assessment_content, dest_filename, errors=None): """Updates the content of an assessment file on the file system.""" if errors is None: errors = [] path = self._app_context.fs.impl.physical_to_logical(dest_filename) root_name = 'assessment' try: content, noverify_text = verify.convert_javascript_to_python( assessment_content, root_name) assessment = verify.evaluate_python_expression_from_text( content, root_name, verify.Assessment().scope, noverify_text) except Exception: # pylint: disable=broad-except errors.append('Unable to parse %s:\n%s' % ( root_name, str(sys.exc_info()[1]))) return verifier = verify.Verifier() try: verifier.verify_assessment_instance(assessment, path) except verify.SchemaException as ex: errors.append('Error validating %s\n%s' % ( root_name, ex.message or '')) return self.set_file_content( dest_filename, vfs.string_to_stream(assessment_content), is_draft=not unit.now_available) def set_assessment_content(self, unit, assessment_content, errors=None): """Updates the content of an assessment.""" self.set_assessment_file_content( unit, assessment_content, self.get_assessment_filename(unit.unit_id), errors=errors ) def set_review_form(self, unit, review_form, errors=None): """Sets the content of a review form.""" self.set_assessment_file_content( unit, review_form, self.get_review_filename(unit.unit_id), errors=errors ) def set_activity_content(self, lesson, activity_content, errors=None): """Updates the content of an activity.""" if errors is None: errors = [] filename = self.get_activity_filename(lesson.unit_id, lesson.lesson_id) path = self._app_context.fs.impl.physical_to_logical(filename) root_name = 'activity' try: content, noverify_text = verify.convert_javascript_to_python( activity_content, root_name) activity = verify.evaluate_python_expression_from_text( content, root_name, verify.Activity().scope, noverify_text) except Exception: # pylint: disable=broad-except errors.append('Unable to parse %s:\n%s' % ( root_name, str(sys.exc_info()[1]))) return verifier = verify.Verifier() try: verifier.verify_activity_instance(activity, path) except verify.SchemaException as ex: errors.append('Error validating %s\n%s' % ( root_name, ex.message or '')) return self.set_file_content(filename, vfs.string_to_stream(activity_content), is_draft=not lesson.now_available) def import_from(self, src_course, errors): """Imports a content of another course into this course.""" def copy_assessment12_into_assessment13(src_unit, dst_unit, errors): """Copies old an style assessment to a new style assessment.""" assessment = src_course.get_content_as_dict_safe(src_unit, errors) if errors or not assessment: return False workflow_dict = src_unit.workflow.to_dict() if len(ALLOWED_MATCHERS_NAMES) == 1: workflow_dict[MATCHER_KEY] = ( ALLOWED_MATCHERS_NAMES.keys()[0]) dst_unit.workflow_yaml = yaml.safe_dump(workflow_dict) dst_unit.workflow.validate(errors=errors) if errors: return False if assessment.get('checkAnswers'): dst_unit.html_check_answers = assessment['checkAnswers'].value # Import questions in the assessment and the review questionnaire html_content = [] html_review_form = [] if assessment.get('preamble'): html_content.append(assessment['preamble']) # prepare all the dtos for the questions in the assignment content question_dtos = QuestionImporter.build_question_dtos( assessment, 'Imported from assessment "%s" (question #%s)', dst_unit, errors) if question_dtos is None: return False # prepare the questions for the review questionnaire, if necessary review_dtos = [] if dst_unit.needs_human_grader(): review_dict = src_course.get_content_as_dict_safe( src_unit, errors, kind='review') if errors: return False if review_dict.get('preamble'): html_review_form.append(review_dict['preamble']) review_dtos = QuestionImporter.build_question_dtos( review_dict, 'Imported from assessment "%s" (review question #%s)', dst_unit, errors) if review_dtos is None: return False # batch submit the questions and split out their resulting id's all_dtos = question_dtos + review_dtos all_ids = models.QuestionDAO.save_all(all_dtos) question_ids = all_ids[:len(question_dtos)] review_ids = all_ids[len(question_dtos):] # insert question tags for the assessment content for quid in question_ids: html_content.append( str(safe_dom.Element( 'question', quid=str(quid), instanceid=common_utils.generate_instance_id()))) dst_unit.html_content = '\n'.join(html_content) # insert question tags for the review questionnaire for quid in review_ids: html_review_form.append( str(safe_dom.Element( 'question', quid=str(quid), instanceid=common_utils.generate_instance_id()))) dst_unit.html_review_form = '\n'.join(html_review_form) return True def copy_unit12_into_unit13(src_unit, dst_unit, errors): """Copies unit object attributes between versions.""" assert dst_unit.type == src_unit.type dst_unit.release_date = src_unit.release_date dst_unit.now_available = src_unit.now_available if verify.UNIT_TYPE_LINK == dst_unit.type: dst_unit.href = src_unit.href # Copy over the assessment. if dst_unit.is_assessment(): copy_assessment12_into_assessment13(src_unit, dst_unit, errors) def copy_unit13_into_unit13(src_unit, dst_unit, src_course, errors): """Copies unit13 attributes to a new unit.""" dst_unit.release_date = src_unit.release_date dst_unit.now_available = src_unit.now_available dst_unit.workflow_yaml = src_unit.workflow_yaml if dst_unit.is_assessment(): if src_unit.is_old_style_assessment(src_course): copy_assessment12_into_assessment13( src_unit, dst_unit, errors) else: dst_unit.properties = copy.deepcopy(src_unit.properties) dst_unit.weight = src_unit.weight dst_unit.html_content = src_unit.html_content dst_unit.html_check_answers = src_unit.html_check_answers dst_unit.html_review_form = src_unit.html_review_form def import_lesson12_activities( text, unit, lesson_w_activity, lesson_title, errors): try: content, noverify_text = verify.convert_javascript_to_python( text, 'activity') activity = verify.evaluate_python_expression_from_text( content, 'activity', verify.Activity().scope, noverify_text) if noverify_text: lesson_w_activity.objectives = ( ('<script>\n// This script is inserted by 1.2 to 1.3 ' 'import function\n%s\n</script>\n') % noverify_text) except Exception: # pylint: disable=broad-except errors.append( 'Unable to parse activity: %s.' % lesson_title) return False try: verify.Verifier().verify_activity_instance(activity, 'none') except verify.SchemaException: errors.append( 'Unable to validate activity: %s.' % lesson_title) return False question_number = 1 task = [] try: for item in activity['activity']: if isinstance(item, basestring): item = item.decode('string-escape') task.append(item) else: qid, instance_id = QuestionImporter.import_question( item, unit, lesson_title, question_number, task) task = [] if item['questionType'] == 'multiple choice group': question_tag = ( '<question-group qgid="%s" instanceid="%s">' '</question-group>') % (qid, instance_id) elif item['questionType'] == 'freetext': question_tag = ( '<question quid="%s" instanceid="%s">' '</question>') % (qid, instance_id) elif item['questionType'] == 'multiple choice': question_tag = ( '<question quid="%s" instanceid="%s">' '</question>') % (qid, instance_id) else: raise ValueError( 'Unknown question type: %s' % item['questionType']) lesson_w_activity.objectives += question_tag question_number += 1 if task: lesson_w_activity.objectives += ''.join(task) except models.CollisionError: errors.append('Duplicate activity: %s' % task) return False except models.ValidationError as e: errors.append(str(e)) return False except Exception as e: # pylint: disable=broad-except errors.append('Unable to convert: %s, Error: %s' % (task, e)) return False return True def copy_to_lesson_13( src_unit, src_lesson, dst_unit, dst_lesson, now_available, errors): dst_lesson.objectives = src_lesson.objectives dst_lesson.video = src_lesson.video dst_lesson.notes = src_lesson.notes dst_lesson.duration = src_lesson.duration dst_lesson.activity_listed = False dst_lesson.now_available = now_available # Copy over the activity. Note that we copy files directly and # avoid all logical validations of their content. This is done for a # purpose - at this layer we don't care what is in those files. if src_lesson.activity: # create a lesson with activity if src_lesson.activity_title: title = src_lesson.activity_title else: title = 'Activity' lesson_w_activity = self.add_lesson(dst_unit, title) lesson_w_activity.auto_index = False lesson_w_activity.activity_listed = False lesson_w_activity.now_available = now_available src_filename = os.path.join( src_course.app_context.get_home(), src_course.get_activity_filename( src_unit.unit_id, src_lesson.lesson_id)) if src_course.app_context.fs.isfile(src_filename): text = src_course.app_context.fs.get(src_filename) import_lesson12_activities( text, dst_unit, lesson_w_activity, src_lesson.title, errors) def copy_lesson12_into_lesson13( src_unit, src_lesson, dst_unit, dst_lesson, errors): copy_to_lesson_13( src_unit, src_lesson, dst_unit, dst_lesson, True, errors) dst_lesson.now_available = True def copy_lesson13_into_lesson13( src_unit, src_lesson, dst_unit, dst_lesson, errors): copy_to_lesson_13( src_unit, src_lesson, dst_unit, dst_lesson, src_lesson.now_available, errors) dst_lesson.now_available = src_lesson.now_available dst_lesson.scored = src_lesson.scored dst_lesson.properties = src_lesson.properties def _copy_entities_between_namespaces(entity_types, from_ns, to_ns): """Copies entities between different namespaces.""" def _mapper_func(entity, unused_ns): _add_entity_instance_to_a_namespace( to_ns, entity.__class__, entity.key().id_or_name(), entity.data) old_namespace = namespace_manager.get_namespace() try: namespace_manager.set_namespace(from_ns) for _entity_class in entity_types: mapper = utils.QueryMapper( _entity_class.all(), batch_size=DEFAULT_FETCH_LIMIT, report_every=0) mapper.run(_mapper_func, from_ns) finally: namespace_manager.set_namespace(old_namespace) def _add_entity_instance_to_a_namespace( ns, entity_class, _id_or_name, data): """Add new entity to the datastore of and a given namespace.""" old_namespace = namespace_manager.get_namespace() try: namespace_manager.set_namespace(ns) new_key = db.Key.from_path(entity_class.__name__, _id_or_name) new_instance = entity_class(key=new_key) new_instance.data = data new_instance.put() finally: namespace_manager.set_namespace(old_namespace) # check editable if not self._app_context.is_editable_fs(): errors.append( 'Target course %s must be ' 'on read-write media.' % self.app_context.raw) return None, None # check empty if self.get_units(): errors.append( 'Target course %s must be empty.' % self.app_context.raw) return None, None # import course settings dst_settings = self.app_context.get_environ() src_settings = src_course.app_context.get_environ() dst_settings = deep_dict_merge(dst_settings, src_settings) if not self.save_settings(dst_settings): errors.append('Failed to import course settings.') return None, None # iterate over course structure and assets and import each item with Namespace(self.app_context.get_namespace_name()): for unit in src_course.get_units(): # import unit new_unit = self.add_unit(unit.type, unit.title) if src_course.version == CourseModel13.VERSION: copy_unit13_into_unit13(unit, new_unit, src_course, errors) elif src_course.version == CourseModel12.VERSION: copy_unit12_into_unit13(unit, new_unit, errors) else: raise Exception( 'Unsupported course version: %s', src_course.version) # import contained lessons for lesson in src_course.get_lessons(unit.unit_id): new_lesson = self.add_lesson(new_unit, lesson.title) if src_course.version == CourseModel13.VERSION: copy_lesson13_into_lesson13( unit, lesson, new_unit, new_lesson, errors) elif src_course.version == CourseModel12.VERSION: copy_lesson12_into_lesson13( unit, lesson, new_unit, new_lesson, errors) else: raise Exception( 'Unsupported course version: ' '%s', src_course.version) # assign weights to assignments imported from version 12 if src_course.version == CourseModel12.VERSION: if self.get_assessments(): w = common_utils.truncate( 100.0 / len(self.get_assessments())) for x in self.get_assessments(): x.weight = w # import course dependencies from the datastore _copy_entities_between_namespaces( list(COURSE_CONTENT_ENTITIES) + list( ADDITIONAL_ENTITIES_FOR_COURSE_IMPORT), src_course.app_context.get_namespace_name(), self.app_context.get_namespace_name()) return src_course, self def to_json(self): """Creates JSON representation of this instance.""" persistent = PersistentCourse13( next_id=self._next_id, units=self._units, lessons=self._lessons) return transforms.dumps( persistent.to_dict(), indent=4, sort_keys=True, default=lambda o: o.__dict__) class Workflow(object): """Stores workflow specifications for assessments.""" def __init__(self, yaml_str): """Sets yaml_str (the workflow spec), without doing any validation.""" self._yaml_str = yaml_str def to_yaml(self): return self._yaml_str def to_dict(self): if not self._yaml_str: return {} obj = yaml.safe_load(self._yaml_str) assert isinstance(obj, dict) return obj def _convert_date_string_to_datetime(self, date_str): """Returns a datetime object.""" if not date_str: return None return datetime.strptime(date_str, ISO_8601_DATE_FORMAT) def get_grader(self): """Returns the associated grader.""" return self.to_dict().get(GRADER_KEY) def get_matcher(self): return self.to_dict().get(MATCHER_KEY) def get_submission_due_date(self): date_str = self.to_dict().get(SUBMISSION_DUE_DATE_KEY) if date_str is None: return None return self._convert_date_string_to_datetime(date_str) def get_review_due_date(self): date_str = self.to_dict().get(REVIEW_DUE_DATE_KEY) if date_str is None: return None return self._convert_date_string_to_datetime(date_str) def get_review_min_count(self): return self.to_dict().get(REVIEW_MIN_COUNT_KEY) def get_review_window_mins(self): return self.to_dict().get(REVIEW_WINDOW_MINS_KEY) def _ensure_value_is_nonnegative_int(self, workflow_dict, key, errors): """Checks that workflow_dict[key] is a non-negative integer.""" value = workflow_dict[key] if not isinstance(value, int): errors.append('%s should be an integer' % key) elif value < 0: errors.append('%s should be a non-negative integer' % key) def validate(self, errors=None): """Tests whether the current Workflow object is valid.""" if errors is None: errors = [] try: # Validate the workflow specification (in YAML format). assert self._yaml_str, 'missing key: %s.' % GRADER_KEY workflow_dict = yaml.safe_load(self._yaml_str) assert isinstance(workflow_dict, dict), ( 'expected the YAML representation of a dict') assert GRADER_KEY in workflow_dict, 'missing key: %s.' % GRADER_KEY assert workflow_dict[GRADER_KEY] in ALLOWED_GRADERS, ( 'invalid grader, should be one of: %s' % ', '.join(ALLOWED_GRADERS)) workflow_errors = [] submission_due_date = None if SUBMISSION_DUE_DATE_KEY in workflow_dict.keys(): try: submission_due_date = self._convert_date_string_to_datetime( workflow_dict[SUBMISSION_DUE_DATE_KEY]) except Exception as e: # pylint: disable=broad-except workflow_errors.append( 'dates should be formatted as YYYY-MM-DD hh:mm ' '(e.g. 1997-07-16 19:20) and be specified in the UTC ' 'timezone') if workflow_errors: raise Exception('%s.' % '; '.join(workflow_errors)) if workflow_dict[GRADER_KEY] == HUMAN_GRADER: missing_keys = [] for key in HUMAN_GRADED_ASSESSMENT_KEY_LIST: if key not in workflow_dict: missing_keys.append(key) elif (isinstance(workflow_dict[key], basestring) and not workflow_dict[key]): missing_keys.append(key) assert not missing_keys, ( 'missing key(s) for a human-reviewed assessment: %s.' % ', '.join(missing_keys)) if (workflow_dict[MATCHER_KEY] not in review.ALLOWED_MATCHERS): workflow_errors.append( 'invalid matcher, should be one of: %s' % ', '.join(review.ALLOWED_MATCHERS)) self._ensure_value_is_nonnegative_int( workflow_dict, REVIEW_MIN_COUNT_KEY, workflow_errors) self._ensure_value_is_nonnegative_int( workflow_dict, REVIEW_WINDOW_MINS_KEY, workflow_errors) try: review_due_date = self._convert_date_string_to_datetime( workflow_dict[REVIEW_DUE_DATE_KEY]) if submission_due_date > review_due_date: workflow_errors.append( 'submission due date should be earlier than ' 'review due date') except Exception as e: # pylint: disable=broad-except workflow_errors.append( 'dates should be formatted as YYYY-MM-DD hh:mm ' '(e.g. 1997-07-16 19:20) and be specified in the UTC ' 'timezone') if workflow_errors: raise Exception('%s.' % '; '.join(workflow_errors)) return True except Exception as e: # pylint: disable=broad-except errors.append('Error validating workflow specification: %s' % e) return False class Course(object): """Manages a course and all of its components.""" # Place for modules to register additional schema fields for setting # course options. Used in create_common_settings_schema(). # # This is a dict of lists. The dict key is a string matching a # sub-registry in the course schema. It is legitimate and expected usage # to name a sub-schema that's created in create_common_settings_schema(), # in which case the relevant settings are added to that subsection, and # will appear with other settings in that subsection in the admin editor # page. # # It is also reasonable to add a new subsection name. If you do that, you # should also edit the registration of the settings sub-tabs in # modules.dashboard.dashboard.register_module() to add either a new # sub-tab, or add your section to an existing sub-tab. # # Schema providers are expected to be functions which take one argument: # the current course. Providers should return exactly one SchemaField # object, which will be added to the appropriate subsection. OPTIONS_SCHEMA_PROVIDERS = collections.defaultdict(list) # Holds callback functions which are passed the course object after it it # loaded, to perform any further processing on loaded course data. An # instance of the newly created course is passed into each of the hook # methods in the order they were added to the list. POST_LOAD_HOOKS = [] # Holds callback functions which are passed the course env dict after it is # loaded, to perform any further processing on it. COURSE_ENV_POST_LOAD_HOOKS = [] # Holds callback functions which are passed the course env dict after it is # saved. COURSE_ENV_POST_SAVE_HOOKS = [] # Data which is patched onto the course environment - for testing use only. ENVIRON_TEST_OVERRIDES = {} SCHEMA_SECTION_COURSE = 'course' SCHEMA_SECTION_HOMEPAGE = 'homepage' SCHEMA_SECTION_REGISTRATION = 'registration' SCHEMA_SECTION_UNITS_AND_LESSONS = 'unit' SCHEMA_SECTION_ASSESSMENT = 'assessment' SCHEMA_SECTION_I18N = 'i18n' SCHEMA_LOCALE_AVAILABILITY = 'availability' SCHEMA_LOCALE_AVAILABILITY_AVAILABLE = 'available' SCHEMA_LOCALE_AVAILABILITY_UNAVAILABLE = 'unvailable' SCHEMA_LOCALE_LOCALE = 'locale' # here we keep current course available to thread INSTANCE = threading.local() @classmethod def get_schema_sections(cls): ret = set([ cls.SCHEMA_SECTION_COURSE, cls.SCHEMA_SECTION_HOMEPAGE, cls.SCHEMA_SECTION_REGISTRATION, cls.SCHEMA_SECTION_UNITS_AND_LESSONS, cls.SCHEMA_SECTION_ASSESSMENT, cls.SCHEMA_SECTION_I18N, ]) for name in cls.OPTIONS_SCHEMA_PROVIDERS: ret.add(name) return ret @classmethod def make_locale_environ_key(cls, locale): """Returns key used to store localized settings in memcache.""" return 'course:environ:locale:%s:%s' % ( os.environ.get('CURRENT_VERSION_ID'), locale) @classmethod def get_environ(cls, app_context): """Returns currently defined course settings as a dictionary.""" # pylint: disable=protected-access # get from local cache env = app_context._cached_environ if env: return copy.deepcopy(env) # get from global cache _locale = app_context.get_current_locale() _key = cls.make_locale_environ_key(_locale) env = models.MemcacheManager.get( _key, namespace=app_context.get_namespace_name()) if env: return env models.MemcacheManager.begin_readonly() try: # get from datastore env = cls._load_environ(app_context) # Monkey patch to defend against infinite recursion. Downstream # calls do not reload the env but just return the copy we have here. old_get_environ = cls.get_environ cls.get_environ = classmethod(lambda cl, ac: env) try: # run hooks for hook in cls.COURSE_ENV_POST_LOAD_HOOKS: hook(env) # put into local and global cache app_context._cached_environ = env models.MemcacheManager.set( _key, env, namespace=app_context.get_namespace_name()) finally: # Restore the original method from monkey-patch cls.get_environ = old_get_environ finally: models.MemcacheManager.end_readonly() return copy.deepcopy(env) @classmethod def _load_environ(cls, app_context): course_data_filename = app_context.get_config_filename() course_yaml = app_context.fs.open(course_data_filename) if not course_yaml: return deep_dict_merge(DEFAULT_COURSE_YAML_DICT, COURSE_TEMPLATE_DICT) course_yaml_dict = None try: course_yaml_dict = yaml.safe_load( course_yaml.read().decode('utf-8')) except Exception as e: # pylint: disable=broad-except logging.info( 'Error: course.yaml file at %s not accessible, ' 'loading defaults. %s', course_data_filename, e) if not course_yaml_dict: return deep_dict_merge(DEFAULT_COURSE_YAML_DICT, COURSE_TEMPLATE_DICT) return deep_dict_merge( cls.ENVIRON_TEST_OVERRIDES, course_yaml_dict, DEFAULT_EXISTING_COURSE_YAML_DICT, COURSE_TEMPLATE_DICT) @classmethod def create_base_settings_schema(cls): """Create the registry for course properties.""" reg = schema_fields.FieldRegistry('Course Settings', description='Course Settings', extra_schema_dict_values={ 'className': 'inputEx-Group new-form-layout'}) course_opts = reg.add_sub_registry( Course.SCHEMA_SECTION_COURSE, 'Course') course_opts.add_property(schema_fields.SchemaField( 'course:now_available', 'Availability', 'boolean', description='Make the course available to students.')) course_opts.add_property(schema_fields.SchemaField( 'course:browsable', 'Make Course Browsable', 'boolean', description='Allow non-registered users to view course content.')) course_opts.add_property(schema_fields.SchemaField( 'course:admin_user_emails', 'Course Admin Emails', 'string', i18n=False, description='A list of email addresses of course administrators. ' 'Syntax: Entries may be separated with any combination of ' 'tabs, spaces, commas, or newlines. Existing values using "[" and ' '"]" around email addresses continues to be supported. ' 'Regular expressions are not supported.')) course_opts.add_property(schema_fields.SchemaField( 'course:forum_email', 'Forum Email', 'string', optional=True, description='Email for the forum, e.g. ' '\'My-Course@googlegroups.com\'.', i18n=False)) course_opts.add_property(schema_fields.SchemaField( 'course:forum_embed_url', 'Forum URL for embedding', 'string', optional=True, description='URL for the forum &lt;iframe&gt;.')) course_opts.add_property(schema_fields.SchemaField( 'course:forum_url', 'Forum URL', 'string', optional=True, description='URL for the forum.')) course_opts.add_property(schema_fields.SchemaField( 'course:announcement_list_url', 'Announcement List URL', 'string', optional=True, description='URL for the mailing list ' 'where students can register to receive course announcements.')) course_opts.add_property(schema_fields.SchemaField( 'course:announcement_list_email', 'Announcement List Email', 'string', optional=True, description='Email for the mailing list ' 'where students can register to receive course announcements, e.g. ' '\'My-Course-Announce@googlegroups.com\'', i18n=False)) course_opts.add_property(schema_fields.SchemaField( 'course:start_date', 'Course Start Date', 'string', optional=True, i18n=False)) course_opts.add_property(schema_fields.SchemaField( 'course:google_analytics_id', 'ID for Google Analytics', 'string', optional=True, i18n=False, description='This ID tells Google Analytics who is ' 'calling, and allows it to string together routes that visitors ' 'take through pages. Obtain this ID by signing up at ' 'http://www.google.com/analytics')) course_opts.add_property(schema_fields.SchemaField( 'course:google_tag_manager_id', 'ID for Google Tag Manager', 'string', optional=True, i18n=False, description='This ID tells Google Tag ' 'Manager who is calling. This allows the Tag Manager to notify ' 'other site use tracking services what users are doing on the ' 'site. Obtain this ID by signing up at ' 'http://www.google.com/tagmanager')) homepage_opts = reg.add_sub_registry( Course.SCHEMA_SECTION_HOMEPAGE, 'Homepage') homepage_opts.add_property(schema_fields.SchemaField( 'base:show_gplus_button', 'Show G+ Button', 'boolean', optional=True, description='Whether to show a G+ button on the ' 'header of all pages.')) homepage_opts.add_property(schema_fields.SchemaField( 'base:nav_header', 'Organization Name', 'string', optional=True, description='Header phrase for the main navigation bar')) homepage_opts.add_property(schema_fields.SchemaField( 'course:title', 'Course Name', 'string')) homepage_opts.add_property(schema_fields.SchemaField( 'course:blurb', 'Course Abstract', 'html', optional=True, description='Text, shown on the course homepage, that explains ' 'what the course is about.', extra_schema_dict_values={ 'supportCustomTags': common.tags.CAN_USE_DYNAMIC_TAGS.value, 'excludedCustomTags': common.tags.EditorBlacklists.COURSE_SCOPE})) homepage_opts.add_property(schema_fields.SchemaField( 'course:instructor_details', 'Instructor Details', 'html', optional=True)) homepage_opts.add_property(schema_fields.SchemaField( 'course:main_video:url', 'Course Video', 'url', optional=True, description='URL for the preview video shown on the course ' 'homepage (e.g. https://www.youtube.com/embed/Kdg2drcUjYI ).')) homepage_opts.add_property(schema_fields.SchemaField( 'course:main_image:url', 'Course Image', 'string', optional=True, description='URL for the preview image shown on the course ' 'homepage. This will only be shown if no course video is ' 'specified.')) homepage_opts.add_property(schema_fields.SchemaField( 'course:main_image:alt_text', 'Alternate Text', 'string', optional=True, description='Alt text for the preview image on the course ' 'homepage.')) homepage_opts.add_property(schema_fields.SchemaField( 'base:privacy_terms_url', 'Privacy Terms URL', 'string', optional=True, description='Link to your privacy policy ' 'and terms of service')) registration_opts = reg.add_sub_registry( Course.SCHEMA_SECTION_REGISTRATION, 'Registration') registration_opts.add_property(schema_fields.SchemaField( 'reg_form:can_register', 'Enable Registrations', 'boolean', description='Checking this box allows new students to register for ' 'the course.')) registration_opts.add_property(schema_fields.SchemaField( 'reg_form:header_text', 'Welcome Text', 'string', optional=True, description='Text shown to students at the top of the registration ' 'page encouraging them to sign up for the course.')) registration_opts.add_property(schema_fields.SchemaField( 'reg_form:additional_registration_fields', 'Additional Fields', 'html', description='Additional registration text or questions.')) registration_opts.add_property(schema_fields.SchemaField( 'course:whitelist', 'Whitelisted Students', 'text', optional=True, i18n=False, description='List of email addresses of students who may register.' 'Syntax: Entries may be separated with any combination of ' 'tabs, spaces, commas, or newlines. Existing values using "[" and ' '"]" around email addresses continues to be supported. ' 'Regular expressions are not supported.')) registration_opts.add_property(schema_fields.SchemaField( 'course:send_welcome_notifications', 'Send welcome notifications', 'boolean', description='If enabled, ' 'welcome notifications will be sent when new users register for ' 'the course. Must also set "Welcome notifications sender" for ' 'messages to be sent successfully, and you must have both the ' 'notifications and unsubscribe modules active (which is the ' 'default)')) registration_opts.add_property(schema_fields.SchemaField( 'course:welcome_notifications_sender', 'Welcome notifications sender', 'string', optional=True, i18n=False, description='The "From:" email address used on outgoing ' 'notifications. If "Send welcome notifications" is enabled, you ' 'must set this to a valid value for App Engine email or outgoing ' 'messages will fail. Note that you cannot use the user in session. ' 'See https://developers.google.com/appengine/docs/python/mail/' 'emailmessagefields for details')) registration_opts.add_property(schema_fields.SchemaField( 'course:welcome_notifications_subject', 'Welcome notifications subject', 'string', optional=True, description='The subject line in welcome notifications emails for ' 'this course. Use the string {{student_name}} to include the name ' 'of the student in the subject line and {{course_title}} to ' 'include the course title.')) registration_opts.add_property(schema_fields.SchemaField( 'course:welcome_notifications_body', 'Welcome notifications body', 'text', optional=True, description='The body of welcome emails to this course. Use the ' 'string {{student_name}} to include the name of the student in the ' 'message and use {{course_title}} to include the course title. To ' 'avoid spamming, you should always include the string ' '{{unsubscribe_url}} in your message to include a link which the ' 'recipient can use to unsubscribe from future mailings.')) # Course-level Google API configuration settings. if COURSES_CAN_USE_GOOGLE_APIS.value: course_opts.add_property(schema_fields.SchemaField( CONFIG_KEY_GOOGLE_API_KEY, 'Google API Key', 'string', optional=True, i18n=False, description='Google API Key')) course_opts.add_property(schema_fields.SchemaField( CONFIG_KEY_GOOGLE_CLIENT_ID, 'Google Client Id', 'string', optional=True, i18n=False, description='Google Client Id')) # Unit level settings. unit_opts = reg.add_sub_registry( Course.SCHEMA_SECTION_UNITS_AND_LESSONS, 'Units and Lessons') unit_opts.add_property(schema_fields.SchemaField( 'unit:hide_lesson_navigation_buttons', 'Hide Lesson Navigation Buttons', 'boolean', description='Whether to hide the \'Previous Page\' and ' ' \'Next Page\' buttons below lesson and activity pages')) unit_opts.add_property(schema_fields.SchemaField( 'unit:hide_assessment_navigation_buttons', 'Hide Assessment Navigation Buttons', 'boolean', description='Whether to hide the \'Previous Page\' and ' ' \'Next Page\' buttons below pre/post assessments within units')) unit_opts.add_property(schema_fields.SchemaField( 'unit:show_unit_links_in_leftnav', 'Show Units in Side Bar', 'boolean', description='Whether to show the unit links in the side ' 'navigation bar.')) unit_opts.add_property(schema_fields.SchemaField( 'course:display_unit_title_without_index', 'Display Unit Title Without Index', 'boolean', description='Omit the unit number when displaying unit titles.')) def must_contain_one_string_substitution(value, errors): if value and len(re.findall(r'%s', value)) != 1: errors.append( 'Value must contain exactly one string substitution ' 'marker "%s".') assessment_opts = reg.add_sub_registry( Course.SCHEMA_SECTION_ASSESSMENT, 'Assessments') assessment_opts.add_property(schema_fields.SchemaField( 'assessment_confirmations:result_text:pass', 'Pass', 'string', optional=True, description='Text shown to the student on a passing result.', validator=must_contain_one_string_substitution)) assessment_opts.add_property(schema_fields.SchemaField( 'assessment_confirmations:result_text:fail', 'Fail', 'string', optional=True, description='Text shown to the student on a failing result.', validator=must_contain_one_string_substitution)) i18n_opts = reg.add_sub_registry( Course.SCHEMA_SECTION_I18N, 'I18N') i18n_opts.add_property(schema_fields.SchemaField( 'course:can_student_change_locale', 'Let Student Change Locale', 'boolean', optional=True, description='Allow student to change locale at any time ' 'during the course. If True, a language picker is shown to the ' 'student and locale changes are allowed at any time. If False, a ' 'language picker is not shown to the student and the desired ' 'locale must be assigned during registration process via Locale ' 'Labels. Current locale for any request is determined by looking ' 'into student Locale Labels first, and then (if this value here ' 'is set to True) into student preferences set by the language ' 'picker.')) locale_data_for_select = [ (loc, locales.get_locale_display_name(loc)) for loc in locales.get_system_supported_locales()] i18n_opts.add_property(schema_fields.SchemaField( 'course:locale', 'Base Locale', 'string', i18n=False, select_data=locale_data_for_select)) locale_type = schema_fields.FieldRegistry( 'Locale', extra_schema_dict_values={'className': 'settings-list-item'}) locale_type.add_property(schema_fields.SchemaField( 'locale', 'Locale', 'string', optional=True, i18n=False, select_data=locale_data_for_select)) select_data = [ ( cls.SCHEMA_LOCALE_AVAILABILITY_UNAVAILABLE, 'Unavailable'), ( cls.SCHEMA_LOCALE_AVAILABILITY_AVAILABLE, 'Available')] locale_type.add_property(schema_fields.SchemaField( cls.SCHEMA_LOCALE_AVAILABILITY, 'Availability', 'boolean', optional=True, select_data=select_data)) i18n_opts.add_property(schema_fields.FieldArray( 'extra_locales', 'Extra locales', item_type=locale_type, description=( 'Locales which are listed here and marked as available can be ' 'selected by students as their preferred locale.'), extra_schema_dict_values={ 'className': 'settings-list', 'listAddLabel': 'Add a locale', 'listRemoveLabel': 'Delete locale'})) i18n_opts.add_property(schema_fields.SchemaField( 'course:prevent_translation_edits', 'Prevent Translation Edits', 'boolean', optional=True, description='Prevent editing of translations. If False, ' 'translations can be edited. If True, editing of translations is ' 'not allowed, while advance caching and performance boost logic' 'is applied.')) return reg @classmethod def create_common_settings_schema(cls, course): reg = cls.create_base_settings_schema() for schema_section in cls.OPTIONS_SCHEMA_PROVIDERS: sub_registry = reg.get_sub_registry(schema_section) if not sub_registry: sub_registry = reg.add_sub_registry( schema_section, schema_section.replace('_', ' ').title()) for schema_provider in cls.OPTIONS_SCHEMA_PROVIDERS[schema_section]: sub_registry.add_property(schema_provider(course)) return reg def get_course_setting(self, name): course_settings = self.get_environ(self._app_context).get('course') if not course_settings: return None return course_settings.get(name) @classmethod def validate_course_yaml(cls, raw_string, course): errors = [] parsed_content = yaml.safe_load(raw_string) schema = cls.create_settings_schema(course) schema.validate(parsed_content, errors) if errors: raise ValueError('\n'.join(errors)) @property def version(self): return self._model.VERSION @classmethod def create_new_default_course(cls, app_context): return CourseModel13(app_context) @classmethod def custom_new_default_course_for_test(cls, app_context): # There is an expectation in our tests of automatic import # of data/*.csv files. This method can be used in tests to achieve # exactly that. model = CourseModel12.load(app_context) if model: return model return CourseModel13(app_context) @classmethod def _load(cls, app_context): """Loads course data from persistence storage into this instance.""" if not app_context.is_editable_fs(): model = CourseModel12.load(app_context) if model: return model else: model = CourseModel13.load(app_context) if model: return model return cls.create_new_default_course(app_context) @classmethod def get(cls, app_context): """Gets this thread current course instance or creates new instance. Making a new instance of existing Course is expensive. It involves db operations, CPU intensive transaltions and other things. Thus it's better to avoid making new instances all the time and rather use cached instance. In most cases when you need "any valid instance of current Course" use Course.get(), which provides request scope caching. It will return a cached instance or will create a new one for you if none yet exists. Only create a fresh new instance of course via constructor Course() when you are executing mutations and want to have the most up to date instance. Args: app_context: an app_context of the Course, instance of which you need Returns: an instance of a course: cached or newly created if nothing cached """ if cls.has_current(): _app_context, _course = cls.INSTANCE.current if _course and (app_context == _app_context or app_context is None): return _course _course = Course(None, app_context) cls.set_current(_course) return _course @classmethod def set_current(cls, course): """Set current course for this thread.""" if course: cls.INSTANCE.current = (course.app_context, course) else: cls.INSTANCE.current = (None, None) @classmethod def has_current(cls): """Checks if this thread has current course set.""" return hasattr(cls.INSTANCE, 'current') @classmethod def clear_current(cls): """Clears this thread current course.""" if cls.has_current(): del cls.INSTANCE.current @appengine_config.timeandlog('Course.init') def __init__(self, handler, app_context=None): """Makes an instance of brand new or loads existing course is exists. Making a new instance of existing Course is expensive. It involves db operations, CPU intensive transaltions and other things. Thus it's better to avoid making new instances all the time and rather use cached instance. In most cases when you need "any valid instance of current Course" use Course.get(), which provides request scope caching. It will return a cached instance or will create a new one for you if none yet exists. Only create a fresh new instance of course via constructor Course() when you are executing mutations and want to have the most up to date instance. Args: handler: a request handler for the course app_context: an app_context of the Course, instance of which you need Returns: an instance of a course: cached or newly created if nothing cached """ self._app_context = app_context if app_context else handler.app_context self._namespace = self._app_context.get_namespace_name() self._model = self._load(self._app_context) self._tracker = None self._reviews_processor = None for hook in self.POST_LOAD_HOOKS: try: hook(self) except Exception: # pylint: disable=broad-except logging.exception('Error in post-load hook') @property def app_context(self): return self._app_context @property def default_locale(self): return self._app_context.default_locale @property def all_locales(self): return self._app_context.get_all_locales() @property def title(self): return self._app_context.get_title() def to_json(self): return self._model.to_json() def create_settings_schema(self): return Course.create_common_settings_schema(self) def invalidate_cached_course_settings(self): self._model.invalidate_cached_course_settings() def save_settings(self, course_settings): retval = self._model.save_settings(course_settings) common_utils.run_hooks(self.COURSE_ENV_POST_SAVE_HOOKS, course_settings) return retval def get_progress_tracker(self): if not self._tracker: self._tracker = progress.UnitLessonCompletionTracker(self) return self._tracker def get_reviews_processor(self): if not self._reviews_processor: self._reviews_processor = review.ReviewsProcessor(self) return self._reviews_processor def get_units(self): units = self._model.get_units() for unit in units: if unit.is_custom_unit(): cu = custom_units.UnitTypeRegistry.get(unit.custom_unit_type) if cu: unit.set_custom_unit_url(self.app_context.canonicalize_url( cu.visible_url(unit))) return units def get_units_of_type(self, unit_type): return [unit for unit in self.get_units() if unit_type == unit.type] def get_track_matching_student(self, student): return models.LabelDAO.apply_course_track_labels_to_student_labels( self, student, self.get_units()) def get_unit_track_labels(self, unit): all_track_ids = models.LabelDAO.get_set_of_ids_of_type( models.LabelDTO.LABEL_TYPE_COURSE_TRACK) return set([int(label_id) for label_id in common_utils.text_to_list(unit.labels) if int(label_id) in all_track_ids]) def get_lessons(self, unit_id): return self._model.get_lessons(unit_id) def get_lessons_for_all_units(self): lessons = [] for unit in self.get_units(): for lesson in self.get_lessons(unit.unit_id): lessons.append(lesson) return lessons def get_unit_for_lesson(self, the_lesson): for unit in self.get_units(): for lesson in self.get_lessons(unit.unit_id): if lesson.lesson_id == the_lesson.lesson_id: return unit return None def save(self): return self._model.save() def find_unit_by_id(self, unit_id): return self._model.find_unit_by_id(unit_id) def find_lesson_by_id(self, unit, lesson_id): return self._model.find_lesson_by_id(unit, lesson_id) def is_last_assessment(self, unit): """Checks whether the given unit is the last of all the assessments.""" for current_unit in reversed(self.get_units()): if current_unit.type == verify.UNIT_TYPE_ASSESSMENT: return current_unit.unit_id == unit.unit_id elif current_unit.type == verify.UNIT_TYPE_UNIT: if current_unit.post_assessment: return current_unit.post_assessment == unit.unit_id if current_unit.pre_assessment: return current_unit.pre_assessment == unit.unit_id return False def add_unit(self): """Adds new unit to a course.""" return self._model.add_unit('U', 'New Unit') def add_link(self): """Adds new link (other) to a course.""" return self._model.add_unit('O', 'New Link') def add_assessment(self): """Adds new assessment to a course.""" return self._model.add_unit('A', 'New Assessment') def add_lesson(self, unit): return self._model.add_lesson(unit, 'New Lesson') def add_custom_unit(self, unit_type): """Adds new custom unit to a course.""" cu = custom_units.UnitTypeRegistry.get(unit_type) assert cu unit = self._model.add_unit( verify.UNIT_TYPE_CUSTOM, 'New %s' % cu.name, custom_unit_type=unit_type) cu.add_unit(self, unit) return unit def update_unit(self, unit): return self._model.update_unit(unit) def update_lesson(self, lesson): return self._model.update_lesson(lesson) def move_lesson_to(self, lesson, unit): return self._model.move_lesson_to(lesson, unit) def delete_all(self): return self._model.delete_all() def delete_unit(self, unit): return self._model.delete_unit(unit) def delete_lesson(self, lesson): return self._model.delete_lesson(lesson) def get_score(self, student, unit_id): """Gets a student's score for a particular assessment.""" assert (self.is_valid_assessment_id(unit_id) or self.is_valid_custom_unit(unit_id)) scores = transforms.loads(student.scores) if student.scores else {} return scores.get(unit_id) def get_overall_score(self, student): """Gets the overall course score for a student.""" score_list = self.get_all_scores(student) overall_score = 0 total_weight = 0 for unit in score_list: if not unit['human_graded']: total_weight += unit['weight'] overall_score += unit['weight'] * unit['score'] if total_weight == 0: return None return int(float(overall_score) / total_weight) def is_course_complete(self, student): """Returns true if the student has completed the course.""" score_list = self.get_all_scores(student) for unit in score_list: if not unit['completed']: return False return True def update_final_grades(self, student): """Updates the final grades of the student.""" if (models.CAN_SHARE_STUDENT_PROFILE.value and self.is_course_complete(student)): overall_score = self.get_overall_score(student) models.StudentProfileDAO.update( student.user_id, student.email, final_grade=overall_score) def get_overall_result(self, student): """Gets the overall result based on a student's score profile.""" score = self.get_overall_score(student) if score is None: return None # This can be replaced with a custom definition for an overall result # string. return 'pass' if score >= 70 else 'fail' def get_all_scores(self, student): """Gets all score data for a student. Args: student: the student whose scores should be retrieved. Returns: an array of dicts, each representing an assessment. Each dict has the keys 'id', 'title', 'weight' and 'score' (if available), representing the unit id, the assessment title, the weight contributed by the assessment to the final score, and the assessment score. """ unit_list = self.get_units() scores = transforms.loads(student.scores) if student.scores else {} progress_tracker = self.get_progress_tracker() student_progress = progress_tracker.get_or_create_progress(student) assessment_score_list = [] for unit in unit_list: if unit.is_custom_unit(): cu = custom_units.UnitTypeRegistry.get(unit.custom_unit_type) if not cu or not cu.is_graded: continue elif not unit.is_assessment(): continue # Compute the weight for this assessment. weight = 0 if hasattr(unit, 'weight'): weight = unit.weight elif unit.unit_id in DEFAULT_LEGACY_ASSESSMENT_WEIGHTS: weight = DEFAULT_LEGACY_ASSESSMENT_WEIGHTS[unit.unit_id] completed = False if unit.is_assessment(): completed = progress_tracker.is_assessment_completed( student_progress, unit.unit_id) else: completed = progress_tracker.is_custom_unit_completed( student_progress, unit.unit_id) # If a human-reviewed assessment is completed, ensure that the # required reviews have also been completed. if completed and self.needs_human_grader(unit): reviews = self.get_reviews_processor().get_review_steps_by( unit.unit_id, student.get_key()) review_min_count = unit.workflow.get_review_min_count() if not review.ReviewUtils.has_completed_enough_reviews( reviews, review_min_count): completed = False assessment_score_list.append({ 'id': str(unit.unit_id), 'title': unit.title, 'weight': weight, 'completed': completed, 'attempted': str(unit.unit_id) in scores, 'human_graded': self.needs_human_grader(unit), 'score': (scores[str(unit.unit_id)] if str(unit.unit_id) in scores else 0), }) return assessment_score_list def get_assessment_list(self): """Returns a list of dup units that are assessments.""" # TODO(psimakov): Streamline this so that it does not require a full # iteration on each request, probably by modifying the index() method. assessments = [x for x in self.get_units() if x.is_assessment()] return copy.deepcopy(assessments) def get_peer_reviewed_units(self): """Returns a list of units that are peer-reviewed assessments. Returns: A list of units that are peer-reviewed assessments. Each unit in the list has a unit_id of type string. """ assessment_list = self.get_assessment_list() units = copy.deepcopy([unit for unit in assessment_list if ( unit.workflow.get_grader() == HUMAN_GRADER and unit.workflow.get_matcher() == review.PEER_MATCHER)]) for unit in units: unit.unit_id = str(unit.unit_id) return units def get_assessment_filename(self, unit_id): return self._model.get_assessment_filename(unit_id) def get_review_filename(self, unit_id): return self._model.get_review_filename(unit_id) def get_activity_filename(self, unit_id, lesson_id): return self._model.get_activity_filename(unit_id, lesson_id) def get_parent_unit(self, unit_id): return self._model.get_parent_unit(unit_id) def get_components(self, unit_id, lesson_id): """Returns a list of dicts representing the components in a lesson. Args: unit_id: the id of the unit containing the lesson lesson_id: the id of the lesson Returns: A list of dicts. Each dict represents one component and has two keys: - instanceid: the instance id of the component - cpt_name: the name of the component tag (e.g. gcb-googlegroup) """ unit = self.find_unit_by_id(unit_id) lesson = self.find_lesson_by_id(unit, lesson_id) if not lesson.objectives: return [] return common.tags.get_components_from_html(lesson.objectives) def get_content_as_dict_safe(self, unit, errors, kind='assessment'): """Validate the assessment or review script and return as a dict.""" try: if kind == 'assessment': r = self._model.get_assessment_content(unit) else: r = self._model.get_review_content(unit) return r['assessment'] except verify.SchemaException as e: logging.error('Unable to validate %s %s: %s', kind, unit.unit_id, e) errors.append( 'Unable to validate %s: %s' % (kind, unit.unit_id)) except Exception as e: # pylint: disable=broad-except logging.error('Unable to parse %s: %s.', kind, str(e)) errors.append( 'Unable to parse %s: %s' % (kind, unit.unit_id)) return None def get_assessment_components(self, unit_id): """Returns a list of dicts representing components in an assessment. Args: unit_id: the id of the assessment unit Returns: A list of dicts. Each dict represents one component and has two keys: - instanceid: the instance id of the component - cpt_name: the name of the component tag (e.g. gcb-googlegroup) """ unit = self.find_unit_by_id(unit_id) if not getattr(unit, 'html_content', None): return [] return common.tags.get_components_from_html(unit.html_content) def get_components_with_name(self, unit_id, lesson_id, component_name): """Returns a list of dicts representing this component in a lesson.""" components = self.get_components(unit_id, lesson_id) return [ component for component in components if component.get('cpt_name') == component_name ] def get_question_components(self, unit_id, lesson_id): """Returns a list of dicts representing the questions in a lesson.""" return self.get_components_with_name(unit_id, lesson_id, 'question') def get_question_group_components(self, unit_id, lesson_id): """Returns a list of dicts representing the q_groups in a lesson.""" return self.get_components_with_name( unit_id, lesson_id, 'question-group') def get_component_locations(self): """Returns 2 dicts containing the locations of questions and groups. Returns: A tuple (question_locations, group_locations) which are dictionaries that map component_id to location information about that component. Location information is a dict that can have the following keys: - assessments: a dict that maps assessments to the number of times it contains the component. - lessons: a dict that maps (unit, lesson) to the number of times it contains the component. Example: [ ( <quid_1>: { 'assessments': { <assessment_id_1>: <assessment_count_1>, <assessment_id_2>: <assessment_count_1> }, 'lessons':{ (<unit_id_1>, <lesson_id_1>): <lesson_count_1>, (<unit_id_2>, <lesson_id_2>): <_lessoncount_2>, } }, <quid_2>: ... ), ( <qgid_1>: { ... }, <qgid_2>: { ... } ) ] """ qulocations = {} qglocations = {} def _add_to_map(component, unit, lesson=None): try: if component.get('cpt_name') == 'question': compononent_locations = qulocations.setdefault( long(component.get('quid')), {'lessons': {}, 'assessments': {}} ) elif component.get('cpt_name') == 'question-group': compononent_locations = qglocations.setdefault( long(component.get('qgid')), {'lessons': {}, 'assessments': {}} ) else: return except ValueError: title = lesson.title if lesson else unit.title logging.exception('Bad component ID found in "%s"', title) return if lesson is not None: lessons = compononent_locations.setdefault( 'lessons', {}) lessons[(lesson, unit)] = lessons.get( (lesson, unit), 0) + 1 else: assessments = compononent_locations.setdefault( 'assessments', {}) assessments[unit] = assessments.get(unit, 0) + 1 for unit in self.get_units(): if unit.type == verify.UNIT_TYPE_ASSESSMENT: for component in self.get_assessment_components(unit.unit_id): _add_to_map(component, unit) elif unit.type == verify.UNIT_TYPE_UNIT: for lesson in self.get_lessons(unit.unit_id): for component in self.get_components( unit.unit_id, lesson.lesson_id): _add_to_map(component, unit, lesson) return (qulocations, qglocations) def needs_human_grader(self, unit): return unit.workflow.get_grader() == HUMAN_GRADER def reorder_units(self, order_data): return self._model.reorder_units(order_data) def get_file_content(self, filename): return self._model.get_file_content(filename) def set_file_content(self, filename, content): self._model.set_file_content(filename, content) def delete_file(self, filename): return self._model.delete_file(filename) def get_assessment_content(self, unit): """Returns the schema for an assessment as a Python dict.""" return self._model.get_assessment_content(unit) def get_assessment_model_version(self, unit): return self._model.get_assessment_model_version(unit) def get_review_content(self, unit): """Returns the schema for a review form as a Python dict.""" return self._model.get_review_content(unit) def set_assessment_content(self, unit, assessment_content, errors=None): return self._model.set_assessment_content( unit, assessment_content, errors=errors) def set_review_form(self, unit, review_form, errors=None): return self._model.set_review_form(unit, review_form, errors=errors) def set_activity_content(self, lesson, activity_content, errors=None): return self._model.set_activity_content( lesson, activity_content, errors=errors) def is_valid_assessment_id(self, assessment_id): """Tests whether the given assessment id is valid.""" return any(x for x in self.get_units() if x.is_assessment() and str( assessment_id) == str(x.unit_id)) def is_valid_custom_unit(self, unit_id): """Tests whether the given assessment id is valid.""" return any(x for x in self.get_units() if x.is_custom_unit() and str( unit_id) == str(x.unit_id)) def is_valid_unit_lesson_id(self, unit_id, lesson_id): """Tests whether the given unit id and lesson id are valid.""" for unit in self.get_units(): if str(unit.unit_id) == str(unit_id): for lesson in self.get_lessons(unit_id): if str(lesson.lesson_id) == str(lesson_id): return True return False def import_from(self, app_context, errors=None): """Import course structure and assets from another courses.""" src_course = Course(None, app_context=app_context) if errors is None: errors = [] # Import 1.2 or 1.3 -> 1.3 if (src_course.version in [ CourseModel12.VERSION, CourseModel13.VERSION]): result = self._model.import_from(src_course, errors) self.app_context.clear_per_request_cache() return result errors.append( 'Import of ' 'course %s (version %s) into ' 'course %s (version %s) ' 'is not supported.' % ( app_context.raw, src_course.version, self.app_context.raw, self.version)) return None, None def get_course_announcement_list_email(self): """Get Announcement email address for the course.""" course_env = self.get_environ(self._app_context) if not course_env: return None if 'course' not in course_env: return None course_dict = course_env['course'] if 'announcement_list_email' not in course_dict: return None announcement_list_email = course_dict['announcement_list_email'] if announcement_list_email: return announcement_list_email return None def init_new_course_settings(self, title, admin_email): """Initializes new course.yaml file if it does not yet exists.""" fs = self.app_context.fs.impl course_yaml = fs.physical_to_logical('/course.yaml') if fs.isfile(course_yaml): return False title = title.replace('\'', '\'\'') course_yaml_text = u"""# my new course.yaml course: title: '%s' admin_user_emails: '[%s]' now_available: False """ % (title, admin_email) fs.put(course_yaml, vfs.string_to_stream(course_yaml_text)) self.app_context.clear_per_request_cache() return True
Python
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Manages dynamic properties of an application and/or its modules. An application must explicitly declare properties and provide a type, doc string and default value for each. The default property values are overridden by the new values found in the environment variable with the same name. Those are further overridden by the values found in the datastore. We also try to do all of this with performance in mind. """ __author__ = 'Pavel Simakov (psimakov@google.com)' import logging import os import threading import time import entities import transforms import appengine_config from google.appengine.api import namespace_manager from google.appengine.ext import db # The default update interval supported. DEFAULT_UPDATE_INTERVAL_SEC = 60 # The longest update interval supported. MAX_UPDATE_INTERVAL_SEC = 60 * 5 # Allowed property types. TYPE_INT = int TYPE_STR = str TYPE_BOOL = bool ALLOWED_TYPES = frozenset([TYPE_INT, TYPE_STR, TYPE_BOOL]) class ConfigProperty(object): """A property with name, type, doc_string and a default value.""" def __init__( self, name, value_type, doc_string, default_value=None, multiline=False, validator=None, after_change=None): """Create a new global config property. These properties are persisted as ConfigPropertyEntity in the default namespace. As such, these properties apply to the installation as a whole, rather than individual courses. Args: name: A name, by convention starting with "gcb_" for Google Course Builder, and something else for third-party extensions. value_type: A Python type, one of {bool, str, int} doc_string: A brief description displayed on the admin page listing all the config variables default_value: The value used when no override has been set by the site admin. multiline: Whether the value, if value_type is str, can be expected to extend to multiple lines of text. validator: A function taking two parameters: value: The value to validate errors: A list of strings indicating problems. If the value is acceptable, 'errors' must not be appended to, and conversely. after_change: This is a function which is called only when the value is changed by the site administrator via the UI. (It is not called when the underlying ConfigPropertyEntity is directly modified). This function takes two one parameters: the ConfigProperty instance, and the previous value. """ if value_type not in ALLOWED_TYPES: raise Exception('Bad value type: %s' % value_type) self._validator = validator self._multiline = multiline self._name = name self._type = value_type self._doc_string = doc_string self._default_value = value_type(default_value) self._after_change = after_change errors = [] if self._validator and self._default_value: self._validator(self._default_value, errors) if errors: raise Exception('Default value is invalid: %s.' % errors) Registry.registered[name] = self if name in Registry.db_items: item = Registry.db_items[name] del Registry.db_items[name] # pylint: disable=protected-access Registry._config_property_entity_changed(item) @property def validator(self): return self._validator @property def after_change(self): """Properties may register callbacks to notice changes to value.""" return self._after_change @property def multiline(self): return self._multiline @property def name(self): return self._name @property def value_type(self): return self._type @property def doc_string(self): return self._doc_string @property def default_value(self): return self._default_value def get_environ_value(self): """Tries to get value from the environment variables.""" # Look for a name in lower or upper case. name = None if self._name.lower() in os.environ: name = self._name.lower() else: if self._name.upper() in os.environ: name = self._name.upper() if name: try: return True, transforms.string_to_value( os.environ[name], self.value_type) except Exception: # pylint: disable=broad-except logging.error( 'Property %s failed to cast to type %s; removing.', self._name, self._type) del os.environ[name] return False, None def get_value(self, db_overrides=None): """Gets value from overrides (datastore, environment) or default.""" # Try testing overrides. overrides = Registry.test_overrides if overrides and self.name in overrides: return overrides[self.name] # Try datastore overrides. if db_overrides and self.name in db_overrides: return db_overrides[self.name] # Try environment variable overrides. has_value, environ_value = self.get_environ_value() if has_value: return environ_value # Use default value as last resort. return self._default_value @property def value(self): return self.get_value(db_overrides=Registry.get_overrides()) class ValidateLength(object): def __init__(self, length): self._length = length def validator(self, value, errors): if len(value) != self._length: errors.append( 'The length of this field must be exactly %d, ' % self._length + 'but the value "%s" is of length %d.' % (value, len(value))) class Registry(object): """Holds all registered properties and their various overrides.""" registered = {} test_overrides = {} db_items = {} db_overrides = {} names_with_draft = {} last_update_time = 0 update_index = 0 threadlocal = threading.local() REENTRY_ATTR_NAME = 'busy' @classmethod def get_overrides(cls, force_update=False): """Returns current property overrides, maybe cached.""" now = long(time.time()) age = now - cls.last_update_time max_age = UPDATE_INTERVAL_SEC.get_value(db_overrides=cls.db_overrides) # do not update if call is reentrant or outer db transaction exists busy = hasattr(cls.threadlocal, cls.REENTRY_ATTR_NAME) or ( db.is_in_transaction()) if (not busy) and (force_update or age < 0 or age >= max_age): # Value of '0' disables all datastore overrides. if UPDATE_INTERVAL_SEC.get_value() == 0: cls.db_overrides = {} return cls.db_overrides # Load overrides from a datastore. setattr(cls.threadlocal, cls.REENTRY_ATTR_NAME, True) try: old_namespace = namespace_manager.get_namespace() try: namespace_manager.set_namespace( appengine_config.DEFAULT_NAMESPACE_NAME) cls._load_from_db() finally: namespace_manager.set_namespace(old_namespace) except Exception as e: # pylint: disable=broad-except logging.error( 'Failed to load properties from a database: %s.', str(e)) finally: delattr(cls.threadlocal, cls.REENTRY_ATTR_NAME) # Avoid overload and update timestamp even if we failed. cls.last_update_time = now cls.update_index += 1 return cls.db_overrides @classmethod def _load_from_db(cls): """Loads dynamic properties from db.""" items = {} overrides = {} drafts = set() for item in ConfigPropertyEntity.all().fetch(1000): items[item.key().name()] = item cls._set_value(item, overrides, drafts) cls.db_items = items cls.db_overrides = overrides cls.names_with_draft = drafts @classmethod def _config_property_entity_changed(cls, item): cls._set_value(item, cls.db_overrides, cls.names_with_draft) @classmethod def _set_value(cls, item, overrides, drafts): name = item.key().name() target = cls.registered.get(name, None) if not target: logging.warning( 'Property is not registered (skipped): %s', name) return if item.is_draft: if name in overrides: del overrides[name] drafts.add(name) else: if name in drafts: drafts.remove(name) # Enforce value type. try: value = transforms.string_to_value( item.value, target.value_type) except Exception: # pylint: disable=broad-except logging.error( 'Property %s failed to cast to a type %s; removing.', target.name, target.value_type) return # Enforce value validator. if target.validator: errors = [] try: target.validator(value, errors) except Exception as e: # pylint: disable=broad-except errors.append( 'Error validating property %s.\n%s', (target.name, e)) if errors: logging.error( 'Property %s has invalid value:\n%s', target.name, '\n'.join(errors)) return overrides[name] = value class ConfigPropertyEntity(entities.BaseEntity): """A class that represents a named configuration property.""" value = db.TextProperty(indexed=False) is_draft = db.BooleanProperty(indexed=False) def put(self): # Persist to DB. super(ConfigPropertyEntity, self).put() # And tell local registry. Do this by direct call and synchronously # so that this setting will be internally consistent within the # remainder of this server's path of execution. (Note that the # setting is _not_ going to be immediately available at all other # instances; they will pick it up in due course after # UPDATE_INTERVAL_SEC has elapsed. # pylint: disable=protected-access Registry._config_property_entity_changed(self) def run_all_unit_tests(): """Runs all unit tests for this modules.""" str_prop = ConfigProperty('gcb-str-prop', str, ('doc for str_prop'), 'foo') int_prop = ConfigProperty('gcb-int-prop', int, ('doc for int_prop'), 123) assert str_prop.default_value == 'foo' assert str_prop.value == 'foo' assert int_prop.default_value == 123 assert int_prop.value == 123 # Check os.environ override works. os.environ[str_prop.name] = 'bar' assert str_prop.value == 'bar' del os.environ[str_prop.name] assert str_prop.value == 'foo' # Check os.environ override with type casting. os.environ[int_prop.name] = '12345' assert int_prop.value == 12345 # Check setting of value is disallowed. try: str_prop.value = 'foo' raise Exception() except AttributeError: pass # Check value of bad type is disregarded. os.environ[int_prop.name] = 'foo bar' assert int_prop.value == int_prop.default_value def validate_update_interval(value, errors): value = int(value) if value <= 0 or value >= MAX_UPDATE_INTERVAL_SEC: errors.append( 'Expected a value between 0 and %s, exclusive.' % ( MAX_UPDATE_INTERVAL_SEC)) UPDATE_INTERVAL_SEC = ConfigProperty( 'gcb_config_update_interval_sec', int, ( 'An update interval (in seconds) for reloading runtime properties ' 'from a datastore. Using this editor, you can set this value to an ' 'integer between 1 and %s, inclusive. To completely disable reloading ' 'properties from a datastore, you must set the value to 0. However, ' 'you can only set the value to 0 by directly modifying the app.yaml ' 'file.' % MAX_UPDATE_INTERVAL_SEC), default_value=DEFAULT_UPDATE_INTERVAL_SEC, validator=validate_update_interval) if __name__ == '__main__': run_all_unit_tests()
Python
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implement resource abstraction for Course-level items.""" __author__ = 'Mike Gainer (mgainer@google.com)' import cgi import yaml import models import courses import messages from common import resource from common import safe_dom from common import schema_fields from common import tags from common import utils as common_utils from tools import verify DRAFT_TEXT = 'Private' PUBLISHED_TEXT = 'Public' # Allowed graders. Keys of this dict represent internal keys for the grader # type, and the value represents the corresponding string that will appear in # the dashboard UI. AUTO_GRADER_NAME = 'Automatic Grading' HUMAN_GRADER_NAME = 'Peer Review' ALLOWED_GRADERS_NAMES = { courses.AUTO_GRADER: AUTO_GRADER_NAME, courses.HUMAN_GRADER: HUMAN_GRADER_NAME, } # When expanding GCB tags within questions, these tags may not be used # (so as to forestall infinite recursion) TAGS_EXCLUDED_FROM_QUESTIONS = set( ['question', 'question-group', 'gcb-questionnaire', 'text-file-upload-tag']) class SaQuestionConstants(object): DEFAULT_WIDTH_COLUMNS = 100 DEFAULT_HEIGHT_ROWS = 1 class ResourceQuestionBase(resource.AbstractResourceHandler): TYPE_MC_QUESTION = 'question_mc' TYPE_SA_QUESTION = 'question_sa' @classmethod def get_question_key_type(cls, qu): """Utility to convert between question type codes.""" if qu.type == models.QuestionDTO.MULTIPLE_CHOICE: return cls.TYPE_MC_QUESTION elif qu.type == models.QuestionDTO.SHORT_ANSWER: return cls.TYPE_SA_QUESTION else: raise ValueError('Unknown question type: %s' % qu.type) @classmethod def get_resource(cls, course, key): return models.QuestionDAO.load(key) @classmethod def get_resource_title(cls, rsrc): return rsrc.description @classmethod def get_data_dict(cls, course, key): return cls.get_resource(course, key).dict @classmethod def get_view_url(cls, rsrc): return None @classmethod def get_edit_url(cls, key): return 'dashboard?action=edit_question&key=%s' % key class ResourceSAQuestion(ResourceQuestionBase): TYPE = ResourceQuestionBase.TYPE_SA_QUESTION GRADER_TYPES = [ ('case_insensitive', 'Case insensitive string match'), ('regex', 'Regular expression'), ('numeric', 'Numeric')] @classmethod def get_schema(cls, course, key): """Get the InputEx schema for the short answer question editor.""" sa_question = schema_fields.FieldRegistry( 'Short Answer Question', description='short answer question', extra_schema_dict_values={'className': 'sa-container'}) sa_question.add_property(schema_fields.SchemaField( 'version', '', 'string', optional=True, hidden=True)) sa_question.add_property(schema_fields.SchemaField( 'question', 'Question', 'html', optional=True, extra_schema_dict_values={ 'supportCustomTags': tags.CAN_USE_DYNAMIC_TAGS.value, 'excludedCustomTags': TAGS_EXCLUDED_FROM_QUESTIONS, 'className': 'sa-question'})) sa_question.add_property(schema_fields.SchemaField( 'description', 'Description', 'string', optional=True, extra_schema_dict_values={'className': 'sa-description'}, description=messages.QUESTION_DESCRIPTION)) sa_question.add_property(schema_fields.SchemaField( 'hint', 'Hint', 'html', optional=True, extra_schema_dict_values={'className': 'sa-hint'})) sa_question.add_property(schema_fields.SchemaField( 'defaultFeedback', 'Feedback', 'html', optional=True, extra_schema_dict_values={ 'supportCustomTags': tags.CAN_USE_DYNAMIC_TAGS.value, 'excludedCustomTags': TAGS_EXCLUDED_FROM_QUESTIONS, 'className': 'sa-feedback'}, description=messages.INCORRECT_ANSWER_FEEDBACK)) sa_question.add_property(schema_fields.SchemaField( 'rows', 'Rows', 'string', optional=True, i18n=False, extra_schema_dict_values={ 'className': 'sa-rows', 'value': SaQuestionConstants.DEFAULT_HEIGHT_ROWS }, description=messages.INPUT_FIELD_HEIGHT_DESCRIPTION)) sa_question.add_property(schema_fields.SchemaField( 'columns', 'Columns', 'string', optional=True, i18n=False, extra_schema_dict_values={ 'className': 'sa-columns', 'value': SaQuestionConstants.DEFAULT_WIDTH_COLUMNS }, description=messages.INPUT_FIELD_WIDTH_DESCRIPTION)) grader_type = schema_fields.FieldRegistry( 'Answer', extra_schema_dict_values={'className': 'sa-grader'}) grader_type.add_property(schema_fields.SchemaField( 'score', 'Score', 'string', optional=True, i18n=False, extra_schema_dict_values={'className': 'sa-grader-score'})) grader_type.add_property(schema_fields.SchemaField( 'matcher', 'Grading', 'string', optional=True, i18n=False, select_data=cls.GRADER_TYPES, extra_schema_dict_values={'className': 'sa-grader-score'})) grader_type.add_property(schema_fields.SchemaField( 'response', 'Response', 'string', optional=True, extra_schema_dict_values={'className': 'sa-grader-text'})) grader_type.add_property(schema_fields.SchemaField( 'feedback', 'Feedback', 'html', optional=True, extra_schema_dict_values={ 'supportCustomTags': tags.CAN_USE_DYNAMIC_TAGS.value, 'excludedCustomTags': TAGS_EXCLUDED_FROM_QUESTIONS, 'className': 'sa-grader-feedback'})) graders_array = schema_fields.FieldArray( 'graders', '', item_type=grader_type, extra_schema_dict_values={ 'className': 'sa-grader-container', 'listAddLabel': 'Add an answer', 'listRemoveLabel': 'Delete this answer'}) sa_question.add_property(graders_array) return sa_question class ResourceMCQuestion(ResourceQuestionBase): TYPE = ResourceQuestionBase.TYPE_MC_QUESTION @classmethod def get_schema(cls, course, key): """Get the InputEx schema for the multiple choice question editor.""" mc_question = schema_fields.FieldRegistry( 'Multiple Choice Question', description='multiple choice question', extra_schema_dict_values={'className': 'mc-container'}) mc_question.add_property(schema_fields.SchemaField( 'version', '', 'string', optional=True, hidden=True)) mc_question.add_property(schema_fields.SchemaField( 'question', 'Question', 'html', optional=True, extra_schema_dict_values={ 'supportCustomTags': tags.CAN_USE_DYNAMIC_TAGS.value, 'excludedCustomTags': TAGS_EXCLUDED_FROM_QUESTIONS, 'className': 'mc-question'})) mc_question.add_property(schema_fields.SchemaField( 'description', 'Description', 'string', optional=True, extra_schema_dict_values={'className': 'mc-description'}, description=messages.QUESTION_DESCRIPTION)) mc_question.add_property(schema_fields.SchemaField( 'multiple_selections', 'Selection', 'boolean', optional=True, select_data=[ ('false', 'Allow only one selection'), ('true', 'Allow multiple selections')], extra_schema_dict_values={ '_type': 'radio', 'className': 'mc-selection'})) choice_type = schema_fields.FieldRegistry( 'Choice', extra_schema_dict_values={'className': 'mc-choice'}) choice_type.add_property(schema_fields.SchemaField( 'score', 'Score', 'string', optional=True, i18n=False, extra_schema_dict_values={ 'className': 'mc-choice-score', 'value': '0'})) choice_type.add_property(schema_fields.SchemaField( 'text', 'Text', 'html', optional=True, extra_schema_dict_values={ 'supportCustomTags': tags.CAN_USE_DYNAMIC_TAGS.value, 'excludedCustomTags': TAGS_EXCLUDED_FROM_QUESTIONS, 'className': 'mc-choice-text'})) choice_type.add_property(schema_fields.SchemaField( 'feedback', 'Feedback', 'html', optional=True, extra_schema_dict_values={ 'supportCustomTags': tags.CAN_USE_DYNAMIC_TAGS.value, 'excludedCustomTags': TAGS_EXCLUDED_FROM_QUESTIONS, 'className': 'mc-choice-feedback'})) choices_array = schema_fields.FieldArray( 'choices', '', item_type=choice_type, extra_schema_dict_values={ 'className': 'mc-choice-container', 'listAddLabel': 'Add a choice', 'listRemoveLabel': 'Delete choice'}) mc_question.add_property(choices_array) return mc_question class ResourceQuestionGroup(resource.AbstractResourceHandler): TYPE = 'question_group' @classmethod def get_resource(cls, course, key): return models.QuestionGroupDAO.load(key) @classmethod def get_resource_title(cls, rsrc): return rsrc.description @classmethod def get_schema(cls, course, key): """Return the InputEx schema for the question group editor.""" question_group = schema_fields.FieldRegistry( 'Question Group', description='question_group') question_group.add_property(schema_fields.SchemaField( 'version', '', 'string', optional=True, hidden=True)) question_group.add_property(schema_fields.SchemaField( 'description', 'Description', 'string', optional=True)) question_group.add_property(schema_fields.SchemaField( 'introduction', 'Introduction', 'html', optional=True)) item_type = schema_fields.FieldRegistry( 'Item', extra_schema_dict_values={'className': 'question-group-item'}) item_type.add_property(schema_fields.SchemaField( 'weight', 'Weight', 'string', optional=True, i18n=False, extra_schema_dict_values={'className': 'question-group-weight'})) question_select_data = [(q.id, q.description) for q in sorted( models.QuestionDAO.get_all(), key=lambda x: x.description)] item_type.add_property(schema_fields.SchemaField( 'question', 'Question', 'string', optional=True, i18n=False, select_data=question_select_data, extra_schema_dict_values={'className': 'question-group-question'})) item_array_classes = 'question-group-items' if not question_select_data: item_array_classes += ' empty-question-list' item_array = schema_fields.FieldArray( 'items', '', item_type=item_type, extra_schema_dict_values={ 'className': item_array_classes, 'sortable': 'true', 'listAddLabel': 'Add a question', 'listRemoveLabel': 'Remove'}) question_group.add_property(item_array) return question_group @classmethod def get_data_dict(cls, course, key): return models.QuestionGroupDAO.load(int(key)).dict @classmethod def get_view_url(cls, rsrc): return None @classmethod def get_edit_url(cls, key): return 'dashboard?action=edit_question_group&key=%s' % key class ResourceCourseSettings(resource.AbstractResourceHandler): TYPE = 'course_settings' @classmethod def get_resource(cls, course, key): entire_schema = course.create_settings_schema() return entire_schema.clone_only_items_named([key]) @classmethod def get_resource_title(cls, rsrc): return ' '.join([sr.title for sr in rsrc.sub_registries.itervalues()]) @classmethod def get_schema(cls, course, key): return cls.get_resource(course, key) @classmethod def get_data_dict(cls, course, key): schema = cls.get_schema(course, key) json_entity = {} schema.convert_entity_to_json_entity( course.get_environ(course.app_context), json_entity) return json_entity[key] @classmethod def get_view_url(cls, rsrc): return None @classmethod def get_edit_url(cls, key): return 'dashboard?action=settings&tab=%s' % key def workflow_key(key): return 'workflow:%s' % key class LabelGroupsHelper(object): """Various methods that make it easier to attach labels to objects.""" @classmethod def make_labels_group_schema_field(cls): label = schema_fields.FieldRegistry(None, description='label') label.add_property(schema_fields.SchemaField( 'id', 'ID', 'integer', hidden=True, editable=False)) label.add_property(schema_fields.SchemaField( 'checked', None, 'boolean')) label.add_property(schema_fields.SchemaField( 'title', None, 'string', optional=True, editable=False)) label.add_property(schema_fields.SchemaField( 'description', None, 'string', optional=True, editable=False, extra_schema_dict_values={ 'className': 'label-description'})) label.add_property(schema_fields.SchemaField( 'no_labels', None, 'string', optional=True, editable=False, extra_schema_dict_values={ 'className': 'label-none-in-group'})) label_group = schema_fields.FieldRegistry( '', description='label groups') label_group.add_property(schema_fields.SchemaField( 'title', None, 'string', editable=False)) label_group.add_property(schema_fields.FieldArray( 'labels', None, item_type=label, extra_schema_dict_values={ 'className': 'label-group'})) return label_group @classmethod def decode_labels_group(cls, label_groups): """Decodes label_group JSON.""" labels = set() for label_group in label_groups: for label in label_group['labels']: if label['checked'] and label['id'] > 0: labels.add(label['id']) return labels @classmethod def announcement_labels_to_dict(cls, announcement): return cls._all_labels_to_dict( common_utils.text_to_list(announcement.labels)) @classmethod def unit_labels_to_dict(cls, course, unit): parent_unit = course.get_parent_unit(unit.unit_id) labels = common_utils.text_to_list(unit.labels) def should_skip(label_type): return ( parent_unit and label_type.type == models.LabelDTO.LABEL_TYPE_COURSE_TRACK) return cls._all_labels_to_dict(labels, should_skip=should_skip) @classmethod def _all_labels_to_dict(cls, labels, should_skip=None): all_labels = models.LabelDAO.get_all() label_groups = [] for label_type in sorted(models.LabelDTO.LABEL_TYPES, lambda a, b: cmp(a.menu_order, b.menu_order)): if should_skip is not None and should_skip(label_type): continue label_group = [] for label in sorted(all_labels, lambda a, b: cmp(a.title, b.title)): if label.type == label_type.type: label_group.append({ 'id': label.id, 'title': label.title, 'description': label.description, 'checked': str(label.id) in labels, 'no_labels': '', }) if not label_group: label_group.append({ 'id': -1, 'title': '', 'description': '', 'checked': False, 'no_labels': '-- No labels of this type --', }) label_groups.append({ 'title': label_type.title, 'labels': label_group, }) return label_groups class UnitTools(object): def __init__(self, course): self._course = course def apply_updates(self, unit, updated_unit_dict, errors): if unit.type == verify.UNIT_TYPE_ASSESSMENT: self._apply_updates_to_assessment(unit, updated_unit_dict, errors) elif unit.type == verify.UNIT_TYPE_LINK: self._apply_updates_to_link(unit, updated_unit_dict, errors) elif unit.type == verify.UNIT_TYPE_UNIT: self._apply_updates_to_unit(unit, updated_unit_dict, errors) else: raise ValueError('Unknown unit type %s' % unit.type) def _apply_updates_common(self, unit, updated_unit_dict, errors): """Apply changes common to all unit types.""" unit.title = updated_unit_dict.get('title') unit.description = updated_unit_dict.get('description') unit.now_available = not updated_unit_dict.get('is_draft') labels = LabelGroupsHelper.decode_labels_group( updated_unit_dict['label_groups']) if self._course.get_parent_unit(unit.unit_id): track_label_ids = models.LabelDAO.get_set_of_ids_of_type( models.LabelDTO.LABEL_TYPE_COURSE_TRACK) if track_label_ids.intersection(labels): errors.append('Cannot set track labels on entities which ' 'are used within other units.') unit.labels = common_utils.list_to_text(labels) def _apply_updates_to_assessment(self, unit, updated_unit_dict, errors): """Store the updated assessment.""" entity_dict = {} ResourceAssessment.get_schema(None, None).convert_json_to_entity( updated_unit_dict, entity_dict) self._apply_updates_common(unit, entity_dict, errors) try: unit.weight = float(entity_dict.get('weight')) if unit.weight < 0: errors.append('The weight must be a non-negative integer.') except ValueError: errors.append('The weight must be an integer.') content = entity_dict.get('content') if content: self._course.set_assessment_content( unit, entity_dict.get('content'), errors=errors) unit.html_content = entity_dict.get('html_content') unit.html_check_answers = entity_dict.get('html_check_answers') workflow_dict = entity_dict.get('workflow') if len(courses.ALLOWED_MATCHERS_NAMES) == 1: workflow_dict[courses.MATCHER_KEY] = ( courses.ALLOWED_MATCHERS_NAMES.keys()[0]) unit.workflow_yaml = yaml.safe_dump(workflow_dict) unit.workflow.validate(errors=errors) # Only save the review form if the assessment needs human grading. if not errors: if self._course.needs_human_grader(unit): review_form = entity_dict.get('review_form') if review_form: self._course.set_review_form( unit, review_form, errors=errors) unit.html_review_form = entity_dict.get('html_review_form') elif entity_dict.get('review_form'): errors.append( 'Review forms for auto-graded assessments should be empty.') def _apply_updates_to_link(self, unit, updated_unit_dict, errors): self._apply_updates_common(unit, updated_unit_dict, errors) unit.href = updated_unit_dict.get('url') def _is_assessment_unused(self, unit, assessment, errors): parent_unit = self._course.get_parent_unit(assessment.unit_id) if parent_unit and parent_unit.unit_id != unit.unit_id: errors.append( 'Assessment "%s" is already asssociated to unit "%s"' % ( assessment.title, parent_unit.title)) return False return True def _is_assessment_version_ok(self, assessment, errors): # Here, we want to establish that the display model for the # assessment is compatible with the assessment being used in # the context of a Unit. Model version 1.4 is not, because # the way sets up submission is to build an entirely new form # from JavaScript (independent of the form used to display the # assessment), and the way it learns the ID of the assessment # is by looking in the URL (as opposed to taking a parameter). # This is incompatible with the URLs for unit display, so we # just disallow older assessments here. model_version = self._course.get_assessment_model_version(assessment) if model_version == courses.ASSESSMENT_MODEL_VERSION_1_4: errors.append( 'The version of assessment "%s" ' % assessment.title + 'is not compatible with use as a pre/post unit element') return False return True def _is_assessment_on_track(self, assessment, errors): if self._course.get_unit_track_labels(assessment): errors.append( 'Assessment "%s" has track labels, ' % assessment.title + 'so it cannot be used as a pre/post unit element') return True return False def _apply_updates_to_unit(self, unit, updated_unit_dict, errors): self._apply_updates_common(unit, updated_unit_dict, errors) unit.unit_header = updated_unit_dict['unit_header'] unit.unit_footer = updated_unit_dict['unit_footer'] unit.pre_assessment = None unit.post_assessment = None unit.manual_progress = updated_unit_dict['manual_progress'] pre_assessment_id = updated_unit_dict['pre_assessment'] if pre_assessment_id >= 0: assessment = self._course.find_unit_by_id(pre_assessment_id) if (self._is_assessment_unused(unit, assessment, errors) and self._is_assessment_version_ok(assessment, errors) and not self._is_assessment_on_track(assessment, errors)): unit.pre_assessment = pre_assessment_id post_assessment_id = updated_unit_dict['post_assessment'] if post_assessment_id >= 0 and pre_assessment_id == post_assessment_id: errors.append( 'The same assessment cannot be used as both the pre ' 'and post assessment of a unit.') elif post_assessment_id >= 0: assessment = self._course.find_unit_by_id(post_assessment_id) if (assessment and self._is_assessment_unused(unit, assessment, errors) and self._is_assessment_version_ok(assessment, errors) and not self._is_assessment_on_track(assessment, errors)): unit.post_assessment = post_assessment_id unit.show_contents_on_one_page = ( updated_unit_dict['show_contents_on_one_page']) def unit_to_dict(self, unit, keys=None): if unit.type == verify.UNIT_TYPE_ASSESSMENT: return self._assessment_to_dict(unit, keys=keys) elif unit.type == verify.UNIT_TYPE_LINK: return self._link_to_dict(unit) elif unit.type == verify.UNIT_TYPE_UNIT: return self._unit_to_dict(unit) else: raise ValueError('Unknown unit type %s' % unit.type) def _unit_to_dict_common(self, unit): return { 'key': unit.unit_id, 'type': verify.UNIT_TYPE_NAMES[unit.type], 'title': unit.title, 'description': unit.description or '', 'is_draft': not unit.now_available, 'label_groups': LabelGroupsHelper.unit_labels_to_dict( self._course, unit)} def _get_assessment_path(self, unit): return self._course.app_context.fs.impl.physical_to_logical( self._course.get_assessment_filename(unit.unit_id)) def _get_review_form_path(self, unit): return self._course.app_context.fs.impl.physical_to_logical( self._course.get_review_filename(unit.unit_id)) def _assessment_to_dict(self, unit, keys=None): """Assemble a dict with the unit data fields.""" assert unit.type == 'A' content = None if keys is not None and 'content' in keys: path = self._get_assessment_path(unit) fs = self._course.app_context.fs if fs.isfile(path): content = fs.get(path) else: content = '' review_form = None if keys is not None and 'review_form' in keys: review_form_path = self._get_review_form_path(unit) if review_form_path and fs.isfile(review_form_path): review_form = fs.get(review_form_path) else: review_form = '' workflow = unit.workflow if workflow.get_submission_due_date(): submission_due_date = workflow.get_submission_due_date().strftime( courses.ISO_8601_DATE_FORMAT) else: submission_due_date = '' if workflow.get_review_due_date(): review_due_date = workflow.get_review_due_date().strftime( courses.ISO_8601_DATE_FORMAT) else: review_due_date = '' unit_common = self._unit_to_dict_common(unit) unit_common.update({ 'weight': str(unit.weight if hasattr(unit, 'weight') else 0), 'content': content, 'html_content': ( '' if unit.is_old_style_assessment(self._course) else unit.html_content), 'html_check_answers': ( False if unit.is_old_style_assessment(self._course) else unit.html_check_answers), workflow_key(courses.SUBMISSION_DUE_DATE_KEY): ( submission_due_date), workflow_key(courses.GRADER_KEY): workflow.get_grader(), }) return { 'assessment': unit_common, 'review_opts': { workflow_key(courses.MATCHER_KEY): workflow.get_matcher(), workflow_key(courses.REVIEW_DUE_DATE_KEY): review_due_date, workflow_key(courses.REVIEW_MIN_COUNT_KEY): ( workflow.get_review_min_count()), workflow_key(courses.REVIEW_WINDOW_MINS_KEY): ( workflow.get_review_window_mins()), 'review_form': review_form, 'html_review_form': ( unit.html_review_form or '' if hasattr(unit, 'html_review_form') else ''), } } def _link_to_dict(self, unit): assert unit.type == 'O' ret = self._unit_to_dict_common(unit) ret['url'] = unit.href return ret def _unit_to_dict(self, unit): assert unit.type == 'U' ret = self._unit_to_dict_common(unit) ret['unit_header'] = unit.unit_header or '' ret['unit_footer'] = unit.unit_footer or '' ret['pre_assessment'] = unit.pre_assessment or -1 ret['post_assessment'] = unit.post_assessment or -1 ret['show_contents_on_one_page'] = ( unit.show_contents_on_one_page or False) ret['manual_progress'] = unit.manual_progress or False return ret class ResourceUnitBase(resource.AbstractResourceHandler): ASSESSMENT_TYPE = 'assessment' UNIT_TYPE = 'unit' LINK_TYPE = 'link' @classmethod def key_for_unit(cls, unit, course=None): if unit.type == verify.UNIT_TYPE_ASSESSMENT: unit_type = cls.ASSESSMENT_TYPE elif unit.type == verify.UNIT_TYPE_LINK: unit_type = cls.LINK_TYPE elif unit.type == verify.UNIT_TYPE_UNIT: unit_type = cls.UNIT_TYPE else: raise ValueError('Unknown unit type: %s' % unit.type) return resource.Key(unit_type, unit.unit_id, course=course) @classmethod def get_resource(cls, course, key): return course.find_unit_by_id(key) @classmethod def get_resource_title(cls, rsrc): return rsrc.title @classmethod def get_data_dict(cls, course, key): unit = course.find_unit_by_id(key) return UnitTools(course).unit_to_dict(unit) @classmethod def _generate_common_schema(cls, title): ret = schema_fields.FieldRegistry(title, extra_schema_dict_values={ 'className': 'inputEx-Group new-form-layout'}) ret.add_property(schema_fields.SchemaField( 'key', 'ID', 'string', editable=False, extra_schema_dict_values={'className': 'inputEx-Field keyHolder'})) ret.add_property(schema_fields.SchemaField( 'type', 'Type', 'string', editable=False)) ret.add_property(schema_fields.SchemaField( 'title', 'Title', 'string', optional=True)) ret.add_property(schema_fields.SchemaField( 'description', 'Description', 'string', optional=True)) ret.add_property(schema_fields.FieldArray( 'label_groups', 'Labels', item_type=LabelGroupsHelper.make_labels_group_schema_field(), extra_schema_dict_values={ 'className': 'inputEx-Field label-group-list'})) ret.add_property(schema_fields.SchemaField( 'is_draft', 'Status', 'boolean', select_data=[(True, DRAFT_TEXT), (False, PUBLISHED_TEXT)], extra_schema_dict_values={ 'className': 'split-from-main-group'})) return ret class ResourceUnit(ResourceUnitBase): TYPE = ResourceUnitBase.UNIT_TYPE @classmethod def get_schema(cls, course, key): schema = cls._generate_common_schema('Unit') schema.add_property(schema_fields.SchemaField( 'unit_header', 'Unit Header', 'html', optional=True, extra_schema_dict_values={ 'supportCustomTags': tags.CAN_USE_DYNAMIC_TAGS.value, 'excludedCustomTags': tags.EditorBlacklists.DESCRIPTIVE_SCOPE, 'className': 'inputEx-Field html-content'})) schema.add_property(schema_fields.SchemaField( 'pre_assessment', 'Pre Assessment', 'integer', optional=True)) schema.add_property(schema_fields.SchemaField( 'post_assessment', 'Post Assessment', 'integer', optional=True)) schema.add_property(schema_fields.SchemaField( 'show_contents_on_one_page', 'Show Contents on One Page', 'boolean', optional=True, description='Whether to show all assessments, lessons, ' 'and activities in a Unit on one page, or to show each on ' 'its own page.')) schema.add_property(schema_fields.SchemaField( 'manual_progress', 'Manual Progress', 'boolean', optional=True, description='When set, the manual progress REST API permits ' 'users to manually mark a unit or lesson as complete, ' 'overriding the automatic progress tracking.')) schema.add_property(schema_fields.SchemaField( 'unit_footer', 'Unit Footer', 'html', optional=True, extra_schema_dict_values={ 'supportCustomTags': tags.CAN_USE_DYNAMIC_TAGS.value, 'excludedCustomTags': tags.EditorBlacklists.DESCRIPTIVE_SCOPE, 'className': 'inputEx-Field html-content'})) return schema @classmethod def get_view_url(cls, rsrc): return 'unit?unit=%s' % rsrc.unit_id @classmethod def get_edit_url(cls, key): return 'dashboard?action=edit_unit&key=%s' % key class ResourceAssessment(ResourceUnitBase): TYPE = ResourceUnitBase.ASSESSMENT_TYPE @classmethod def get_schema(cls, course, key): reg = schema_fields.FieldRegistry( 'Assessment Entity', description='Assessment', extra_schema_dict_values={ 'className': 'inputEx-Group new-form-layout'}) # Course level settings. course_opts = cls._generate_common_schema('Assessment Config') course_opts.add_property(schema_fields.SchemaField( 'weight', 'Weight', 'string', optional=True, i18n=False)) course_opts.add_property(schema_fields.SchemaField( 'content', 'Assessment Content', 'text', optional=True, description=str(messages.ASSESSMENT_CONTENT_DESCRIPTION), extra_schema_dict_values={'className': 'inputEx-Field content'})) course_opts.add_property(schema_fields.SchemaField( 'html_content', 'Assessment Content (HTML)', 'html', optional=True, extra_schema_dict_values={ 'supportCustomTags': tags.CAN_USE_DYNAMIC_TAGS.value, 'excludedCustomTags': tags.EditorBlacklists.ASSESSMENT_SCOPE, 'className': 'inputEx-Field html-content'})) course_opts.add_property(schema_fields.SchemaField( 'html_check_answers', '"Check Answers" Buttons', 'boolean', optional=True, extra_schema_dict_values={ 'className': 'inputEx-Field assessment-editor-check-answers'})) course_opts.add_property(schema_fields.SchemaField( workflow_key(courses.SUBMISSION_DUE_DATE_KEY), 'Submission Due Date', 'string', optional=True, description=str(messages.DUE_DATE_FORMAT_DESCRIPTION))) course_opts.add_property(schema_fields.SchemaField( workflow_key(courses.GRADER_KEY), 'Grading Method', 'string', select_data=ALLOWED_GRADERS_NAMES.items())) reg.add_sub_registry('assessment', 'Assessment Config', registry=course_opts) review_opts = reg.add_sub_registry( 'review_opts', 'Review Config', description=str(messages.ASSESSMENT_DETAILS_DESCRIPTION)) if len(courses.ALLOWED_MATCHERS_NAMES) > 1: review_opts.add_property(schema_fields.SchemaField( workflow_key(courses.MATCHER_KEY), 'Review Matcher', 'string', optional=True, select_data=courses.ALLOWED_MATCHERS_NAMES.items())) review_opts.add_property(schema_fields.SchemaField( 'review_form', 'Reviewer Feedback Form', 'text', optional=True, description=str(messages.REVIEWER_FEEDBACK_FORM_DESCRIPTION), extra_schema_dict_values={ 'className': 'inputEx-Field review-form'})) review_opts.add_property(schema_fields.SchemaField( 'html_review_form', 'Reviewer Feedback Form (HTML)', 'html', optional=True, extra_schema_dict_values={ 'supportCustomTags': tags.CAN_USE_DYNAMIC_TAGS.value, 'excludedCustomTags': tags.EditorBlacklists.ASSESSMENT_SCOPE, 'className': 'inputEx-Field html-review-form'})) review_opts.add_property(schema_fields.SchemaField( workflow_key(courses.REVIEW_DUE_DATE_KEY), 'Review Due Date', 'string', optional=True, description=str(messages.REVIEW_DUE_DATE_FORMAT_DESCRIPTION))) review_opts.add_property(schema_fields.SchemaField( workflow_key(courses.REVIEW_MIN_COUNT_KEY), 'Review Min Count', 'integer', optional=True, description=str(messages.REVIEW_MIN_COUNT_DESCRIPTION))) review_opts.add_property(schema_fields.SchemaField( workflow_key(courses.REVIEW_WINDOW_MINS_KEY), 'Review Window Timeout', 'integer', optional=True, description=str(messages.REVIEW_TIMEOUT_IN_MINUTES))) return reg @classmethod def get_view_url(cls, rsrc): return 'assessment?name=%s' % rsrc.unit_id @classmethod def get_edit_url(cls, key): return 'dashboard?action=edit_assessment&key=%s' % key class ResourceLink(ResourceUnitBase): TYPE = ResourceUnitBase.LINK_TYPE @classmethod def get_schema(cls, course, key): schema = cls._generate_common_schema('Link') schema.add_property(schema_fields.SchemaField( 'url', 'URL', 'string', optional=True, description=messages.LINK_EDITOR_URL_DESCRIPTION)) return schema @classmethod def get_view_url(cls, rsrc): return rsrc.href @classmethod def get_edit_url(cls, key): return 'dashboard?action=edit_link&key=%s' % key class ResourceLesson(resource.AbstractResourceHandler): TYPE = 'lesson' @classmethod def get_key(cls, lesson): return resource.Key(cls.TYPE, lesson.lesson_id) @classmethod def get_resource(cls, course, key): lesson = course.find_lesson_by_id(None, key) unit = course.get_unit_for_lesson(lesson) return (unit, lesson) @classmethod def get_resource_title(cls, rsrc): return rsrc[1].title @classmethod def get_schema(cls, course, key): units = course.get_units() # Note GcbRte relies on the structure of this schema. Do not change # without checking the dependency. unit_list = [] for unit in units: if unit.type == 'U': unit_list.append( (unit.unit_id, cgi.escape(display_unit_title(unit, course.app_context)))) lesson = schema_fields.FieldRegistry( 'Lesson', description='Lesson', extra_schema_dict_values={ 'className': 'inputEx-Group new-form-layout'}) lesson.add_property(schema_fields.SchemaField( 'key', 'ID', 'string', editable=False, extra_schema_dict_values={'className': 'inputEx-Field keyHolder'})) lesson.add_property(schema_fields.SchemaField( 'title', 'Title', 'string')) lesson.add_property(schema_fields.SchemaField( 'unit_id', 'Parent Unit', 'string', i18n=False, select_data=unit_list)) lesson.add_property(schema_fields.SchemaField( 'video', 'Video ID', 'string', optional=True, description=messages.LESSON_VIDEO_ID_DESCRIPTION)) lesson.add_property(schema_fields.SchemaField( 'scored', 'Scored', 'string', optional=True, i18n=False, description=messages.LESSON_SCORED_DESCRIPTION, select_data=[ ('scored', 'Questions are scored'), ('not_scored', 'Questions only give feedback')])) lesson.add_property(schema_fields.SchemaField( 'objectives', 'Lesson Body', 'html', optional=True, description=messages.LESSON_OBJECTIVES_DESCRIPTION, extra_schema_dict_values={ 'supportCustomTags': tags.CAN_USE_DYNAMIC_TAGS.value})) lesson.add_property(schema_fields.SchemaField( 'notes', 'Notes', 'string', optional=True, description=messages.LESSON_NOTES_DESCRIPTION)) lesson.add_property(schema_fields.SchemaField( 'auto_index', 'Auto Number', 'boolean', description=messages.LESSON_AUTO_INDEX_DESCRIPTION)) lesson.add_property(schema_fields.SchemaField( 'activity_title', 'Activity Title', 'string', optional=True, description=messages.LESSON_ACTIVITY_TITLE_DESCRIPTION)) lesson.add_property(schema_fields.SchemaField( 'activity_listed', 'Activity Listed', 'boolean', optional=True, description=messages.LESSON_ACTIVITY_LISTED_DESCRIPTION)) lesson.add_property(schema_fields.SchemaField( 'activity', 'Activity', 'text', optional=True, description=str(messages.LESSON_ACTIVITY_DESCRIPTION), extra_schema_dict_values={ 'className': 'inputEx-Field activityHolder'})) lesson.add_property(schema_fields.SchemaField( 'manual_progress', 'Manual Progress', 'boolean', optional=True, description=messages.LESSON_MANUAL_PROGRESS_DESCRIPTION)) lesson.add_property(schema_fields.SchemaField( 'is_draft', 'Status', 'boolean', select_data=[(True, DRAFT_TEXT), (False, PUBLISHED_TEXT)], extra_schema_dict_values={ 'className': 'split-from-main-group'})) return lesson @classmethod def get_data_dict(cls, course, key): lesson = course.find_lesson_by_id(None, key) fs = course.app_context.fs path = fs.impl.physical_to_logical(course.get_activity_filename( lesson.unit_id, lesson.lesson_id)) if lesson.has_activity and fs.isfile(path): activity = fs.get(path) else: activity = '' lesson_dict = { 'key': lesson.lesson_id, 'title': lesson.title, 'unit_id': lesson.unit_id, 'scored': 'scored' if lesson.scored else 'not_scored', 'objectives': lesson.objectives, 'video': lesson.video, 'notes': lesson.notes, 'auto_index': lesson.auto_index, 'activity_title': lesson.activity_title, 'activity_listed': lesson.activity_listed, 'activity': activity, 'manual_progress': lesson.manual_progress or False, 'is_draft': not lesson.now_available } return lesson_dict @classmethod def get_view_url(cls, rsrc): return 'unit?unit=%s&lesson=%s' % (rsrc[0].unit_id, rsrc[1].lesson_id) @classmethod def get_edit_url(cls, key): return 'dashboard?action=edit_lesson&key=%s' % key def get_unit_title_template(app_context): """Prepare an internationalized display for the unit title.""" course_properties = app_context.get_environ() if course_properties['course'].get('display_unit_title_without_index'): return '%(title)s' else: # I18N: Message displayed as title for unit within a course. # Note that the items %(index) and %(title). The %(index) # will be replaced with a number indicating the unit's # sequence I18N: number within the course, and the %(title) # with the unit's title. return app_context.gettext('Unit %(index)s - %(title)s') def display_unit_title(unit, app_context): """Prepare an internationalized display for the unit title.""" course_properties = app_context.get_environ() template = get_unit_title_template(app_context) return template % {'index': unit.index, 'title': unit.title} def display_short_unit_title(unit, app_context): """Prepare a short unit title.""" course_properties = app_context.get_environ() if course_properties['course'].get('display_unit_title_without_index'): return unit.title if unit.type != 'U': return unit.title # I18N: Message displayed as title for unit within a course. The # "%s" will be replaced with the index number of the unit within # the course. E.g., "Unit 1", "Unit 2" and so on. unit_title = app_context.gettext('Unit %s') return unit_title % unit.index def display_lesson_title(unit, lesson, app_context): """Prepare an internationalized display for the unit title.""" course_properties = app_context.get_environ() content = safe_dom.NodeList() span = safe_dom.Element('span') content.append(span) if lesson.auto_index: prefix = '' if course_properties['course'].get('display_unit_title_without_index'): prefix = '%s ' % lesson.index else: prefix = '%s.%s ' % (unit.index, lesson.index) span.add_text(prefix) _class = '' else: _class = 'no-index' span.add_text(lesson.title) span.set_attribute('className', _class) return content
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Classes supporting dynamically registering custom unit types.""" __author__ = 'Abhinav Khandelwal (abhinavk@google.com)' import logging class UnitTypeRegistry(object): """A registry that holds all custom modules.""" registered_unit_types = {} @classmethod def register_type(cls, custom_type): identifier = custom_type.identifier if identifier in cls.registered_unit_types.keys(): logging.fatal(custom_type.identifier + ' already registered') return cls.registered_unit_types[identifier] = custom_type @classmethod def get(cls, identifier): return cls.registered_unit_types.get(identifier, None) @classmethod def has_type(cls, identifier): return identifier in cls.registered_unit_types @classmethod def list(cls): return cls.registered_unit_types.values() @classmethod def i18n_resource_key(cls, course, unit): assert unit.is_custom_unit() cu = cls.get(unit.custom_unit_type) if not cu: return None return cu.i18n_resource_key(course, unit) class CustomUnit(object): """A class that holds unit information.""" def __init__(self, identifier, name, rest_handler_cls, visible_url_fn, extra_js_files=None, create_helper=None, cleanup_helper=None, is_graded=False, i18n_resource_key_fn=None): self.name = name self.identifier = identifier self.rest_handler = rest_handler_cls # Visible url function should take Unit object as parameter and return # the visible url for the unit page. Look at the example usage below self.visible_url_fn = visible_url_fn self.extra_js_files = extra_js_files # Create helper function should take Course and Unit object as parameter self.create_helper = create_helper # Delete helper function should take Course and Unit object as parameter self.cleanup_helper = cleanup_helper # Is this custom unit graded. self.is_graded = is_graded # Function to generate i18n resource keys self._i18n_resource_key_fn = i18n_resource_key_fn UnitTypeRegistry.register_type(self) def visible_url(self, unit): return self.visible_url_fn(unit) def add_unit(self, course, unit): if self.create_helper: self.create_helper(course, unit) def delete_unit(self, course, unit): if self.cleanup_helper: self.cleanup_helper(course, unit) def i18n_resource_key(self, course, unit): if self._i18n_resource_key_fn is not None: return self._i18n_resource_key_fn(course, unit) return None
Python
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Core service interface definitions.""" class Service(object): """Abstract base service interface.""" def enabled(self): raise NotImplementedError() class Notifications(Service): def query(self, to, intent): """Gets the Status of notifications queued previously via send_async(). Serially performs one datastore query per user in the to list. Args: to: list of string. The recipients of the notification. intent: string. Short string identifier of the intent of the notification (for example, 'invitation' or 'reminder'). Returns: Dict of to string -> [Status, sorted by descending enqueue date]. See modules.notifications.notifications.Status for an example of the Status object. """ raise NotImplementedError() def send_async( self, to, sender, intent, body, subject, audit_trail=None, retention_policy=None): """Asyncronously sends a notification via email. Args: to: string. Recipient email address. Must have a valid form, but we cannot know that the address can actually be delivered to. sender: string. Email address of the sender of the notification. Must be a valid sender for the App Engine deployment at the time the deferred send_mail() call actually executes (meaning it cannot be the email address of the user currently in session, because the user will not be in session at call time). See https://developers.google.com/appengine/docs/python/mail/emailmessagefields. intent: string. Short string identifier of the intent of the notification (for example, 'invitation' or 'reminder'). Each kind of notification you are sending should have its own intent. Used when creating keys in the index; values that cause the resulting key to be >500B will fail. May not contain a colon. body: string. The data payload of the notification. Must fit in a datastore entity. subject: string. Subject line for the notification. audit_trail: JSON-serializable object. An optional audit trail that, when used with the default retention policy, will be retained even after the body is scrubbed from the datastore. retention_policy: RetentionPolicy. The retention policy to use for data after a Notification has been sent. By default, we retain the audit_trail but not the body. Returns: (notification_key, payload_key). A 2-tuple of datastore keys for the created notification and payload. Raises: Exception: if values delegated to model initializers are invalid. ValueError: if to or sender are malformed according to App Engine (note that well-formed values do not guarantee success). """ raise NotImplementedError() class Unsubscribe(Service): def get_unsubscribe_url(self, handler, email): """Create an individualized unsubscribe link for a user. Args: handler: controllers.utils.ApplicationHandler. The current request handler. email: string. The email address of the users for whom the unsubscribe link is being generated. Returns: string. A URL for the users to unsubscribe from notifications. """ raise NotImplementedError() def has_unsubscribed(self, email): """Check whether the user has requested to be unsubscribed. Args: email: string. The email address of the user. Returns: bool. True if the user has requested to be unsubscribed. """ raise NotImplementedError() def set_subscribed(self, email, is_subscribed): """Set the state of a given user. Args: email: string. The email address of the user. is_subscribed: bool. The state to set. True means that the user is subscribed and should continue to receive emails; False means that they should not. Returns: None. """ raise NotImplementedError() notifications = Notifications() unsubscribe = Unsubscribe()
Python
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Helper functions to work with various models.""" __author__ = [ 'johncox@google.com (John Cox)', 'sll@google.com (Sean Lip)', ] import logging import transforms _LOG = logging.getLogger('models.utils') logging.basicConfig() class Error(Exception): """Base error class.""" class StopMapping(Error): """Raised by user's map function to stop execution.""" class QueryMapper(object): """Mapper that applies a function to each result of a db.query. QueryMapper works with result sets larger than 1000. Usage: def map_fn(model, named_arg, keyword_arg=None): [...] query = MyModel.all() # We manipulate query, so it cannot be reused after it's fed to # QueryMapper. mapper = QueryMapper(query) mapper.run(map_fn, 'foo', keyword_arg='bar') """ def __init__(self, query, batch_size=20, counter=None, report_every=None): """Constructs a new QueryMapper. Args: query: db.Query. The query to run. Cannot be reused after the query mapper's run() method is invoked. batch_size: int. Number of results to fetch per batch. counter: entities.PerfCounter or None. If given, the counter to increment once for every entity retrieved by query. report_every: int or None. If specified, every report_every results we will log the number of results processed at level info. By default we will do this every 10 batches. Set to 0 to disable logging. """ if report_every is None: report_every = 10 * batch_size self._batch_size = batch_size self._counter = counter self._query = query self._report_every = report_every def run(self, fn, *fn_args, **fn_kwargs): """Runs the query in batches, applying a function to each result. Args: fn: function. Takes a single query result (either a db.Key or db.Model) instance as its first arg, then any number of positional and keyword arguments. Called on each result returned by the query. *fn_args: positional args delegated to fn. **fn_kwargs: keyword args delegated to fn. Returns: Integer. Total number of results processed. """ total_count = 0 cursor = None while True: batch_count, cursor = self._handle_batch( cursor, fn, *fn_args, **fn_kwargs) total_count += batch_count if not (batch_count and cursor): return total_count if self._report_every != 0 and not total_count % self._report_every: _LOG.info( 'Models processed by %s.%s so far: %s', fn.__module__, fn.func_name, total_count) def _handle_batch(self, cursor, fn, *fn_args, **fn_kwargs): if cursor: self._query.with_cursor(start_cursor=cursor) count = 0 empty = True batch = self._query.fetch(limit=self._batch_size) if self._counter: self._counter.inc(increment=len(batch)) for result in batch: try: fn(result, *fn_args, **fn_kwargs) except StopMapping: return count, None count += 1 empty = False cursor = None if not empty: cursor = self._query.cursor() return count, cursor def set_answer(answers, assessment_name, answer): """Stores the answer array for the given student and assessment. The caller must call answers.put() to commit. This does not do any type-checking on 'answer'; it just stores whatever is passed in. Args: answers: the StudentAnswers entity in which the answer should be stored. assessment_name: the name of the assessment. answer: an array containing the student's answers. """ if not answers.data: score_dict = {} else: score_dict = transforms.loads(answers.data) score_dict[assessment_name] = answer answers.data = transforms.dumps(score_dict) def set_score(student, assessment_name, score): """Stores the score for the given student and assessment. The caller must call student.put() to commit. This does not do any type-checking on 'score'; it just stores whatever is passed in. Args: student: the student whose answer should be stored. assessment_name: the name of the assessment. score: the student's score. """ if not student.scores: score_dict = {} else: score_dict = transforms.loads(student.scores) score_dict[assessment_name] = score student.scores = transforms.dumps(score_dict)
Python
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Models and helper utilities for the review workflow.""" __author__ = 'mgainer@google.com (Mike Gainer)' from common import utils as common_utils from controllers import utils import models from models import transforms from google.appengine.api import users PARAMETER_LABELS = 'labels' STUDENT_LABELS_URL = '/rest/student/labels' class StudentLabelsRestHandler(utils.ApplicationHandler): """Allow web pages to mark students as having labels.""" def get(self): student = self._setup() if not student: return label_ids = self._get_existing_label_ids(student) return self._send_response(student, label_ids) def put(self): student = self._setup() if not student: return request_ids = self._get_request_label_ids() if not self._request_label_ids_ok(request_ids): return self._save_labels(student, request_ids) return self._send_response(student, request_ids) def post(self): student = self._setup() if not student: return request_ids = self._get_request_label_ids() if not self._request_label_ids_ok(request_ids): return existing_ids = self._get_existing_label_ids(student) label_ids = existing_ids.union(request_ids) self._save_labels(student, existing_ids.union(label_ids)) return self._send_response(student, label_ids) def delete(self): student = self._setup() if not student: return label_ids = [] self._save_labels(student, label_ids) return self._send_response(student, label_ids) def _setup(self): user = users.get_current_user() if not user: self._send_response(None, [], 403, 'No logged-in user') return None student = ( models.StudentProfileDAO.get_enrolled_student_by_email_for( user.email(), self.app_context)) if not student or not student.is_enrolled: self._send_response(None, [], 403, 'User is not enrolled') return None return student def _get_request_label_ids(self): return set([int(l) for l in common_utils.text_to_list( self.request.get(PARAMETER_LABELS))]) def _request_label_ids_ok(self, label_ids): all_label_ids = {label.id for label in models.LabelDAO.get_all()} invalid = label_ids.difference(all_label_ids) if invalid: self._send_response( None, [], 400, 'Unknown label id(s): %s' % ([str(label_id) for label_id in invalid])) return False return True def _get_existing_label_ids(self, student): # Prune label IDs that no longer refer to a valid Label object. all_label_ids = {label.id for label in models.LabelDAO.get_all()} existing_labels = set([int(label_id) for label_id in common_utils.text_to_list(student.labels)]) return existing_labels.intersection(all_label_ids) def _save_labels(self, student, labels): student.labels = common_utils.list_to_text(labels) student.put() def _send_response(self, student, label_ids, status_code=None, message=None): transforms.send_json_response( self, status_code or 200, message or 'OK', {'labels': list(label_ids)}) def get_namespaced_handlers(): ret = [] ret.append((STUDENT_LABELS_URL, StudentLabelsRestHandler)) return ret
Python
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Common classes and methods for processing text content.""" __author__ = 'Pavel Simakov (psimakov@google.com)' from pyparsing import alphas from pyparsing import Combine from pyparsing import Each from pyparsing import Group from pyparsing import Literal from pyparsing import nums from pyparsing import Optional from pyparsing import QuotedString from pyparsing import Regex from pyparsing import Suppress from pyparsing import Word from pyparsing import ZeroOrMore from tools import verify def sep(text): """Makes a separator.""" return Suppress(Literal(text)) def key(name): """Makes grammar expression for a key.""" return ( Literal(name) ^ (sep('\'') + Literal(name) + sep('\'')) ^ (sep('"') + Literal(name) + sep('"'))) def list_of(term): """Makes a delimited list of terms.""" return ( Optional( term + ZeroOrMore(Suppress(Literal(',')) + term) + Optional(Suppress(Literal(','))) ) ) def chunks(l, n): """Partitions the list l into disjoint sub-lists of length n.""" if len(l) % n != 0: raise Exception('List length is not a multiple on %s', n) return [l[i:i+n] for i in range(0, len(l), n)] def make_dict(unused_s, unused_l, toks): """Makes a dict from the list using even items as keys, odd as values.""" result = {} key_value_pairs = chunks(toks, 2) for key_value_pair in key_value_pairs: result[key_value_pair[0]] = key_value_pair[1] return result def make_list(unused_s, unused_l, toks): """Makes a list out of a token tuple holding a list.""" result = [] for item in toks: result.append(item.asList()) return result def make_bool(value): """Makes a boolean value lambda.""" def make_value(): return verify.Term(verify.BOOLEAN, value) return make_value def make_int(value): """Makes an int value lambda.""" return int(value[0]) def make_float(value): """Makes an float value lambda.""" return float(value[0]) class AssessmentParser13(object): """Grammar and parser for the assessment.""" string = ( QuotedString('\'', escChar='\\', multiline=True) ^ QuotedString('"', escChar='\\', multiline=True)) boolean = ( Literal('true').setParseAction(make_bool(True)) ^ Literal('false').setParseAction(make_bool(False))) float = Combine( Word(nums) + Optional(Literal('.') + Word(nums)) ).setParseAction(make_float) integer = Word(nums).setParseAction(make_int) choice_decl = ( string ^ Combine( sep('correct(') + string + sep(')') ).setParseAction(lambda x: verify.Term(verify.CORRECT, x[0])) ) regex = ( Regex('/(.*)/i') ^ Combine( sep('regex(') + QuotedString('"', escChar='\\') + sep(')') ).setParseAction(lambda x: verify.Term(verify.REGEX, x[0])) ) question_decl = ( sep('{') + Each( Optional( key('questionHTML') + sep(':') + string + Optional(sep(','))) + Optional( key('lesson') + sep(':') + string + Optional(sep(','))) + Optional( key('correctAnswerString') + sep(':') + string + Optional(sep(','))) + Optional( key('correctAnswerRegex') + sep(':') + regex + Optional(sep(','))) + Optional( key('correctAnswerNumeric') + sep(':') + float + Optional(sep(','))) + Optional( key('choiceScores') + sep(':') + sep('[') + Group(list_of(float)).setParseAction(make_list) + sep(']') + Optional(sep(','))) + Optional( key('weight') + sep(':') + integer + Optional(sep(','))) + Optional( key('multiLine') + sep(':') + boolean + Optional(sep(','))) + Optional( key('choices') + sep(':') + sep('[') + Group(list_of(choice_decl)).setParseAction(make_list) + sep(']') + Optional(sep(','))) ) + sep('}')).setParseAction(make_dict) assessment_grammar = ( sep('assessment') + sep('=') + sep('{') + Each( Optional( key('assessmentName') + sep(':') + string + Optional(sep(','))) + Optional( key('preamble') + sep(':') + string + Optional(sep(','))) + Optional( key('checkAnswers') + sep(':') + boolean + Optional(sep(','))) + Optional( key('questionsList') + sep(':') + sep('[') + Group(list_of(question_decl)).setParseAction(make_list) + sep(']') + Optional(sep(','))) ) + sep('}') + Optional(sep(';'))).setParseAction(make_dict) @classmethod def parse_string(cls, content): return cls.assessment_grammar.parseString(content) @classmethod def parse_string_in_scope(cls, content, scope, root_name): """Parses assessment text following grammar.""" if 'assessment' != root_name: raise Exception('Unsupported schema: %s', root_name) # we need to extract the results as a dictionary; so we remove the # outer array holding it ast = cls.parse_string(content).asList() if len(ast) == 1: ast = ast[0] return dict( scope.items() + {'__builtins__': {}}.items() + {root_name: ast}.items()) class ActivityParser13(object): """Grammar and parser for the activity.""" variable = Word(alphas) integer = Word(nums).setParseAction(make_int) string = ( QuotedString('\'', escChar='\\', multiline=True) ^ QuotedString('"', escChar='\\', multiline=True)) boolean = ( Literal('true').setParseAction(make_bool(True)) ^ Literal('false').setParseAction(make_bool(False))) regex = ( Regex('/(.*)/i') ^ Combine( sep('regex(') + QuotedString('"', escChar='\\') + sep(')') ).setParseAction(lambda x: verify.Term(verify.REGEX, x[0])) ) choice_decl = Group( sep('[') + string + sep(',') + boolean + sep(',') + string + sep(']') ) choices_decl = Group( sep('[') + Optional(list_of(choice_decl)) + sep(']') ).setParseAction(make_list) multiple_choice_decl = ( key('questionType') + sep(':') + key('multiple choice') + Optional(sep(',')) ) multiple_choice = ( sep('{') + multiple_choice_decl + Each( Optional( key('questionHTML') + sep(':') + string + Optional(sep(','))) + Optional( key('choices') + sep(':') + choices_decl + Optional(sep(','))) ) + sep('}') ).setParseAction(make_dict) free_text_decl = ( key('questionType') + sep(':') + key('freetext') + Optional(sep(',')) ) free_text = ( sep('{') + free_text_decl + Each( Optional( key('questionHTML') + sep(':') + string + Optional(sep(','))) + Optional( key('correctAnswerRegex') + sep(':') + regex + Optional(sep(','))) + Optional( key('correctAnswerOutput') + sep(':') + string + Optional(sep(','))) + Optional( key('incorrectAnswerOutput') + sep(':') + string + Optional(sep(','))) + Optional( key('showAnswerPrompt') + sep(':') + string + Optional(sep(','))) + Optional( key('showAnswerOutput') + sep(':') + string + Optional(sep(','))) + Optional( key('outputHeight') + sep(':') + string + Optional(sep(','))) ) + sep('}') ).setParseAction(make_dict) question_list_decl = ( sep('{') + Each( Optional( key('questionHTML') + sep(':') + string + Optional(sep(','))) + Optional( key('choices') + sep(':') + sep('[') + Group(list_of(string)).setParseAction(make_list) + sep(']') + Optional(sep(','))) + Optional( key('correctIndex') + sep(':') + (integer ^ ( sep('[') + Group(list_of(integer)).setParseAction(make_list) + sep(']'))) + Optional(sep(','))) + Optional( key('multiSelect') + sep(':') + boolean + Optional(sep(','))), ) + sep('}')).setParseAction(make_dict) questions_list_decl = Group( sep('[') + Optional(list_of(question_list_decl)) + sep(']') ).setParseAction(make_list) multiple_choice_group_decl = ( key('questionType') + sep(':') + key('multiple choice group') + Optional(sep(',')) ) multiple_choice_group = ( sep('{') + multiple_choice_group_decl + Each( Optional( key('questionGroupHTML') + sep(':') + string + Optional(sep(','))) + Optional( key('allCorrectMinCount') + sep(':') + integer + Optional(sep(','))) + Optional( key('allCorrectOutput') + sep(':') + string + Optional(sep(','))) + Optional( key('someIncorrectOutput') + sep(':') + string + Optional(sep(','))) + Optional( key('questionsList') + sep(':') + questions_list_decl + Optional(sep(','))) ) + sep('}') ).setParseAction(make_dict) activity_grammar = ( sep('activity') + sep('=') + sep('[') + Optional(list_of( string ^ multiple_choice ^ free_text ^ multiple_choice_group)) + sep(']') + Optional(sep(';'))) @classmethod def parse_string(cls, content): return cls.activity_grammar.parseString(content) @classmethod def parse_string_in_scope(cls, content, scope, root_name): """Parses activity text following grammar.""" if 'activity' != root_name: raise Exception('Unsupported schema: %s', root_name) return dict( scope.items() + {'__builtins__': {}}.items() + {root_name: cls.parse_string(content).asList()}.items()) # here we register all the parser SUPPORTED_PARSERS = { 'activity': ActivityParser13, 'assessment': AssessmentParser13} def verify_activity(activity_text): """Parses and semantically verifies activity.""" activity = ActivityParser13.parse_string_in_scope( activity_text, verify.Activity().scope, 'activity') assert activity verifier = verify.Verifier() verifier.verify_activity_instance(activity, 'test') def verify_assessment(assessment_text): """Parses and semantically verifies assessment.""" assessment = AssessmentParser13.parse_string_in_scope( assessment_text, verify.Assessment().scope, 'assessment') assert assessment verifier = verify.Verifier() verifier.verify_assessment_instance(assessment, 'test') def parse_string_in_scope(content, scope, root_name): parser = SUPPORTED_PARSERS.get(root_name) if not parser: raise Exception('Unsupported schema: %s', root_name) return parser.parse_string_in_scope(content, scope, root_name) def test_activity_multiple_choice_group(): """Test activity parsing.""" activity_text = ( """activity = [ '<p>This is text.</p>', { questionType: 'multiple choice group', questionGroupHTML: '<p>This is text.</p>', allCorrectMinCount: 55, allCorrectOutput: '<p>This is text.</p>', someIncorrectOutput: '<p>This is text.</p>', questionsList: [ {questionHTML: '<p>This is text.</p>'}, {correctIndex: [1, 2, 3]}, {questionHTML: '<p>This is text.</p>', correctIndex: 0, multiSelect: false, choices: ['foo', 'bar'],}, ] }, { "questionType": 'multiple choice group', questionGroupHTML: '<p>This section will test you on colors and numbers.</p>', questionsList: [ {questionHTML: 'Pick all <i>odd</i> numbers:', choices: ['1', '2', '3', '4', '5'], correctIndex: [0, 2, 4]}, {questionHTML: 'Pick one <i>even</i> number:', choices: ['1', '2', '3', '4', '5'], correctIndex: [1, 3], multiSelect: false}, {questionHTML: 'What color is the sky?', choices: ['#00FF00', '#00FF00', '#0000FF'], correctIndex: 2} ], allCorrectMinCount: 2, allCorrectOutput: 'Great job! You know the material well.', someIncorrectOutput: 'You must answer at least two questions correctly.' } ]; """) verify_activity(activity_text) def test_activity_multiple_choice(): """Test activity parsing.""" activity_text = ( """activity = [ '<p>This is text.</p>', { questionType: 'multiple choice', questionHTML: '<p>This is text.</p>', choices: [ ['<p>This is text.</p>', false, '<p>This is text.</p>'], ['<p>This is text.</p>', true, '<p>This is text.</p>'], ] } ]; """) verify_activity(activity_text) def test_activity_free_text(): """Test activity parsing.""" activity_text = ( """activity = [ '<p>This is text.</p>', { 'questionType': 'freetext', questionHTML: '<p>This is text.</p>', showAnswerPrompt: '<p>This is text.</p>', showAnswerOutput: '<p>This is text.</p>', correctAnswerRegex: regex("/4|four/i"), correctAnswerOutput: '<p>This is text.</p>', incorrectAnswerOutput: '<p>This is text.</p>', }, { questionType: 'freetext', questionHTML: '<p>What color is the snow?</p>', correctAnswerRegex: regex("/white/i"), correctAnswerOutput: 'Correct!', incorrectAnswerOutput: 'Try again.', showAnswerOutput: 'Our search expert says: white!' }, ]; """) verify_activity(activity_text) def test_assessment(): """Test assessment parsing.""" # pylint: disable=anomalous-backslash-in-string assessment_text = ( """assessment = { assessmentName: '12345', preamble: '<p>This is text.</p>', checkAnswers: false, questionsList: [ {questionHTML: '<p>This is text.</p>', choices: ["A and B", "D and B", correct("A and C"), "C and D", "I don't know"] }, {questionHTML: '<p>This is text.</p>', choiceScores: [0, 0.5, 1.0], weight: 3, choices: [correct("True"), "False", "I don't know"] }, {questionHTML: '<p>This is text.</p>', correctAnswerString: 'sunrise', correctAnswerNumeric: 7.9 }, {questionHTML: '<p>This is text.</p>', correctAnswerNumeric: 7, correctAnswerRegex: regex("/354\s*[+]\s*651/") } ], }; """) # pylint: enable=anomalous-backslash-in-string verify_assessment(assessment_text) def test_activity_ast(): """Test a mix of various activities using legacy and new parser.""" activity_text = ( """activity = [ '<p>This is just some <i>HTML</i> text!</p>', { questionType: 'multiple choice', questionHTML: '<p>What letter am I thinking about now?</p>', choices: [ ['A', false, '"A" is wrong, try again.'], ['B', true, '"B" is correct!'], ['C', false, '"C" is wrong, try again.'], ['D', false, '"D" is wrong, try again.'] ] }, { questionType: 'freetext', questionHTML: '<p>What color is the snow?</p>', correctAnswerRegex: regex("/white/i"), correctAnswerOutput: 'Correct!', incorrectAnswerOutput: 'Try again.', showAnswerOutput: 'Our search expert says: white!' }, { questionType: 'multiple choice group', questionGroupHTML: '<p>This section will test you on colors and numbers.</p>', allCorrectMinCount: 2, questionsList: [ {questionHTML: 'Pick all <i>odd</i> numbers:', choices: ['1', '2', '3', '4', '5'], correctIndex: [0, 2, 4]}, {questionHTML: 'Pick one <i>even</i> number:', choices: ['1', '2', '3', '4', '5'], correctIndex: [1, 3], multiSelect: false}, {questionHTML: 'What color is the sky?', choices: ['#00FF00', '#00FF00', '#0000FF'], correctIndex: 2} ], allCorrectOutput: 'Great job! You know the material well.', someIncorrectOutput: 'You must answer at least two questions correctly.' } ]; """) verify_activity(activity_text) scope = verify.Activity().scope current_ast = ActivityParser13.parse_string_in_scope( activity_text, scope, 'activity') expected_ast = verify.legacy_eval_python_expression_for_test( activity_text, scope, 'activity') same = ( len(current_ast.get('activity')) == 4 and current_ast.get('activity') == expected_ast.get('activity') and current_ast == expected_ast) if not same: import pprint pprint.pprint(current_ast.get('activity')) pprint.pprint(expected_ast.get('activity')) assert same def test_assessment_ast(): """Test a mix of various activities using legacy and new parser.""" # pylint: disable=anomalous-backslash-in-string assessment_text = ( """assessment = { preamble: '<p>This is text.</p>', questionsList: [ {'questionHTML': '<p>This is text.</p>', choices: ["A and B", "D and B", correct("A and C"), "C and D", "I don't know"] }, {"questionHTML": '<p>This is text.</p>', choices: [correct("True"), "False", "I don't know"], choiceScores: [0, 0.5, 1.0], weight: 3 }, {questionHTML: '<p>This is text.</p>', correctAnswerString: 'sunrise' }, {questionHTML: '<p>This is text.</p>', correctAnswerRegex: regex("/354\s*[+]\s*651/") } ], assessmentName: 'Pre', checkAnswers: false } """) # pylint: enable=anomalous-backslash-in-string verify_assessment(assessment_text) scope = verify.Assessment().scope current_ast = AssessmentParser13.parse_string_in_scope( assessment_text, scope, 'assessment') expected_ast = verify.legacy_eval_python_expression_for_test( assessment_text, scope, 'assessment') same = ( len(current_ast.get('assessment')) == 4 and len(current_ast.get('assessment').get('questionsList')) == 4 and current_ast.get('assessment') == expected_ast.get('assessment') and current_ast == expected_ast) if not same: import pprint pprint.pprint(current_ast.get('assessment')) pprint.pprint(expected_ast.get('assessment')) assert same def test_list_of(): """Test delimited list.""" grammar = Optional( Literal('[') + Optional(list_of(Literal('a') ^ Literal('b'))) + Literal(']')) assert str(['[', ']']) == str(grammar.parseString('[]')) assert str(['[', 'a', ']']) == str(grammar.parseString('[a]')) assert str(['[', 'b', ']']) == str(grammar.parseString('[b]')) assert str(['[', 'a', ']']) == str(grammar.parseString('[a,]')) assert str(['[', 'b', ']']) == str(grammar.parseString('[b,]')) assert str(['[', 'a', 'a', 'a', 'a', ']']) == str( grammar.parseString('[a, a, a, a]')) assert str(['[', 'a', 'a', 'a', 'a', ']']) == str( grammar.parseString('[a,a,a,a]')) assert str(['[', 'a', 'a', 'a', 'a', ']']) == str( grammar.parseString('[a,a,a,a,]')) assert str(['[', 'a', 'b', 'a', 'b', ']']) == str( grammar.parseString('[a,b,a,b]')) assert str(['[', 'b', 'a', 'b', 'a', ']']) == str( grammar.parseString('[b,a,b,a]')) assert str(['[', 'b', 'b', 'b', 'b', ']']) == str( grammar.parseString('[b,b,b,b]')) assert not grammar.parseString('') assert not grammar.parseString('[c]') assert not grammar.parseString('[a,c,b]') def run_all_unit_tests(): """Run all unit tests.""" original = verify.parse_content try: verify.parse_content = parse_string_in_scope test_list_of() test_activity_multiple_choice() test_activity_free_text() test_activity_multiple_choice_group() test_activity_ast() test_assessment() test_assessment_ast() # test existing verifier using parsing instead of exec/compile verify.test_sample_assets() finally: verify.parse_content = original if __name__ == '__main__': run_all_unit_tests()
Python
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Classes supporting dynamically registering custom modules.""" __author__ = 'Pavel Simakov (psimakov@google.com)' class Module(object): """A class that holds module information.""" def __init__( self, name, desc, global_routes, namespaced_routes, notify_module_enabled=None, notify_module_disabled=None): self._name = name self._desc = desc self._global_routes = global_routes self._namespaced_routes = namespaced_routes self._notify_module_enabled = notify_module_enabled self._notify_module_disabled = ( notify_module_disabled or Module.module_disabling_is_deprecated) Registry.registered_modules[self._name] = self def disable(self): raise NotImplementedError('Disabling modules is not supported.') @staticmethod def module_disabling_is_deprecated(): raise NotImplementedError('Disabling modules is not supported.') def enable(self): Registry.enabled_module_names.add(self.name) if self._notify_module_enabled: self._notify_module_enabled() @property def enabled(self): return self.name in Registry.enabled_module_names @property def name(self): return self._name @property def desc(self): return self._desc @property def global_routes(self): if self.name in Registry.enabled_module_names: return self._global_routes else: return [] @property def namespaced_routes(self): if self.name in Registry.enabled_module_names: return self._namespaced_routes else: return [] class Registry(object): """A registry that holds all custom modules.""" registered_modules = {} enabled_module_names = set() @classmethod def get_all_routes(cls): global_routes = [] namespaced_routes = [] for registered_module in cls.registered_modules.values(): if registered_module.enabled: # Only populate the routing table with enabled modules. global_routes += registered_module.global_routes namespaced_routes += registered_module.namespaced_routes return global_routes, namespaced_routes
Python
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Analytics for extracting facts based on StudentAnswerEntity entries.""" __author__ = 'Mike Gainer (mgainer@google.com)' import collections import logging import courses from common import tags import models from tools import verify QuestionAnswerInfo = collections.namedtuple( 'QuestionAnswerInfo', ['unit_id', 'lesson_id', 'sequence', # 0-based index of the question within the lesson/assessment. 'question_id', # ID of the QuestionEntity to which this is an answer. 'question_type', # McQuestion, SaQuestion, etc. 'timestamp', # Timestamp from the event. 'answers', # The answer (or answers, if multiple-answer multiple-choice). 'score', # Unweighted score for the answer. 'weighted_score', # Score fully weighted by question instance in HTML # or question usage in group and assessment (if in # assessment) 'tallied', # Boolean: False for lessons where questions are not scored. ]) def _unpack_single_question_answer_1_5( info, types, score, assessment_weight, timestamp, answers, valid_question_ids): if info['id'] not in valid_question_ids: logging.info('Question with ID "%s" is no longer present; ' 'ignoring data for it.', info['id']) return [] weighted_score = score * info['weight'] * assessment_weight return [QuestionAnswerInfo( info['unit'], info['lesson'], info['sequence'], info['id'], types, timestamp, answers, score, weighted_score, tallied=True)] def _unpack_question_group_answer_1_5( info, types, scores, assessment_weight, timestamp, answers, usage_id, unit_responses, group_to_questions, valid_question_ids): # Sometimes the event contains enough information to get the # question IDs in the question group directly; this happens for # assessments. For graded lessons, we don't have that luxury, and # we need to (attempt to) rediscover the question IDs from # information gathered at map/reduce time. ret = [] seqs = [] q_ids = [] if info['id'] not in group_to_questions: logging.info( 'Question group with ID %s is referenced in an event, but ' 'is no longer present in the course. Ignoring the ' 'question group answer.', info['id']) return [] if usage_id in unit_responses: # Assessment events contain packed strings of the form # <question-usage-id-string>.<sequence#>.<QuestionEntity id> # keyed by the usage-ID string for the question group. # Unpack these into arrays for use below. packed_ids = unit_responses[usage_id].keys() packed_ids.sort(key=lambda packed: int(packed.split('.')[1])) for packed_id in packed_ids: _, seq, q_id = packed_id.split('.') seqs.append(seq) if q_id not in valid_question_ids: logging.info('Question with ID "%s" is no longer present; ' 'ignoring it and the question group containing ' 'it.', info['id']) return [] q_ids.append(q_id) else: for seq, q_info in enumerate(group_to_questions[info['id']]): seqs.append(seq) q_id = q_info['question'] if q_id not in valid_question_ids: logging.info('Question with ID "%s" is no longer present; ' 'ignoring it and the question group containing ' 'it.', info['id']) return [] q_ids.append(q_id) if (len(q_ids) != len(answers) or len(q_ids) != len(group_to_questions[info['id']])): logging.info( 'Question group usage "%s" in location "%s" has ' 'changed length since an older event was recorded; ' 'ignoring the unusable group answer.', usage_id, unit_responses.get('location', '')) return [] for q_id, seq, answer, q_type, q_score in zip( q_ids, seqs, answers, types, scores): # Here, we are guessing at the actual weight, since the # weight for each question is not supplied in the event. # We do, however, have the question ID, so if that question # is still part of the question group, we can use the current # weight value. # TODO(mgainer): When we get server-side grading, this mess # can finally get ripped out. weight_in_group = 1.0 for item in group_to_questions.get(info['id'], []): if item['question'] == q_id: weight_in_group = item['weight'] weighted_score = q_score * weight_in_group * assessment_weight ret.append(QuestionAnswerInfo( info['unit'], info['lesson'], info['sequence'] + int(seq), q_id, q_type, timestamp, answer, q_score, weighted_score, tallied=True)) return ret def unpack_student_answer_1_5(questions_info, valid_question_ids, assessment_weights, group_to_questions, unit_responses, timestamp): """Unpack JSON from event; convert to QuestionAnswerInfo objects. The JSON for events is unusually shaped; function regularizes it into plain-old-data objects. Also translates from question-usage ID to unit_id/lesson_id/question_id. (Note that this makes the reasonable assumption that a question will only be used once per lesson). Note that this function flattens question groups, unpacking everything as a single array of questions. Args: questions_info: A map from question usage ID to unit/lesson/question IDs. Generate this by calling get_questions_by_usage_id(). assessment_weights: Map from assessment ID to weight for that assessment. group_to_questions: Map from question group ID to list of dicts holding question ID as 'question' and weight as 'weight'. unit_responses: The user's responses. Obtain this by unpacking an event of type 'submit-assessment' and picking out the 'values' item, or an event of type 'attempt-lesson' and picking out 'answers'. timestamp: Timestamp from the event. Value is copied into the results, but not otherwise used. Returns: An array of QuestionAnswerInfo corresponding to the answers given by the student, as recorded in the submitted event. """ ret = [] contained_types = unit_responses['containedTypes'] for usage_id, answers in unit_responses['answers'].items(): if usage_id == 'version': # Found in graded assessments. continue if usage_id not in questions_info: logging.info('Question or question-group ID "%s" in event is ' 'no longer present', usage_id) continue # Skip items from no-longer-present questions. # Note: The variable names here are in plural, but for single # questions, 'types', 'score' and 'answers' contain just one # item. (whereas for question groups, these are all arrays) info = questions_info[usage_id] types = contained_types[usage_id] score = unit_responses['individualScores'][usage_id] unit_id = info['unit'] assessment_weight = assessment_weights.get(str(unit_id), 1.0) # Single question - give its answer. if types == 'McQuestion' or types == 'SaQuestion': ret.extend(_unpack_single_question_answer_1_5( info, types, score, assessment_weight, timestamp, answers, valid_question_ids)) # Question group. Fetch IDs of sub-questions, which are packed as # <group-usage-id>.<sequence>.<question-id>. # Order by <sequence>, which is 0-based within question-group. elif isinstance(types, list): ret.extend(_unpack_question_group_answer_1_5( info, types, score, assessment_weight, timestamp, answers, usage_id, unit_responses, group_to_questions, valid_question_ids)) return ret def unpack_check_answers( content, questions_info, valid_question_ids, assessment_weights, group_to_questions, timestamp): """Parse check-answers submissions for ungraded questions. The JSON for events is unusually shaped; function regularizes it into plain-old-data objects. Also translates from question-usage ID to unit_id/lesson_id/question_id. (Note that this makes the reasonable assumption that a question will only be used once per lesson). Note that this function flattens question groups, unpacking everything as a single array of questions. Args: content: The dict unpacked from a JSON string for an event with a source of 'tag-assessment'. questions_info: A map from question usage ID to unit/lesson/question IDs. Generate this by calling get_questions_by_usage_id(). assessment_weights: Map from assessment ID to weight for that assessment. group_to_questions: A map of group ID to dicts, as follows. Generate this by calling group_to_questions(), below. 'question' -> string containing question ID. 'weight' -> float representing the weight of that question in this group timestamp: Timestamp from the event. Value is copied into the results, but not otherwise used. Returns: An array of QuestionAnswerInfo corresponding to the answers given by the student, as recorded in the submitted event. """ qtype = content.get('type') usage_id = content['instanceid'] if usage_id not in questions_info: logging.info('Question or question-group ID "%s" in event is ' 'no longer present', usage_id) return [] info = questions_info[usage_id] assessment_weight = assessment_weights.get(info['unit'], 1.0) if qtype == 'SaQuestion' or qtype == 'McQuestion': if info['id'] not in valid_question_ids: logging.info('Question with ID "%s" is no longer present; ' 'ignoring data for it.', info['id']) return [] score = content.get('score', 0.0) weighted_score = score * info['weight'] * assessment_weight answers = [QuestionAnswerInfo( info['unit'], info['lesson'], info['sequence'], info['id'], qtype, timestamp, content['answer'], score, weighted_score, tallied=False)] elif qtype == 'QuestionGroup': values = content.get('answer') scores = content.get('individualScores') types = content.get('containedTypes') # Here, we have to hope that the length and order of questions within # a group has not changed since the event was recorded, as the events # do not record the question ID within the group. We just assume that # the index at the time the check-answer event was recorded is the # same as in the question group currently. # TODO(mgainer): When we get server-side grading, buff this up. group_id = questions_info[usage_id]['id'] if group_id not in group_to_questions: logging.info( 'Question group with ID %s is referenced in an event, but ' 'is no longer present in the course. Ignoring the unusable ' 'question group answer.', group_id) return [] q_infos = group_to_questions.get(group_id, []) if len(q_infos) != len(values): logging.info('Ignoring event for question group "%s": ' 'This group currently has length %d, ' 'but event has length %d.', usage_id, len(q_infos), len(values)) return [] answers = [] i = 0 for q_info, val, score, qtype in zip(q_infos, values, scores, types): weighted_score = score * q_info['weight'] * assessment_weight answers.append(QuestionAnswerInfo( info['unit'], info['lesson'], info['sequence'] + i, q_info['question'], qtype, timestamp, val, score, weighted_score, tallied=False)) i += 1 else: logging.warning('Not handling unknown question or group type "%s"', qtype) answers = [] return answers def _add_questions_from_html( questions_by_usage_id, unit_id, lesson_id, html, question_group_lengths): """Parse rich-text HTML and add questions found to map by ID.""" sequence_counter = 0 for component in tags.get_components_from_html(html): if component['cpt_name'] == 'question': questions_by_usage_id[component['instanceid']] = { 'unit': unit_id, 'lesson': lesson_id, 'sequence': sequence_counter, 'id': component['quid'], 'weight': float(component.get('weight', 1.0)), } sequence_counter += 1 elif component['cpt_name'] == 'question-group': questions_by_usage_id[component['instanceid']] = { 'unit': unit_id, 'lesson': lesson_id, 'sequence': sequence_counter, 'id': component['qgid'], } if component['qgid'] in question_group_lengths: sequence_counter += ( question_group_lengths[component['qgid']]) def get_questions_by_usage_id(app_context): """Build map: question-usage-ID to {question ID, unit ID, sequence}. When a question or question-group is mentioned on a CourseBuilder HTML page, it is identified by a unique opaque ID which indicates *that usage* of a particular question. Args: app_context: Normal context object giving namespace, etc. Returns: A map of precalculated facts to be made available to mapper workerbee instances. """ questions_by_usage_id = {} # To know a question's sequence number within an assessment, we need # to know how many questions a question group contains. question_group_lengths = {} for group in models.QuestionGroupDAO.get_all(): question_group_lengths[str(group.id)] = ( len(group.question_ids)) # Run through course. For each assessment, parse the HTML content # looking for questions and question groups. For each of those, # record the unit ID, use-of-item-on-page-instance-ID (a string # like 'RK3q5H2dS7So'), and the sequence on the page. Questions # count as one position. Question groups increase the sequence # count by the number of questions they contain. course = courses.Course(None, app_context) for unit in course.get_units(): _add_questions_from_html(questions_by_usage_id, unit.unit_id, None, unit.html_content, question_group_lengths) for lesson in course.get_lessons(unit.unit_id): _add_questions_from_html(questions_by_usage_id, unit.unit_id, lesson.lesson_id, lesson.objectives, question_group_lengths) return questions_by_usage_id def get_assessment_weights(app_context): ret = {} course = courses.Course(None, app_context) for unit in course.get_units(): if unit.type == verify.UNIT_TYPE_ASSESSMENT: ret[str(unit.unit_id)] = float(unit.weight) return ret def get_group_to_questions(): ret = {} for group in models.QuestionGroupDAO.get_all(): items = group.items for element in items: element['question'] = str(element['question']) element['weight'] = float(element['weight']) ret[str(group.id)] = items return ret def get_unscored_lesson_ids(app_context): ret = [] for lesson in courses.Course(None, app_context).get_lessons_for_all_units(): if not lesson.scored: ret.append(lesson.lesson_id) return ret def get_valid_question_ids(): ret = [] for question in models.QuestionDAO.get_all(): ret.append(str(question.id)) return ret
Python
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Review processor that is used for managing human-reviewed assessments.""" __author__ = [ 'sll@google.com (Sean Lip)', ] import entities import student_work import transforms from modules.review import domain # Indicates that a human-graded assessment is peer-graded. PEER_MATCHER = 'peer' # Allowed matchers. ALLOWED_MATCHERS = [PEER_MATCHER] class ReviewsProcessor(object): """A class that processes review arrangements.""" TYPE_IMPL_MAPPING = { PEER_MATCHER: None, } @classmethod def set_peer_matcher(cls, matcher): cls.TYPE_IMPL_MAPPING[PEER_MATCHER] = matcher def __init__(self, course): self._course = course def _get_course(self): return self._course def _get_impl(self, unit_id): unit = self._get_course().find_unit_by_id(unit_id) return self.TYPE_IMPL_MAPPING[unit.workflow.get_matcher()] def _get_review_step_keys_by(self, unit_id, reviewer_key): impl = self._get_impl(unit_id) return impl.get_review_step_keys_by(str(unit_id), reviewer_key) def _get_submission_and_review_step_keys(self, unit_id, reviewee_key): impl = self._get_impl(unit_id) return impl.get_submission_and_review_step_keys( str(unit_id), reviewee_key) def add_reviewer(self, unit_id, reviewee_key, reviewer_key): submission_key = student_work.Submission.get_key(unit_id, reviewee_key) impl = self._get_impl(unit_id) return impl.add_reviewer( str(unit_id), submission_key, reviewee_key, reviewer_key) def delete_reviewer(self, unit_id, review_step_key): impl = self._get_impl(unit_id) return impl.delete_reviewer(review_step_key) def get_new_review(self, unit_id, reviewer_key): impl = self._get_impl(unit_id) return impl.get_new_review(str(unit_id), reviewer_key) def get_review_steps_by(self, unit_id, reviewer_key): review_step_keys = self._get_review_step_keys_by(unit_id, reviewer_key) return self.get_review_steps_by_keys(unit_id, review_step_keys) def get_reviews_by_keys( self, unit_id, review_keys, handle_empty_keys=False): """Gets a list of reviews, given their review keys. If handle_empty_keys is True, then no error is thrown on supplied keys that are None; the elements in the result list corresponding to those keys simply return None. This usually arises when this method is called immediately after get_review_steps_by_keys(). Args: unit_id: string. Id of the unit to get the reviews for. review_keys: [db.Key of peer.ReviewStep]. May include None, if handle_empty_keys is True. handle_empty_keys: if True, the return value contains None for keys that are None. If False, the method throws if empty keys are supplied. Returns: List with the same number of elements as review_keys. It contains: - the JSON-decoded contents of the review corresponding to that review_key, or - None if either: - no review has been submitted for that review key, or - handle_empty_keys == True and the review_key is None. """ impl = self._get_impl(unit_id) reviews = [] if not handle_empty_keys: reviews = impl.get_reviews_by_keys(review_keys) else: nonempty_review_indices = [] nonempty_review_keys = [] for idx, review_key in enumerate(review_keys): if review_key is not None: nonempty_review_indices.append(idx) nonempty_review_keys.append(review_key) tmp_reviews = impl.get_reviews_by_keys(nonempty_review_keys) reviews = [None] * len(review_keys) for (i, idx) in enumerate(nonempty_review_indices): reviews[idx] = tmp_reviews[i] return [(transforms.loads(rev.contents) if rev else None) for rev in reviews] def get_review_steps_by_keys(self, unit_id, review_step_keys): impl = self._get_impl(unit_id) return impl.get_review_steps_by_keys(review_step_keys) def get_submission_and_review_steps(self, unit_id, reviewee_key): """Gets the submission and a list of review steps for a unit/reviewee. Note that review steps marked removed are included in the result set. Args: unit_id: string. Id of the unit to get the data for. reviewee_key: db.Key of models.models.Student. The student to get the data for. Returns: - None if no submission was found for the given unit_id, reviewee_key pair. - (Object, [peer.ReviewStep]) otherwise. The first element is the de-JSONified content of the reviewee's submission. The second element is a list of review steps for this submission, sorted by creation date. """ submission_and_review_step_keys = ( self._get_submission_and_review_step_keys(unit_id, reviewee_key)) if submission_and_review_step_keys is None: return None submission_contents = student_work.Submission.get_contents_by_key( submission_and_review_step_keys[0]) review_step_keys = submission_and_review_step_keys[1] sorted_review_steps = sorted( self.get_review_steps_by_keys(unit_id, review_step_keys), key=lambda r: r.create_date) return [submission_contents, sorted_review_steps] def does_submission_exist(self, unit_id, reviewee_key): submission_key = student_work.Submission.get_key(unit_id, reviewee_key) return bool(entities.get(submission_key)) def start_review_process_for(self, unit_id, submission_key, reviewee_key): impl = self._get_impl(unit_id) return impl.start_review_process_for( str(unit_id), submission_key, reviewee_key) def write_review( self, unit_id, review_step_key, review_payload, mark_completed): impl = self._get_impl(unit_id) return impl.write_review( review_step_key, transforms.dumps(review_payload), mark_completed=mark_completed) class ReviewUtils(object): """A utility class for processing data relating to assessment reviews.""" @classmethod def count_completed_reviews(cls, review_steps): """Counts the number of completed reviews in the given set.""" count = 0 for review_step in review_steps: if review_step.state == domain.REVIEW_STATE_COMPLETED: count += 1 return count @classmethod def has_completed_all_assigned_reviews(cls, review_steps): """Returns whether the student has completed all assigned reviews.""" for review_step in review_steps: if review_step.state != domain.REVIEW_STATE_COMPLETED: return False return True @classmethod def has_completed_enough_reviews(cls, reviews, review_min_count): """Checks whether the review count is at least the minimum required.""" return cls.count_completed_reviews(reviews) >= review_min_count @classmethod def get_review_progress( cls, review_steps, review_min_count, progress_tracker): """Gets the progress value based on the number of reviews done. Args: review_steps: a list of ReviewStep objects. review_min_count: the minimum number of reviews that the student is required to complete for this assessment. progress_tracker: the course progress tracker. Returns: the corresponding progress value: 0 (not started), 1 (in progress) or 2 (completed). """ completed_reviews = cls.count_completed_reviews(review_steps) if cls.has_completed_enough_reviews(review_steps, review_min_count): return progress_tracker.COMPLETED_STATE elif completed_reviews > 0: return progress_tracker.IN_PROGRESS_STATE else: return progress_tracker.NOT_STARTED_STATE
Python
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Virtual file system for managing files locally or in the cloud.""" __author__ = 'Pavel Simakov (psimakov@google.com)' import datetime import os import re import sys import threading import unittest from config import ConfigProperty from counters import PerfCounter from entities import BaseEntity from entities import put as entities_put import jinja2 from common import caching from common import jinja_utils from google.appengine.api import namespace_manager from google.appengine.ext import db # all caches must have limits MAX_GLOBAL_CACHE_SIZE_BYTES = 16 * 1024 * 1024 # max size of each item; no point in storing images for example MAX_GLOBAL_CACHE_ITEM_SIZE_BYTES = 256 * 1024 # The maximum number of bytes stored per VFS cache shard. _MAX_VFS_SHARD_SIZE = 1000 * 1000 # Max number of shards for a single VFS cached file. _MAX_VFS_NUM_SHARDS = 4 # Global memcache controls. CAN_USE_VFS_IN_PROCESS_CACHE = ConfigProperty( 'gcb_can_use_vfs_in_process_cache', bool, ( 'Whether or not to cache content objects. For production this value ' 'should be on to enable maximum performance. For development this ' 'value should be off so you can see your changes to course content ' 'instantaneously.'), default_value=True) class AbstractFileSystem(object): """A generic file system interface that forwards to an implementation.""" def __init__(self, impl): self._impl = impl self._readonly = False @property def impl(self): return self._impl @classmethod def normpath(cls, path): """Make Windows and Linux filenames to have the same separator '/'.""" # Replace '\' into '/' and force Unicode. if not path: return path return u'' + path.replace('\\', '/') def begin_readonly(self): """Activates caching of resources and prevents mutations.""" self._assert_not_readonly() self._readonly = True def end_readonly(self): """Deactivates caching of resources and enables mutations.""" if not self._readonly: raise Exception('Not readonly.') self._readonly = False @property def is_readonly(self): return self._readonly def _assert_not_readonly(self): if self._readonly: raise Exception( 'Unable to execute requested operation while readonly.') def isfile(self, filename): """Checks if file exists, similar to os.path.isfile(...).""" return self._impl.isfile(filename) def open(self, filename): """Returns a stream with the file content, similar to open(...).""" return self._impl.get(filename) def get(self, filename): """Returns bytes with the file content, but no metadata.""" return self.open(filename).read() def put(self, filename, stream, **kwargs): """Replaces the contents of the file with the bytes in the stream.""" self._assert_not_readonly() self._impl.put(filename, stream, **kwargs) def delete(self, filename): """Deletes a file and metadata associated with it.""" self._assert_not_readonly() self._impl.delete(filename) def list(self, dir_name, include_inherited=False): """Lists all files in a directory.""" return self._impl.list(dir_name, include_inherited) def get_jinja_environ(self, dir_names, autoescape=True): """Configures jinja environment loaders for this file system.""" return self._impl.get_jinja_environ(dir_names, autoescape=autoescape) def is_read_write(self): return self._impl.is_read_write() def is_draft(self, stream): if not hasattr(stream, 'metadata'): return False if not stream.metadata: return False return stream.metadata.is_draft class LocalReadOnlyFileSystem(object): """A read-only file system serving only local files.""" def __init__(self, logical_home_folder=None, physical_home_folder=None): """Creates a new instance of the disk-backed read-only file system. Args: logical_home_folder: A logical home dir of all files (/a/b/c/...). physical_home_folder: A physical location on the file system (/x/y). Returns: A new instance of the object. """ self._logical_home_folder = AbstractFileSystem.normpath( logical_home_folder) self._physical_home_folder = AbstractFileSystem.normpath( physical_home_folder) def _logical_to_physical(self, filename): filename = AbstractFileSystem.normpath(filename) if not (self._logical_home_folder and self._physical_home_folder): return filename filename = os.path.join( self._physical_home_folder, os.path.relpath(filename, self._logical_home_folder)) return AbstractFileSystem.normpath(filename) def _physical_to_logical(self, filename): filename = AbstractFileSystem.normpath(filename) if not (self._logical_home_folder and self._physical_home_folder): return filename filename = os.path.join( self._logical_home_folder, os.path.relpath(filename, self._physical_home_folder)) return AbstractFileSystem.normpath(filename) def isfile(self, filename): return os.path.isfile(self._logical_to_physical(filename)) def get(self, filename): if not self.isfile(filename): return None return open(self._logical_to_physical(filename), 'rb') def put(self, unused_filename, unused_stream): raise Exception('Not implemented.') def delete(self, unused_filename): raise Exception('Not implemented.') # Need argument to be named exactly 'include_inherited' to match # keyword-parameter names from derived/related classes. # pylint: disable=unused-argument def list(self, root_dir, include_inherited=False): """Lists all files in a directory.""" files = [] for dirname, unused_dirnames, filenames in os.walk( self._logical_to_physical(root_dir)): for filename in filenames: files.append( self._physical_to_logical(os.path.join(dirname, filename))) return sorted(files) def get_jinja_environ(self, dir_names, autoescape=True): """Configure the environment for Jinja templates.""" physical_dir_names = [] for dir_name in dir_names: physical_dir_names.append(self._logical_to_physical(dir_name)) return jinja_utils.create_jinja_environment( loader=jinja2.FileSystemLoader(physical_dir_names), autoescape=autoescape) def is_read_write(self): return False class FileMetadataEntity(BaseEntity): """An entity to represent a file metadata; absolute file name is a key.""" # TODO(psimakov): do we need 'version' to support concurrent updates # TODO(psimakov): can we put 'data' here and still have fast isfile/list? created_on = db.DateTimeProperty(auto_now_add=True, indexed=False) updated_on = db.DateTimeProperty(indexed=True) # Draft file is just as any other file. It's up to the consumer of the file # to decide whether to treat draft differently (not to serve it to the # public, for example). This class does not care and just stores the bit. is_draft = db.BooleanProperty(indexed=False) size = db.IntegerProperty(indexed=False) class FileDataEntity(BaseEntity): """An entity to represent file content; absolute file name is a key.""" data = db.BlobProperty() class FileStreamWrapped(object): """A class that wraps a file stream, but adds extra attributes to it.""" def __init__(self, metadata, data): self._metadata = metadata self._data = data def read(self): """Emulates stream.read(). Returns all bytes and emulates EOF.""" data = self._data self._data = '' return data @property def metadata(self): return self._metadata class StringStream(object): """A wrapper to pose a string as a UTF-8 byte stream.""" def __init__(self, text): self._data = unicode.encode(text, 'utf-8') def read(self): """Emulates stream.read(). Returns all bytes and emulates EOF.""" data = self._data self._data = '' return data def string_to_stream(text): return StringStream(text) def stream_to_string(stream): return stream.read().decode('utf-8') class VirtualFileSystemTemplateLoader(jinja2.BaseLoader): """Loader of jinja2 templates from a virtual file system.""" def __init__(self, fs, logical_home_folder, dir_names): self._fs = fs self._logical_home_folder = AbstractFileSystem.normpath( logical_home_folder) self._dir_names = [] if dir_names: for dir_name in dir_names: self._dir_names.append(AbstractFileSystem.normpath(dir_name)) def get_source(self, unused_environment, template): for dir_name in self._dir_names: filename = AbstractFileSystem.normpath( os.path.join(dir_name, template)) stream = self._fs.open(filename) if stream: return stream.read().decode('utf-8'), filename, True raise jinja2.TemplateNotFound(template) def list_templates(self): all_templates = [] for dir_name in self._dir_names: all_templates += self._fs.list(dir_name) return all_templates class ProcessScopedVfsCache(caching.ProcessScopedSingleton): """This class holds in-process global cache of VFS objects.""" @classmethod def get_vfs_cache_len(cls): # pylint: disable=protected-access return len(ProcessScopedVfsCache.instance()._cache.items.keys()) @classmethod def get_vfs_cache_size(cls): # pylint: disable=protected-access return ProcessScopedVfsCache.instance()._cache.total_size def __init__(self): self._cache = caching.LRUCache( max_size_bytes=MAX_GLOBAL_CACHE_SIZE_BYTES, max_item_size_bytes=MAX_GLOBAL_CACHE_ITEM_SIZE_BYTES) self._cache.get_entry_size = self._get_entry_size def _get_entry_size(self, key, value): return sys.getsizeof(key) + value.getsizeof() if value else 0 @property def cache(self): return self._cache VFS_CACHE_LEN = PerfCounter( 'gcb-models-VfsCacheConnection-cache-len', 'A total number of items in vfs cache.') VFS_CACHE_SIZE_BYTES = PerfCounter( 'gcb-models-VfsCacheConnection-cache-bytes', 'A total size of items in vfs cache in bytes.') VFS_CACHE_LEN.poll_value = ProcessScopedVfsCache.get_vfs_cache_len VFS_CACHE_SIZE_BYTES.poll_value = ProcessScopedVfsCache.get_vfs_cache_size class CacheFileEntry(caching.AbstractCacheEntry): """Cache entry representing a file.""" def __init__(self, filename, metadata, body): self.filename = filename self.metadata = metadata self.body = body self.created_on = datetime.datetime.utcnow() def getsizeof(self): return ( sys.getsizeof(self.filename) + sys.getsizeof(self.metadata) + sys.getsizeof(self.body) + sys.getsizeof(self.created_on)) def is_up_to_date(self, key, update): metadata = update if not self.metadata and not metadata: return True if self.metadata and metadata: return ( metadata.updated_on == self.metadata.updated_on and metadata.is_draft == self.metadata.is_draft) return False def updated_on(self): return self.metadata.updated_on @classmethod def externalize(cls, key, entry): return FileStreamWrapped(entry.metadata, entry.body) @classmethod def internalize(cls, key, metadata, data): if metadata and data: return CacheFileEntry(key, metadata, data) return None class VfsCacheConnection(caching.AbstractCacheConnection): PERSISTENT_ENTITY = FileMetadataEntity CACHE_ENTRY = CacheFileEntry @classmethod def init_counters(cls): super(VfsCacheConnection, cls).init_counters() cls.CACHE_NO_METADATA = PerfCounter( 'gcb-models-VfsCacheConnection-cache-no-metadata', 'A number of times an object was requested, but was not found and ' 'had no metadata.') cls.CACHE_INHERITED = PerfCounter( 'gcb-models-VfsCacheConnection-cache-inherited', 'A number of times an object was obtained from the inherited vfs.') @classmethod def is_enabled(cls): return CAN_USE_VFS_IN_PROCESS_CACHE.value def __init__(self, namespace): super(VfsCacheConnection, self).__init__(namespace) self.cache = ProcessScopedVfsCache.instance().cache VfsCacheConnection.init_counters() class DatastoreBackedFileSystem(object): """A read-write file system backed by a datastore.""" @classmethod def make_key(cls, filename): return 'vfs:dsbfs:%s' % filename def __init__( self, ns, logical_home_folder, inherits_from=None, inheritable_folders=None): """Creates a new instance of the datastore-backed file system. Args: ns: A datastore namespace to use for storing all data and metadata. logical_home_folder: A logical home dir of all files (/a/b/c/...). inherits_from: A file system to use for the inheritance. inheritable_folders: A list of folders that support inheritance. Returns: A new instance of the object. Raises: Exception: if invalid inherits_from is given. """ if inherits_from and not isinstance( inherits_from, LocalReadOnlyFileSystem): raise Exception('Can only inherit from LocalReadOnlyFileSystem.') self._ns = ns self._logical_home_folder = AbstractFileSystem.normpath( logical_home_folder) self._inherits_from = inherits_from self._inheritable_folders = [] self._cache = threading.local() if inheritable_folders: for folder in inheritable_folders: self._inheritable_folders.append(AbstractFileSystem.normpath( folder)) def __getstate__(self): """Remove transient members that can't survive pickling.""" # TODO(psimakov): we need to properly pickle app_context so vfs is not # being serialized at all state = self.__dict__.copy() if '_cache' in state: del state['_cache'] return state def __setstate__(self, state_dict): """Set persistent members and re-initialize transient members.""" self.__dict__ = state_dict self._cache = threading.local() def __getattribute__(self, name): attr = object.__getattribute__(self, name) # Don't intercept access to private methods and attributes. if name.startswith('_'): return attr # Do intercept all methods. if hasattr(attr, '__call__'): def newfunc(*args, **kwargs): """Set proper namespace for each method call.""" old_namespace = namespace_manager.get_namespace() try: namespace_manager.set_namespace(self._ns) if not hasattr(self._cache, 'connection'): self._cache.connection = ( VfsCacheConnection.new_connection(self.ns)) return attr(*args, **kwargs) finally: namespace_manager.set_namespace(old_namespace) return newfunc # Don't intercept access to non-method attributes. return attr @property def ns(self): return self._ns @property def cache(self): return self._cache.connection def _logical_to_physical(self, filename): filename = AbstractFileSystem.normpath(filename) # For now we only support '/' as a physical folder name. if self._logical_home_folder == '/': return filename if not filename.startswith(self._logical_home_folder): raise Exception( 'Expected path \'%s\' to start with a prefix \'%s\'.' % ( filename, self._logical_home_folder)) rel_path = filename[len(self._logical_home_folder):] if not rel_path.startswith('/'): rel_path = '/%s' % rel_path return rel_path def physical_to_logical(self, filename): """Converts an internal filename to and external filename.""" # This class receives and stores absolute file names. The logical # filename is the external file name. The physical filename is an # internal filename. This function does the convertions. # Let's say you want to store a file named '/assets/img/foo.png'. # This would be a physical filename in the VFS. But the put() operation # expects an absolute filename from the root of the app installation, # i.e. something like '/dev/apps/coursebuilder/assets/img/foo.png', # which is called a logical filename. This is a legacy expectation from # the days the course was defined as files on the file system. # # This function will do the conversion you need. return self._physical_to_logical(filename) def _physical_to_logical(self, filename): filename = AbstractFileSystem.normpath(filename) # For now we only support '/' as a physical folder name. if filename and not filename.startswith('/'): filename = '/' + filename if self._logical_home_folder == '/': return filename return '%s%s' % (self._logical_home_folder, filename) def _can_inherit(self, filename): """Checks if a file can be inherited from a parent file system.""" for prefix in self._inheritable_folders: if filename.startswith(prefix): return True return False def get(self, afilename): return self.open(afilename) def open(self, afilename): """Gets a file from a datastore. Raw bytes stream, no encodings.""" filename = self._logical_to_physical(afilename) found, stream = self.cache.get(filename) if found and stream: return stream if not found: metadata = FileMetadataEntity.get_by_key_name(filename) if metadata: keys = self._generate_file_key_names(filename, metadata.size) data_shards = [] for data_entity in FileDataEntity.get_by_key_name(keys): data_shards.append(data_entity.data) data = ''.join(data_shards) if data: # TODO: Note that this will ask the cache to accept # potentially very large items. The caching strategy both # for in-memory and Memcache should be revisited to # determine how best to address chunking strategies. self.cache.put(filename, metadata, data) return FileStreamWrapped(metadata, data) # lets us cache the (None, None) so next time we asked for this key # we fall right into the inherited section without trying to load # the metadata/data from the datastore; if a new object with this # key is added in the datastore, we will see it in the update list VfsCacheConnection.CACHE_NO_METADATA.inc() self.cache.put(filename, None, None) result = None if self._inherits_from and self._can_inherit(filename): result = self._inherits_from.get(afilename) if result: VfsCacheConnection.CACHE_INHERITED.inc() return FileStreamWrapped(None, result.read()) VfsCacheConnection.CACHE_NOT_FOUND.inc() return None def put(self, filename, stream, is_draft=False, metadata_only=False): """Puts a file stream to a database. Raw bytes stream, no encodings.""" if stream: # Must be outside the transactional operation content = stream.read() else: content = stream self._transactional_put(filename, content, is_draft, metadata_only) @db.transactional(xg=True) def _transactional_put( self, filename, stream, is_draft=False, metadata_only=False): self.non_transactional_put( filename, stream, is_draft=is_draft, metadata_only=metadata_only) @classmethod def _generate_file_key_names(cls, filename, size): """Generate names for key(s) for DB entities holding file data. Files may be larger than 1M, the AppEngine limit. To work around that, just store more entities. Names of additional entities beyond the first are of the form "<filename>:shard:<number>". This naming scheme is "in-band", in the sense that it is possible that a user could try to name a file with this format. However, that format is unusual enough that prohibiting it in incoming file names is both simple and very unlikely to cause users undue distress. Args: filename: The base name of the file. size: The size of the file, in bytes. Returns: A list of database entity keys. Files smaller than _MAX_VFS_SHARD_SIZE are stored in one entity named by the 'filename' parameter. If larger, sufficient additional names of the form <filename>/0, <filename>/1, ..... <filename>/N are added. """ if re.search(':shard:[0-9]+$', filename): raise ValueError( 'Files may not end with ":shard:NNN"; this pattern is ' 'reserved for internal use. Filename "%s" violates this. ' % filename) if size > _MAX_VFS_SHARD_SIZE * _MAX_VFS_NUM_SHARDS: raise ValueError( 'Cannot store file "%s"; its size of %d bytes is larger than ' 'the maximum supported size of %d.' % ( filename, size, _MAX_VFS_SHARD_SIZE * _MAX_VFS_NUM_SHARDS)) key_names = [filename] for segment_id in range(size // _MAX_VFS_SHARD_SIZE): key_names.append('%s:shard:%d' % (filename, segment_id)) return key_names def non_transactional_put( self, filename, content, is_draft=False, metadata_only=False): """Non-transactional put; use only when transactions are impossible.""" filename = self._logical_to_physical(filename) metadata = FileMetadataEntity.get_by_key_name(filename) if not metadata: metadata = FileMetadataEntity(key_name=filename) metadata.updated_on = datetime.datetime.utcnow() metadata.is_draft = is_draft if not metadata_only: # We operate with raw bytes. The consumer must deal with encoding. metadata.size = len(content) # Chunk the data into entites based on max entity size limits # imposed by AppEngine key_names = self._generate_file_key_names(filename, metadata.size) shard_entities = [] for index, key_name in enumerate(key_names): data = FileDataEntity(key_name=key_name) start_offset = index * _MAX_VFS_SHARD_SIZE end_offset = (index + 1) * _MAX_VFS_SHARD_SIZE data.data = content[start_offset:end_offset] shard_entities.append(data) entities_put(shard_entities) metadata.put() self.cache.delete(filename) def put_multi_async(self, filedata_list): """Initiate an async put of the given files. This method initiates an asynchronous put of a list of file data (presented as pairs of the form (filename, data_source)). It is not transactional, and does not block, and instead immediately returns a callback function. When this function is called it will block until the puts are confirmed to have completed. For maximum efficiency it's advisable to defer calling the callback until all other request handling has completed, but in any event, it MUST be called before the request handler can exit successfully. Args: filedata_list: list. A list of tuples. The first entry of each tuple is the file name, the second is a filelike object holding the file data. Returns: callable. Returns a wait-and-finalize function. This function must be called at some point before the request handler exists, in order to confirm that the puts have succeeded. """ filename_list = [] data_list = [] metadata_list = [] for filename, stream in filedata_list: filename = self._logical_to_physical(filename) filename_list.append(filename) metadata = FileMetadataEntity.get_by_key_name(filename) if not metadata: metadata = FileMetadataEntity(key_name=filename) metadata_list.append(metadata) metadata.updated_on = datetime.datetime.utcnow() # We operate with raw bytes. The consumer must deal with encoding. raw_bytes = stream.read() metadata.size = len(raw_bytes) data = FileDataEntity(key_name=filename) data_list.append(data) data.data = raw_bytes # we do call delete here; so this instance will not increment EVICT # counter value, but the DELETE value; other instance will not # record DELETE, but EVICT when they query for updates self.cache.delete(filename) data_future = db.put_async(data_list) metadata_future = db.put_async(metadata_list) def wait_and_finalize(): data_future.check_success() metadata_future.check_success() return wait_and_finalize @db.transactional(xg=True) def delete(self, filename): filename = self._logical_to_physical(filename) metadata = FileMetadataEntity.get_by_key_name(filename) if metadata: metadata.delete() data = FileDataEntity(key_name=filename) if data: data.delete() self.cache.delete(filename) def isfile(self, afilename): """Checks file existence by looking up the datastore row.""" filename = self._logical_to_physical(afilename) metadata = FileMetadataEntity.get_by_key_name(filename) if metadata: return True result = False if self._inherits_from and self._can_inherit(filename): result = self._inherits_from.isfile(afilename) return result def list(self, dir_name, include_inherited=False): """Lists all files in a directory by using datastore query. Args: dir_name: string. Directory to list contents of. include_inherited: boolean. If True, includes all inheritable files from the parent filesystem. Returns: List of string. Lexicographically-sorted unique filenames recursively found in dir_name. """ dir_name = self._logical_to_physical(dir_name) result = set() keys = FileMetadataEntity.all(keys_only=True) for key in keys.fetch(1000): filename = key.name() if filename.startswith(dir_name): result.add(self._physical_to_logical(filename)) if include_inherited and self._inherits_from: for inheritable_folder in self._inheritable_folders: logical_folder = self._physical_to_logical(inheritable_folder) result.update(set(self._inherits_from.list( logical_folder, include_inherited))) return sorted(list(result)) def get_jinja_environ(self, dir_names, autoescape=True): return jinja_utils.create_jinja_environment( loader=VirtualFileSystemTemplateLoader( self, self._logical_home_folder, dir_names), autoescape=autoescape) def is_read_write(self): return True class VfsTests(unittest.TestCase): def test_pickling(self): import pickle pickle.dumps(caching.NoopCacheConnection()) pickle.dumps(caching.AbstractCacheConnection(None)) pickle.dumps(caching.AbstractCacheEntry()) pickle.dumps(CacheFileEntry('foo.bar', 'file metadata', 'file data')) pickle.dumps(DatastoreBackedFileSystem('/', 'ns_test')) with self.assertRaises(TypeError): pickle.dumps(VfsCacheConnection('ns_test')) def _setup_cache_with_one_entry(self, is_draft=True, updated_on=None): ProcessScopedVfsCache.clear_all() conn = VfsCacheConnection('ns_test') meta = FileMetadataEntity() meta.is_draft = is_draft meta.updated_on = updated_on conn.put('sample.txt', meta, 'file data') found, stream = conn.get('sample.txt') self.assertTrue(found) self.assertEquals(stream.metadata.is_draft, meta.is_draft) return conn def test_expire(self): conn = self._setup_cache_with_one_entry() entry = conn.cache.items.get(conn.make_key('ns_test', 'sample.txt')) self.assertTrue(entry) entry.created_on = datetime.datetime.utcnow() - datetime.timedelta( 0, CacheFileEntry.CACHE_ENTRY_TTL_SEC + 1) old_expire_count = VfsCacheConnection.CACHE_EXPIRE.value found, stream = conn.get('sample.txt') self.assertFalse(found) self.assertEquals(stream, None) self.assertEquals( VfsCacheConnection.CACHE_EXPIRE.value - old_expire_count, 1) def test_updates_with_no_changes_dont_evict(self): class _Key(object): def name(self): return 'sample.txt' def _key(): return _Key() for is_draft, updated_on in [ (True, None), (True, datetime.datetime.utcnow()), (False, None), (False, datetime.datetime.utcnow())]: conn = self._setup_cache_with_one_entry( is_draft=is_draft, updated_on=updated_on) _, stream = conn.get('sample.txt') meta = FileMetadataEntity() meta.key = _key meta.is_draft = stream.metadata.is_draft meta.updated_on = stream.metadata.updated_on updates = {'sample.txt': meta} old_expire_count = VfsCacheConnection.CACHE_EVICT.value conn.apply_updates(updates) found, _ = conn.get('sample.txt') self.assertTrue(found) self.assertEquals( VfsCacheConnection.CACHE_EVICT.value - old_expire_count, 0) def test_empty_updates_dont_evict(self): conn = self._setup_cache_with_one_entry() updates = {} old_expire_count = VfsCacheConnection.CACHE_EVICT.value conn.apply_updates(updates) found, _ = conn.get('sample.txt') self.assertTrue(found) self.assertEquals( VfsCacheConnection.CACHE_EVICT.value - old_expire_count, 0) def test_updates_with_changes_do_evict(self): class _Key(object): def name(self): return 'sample.txt' def _key(): return _Key() def set_is_draft(meta, value): meta.is_draft = value def set_updated_on(meta, value): meta.updated_on = value conn = self._setup_cache_with_one_entry() mutations = [ (lambda meta: set_is_draft(meta, False)), (lambda meta: set_updated_on(meta, datetime.datetime.utcnow()))] for mutation in mutations: meta = FileMetadataEntity() meta.key = _key mutation(meta) updates = {'sample.txt': meta} conn.apply_updates(updates) found, _ = conn.get('sample.txt') self.assertFalse(found) def test_apply_updates_expires_entries(self): conn = self._setup_cache_with_one_entry() entry = conn.cache.items.get(conn.make_key('ns_test', 'sample.txt')) self.assertTrue(entry) entry.created_on = datetime.datetime.utcnow() - datetime.timedelta( 0, CacheFileEntry.CACHE_ENTRY_TTL_SEC + 1) updates = {} conn.apply_updates(updates) old_expire_count = VfsCacheConnection.CACHE_EXPIRE.value found, stream = conn.get('sample.txt') self.assertFalse(found) self.assertEquals(stream, None) self.assertEquals( VfsCacheConnection.CACHE_EXPIRE.value - old_expire_count, 1) def test_no_metadata_and_no_data_is_evicted(self): ProcessScopedVfsCache.clear_all() conn = VfsCacheConnection('ns_test') conn.put('sample.txt', None, None) meta = FileMetadataEntity() meta.key = 'sample/txt' updates = {'sample.txt': meta} conn.apply_updates(updates) found, stream = conn.get('sample.txt') self.assertFalse(found) self.assertEquals(stream, None) def test_metadata_but_no_data_is_evicted(self): ProcessScopedVfsCache.clear_all() conn = VfsCacheConnection('ns_test') meta = FileMetadataEntity() meta.is_draft = True meta.updated_on = datetime.datetime.utcnow() conn.put('sample.txt', meta, None) meta = FileMetadataEntity() meta.key = 'sample/txt' updates = {'sample.txt': meta} conn.apply_updates(updates) found, stream = conn.get('sample.txt') self.assertFalse(found) self.assertEquals(stream, None) def run_all_unit_tests(): """Runs all unit tests in this module.""" suites_list = [] for test_class in [VfsTests]: suite = unittest.TestLoader().loadTestsFromTestCase(test_class) suites_list.append(suite) result = unittest.TextTestRunner().run(unittest.TestSuite(suites_list)) if not result.wasSuccessful() or result.errors: raise Exception(result) if __name__ == '__main__': run_all_unit_tests()
Python
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Student progress trackers.""" __author__ = 'Sean Lip (sll@google.com)' import datetime import logging import os from collections import defaultdict import courses import transforms from common import utils from models import QuestionDAO from models import QuestionGroupDAO from models import StudentPropertyEntity from tools import verify # Names of component tags that are tracked for progress calculations. TRACKABLE_COMPONENTS = [ 'question', 'question-group', ] class UnitLessonCompletionTracker(object): """Tracks student completion for a unit/lesson-based linear course.""" PROPERTY_KEY = 'linear-course-completion' # Here are representative examples of the keys for the various entities # used in this class: # Unit 1: u.1 # Unit 1, Lesson 1: u.1.l.1 # Unit 1, Lesson 1, Activity 0: u.1.l.1.a.0 # Unit 1, Lesson 1, Activity 0, Block 4: u.1.l.1.a.0.b.4 # Assessment 'Pre': s.Pre # At the moment, we do not divide assessments into blocks. # # The following keys were added in v1.5: # Unit 1, Lesson 1, HTML: u.1.l.1.h.0 # Unit 1, Lesson 1, HTML, Component with instanceid id: u.1.l.1.h.0.c.id # # The number after the 'h' and 'a' codes is always zero, since a lesson may # have at most one HTML body and one activity. # # IMPORTANT NOTE: The values of the keys mean different things depending on # whether the entity is a composite entity or not. # If it is a composite entity (unit, lesson, activity), then the value is # - 0 if none of its sub-entities has been completed # - 1 if some, but not all, of its sub-entities have been completed # - 2 if all its sub-entities have been completed. # If it is not a composite entity (i.e. block, assessment, component), then # the value is just the number of times the event has been triggered. # Constants for recording the state of composite entities. # TODO(sll): Change these to enums. NOT_STARTED_STATE = 0 IN_PROGRESS_STATE = 1 COMPLETED_STATE = 2 MULTIPLE_CHOICE = 'multiple choice' MULTIPLE_CHOICE_GROUP = 'multiple choice group' QUESTION_GROUP = 'question-group' QUESTION = 'question' EVENT_CODE_MAPPING = { 'course': 'r', 'course_forced': 'r', 'unit': 'u', 'unit_forced': 'u', 'lesson': 'l', 'activity': 'a', 'html': 'h', 'block': 'b', 'assessment': 's', 'component': 'c', 'custom_unit': 'x' } COMPOSITE_ENTITIES = [ EVENT_CODE_MAPPING['course'], EVENT_CODE_MAPPING['unit'], EVENT_CODE_MAPPING['lesson'], EVENT_CODE_MAPPING['activity'], EVENT_CODE_MAPPING['html'], EVENT_CODE_MAPPING['custom_unit'] ] POST_UPDATE_PROGRESS_HOOK = [] def __init__(self, course): self._course = course def _get_course(self): return self._course def get_activity_as_python(self, unit_id, lesson_id): """Gets the corresponding activity as a Python object.""" root_name = 'activity' course = self._get_course() activity_text = course.app_context.fs.get( os.path.join(course.app_context.get_home(), course.get_activity_filename(unit_id, lesson_id))) content, noverify_text = verify.convert_javascript_to_python( activity_text, root_name) activity = verify.evaluate_python_expression_from_text( content, root_name, verify.Activity().scope, noverify_text) return activity def _get_course_key(self): return '%s.0' % ( self.EVENT_CODE_MAPPING['course'], ) def _get_unit_key(self, unit_id): return '%s.%s' % (self.EVENT_CODE_MAPPING['unit'], unit_id) def _get_custom_unit_key(self, unit_id): return '%s.%s' % (self.EVENT_CODE_MAPPING['custom_unit'], unit_id) def _get_lesson_key(self, unit_id, lesson_id): return '%s.%s.%s.%s' % ( self.EVENT_CODE_MAPPING['unit'], unit_id, self.EVENT_CODE_MAPPING['lesson'], lesson_id ) def _get_activity_key(self, unit_id, lesson_id): return '%s.%s.%s.%s.%s.%s' % ( self.EVENT_CODE_MAPPING['unit'], unit_id, self.EVENT_CODE_MAPPING['lesson'], lesson_id, self.EVENT_CODE_MAPPING['activity'], 0 ) def _get_html_key(self, unit_id, lesson_id): return '%s.%s.%s.%s.%s.%s' % ( self.EVENT_CODE_MAPPING['unit'], unit_id, self.EVENT_CODE_MAPPING['lesson'], lesson_id, self.EVENT_CODE_MAPPING['html'], 0 ) def _get_component_key(self, unit_id, lesson_id, component_id): return '%s.%s.%s.%s.%s.%s.%s.%s' % ( self.EVENT_CODE_MAPPING['unit'], unit_id, self.EVENT_CODE_MAPPING['lesson'], lesson_id, self.EVENT_CODE_MAPPING['html'], 0, self.EVENT_CODE_MAPPING['component'], component_id ) def _get_block_key(self, unit_id, lesson_id, block_id): return '%s.%s.%s.%s.%s.%s.%s.%s' % ( self.EVENT_CODE_MAPPING['unit'], unit_id, self.EVENT_CODE_MAPPING['lesson'], lesson_id, self.EVENT_CODE_MAPPING['activity'], 0, self.EVENT_CODE_MAPPING['block'], block_id ) def _get_assessment_key(self, assessment_id): assessment_key = '%s.%s' % ( self.EVENT_CODE_MAPPING['assessment'], assessment_id) # If this assessment is used as a "lesson" within a unit, prepend # the unit identifier. parent_unit = self._get_course().get_parent_unit(assessment_id) if parent_unit: assessment_key = '.'.join([self._get_unit_key(parent_unit.unit_id), assessment_key]) return assessment_key def get_entity_type_from_key(self, progress_entity_key): return progress_entity_key.split('.')[-2] def determine_if_composite_entity(self, progress_entity_key): return self.get_entity_type_from_key( progress_entity_key) in self.COMPOSITE_ENTITIES def get_valid_component_ids(self, unit_id, lesson_id): """Returns a list of cpt ids representing trackable components.""" components = [] for cpt_name in TRACKABLE_COMPONENTS: all_cpts = self._get_course().get_components_with_name( unit_id, lesson_id, cpt_name) components += [ cpt['instanceid'] for cpt in all_cpts if cpt['instanceid']] return components def get_valid_block_ids(self, unit_id, lesson_id): """Returns a list of block ids representing interactive activities.""" valid_blocks_data = self._get_valid_blocks_data(unit_id, lesson_id) return [block[0] for block in valid_blocks_data] def get_valid_blocks(self, unit_id, lesson_id): """Returns a list of blocks representing interactive activities.""" valid_blocks_data = self._get_valid_blocks_data(unit_id, lesson_id) return [block[1] for block in valid_blocks_data] def _get_valid_blocks_data(self, unit_id, lesson_id): """Returns a list of (b_id, block) representing trackable activities.""" valid_blocks = [] # Check if activity exists before calling get_activity_as_python. unit = self._get_course().find_unit_by_id(unit_id) lesson = self._get_course().find_lesson_by_id(unit, lesson_id) if unit and lesson and lesson.activity: # Get the activity corresponding to this unit/lesson combination. activity = self.get_activity_as_python(unit_id, lesson_id) for block_id in range(len(activity['activity'])): block = activity['activity'][block_id] if isinstance(block, dict): valid_blocks.append((block_id, block)) return valid_blocks def get_id_to_questions_dict(self): """Returns a dict that maps each question to a list of its answers. Returns: A dict that represents the questions in lessons. The keys of this dict are question ids, and the corresponding values are dicts, each containing the following five key-value pairs: - answers: a list of 0's with length corresponding to number of choices a question has. - location: str. href value of the location of the question in the course. - num_attempts: int. Number of attempts for this question. This is used as the denominator when calculating the average score for a question. This value may differ from the sum of the elements in 'answers' because of event entities that record an answer but not a score. - score: int. Aggregated value of the scores. - label: str. Human readable identifier for this question. """ id_to_questions = {} for unit in self._get_course().get_units_of_type(verify.UNIT_TYPE_UNIT): unit_id = unit.unit_id for lesson in self._get_course().get_lessons(unit_id): lesson_id = lesson.lesson_id # Add mapping dicts for questions in old-style activities. if lesson.activity: blocks = self._get_valid_blocks_data(unit_id, lesson_id) for block_index, (block_id, block) in enumerate(blocks): if block['questionType'] == self.MULTIPLE_CHOICE: # Old style question. id_to_questions.update( self._create_old_style_question_dict( block, block_id, block_index, unit, lesson)) elif (block['questionType'] == self.MULTIPLE_CHOICE_GROUP): # Old style multiple choice group. for ind, q in enumerate(block['questionsList']): id_to_questions.update( self._create_old_style_question_dict( q, block_id, block_index, unit, lesson, index=ind)) # Add mapping dicts for CBv1.5 style questions. if lesson.objectives: for cpt in self._get_course().get_question_components( unit_id, lesson_id): # CB v1.5 style questions. id_to_questions.update( self._create_v15_lesson_question_dict( cpt, unit, lesson)) for cpt in self._get_course().get_question_group_components( unit_id, lesson_id): # CB v1.5 style question groups. id_to_questions.update( self._create_v15_lesson_question_group_dict( cpt, unit, lesson)) return id_to_questions def get_id_to_assessments_dict(self): """Returns a dict that maps each question to a list of its answers. Returns: A dict that represents the questions in assessments. The keys of this dict are question ids, and the corresponding values are dicts, each containing the following five key-value pairs: - answers: a list of 0's with length corresponding to number of choices a question has. - location: str. href value of the location of the question in the course. - num_attempts: int. Number of attempts for this question. This is used as the denominator when calculating the average score for a question. This value may differ from the sum of the elements in 'answers' because of event entities that record an answer but not a score. - score: int. Aggregated value of the scores. - label: str. Human readable identifier for this question. """ id_to_assessments = {} for assessment in self._get_course().get_assessment_list(): if not self._get_course().needs_human_grader(assessment): assessment_components = self._get_course( ).get_assessment_components(assessment.unit_id) # CB v1.5 style assessments. for cpt in assessment_components: if cpt['cpt_name'] == self.QUESTION_GROUP: id_to_assessments.update( self._create_v15_assessment_question_group_dict( cpt, assessment)) elif cpt['cpt_name'] == self.QUESTION: id_to_assessments.update( self._create_v15_assessment_question_dict( cpt, assessment)) # Old style javascript assessments. try: content = self._get_course().get_assessment_content( assessment) id_to_assessments.update( self._create_old_style_assessment_dict( content['assessment'], assessment)) except AttributeError: # Assessment file does not exist. continue return id_to_assessments def _get_link_for_assessment(self, assessment_id): return 'assessment?name=%s' % (assessment_id) def _get_link_for_activity(self, unit_id, lesson_id): return 'activity?unit=%s&lesson=%s' % (unit_id, lesson_id) def _get_link_for_lesson(self, unit_id, lesson_id): return 'unit?unit=%s&lesson=%s' % (unit_id, lesson_id) def _create_v15_question_dict(self, q_id, label, link, num_choices): """Returns a dict that represents CB v1.5 style question.""" return { q_id: { 'answer_counts': [0] * num_choices, 'label': label, 'location': link, 'score': 0, 'num_attempts': 0 } } def _create_v15_lesson_question_dict(self, cpt, unit, lesson): try: question = QuestionDAO.load(cpt['quid']) if question.type == question.MULTIPLE_CHOICE: q_id = 'u.%s.l.%s.c.%s' % ( unit.unit_id, lesson.lesson_id, cpt['instanceid']) label = 'Unit %s Lesson %s, Question %s' % ( unit.index, lesson.index, question.description) link = self._get_link_for_lesson(unit.unit_id, lesson.lesson_id) num_choices = len(question.dict['choices']) return self._create_v15_question_dict( q_id, label, link, num_choices) else: return {} except Exception as e: # pylint: disable=broad-except logging.error( 'Failed to process the question data. ' 'Error: %s, data: %s', e, cpt) return {} def _create_v15_lesson_question_group_dict(self, cpt, unit, lesson): try: question_group = QuestionGroupDAO.load(cpt['qgid']) questions = {} for ind, quid in enumerate(question_group.question_ids): question = QuestionDAO.load(quid) if question.type == question.MULTIPLE_CHOICE: q_id = 'u.%s.l.%s.c.%s.i.%s' % ( unit.unit_id, lesson.lesson_id, cpt['instanceid'], ind) label = ('Unit %s Lesson %s, Question Group %s Question %s' % (unit.index, lesson.index, question_group.description, question.description)) link = self._get_link_for_lesson( unit.unit_id, lesson.lesson_id) num_choices = len(question.dict['choices']) questions.update(self._create_v15_question_dict( q_id, label, link, num_choices)) return questions except Exception as e: # pylint: disable=broad-except logging.error( 'Failed to process the question data. ' 'Error: %s, data: %s', e, cpt) return {} def _create_v15_assessment_question_group_dict(self, cpt, assessment): try: question_group = QuestionGroupDAO.load(cpt['qgid']) questions = {} for ind, quid in enumerate(question_group.question_ids): question = QuestionDAO.load(quid) if question.type == question.MULTIPLE_CHOICE: q_id = 's.%s.c.%s.i.%s' % ( assessment.unit_id, cpt['instanceid'], ind) label = '%s, Question Group %s Question %s' % ( assessment.title, question_group.description, question.description) link = self._get_link_for_assessment(assessment.unit_id) num_choices = len(question.dict['choices']) questions.update( self._create_v15_question_dict( q_id, label, link, num_choices)) return questions except Exception as e: # pylint: disable=broad-except logging.error( 'Failed to process the question data. ' 'Error: %s, data: %s', e, cpt) return {} def _create_v15_assessment_question_dict(self, cpt, assessment): try: question = QuestionDAO.load(cpt['quid']) if question.type == question.MULTIPLE_CHOICE: q_id = 's.%s.c.%s' % (assessment.unit_id, cpt['instanceid']) label = '%s, Question %s' % ( assessment.title, question.description) link = self._get_link_for_assessment(assessment.unit_id) num_choices = len(question.dict['choices']) return self._create_v15_question_dict( q_id, label, link, num_choices) else: return {} except Exception as e: # pylint: disable=broad-except logging.error( 'Failed to process the question data. ' 'Error: %s, data: %s', e, cpt) return {} def _create_old_style_question_dict(self, block, block_id, block_index, unit, lesson, index=None): try: if index is not None: # Question is in a multiple choice group. b_id = 'u.%s.l.%s.b.%s.i.%s' % ( unit.unit_id, lesson.lesson_id, block_id, index) label = 'Unit %s Lesson %s Activity, Item %s Part %s' % ( unit.index, lesson.index, block_index + 1, index + 1) else: b_id = 'u.%s.l.%s.b.%s' % ( unit.unit_id, lesson.lesson_id, block_id) label = 'Unit %s Lesson %s Activity, Item %s' % ( unit.index, lesson.index, block_index + 1) return { b_id: { 'answer_counts': [0] * len(block['choices']), 'label': label, 'location': self._get_link_for_activity( unit.unit_id, lesson.lesson_id), 'score': 0, 'num_attempts': 0 } } except Exception as e: # pylint: disable=broad-except logging.error( 'Failed to process the question data. ' 'Error: %s, data: %s', e, block) return {} def _create_old_style_assessment_dict(self, content, assessment): try: questions = {} for ind, question in enumerate(content['questionsList']): if 'choices' in question: questions.update( { 's.%s.i.%s' % (assessment.unit_id, ind): { 'answer_counts': [0] * len(question['choices']), 'label': '%s, Question %s' % ( assessment.title, ind + 1), 'location': self._get_link_for_assessment( assessment.unit_id), 'score': 0, 'num_attempts': 0 } } ) return questions except Exception as e: # pylint: disable=broad-except logging.error( 'Failed to process the question data. ' 'Error: %s, data: %s', e, content) return {} def _update_course(self, progress, student): event_key = self._get_course_key() if self._get_entity_value(progress, event_key) == self.COMPLETED_STATE: return self._set_entity_value(progress, event_key, self.IN_PROGRESS_STATE) course = self._get_course() for unit in course.get_track_matching_student(student): if course.get_parent_unit(unit.unit_id): # Completion of an assessment-as-lesson rolls up to its # containing unit; it is not considered for overall course # completion (except insofar as assessment completion # contributes to the completion of its owning unit) pass else: if unit.type == verify.UNIT_TYPE_ASSESSMENT: if not self.is_assessment_completed(progress, unit.unit_id): return elif unit.type == verify.UNIT_TYPE_UNIT: unit_state = self.get_unit_status(progress, unit.unit_id) if unit_state != self.COMPLETED_STATE: return self._set_entity_value(progress, event_key, self.COMPLETED_STATE) def _update_course_forced(self, progress): """Force state of course to completed.""" event_key = self._get_course_key() self._set_entity_value(progress, event_key, self.COMPLETED_STATE) def _update_unit(self, progress, event_key): """Updates a unit's progress if all its lessons have been completed.""" split_event_key = event_key.split('.') assert len(split_event_key) == 2 unit_id = split_event_key[1] if self._get_entity_value(progress, event_key) == self.COMPLETED_STATE: return # Record that at least one lesson in this unit has been completed. self._set_entity_value(progress, event_key, self.IN_PROGRESS_STATE) # Check if all lessons in this unit have been completed. lessons = self._get_course().get_lessons(unit_id) for lesson in lessons: if (self.get_lesson_status( progress, unit_id, lesson.lesson_id) != self.COMPLETED_STATE): return # Check whether pre/post assessments in this unit have been completed. unit = self._get_course().find_unit_by_id(unit_id) pre_assessment_id = unit.pre_assessment if (pre_assessment_id and not self.get_assessment_status(progress, pre_assessment_id)): return post_assessment_id = unit.post_assessment if (post_assessment_id and not self.get_assessment_status(progress, post_assessment_id)): return # Record that all lessons in this unit have been completed. self._set_entity_value(progress, event_key, self.COMPLETED_STATE) def _update_unit_forced(self, progress, event_key): """Force-mark a unit as completed, ignoring normal criteria.""" # Record that all lessons in this unit have been completed. self._set_entity_value(progress, event_key, self.COMPLETED_STATE) def _update_lesson(self, progress, event_key): """Updates a lesson's progress based on the progress of its children.""" split_event_key = event_key.split('.') assert len(split_event_key) == 4 unit_id = split_event_key[1] lesson_id = split_event_key[3] if self._get_entity_value(progress, event_key) == self.COMPLETED_STATE: return # Record that at least one part of this lesson has been completed. self._set_entity_value(progress, event_key, self.IN_PROGRESS_STATE) lessons = self._get_course().get_lessons(unit_id) for lesson in lessons: if str(lesson.lesson_id) == lesson_id and lesson: # Is the activity completed? if (lesson.activity and self.get_activity_status( progress, unit_id, lesson_id) != self.COMPLETED_STATE): return # Are all components of the lesson completed? if (self.get_html_status( progress, unit_id, lesson_id) != self.COMPLETED_STATE): return # Record that all activities in this lesson have been completed. self._set_entity_value(progress, event_key, self.COMPLETED_STATE) def _update_activity(self, progress, event_key): """Updates activity's progress when all interactive blocks are done.""" split_event_key = event_key.split('.') assert len(split_event_key) == 6 unit_id = split_event_key[1] lesson_id = split_event_key[3] if self._get_entity_value(progress, event_key) == self.COMPLETED_STATE: return # Record that at least one block in this activity has been completed. self._set_entity_value(progress, event_key, self.IN_PROGRESS_STATE) valid_block_ids = self.get_valid_block_ids(unit_id, lesson_id) for block_id in valid_block_ids: if not self.is_block_completed( progress, unit_id, lesson_id, block_id): return # Record that all blocks in this activity have been completed. self._set_entity_value(progress, event_key, self.COMPLETED_STATE) def _update_html(self, progress, event_key): """Updates html's progress when all interactive blocks are done.""" split_event_key = event_key.split('.') assert len(split_event_key) == 6 unit_id = split_event_key[1] lesson_id = split_event_key[3] if self._get_entity_value(progress, event_key) == self.COMPLETED_STATE: return # Record that at least one block in this activity has been completed. self._set_entity_value(progress, event_key, self.IN_PROGRESS_STATE) cpt_ids = self.get_valid_component_ids(unit_id, lesson_id) for cpt_id in cpt_ids: if not self.is_component_completed( progress, unit_id, lesson_id, cpt_id): return # Record that all blocks in this activity have been completed. self._set_entity_value(progress, event_key, self.COMPLETED_STATE) def _update_custom_unit(self, student, event_key, state): """Update custom unit.""" if student.is_transient: return progress = self.get_or_create_progress(student) current_state = self._get_entity_value(progress, event_key) if current_state == state or current_state == self.COMPLETED_STATE: return self._set_entity_value(progress, event_key, state) progress.updated_on = datetime.datetime.now() progress.put() UPDATER_MAPPING = { 'activity': _update_activity, 'course': _update_course, 'course_forced': _update_course_forced, 'html': _update_html, 'lesson': _update_lesson, 'unit': _update_unit, 'unit_forced': _update_unit_forced, } # Dependencies for recording derived events. The key is the current # event, and the value is a tuple, each element of which contains: # - the dependent entity to be updated # - the transformation to apply to the id of the current event to get the # id for the derived parent event DERIVED_EVENTS = { 'block': ( { 'entity': 'activity', 'generate_parent_id': (lambda s: '.'.join(s.split('.')[:-2])) }, ), 'activity': ( { 'entity': 'lesson', 'generate_parent_id': (lambda s: '.'.join(s.split('.')[:-2])) }, ), 'lesson': ( { 'entity': 'unit', 'generate_parent_id': (lambda s: '.'.join(s.split('.')[:-2])) }, ), 'component': ( { 'entity': 'html', 'generate_parent_id': (lambda s: '.'.join(s.split('.')[:-2])) }, ), 'html': ( { 'entity': 'lesson', 'generate_parent_id': (lambda s: '.'.join(s.split('.')[:-2])) }, ), 'assessment': ( { 'entity': 'unit', 'generate_parent_id': (lambda s: '.'.join(s.split('.')[:-2])) }, ), } def force_course_completed(self, student): self._put_event( student, 'course_forced', self._get_course_key()) def force_unit_completed(self, student, unit_id): """Records that the given student has completed a unit. NOTE: This should not generally be used directly. The definition of completing a unit is generally taken to be completion of all parts of all components of a unit (assessments, lessons, activities in lessons, etc. Directly marking a unit as complete is provided only for manual marking where the student feels "done", but has not taken a fully completionist approach to the material. Args: student: A logged-in, registered student object. unit_id: The ID of the unit to be marked as complete. """ self._put_event( student, 'unit_forced', self._get_unit_key(unit_id)) def put_activity_completed(self, student, unit_id, lesson_id): """Records that the given student has completed an activity.""" if not self._get_course().is_valid_unit_lesson_id(unit_id, lesson_id): return self._put_event( student, 'activity', self._get_activity_key(unit_id, lesson_id)) def put_html_completed(self, student, unit_id, lesson_id): """Records that the given student has completed a lesson page.""" if not self._get_course().is_valid_unit_lesson_id(unit_id, lesson_id): return self._put_event( student, 'html', self._get_html_key(unit_id, lesson_id)) def put_block_completed(self, student, unit_id, lesson_id, block_id): """Records that the given student has completed an activity block.""" if not self._get_course().is_valid_unit_lesson_id(unit_id, lesson_id): return if block_id not in self.get_valid_block_ids(unit_id, lesson_id): return self._put_event( student, 'block', self._get_block_key(unit_id, lesson_id, block_id) ) def put_component_completed(self, student, unit_id, lesson_id, cpt_id): """Records completion of a component in a lesson body.""" if not self._get_course().is_valid_unit_lesson_id(unit_id, lesson_id): return if cpt_id not in self.get_valid_component_ids(unit_id, lesson_id): return self._put_event( student, 'component', self._get_component_key(unit_id, lesson_id, cpt_id) ) def put_assessment_completed(self, student, assessment_id): """Records that the given student has completed the given assessment.""" if not self._get_course().is_valid_assessment_id(assessment_id): return self._put_event( student, 'assessment', self._get_assessment_key(assessment_id)) def put_custom_unit_completed(self, student, unit_id): """Records that the student has completed the given custom_unit.""" if not self._get_course().is_valid_custom_unit(unit_id): return self._update_custom_unit( student, self._get_custom_unit_key(unit_id), self.COMPLETED_STATE) def put_custom_unit_in_progress(self, student, unit_id): """Records that the given student has started the given custom_unit.""" if not self._get_course().is_valid_custom_unit(unit_id): return self._update_custom_unit( student, self._get_custom_unit_key(unit_id), self.IN_PROGRESS_STATE) def put_activity_accessed(self, student, unit_id, lesson_id): """Records that the given student has accessed this activity.""" # This method currently exists because we need to mark activities # without interactive blocks as 'completed' when they are accessed. if not self.get_valid_block_ids(unit_id, lesson_id): self.put_activity_completed(student, unit_id, lesson_id) def put_html_accessed(self, student, unit_id, lesson_id): """Records that the given student has accessed this lesson page.""" # This method currently exists because we need to mark lesson bodies # without interactive blocks as 'completed' when they are accessed. if not self.get_valid_component_ids(unit_id, lesson_id): self.put_html_completed(student, unit_id, lesson_id) def _put_event(self, student, event_entity, event_key): """Starts a cascade of updates in response to an event taking place.""" if student.is_transient or event_entity not in self.EVENT_CODE_MAPPING: return progress = self.get_or_create_progress(student) self._update_event( student, progress, event_entity, event_key, direct_update=True) progress.updated_on = datetime.datetime.now() progress.put() def _update_event(self, student, progress, event_entity, event_key, direct_update=False): """Updates statistics for the given event, and for derived events. Args: student: the student progress: the StudentProgressEntity for the student event_entity: the name of the affected entity (unit, lesson, etc.) event_key: the key for the recorded event direct_update: True if this event is being updated explicitly; False if it is being auto-updated. """ if direct_update or event_entity not in self.UPDATER_MAPPING: if event_entity in self.UPDATER_MAPPING: # This is a derived event, so directly mark it as completed. self._set_entity_value( progress, event_key, self.COMPLETED_STATE) else: # This is not a derived event, so increment its counter by one. self._inc(progress, event_key) else: self.UPDATER_MAPPING[event_entity](self, progress, event_key) if event_entity in self.DERIVED_EVENTS: for derived_event in self.DERIVED_EVENTS[event_entity]: parent_event_key = derived_event['generate_parent_id']( event_key) if parent_event_key: # Event entities may contribute upwards to more than one # kind of container. Only pass the notification up to the # handler that our event_key indicates we actually have. leaf_type = self.get_entity_type_from_key(parent_event_key) event_entity = derived_event['entity'] if leaf_type == self.EVENT_CODE_MAPPING[event_entity]: self._update_event( student=student, progress=progress, event_entity=event_entity, event_key=parent_event_key) else: # Only update course status when we are at the top of # a containment list self._update_course(progress, student) else: # Or only update course status when we are doing something not # in derived events (Unit, typically). self._update_course(progress, student) utils.run_hooks(self.POST_UPDATE_PROGRESS_HOOK, self._get_course(), student, progress, event_entity, event_key) def get_course_status(self, progress): return self._get_entity_value(progress, self._get_course_key()) def get_unit_status(self, progress, unit_id): return self._get_entity_value(progress, self._get_unit_key(unit_id)) def get_custom_unit_status(self, progress, unit_id): return self._get_entity_value( progress, self._get_custom_unit_key(unit_id)) def get_lesson_status(self, progress, unit_id, lesson_id): return self._get_entity_value( progress, self._get_lesson_key(unit_id, lesson_id)) def get_activity_status(self, progress, unit_id, lesson_id): return self._get_entity_value( progress, self._get_activity_key(unit_id, lesson_id)) def get_html_status(self, progress, unit_id, lesson_id): return self._get_entity_value( progress, self._get_html_key(unit_id, lesson_id)) def get_block_status(self, progress, unit_id, lesson_id, block_id): return self._get_entity_value( progress, self._get_block_key(unit_id, lesson_id, block_id)) def get_assessment_status(self, progress, assessment_id): return self._get_entity_value( progress, self._get_assessment_key(assessment_id)) def is_block_completed(self, progress, unit_id, lesson_id, block_id): value = self._get_entity_value( progress, self._get_block_key(unit_id, lesson_id, block_id)) return value is not None and value > 0 def is_component_completed(self, progress, unit_id, lesson_id, cpt_id): value = self._get_entity_value( progress, self._get_component_key(unit_id, lesson_id, cpt_id)) return value is not None and value > 0 def is_assessment_completed(self, progress, assessment_id): value = self._get_entity_value( progress, self._get_assessment_key(assessment_id)) return value is not None and value > 0 def is_custom_unit_completed(self, progress, unit_id): value = self.get_custom_unit_status(progress, unit_id) return self.COMPLETED_STATE == value @classmethod def get_or_create_progress(cls, student): progress = StudentPropertyEntity.get(student, cls.PROPERTY_KEY) if not progress: progress = StudentPropertyEntity.create( student=student, property_name=cls.PROPERTY_KEY) progress.put() return progress def get_course_progress(self, student): """Return [NOT_STARTED|IN_PROGRESS|COMPLETED]_STATE for course.""" progress = self.get_or_create_progress(student) return self.get_course_status(progress) or self.NOT_STARTED_STATE def get_unit_progress(self, student, progress=None): """Returns a dict with the states of each unit.""" if student.is_transient: return {} units = self._get_course().get_units() if progress is None: progress = self.get_or_create_progress(student) result = {} for unit in units: if unit.type == verify.UNIT_TYPE_ASSESSMENT: result[unit.unit_id] = self.is_assessment_completed( progress, unit.unit_id) elif unit.type == verify.UNIT_TYPE_UNIT: value = self.get_unit_status(progress, unit.unit_id) result[unit.unit_id] = value or 0 elif unit.type == verify.UNIT_TYPE_CUSTOM: value = self.get_custom_unit_status(progress, unit.unit_id) result[unit.unit_id] = value or 0 return result def get_unit_percent_complete(self, student): """Returns a dict with each unit's completion in [0.0, 1.0].""" if student.is_transient: return {} course = self._get_course() units = course.get_units() assessment_scores = {int(s['id']): s['score'] / 100.0 for s in course.get_all_scores(student)} result = {} progress = self.get_or_create_progress(student) for unit in units: # Assessments are scored as themselves. if unit.type == verify.UNIT_TYPE_ASSESSMENT: result[unit.unit_id] = assessment_scores[unit.unit_id] elif unit.type == verify.UNIT_TYPE_UNIT: if (unit.pre_assessment and assessment_scores[unit.pre_assessment] >= 1.0): # Use pre-assessment iff it exists and student scored 100% result[unit.unit_id] = 1.0 else: # Otherwise, count % completion on lessons within unit. num_completed = 0 lesson_progress = self.get_lesson_progress( student, unit.unit_id, progress=progress) if not lesson_progress: result[unit.unit_id] = 0.0 else: for lesson in lesson_progress.values(): if lesson['has_activity']: # Lessons that have activities must be # activity-complete as well as HTML complete. if (lesson['html'] == self.COMPLETED_STATE and lesson['activity'] == self.COMPLETED_STATE): num_completed += 1 else: # Lessons without activities just need HTML if lesson['html'] == self.COMPLETED_STATE: num_completed += 1 result[unit.unit_id] = round( num_completed / float(len(lesson_progress)), 3) return result def get_lesson_progress(self, student, unit_id, progress=None): """Returns a dict saying which lessons in this unit are completed.""" if student.is_transient: return {} lessons = self._get_course().get_lessons(unit_id) if progress is None: progress = self.get_or_create_progress(student) result = {} for lesson in lessons: result[lesson.lesson_id] = { 'html': self.get_html_status( progress, unit_id, lesson.lesson_id) or 0, 'activity': self.get_activity_status( progress, unit_id, lesson.lesson_id) or 0, 'has_activity': lesson.has_activity, } return result def get_component_progress(self, student, unit_id, lesson_id, cpt_id): """Returns the progress status of the given component.""" if student.is_transient: return 0 progress = self.get_or_create_progress(student) return self.is_component_completed( progress, unit_id, lesson_id, cpt_id) or 0 def _get_entity_value(self, progress, event_key): if not progress.value: return None return transforms.loads(progress.value).get(event_key) def _set_entity_value(self, student_property, key, value): """Sets the integer value of a student property. Note: this method does not commit the change. The calling method should call put() on the StudentPropertyEntity. Args: student_property: the StudentPropertyEntity key: the student property whose value should be incremented value: the value to increment this property by """ try: progress_dict = transforms.loads(student_property.value) except (AttributeError, TypeError): progress_dict = {} progress_dict[key] = value student_property.value = transforms.dumps(progress_dict) def _inc(self, student_property, key, value=1): """Increments the integer value of a student property. Note: this method does not commit the change. The calling method should call put() on the StudentPropertyEntity. Args: student_property: the StudentPropertyEntity key: the student property whose value should be incremented value: the value to increment this property by """ try: progress_dict = transforms.loads(student_property.value) except (AttributeError, TypeError): progress_dict = {} if key not in progress_dict: progress_dict[key] = 0 progress_dict[key] += value student_property.value = transforms.dumps(progress_dict) @classmethod def get_elements_from_key(cls, key): """Decomposes the key into a dictionary with its values. Args: key: a string, the key of an element of the progress. For example, u.1.l.5.h.0 Returns: A dictionary mapping each element in the key to its value. For the key u.1.l.5.h.0 the result is: { 'unit': 1, 'lesson': 5, 'html': 0, 'unit_forced': 1 } """ reversed_event_mapping = defaultdict(lambda: []) for full_type, value in cls.EVENT_CODE_MAPPING.iteritems(): reversed_event_mapping[value].append(full_type) key_elements = key.split('.') assert len(key_elements) % 2 == 0 result = {} for index in range(0, len(key_elements), 2): element_type = key_elements[index] element_value = key_elements[index + 1] full_element_types = reversed_event_mapping.get(element_type) for full_element_type in full_element_types: result[full_element_type] = element_value return result class ProgressStats(object): """Defines the course structure definition for course progress tracking.""" def __init__(self, course): self._course = course self._tracker = UnitLessonCompletionTracker(course) def compute_entity_dict(self, entity, parent_ids): """Computes the course structure dictionary. Args: entity: str. Represents for which level of entity the dict is being computed. Valid entity levels are defined as keys to the dict defined below, COURSE_STRUCTURE_DICT. parent_ids: list of ids necessary to get children of the current entity. Returns: A nested dictionary representing the structure of the course. Every other level of the dictionary consists of a key, the label of the entity level defined by EVENT_CODE_MAPPING in UnitLessonCompletionTracker, whose value is a dictionary INSTANCES_DICT. The keys of INSTANCES_DICT are instance_ids of the corresponding entities, and the values are the entity_dicts of the instance's children, in addition to a field called 'label'. Label represents the user-facing name of the entity rather than its intrinsic id. If one of these values is empty, this means that the corresponding entity has no children. Ex: A Course with the following outlined structure: Pre Assessment Unit 1 Lesson 1 Unit 2 will have the following dictionary representation: { 's': { 1: { 'label': 'Pre Assessment' } }, 'u': { 2: { 'l': { 3: { 'label': 1 } }, 'label': 1 }, 4: { 'label': 2 } } 'label': 'UNTITLED COURSE' } """ entity_dict = {'label': self._get_label(entity, parent_ids)} for child_entity, get_children_ids in self.COURSE_STRUCTURE_DICT[ entity]['children']: child_entity_dict = {} for child_id in get_children_ids(self, *parent_ids): new_parent_ids = parent_ids + [child_id] child_entity_dict[child_id] = self.compute_entity_dict( child_entity, new_parent_ids) entity_dict[UnitLessonCompletionTracker.EVENT_CODE_MAPPING[ child_entity]] = child_entity_dict return entity_dict def _get_course(self): return self._course def _get_unit_ids_of_type_unit(self): units = self._get_course().get_units_of_type(verify.UNIT_TYPE_UNIT) return [unit.unit_id for unit in units] def _get_assessment_ids(self): assessments = self._get_course().get_assessment_list() return [a.unit_id for a in assessments] def _get_lesson_ids(self, unit_id): lessons = self._get_course().get_lessons(unit_id) return [lesson.lesson_id for lesson in lessons] def _get_activity_ids(self, unit_id, lesson_id): unit = self._get_course().find_unit_by_id(unit_id) if self._get_course().find_lesson_by_id(unit, lesson_id).activity: return [0] return [] def _get_html_ids(self, unused_unit_id, unused_lesson_id): return [0] def _get_block_ids(self, unit_id, lesson_id, unused_activity_id): return self._tracker.get_valid_block_ids(unit_id, lesson_id) def _get_component_ids(self, unit_id, lesson_id, unused_html_id): return self._tracker.get_valid_component_ids(unit_id, lesson_id) def _get_label(self, entity, parent_ids): return self.ENTITY_TO_HUMAN_READABLE_NAME_DICT[entity]( self, *parent_ids) def _get_course_label(self): # pylint: disable=protected-access return courses.Course.get_environ(self._get_course().app_context)[ 'course']['title'] def _get_unit_label(self, unit_id): unit = self._get_course().find_unit_by_id(unit_id) return 'Unit %s' % unit.index def _get_assessment_label(self, unit_id): assessment = self._get_course().find_unit_by_id(unit_id) return assessment.title def _get_lesson_label(self, unit_id, lesson_id): unit = self._get_course().find_unit_by_id(unit_id) lesson = self._get_course().find_lesson_by_id(unit, lesson_id) return lesson.index def _get_activity_label(self, unit_id, lesson_id, unused_activity_id): return str('L%s.%s' % ( self._get_course().find_unit_by_id(unit_id).index, self._get_lesson_label(unit_id, lesson_id))) def _get_html_label(self, unit_id, lesson_id, unused_html_id): return self._get_activity_label(unit_id, lesson_id, unused_html_id) def _get_block_label(self, unit_id, lesson_id, unused_activity_id, block_id): return str('L%s.%s.%s' % ( self._get_course().find_unit_by_id(unit_id).index, self._get_lesson_label(unit_id, lesson_id), block_id)) def _get_component_label(self, unit_id, lesson_id, unused_html_id, component_id): return self._get_block_label( unit_id, lesson_id, unused_html_id, component_id) # Outlines the structure of the course. The key is the entity level, and # its value is a dictionary with following keys and its values: # 'children': list of tuples. Each tuple consists of string representation # of the child entity(ex: 'lesson') and a function to get the # children elements. If the entity does not have children, the # value will be an empty list. # 'id': instance_id of the entity. If the entity is represented by a class # with an id attribute(ex: units), string representation of the # attribute is stored here. If the entity is defined by a dictionary # (ex: components), then the value is the string 'None'. # COURSE_STRUCTURE_DICT = { 'course': { 'children': [('unit', _get_unit_ids_of_type_unit), ('assessment', _get_assessment_ids)], }, 'unit': { 'children': [('lesson', _get_lesson_ids)], }, 'assessment': { 'children': [], }, 'lesson': { 'children': [('activity', _get_activity_ids), ('html', _get_html_ids)], }, 'activity': { 'children': [('block', _get_block_ids)], }, 'html': { 'children': [('component', _get_component_ids)], }, 'block': { 'children': [], }, 'component': { 'children': [], } } ENTITY_TO_HUMAN_READABLE_NAME_DICT = { 'course': _get_course_label, 'unit': _get_unit_label, 'assessment': _get_assessment_label, 'lesson': _get_lesson_label, 'activity': _get_activity_label, 'html': _get_html_label, 'block': _get_block_label, 'component': _get_component_label }
Python