Beispiel #1
0
def test_page(grade_number, lesson_number):
    if is_logined():
        # def rowdict(row):
        #     d = {}
        #     for column in row:
        #         d[column.question_text] = column.definition

        #     return d

        grade = dbSession.query(Grade).filter_by(id=grade_number).first()
        try:
            lesson = grade.lessons[lesson_number - 1]
            test = Test(user_id=g.user.id,
                        title=lesson.title,
                        question_count=len(lesson.questions),
                        current_question=0,
                        correct_answers=0,
                        lesson_id=lesson.id)
            test.questions = lesson.questions
            question = test.questions[0]
            dbSession.add(test)
            dbSession.commit()
            return render_template('test_page/test_page.html',
                                   test_title=test.title,
                                   test_id=test.id,
                                   question=question)
            # return render_template('test_page/test_page.html' , test_id = test.id , question = question)
        except IndexError as e:
            print(e)
            return render_template('test_page/no_question.html')
    else:
        return redirect(url_for('verification.login'))
Beispiel #2
0
    def test_merge(self):
        branch, platform, builder = _create_some_builder()
        some_build = _create_build(branch, platform, builder)
        some_result = TestResult.get_or_insert_from_parsed_json('some-test', some_build, 50)
        some_test = Test.update_or_insert('some-test', branch, platform)

        other_build = _create_build(branch, platform, builder, 'other-build')
        other_result = TestResult.get_or_insert_from_parsed_json('other-test', other_build, 30)
        other_test = Test.update_or_insert('other-test', branch, platform)

        self.assertOnlyInstances([some_result, other_result])
        self.assertNotEqual(some_result.key(), other_result.key())
        self.assertOnlyInstances([some_test, other_test])

        self.assertRaises(AssertionError, some_test.merge, (some_test))
        self.assertOnlyInstances([some_test, other_test])

        some_test.merge(other_test)
        results_for_some_test = TestResult.all()
        results_for_some_test.filter('name =', 'some-test')
        results_for_some_test = results_for_some_test.fetch(5)
        self.assertEqual(len(results_for_some_test), 2)

        self.assertEqual(results_for_some_test[0].name, 'some-test')
        self.assertEqual(results_for_some_test[1].name, 'some-test')

        if results_for_some_test[0].value == 50:
            self.assertEqual(results_for_some_test[1].value, 30)
        else:
            self.assertEqual(results_for_some_test[1].value, 50)
Beispiel #3
0
    def test_value_single_platform(self):
        webkit_trunk = Branch.create_if_possible('webkit-trunk',
                                                 'WebKit trunk')
        some_platform = Platform.create_if_possible('some-platform',
                                                    'Some Platform')
        self.assertEqual(
            DashboardJSONGenerator().value(), {
                'defaultBranch': 'WebKit trunk',
                'branchToId': {
                    'WebKit trunk': webkit_trunk.id
                },
                'platformToId': {
                    'Some Platform': some_platform.id
                },
                'testToId': {},
            })

        Test.update_or_insert('some-test', webkit_trunk, some_platform)
        self.assertEqual(
            DashboardJSONGenerator().value(), {
                'defaultBranch': 'WebKit trunk',
                'branchToId': {
                    'WebKit trunk': webkit_trunk.id
                },
                'platformToId': {
                    'Some Platform': some_platform.id
                },
                'testToId': {
                    'some-test': Test.get_by_key_name('some-test').id
                },
            })
Beispiel #4
0
    def test_path_or_resource(self):
        c = Client()
        obj = TestModel()
        obj.test = "TESTING"
        obj.save()

        resource = resources1.Test_1_1_Resource()

        list_path = resource.get_resource_list_uri()
        object_path = resource.get_resource_uri(obj)

        result = c._path_or_resource(list_path)
        expected = list_path
        self.assertEqual(result, expected, "Bare path.\nResult:%s\nExpected:%s" % (result, expected))

        result = c._path_or_resource(list_path, obj)
        expected = list_path
        self.assertEqual(result, expected, "Bare path w/obj.\nResult:%s\nExpected:%s" % (result, expected))

        result = c._path_or_resource(resource)
        expected = list_path
        self.assertEqual(result, expected, "Empty resource.\nResult:%s\nExpected:%s" % (result, expected))

        result = c._path_or_resource(resource, obj)
        expected = object_path
        self.assertEqual(result, expected, "Populated resource.\nResult:%s\nExpected:%s" % (result, expected))
Beispiel #5
0
    def test_path_or_resource(self):
        c = Client()
        obj = TestModel()
        obj.test = 'TESTING'
        obj.save()

        resource = resources1.Test_1_1_Resource()

        list_path = resource.get_resource_list_uri()
        object_path = resource.get_resource_uri(obj)

        result = c._path_or_resource(list_path)
        expected = list_path
        self.assertEqual(
            result, expected,
            "Bare path.\nResult:%s\nExpected:%s" % (result, expected))

        result = c._path_or_resource(list_path, obj)
        expected = list_path
        self.assertEqual(
            result, expected,
            "Bare path w/obj.\nResult:%s\nExpected:%s" % (result, expected))

        result = c._path_or_resource(resource)
        expected = list_path
        self.assertEqual(
            result, expected,
            "Empty resource.\nResult:%s\nExpected:%s" % (result, expected))

        result = c._path_or_resource(resource, obj)
        expected = object_path
        self.assertEqual(
            result, expected,
            "Populated resource.\nResult:%s\nExpected:%s" % (result, expected))
Beispiel #6
0
def new_test():
    form = TestForm()
    if form.validate_on_submit():
        test = Test(
            test_name=form.test_name.data,
            num_mc=form.num_mc.data,
            mc_answers = int(form.mc_answers.data),
            num_or=form.num_or.data,
            #or_points = int(form.or_points.data),
            num_students=form.num_students.data,
            #test_data = defaultGrid(form.num_mc.data, int(form.mc_answers.data), form.num_or.data, form.or_points.data,form.num_students.data),
            mc_data = mcDetails(form.num_mc.data, int(form.mc_answers.data)),
            or_data = orDetails(form.num_mc.data,form.num_or.data),
            student_data = studentDetails(form.num_students.data),
            added_by=session['email']
        )
        try:
            test.put()
            test_id = test.key.id()
            test = Test.get_by_id(test_id)
            mc_data = json.dumps(test.mc_data)
            or_data = json.dumps(test.or_data)
            student_data = json.dumps(test.student_data)
            flash(u'Test %s successfully saved.' % test_id, 'success')
            return render_template('test_details.html', test = Test.get_by_id(test_id), test_id = test_id, mc_data = mc_data, or_data = or_data, student_data = student_data)
        except CapabilityDisabledError:
            flash(u'App Engine Datastore is currently in read-only mode.', 'info')
            return redirect(url_for('list_tests'))
    return redirect(url_for('list_tests'))
Beispiel #7
0
    def test_merge(self):
        branch, platform, builder = _create_some_builder()
        some_build = _create_build(branch, platform, builder)
        some_result = TestResult.get_or_insert_from_parsed_json('some-test', some_build, 50)
        some_test = Test.update_or_insert('some-test', branch, platform)

        other_build = _create_build(branch, platform, builder, 'other-build')
        other_result = TestResult.get_or_insert_from_parsed_json('other-test', other_build, 30)
        other_test = Test.update_or_insert('other-test', branch, platform)

        self.assertOnlyInstances([some_result, other_result])
        self.assertNotEqual(some_result.key(), other_result.key())
        self.assertOnlyInstances([some_test, other_test])

        self.assertRaises(AssertionError, some_test.merge, (some_test))
        self.assertOnlyInstances([some_test, other_test])

        some_test.merge(other_test)
        results_for_some_test = TestResult.all()
        results_for_some_test.filter('name =', 'some-test')
        results_for_some_test = results_for_some_test.fetch(5)
        self.assertEqual(len(results_for_some_test), 2)

        self.assertEqual(results_for_some_test[0].name, 'some-test')
        self.assertEqual(results_for_some_test[1].name, 'some-test')

        if results_for_some_test[0].value == 50:
            self.assertEqual(results_for_some_test[1].value, 30)
        else:
            self.assertEqual(results_for_some_test[1].value, 50)
Beispiel #8
0
def get_tests(num=None, start_cursor=None, ancestor_key=None, open=None):
    """Retrieves the num most recent tests, starting at start_cursor, and only for the ancestor if provided"""
    if ancestor_key:
        # This checks for only tests created by this entity
        test_query = Test.query(ancestor=ancestor_key).order(-Test.created)
    else:
        test_query = Test.query().order(-Test.created)
    if open is not None:
        # filter open or closed tests as needed
        test_query = test_query.filter(Test.open == open)
    if start_cursor:
        # Set the query start to the cursor location if provided
        tests, next_cursor, more = test_query.fetch_page(
            num, start_cursor=start_cursor)
        try:
            return {
                'tests': tests,
                'next': next_cursor.urlsafe(),
                'more': more
            }
        except:
            return {'tests': tests, 'next': None, 'more': False}
    elif num:
        # Otherwise return the number of requested results
        return test_query.fetch(num)
    # Or all if no num was specified
    return test_query.fetch()
Beispiel #9
0
 def test_add_edge(self):
     src_id, dst_id = str(uuid.uuid4()), str(uuid.uuid4())
     src, dst = Test(src_id), Test(dst_id)
     edge = Edge1(src_id, dst_id)
     with g.session_scope() as session:
         session.add_all([src, dst])
         session.flush()
         session.add(edge)
         g.edges().filter(Edge1.src_id == src_id).one()
Beispiel #10
0
def index(request):
    entry = Test(name='lidong')
    entry.phone = '13410320008'
    logging.debug('**************')

    # entry.save()
    # resp = "hello %s , phone :%s" %(entry.name, entry.phone)
    # return HttpResponse(resp)
    return HttpResponse('zhangtan')
Beispiel #11
0
    def test_sysan_sanitization(self):
        """It shouldn't be possible to set system annotations keys to
        anything but primitive values.

        """
        a = Test(str(uuid.uuid4()))
        with g.session_scope() as s:
            a = s.merge(a)
            with self.assertRaises(ValueError):
                a.sysan["foo"] = {"bar": "baz"}
Beispiel #12
0
def create_test_backup(request):
    test_obj = json.loads(request.body)
    test = Test()
    #import pdb; pdb.set_trace()
    if request.user.is_authenticated():
        owner = User_Profile.objects.filter(user=request.user)
        test.owner = owner[0]
        test.test_name = test_obj['PRE_TEST']['test_name']
        #test.subject = test_obj['PRE_TEST'].subject
        #test.target_exam = test_obj['PRE_TEST'].target_exam
        #test.topics = test_obj['PRE_TEST'].topics_included
        test.total_time = test_obj['PRE_TEST']['total_time']
        test.pass_criteria = test_obj['PRE_TEST']['pass_criteria']
        test.assoicated_class = Class.objects.get(pk=test_obj['CLASS_INFO'])
        test.save()
        try:
            for item in test_obj['QUESTIONS']:
                question = Question()
                question.question_text = item['question_text']
                question.explanation = item['explanation']
                question.options = json.dumps(item['options'])
                question.hint = item['hint']
                question.difficulty = item['difficulty_level']
                question.points = item['points']
                question.owner = owner[0]
                #question.target_exam = test.target_exam
                #question.subject = test.subject
                #question.topic = item.topic
                question.save()
                test.questions.add(question)
            data = {"status": "success"}
            return JsonResponse(data)
        except Exception, e:
            raise e
Beispiel #13
0
 def test_cascade_delete(self):
     a = Test('a')
     b = Foo('b')
     a.foos = [b]
     with g.session_scope() as s:
         a, b = map(s.merge, (a, b))
     with g.session_scope() as s:
         s.delete(g.nodes(Test).ids('a').one())
     with g.session_scope() as s:
         self.assertIsNone(g.nodes(Test).ids('a').scalar())
         self.assertIsNone(g.edges(Edge2).src('a').dst('b').scalar())
Beispiel #14
0
def _create_results(branch, platform, builder, test_name, values):
    results = []
    for i, value in enumerate(values):
        build = Build(branch=branch, platform=platform, builder=builder,
            buildNumber=i, revision=100 + i, timestamp=datetime.now())
        build.put()
        result = TestResult(name=test_name, build=build, value=value)
        result.put()
        Test.update_or_insert(test_name, branch, platform)
        results.append(result)
    return results
Beispiel #15
0
    def get(self, in_test_id=None):
        template_values = get_template_values(self)
        user = users.get_current_user()
        try:
            entity = Entity.query(Entity.id == user.user_id()).get()
            if not entity.display_name:  # It's only slightly possible to have a user with no display_name
                self.redirect('/login')
        except:
            self.redirect('/login')
        else:
            test_query = Test.query(ancestor=ndb.Key('Entity', user.user_id()))
            if len(test_query.fetch()) > 0:
                if in_test_id:
                    in_query = test_query.filter(
                        Test.id == in_test_id).fetch(1)
                    try:  # The test exists
                        template_values = add_test_to_template(
                            template_values, in_query[0])
                    except IndexError:  # The test does not exist
                        self.redirect("/")

            potential_groups = set(
                itertools.chain(entity.test_groups, default_groups))
            print potential_groups
            grouped_marks = get_grouped_marks(entity.id)

            # Add groups with levels for level dropdown
            template_values['user_levels'] = json.dumps(grouped_marks)

            # Add list of groups for group dropdown
            template_values['user_groups'] = []
            for group in grouped_marks:
                group_test_query = Test.query(
                    Test.group == group['group']).order(-Test.level).fetch()
                try:
                    threshold = group_test_query[0]
                except:
                    threshold = 0
                print threshold
                for mark in grouped_marks:
                    potential_groups = potential_groups - set(group['group'])
                    if mark['group'] == group and mark["level"] >= threshold:
                        template_values['user_groups'].append(group)
            for group in potential_groups:
                template_values['user_groups'].append(group)

            if template_values["user_groups"] == []:
                template_values[
                    'error'] = "You may only create a test in a new category."

            path = os.path.join(os.path.dirname(__file__),
                                os.path.join(template_dir, 'create.html'))
            self.response.out.write(template.render(path, template_values))
        return
Beispiel #16
0
 def test_session_timestamp(self):
     with g.session_scope() as s:
         self.assertIsNone(s._flush_timestamp)
         s.merge(Test(""))
         s.flush()
         self.assertIsNotNone(s._flush_timestamp)
     g.set_flush_timestamps = False
     with g.session_scope() as s:
         s.merge(Test(""))
         s.flush()
         self.assertIsNone(s._flush_timestamp)
Beispiel #17
0
 def test_snapshot_sysan(self):
     a = Test(str(uuid.uuid4()), key2=1)
     with g.session_scope() as s:
         a = s.merge(a)
         s.commit()
         a.sysan['key'] = 1
         a = s.merge(a)
         s.commit()
         self.assertEqual(a._history.one().properties['key2'], 1)
         a.sysan['key'] = 3
         a = s.merge(a)
Beispiel #18
0
 def test_value_two_platforms(self):
     webkit_trunk = Branch.create_if_possible('webkit-trunk', 'WebKit trunk')
     some_platform = Platform.create_if_possible('some-platform', 'Some Platform')
     other_platform = Platform.create_if_possible('other-platform', 'Other Platform')
     Test.update_or_insert('some-test', webkit_trunk, some_platform)
     Test.update_or_insert('some-test', webkit_trunk, other_platform)
     self.assertEqual(DashboardJSONGenerator().value(), {
         'defaultBranch': 'WebKit trunk',
         'branchToId': {'WebKit trunk': webkit_trunk.id},
         'platformToId': {'Some Platform': some_platform.id, 'Other Platform': other_platform.id},
         'testToId': {'some-test': Test.get_by_key_name('some-test').id},
     })
Beispiel #19
0
 def test_unchanged_sysan_snapshot(self):
     nid = str(uuid.uuid4())
     a = Test(nid)
     value = '++ VALUE ++'
     with g.session_scope() as s:
         a.sysan['key1'] = value
         a = s.merge(a)
         s.commit()
         a.sysan['key1'] = value
         a = s.merge(a)
         s.commit()
         self.assertEqual(a._history.all(), [])
Beispiel #20
0
 def test_association_proxy(self):
     a = Test('a')
     b = Foo('b')
     c = Test('c')
     a.foos.append(b)
     a.tests = [c]
     with g.session_scope() as s:
         a, b, c = map(s.merge, (a, b, c))
     with g.session_scope() as s:
         a = g.nodes(Test).ids('a').one()
         self.assertTrue(b in a.foos)
         self.assertEqual(a.tests, [c])
Beispiel #21
0
 def execute(id):
     test = Test.get_by_key_name(testName)
     returnValue = None
     if not test:
         test = Test(id=id, name=testName, key_name=testName)
         returnValue = test
     if branch.key() not in test.branches:
         test.branches.append(branch.key())
     if platform.key() not in test.platforms:
         test.platforms.append(platform.key())
     test.put()
     return returnValue
Beispiel #22
0
    def test_update_or_insert_to_update(self):
        branch = Branch.create_if_possible('some-branch', 'Some Branch')
        platform = Platform.create_if_possible('some-platform', 'Some Platform')
        test = Test.update_or_insert('some-test', branch, platform)
        self.assertOnlyInstance(test)

        other_branch = Branch.create_if_possible('other-branch', 'Other Branch')
        other_platform = Platform.create_if_possible('other-platform', 'Other Platform')
        test = Test.update_or_insert('some-test', other_branch, other_platform, 'ms')
        self.assertOnlyInstance(test)
        self.assertEqualUnorderedList(test.branches, [branch.key(), other_branch.key()])
        self.assertEqualUnorderedList(test.platforms, [platform.key(), other_platform.key()])
        self.assertEqualUnorderedList(test.unit, 'ms')
Beispiel #23
0
    def test_update_or_insert_to_update(self):
        branch = Branch.create_if_possible('some-branch', 'Some Branch')
        platform = Platform.create_if_possible('some-platform', 'Some Platform')
        test = Test.update_or_insert('some-test', branch, platform)
        self.assertOnlyInstance(test)

        other_branch = Branch.create_if_possible('other-branch', 'Other Branch')
        other_platform = Platform.create_if_possible('other-platform', 'Other Platform')
        test = Test.update_or_insert('some-test', other_branch, other_platform, 'ms')
        self.assertOnlyInstance(test)
        self.assertEqualUnorderedList(test.branches, [branch.key(), other_branch.key()])
        self.assertEqualUnorderedList(test.platforms, [platform.key(), other_platform.key()])
        self.assertEqualUnorderedList(test.unit, 'ms')
Beispiel #24
0
 def test_set_sysan(self):
     a = Test('a')
     with g.session_scope() as s:
         a = s.merge(a)
     with g.session_scope() as s:
         a = g.nodes(Test).ids('a').one()
         a = s.merge(a)
         a.sysan['key1'] = True
         s.merge(a)
     with g.session_scope() as s:
         n = g.nodes(Test).ids('a').one()
         print n.sysan
         self.assertTrue(n.sysan['key1'])
Beispiel #25
0
 def test_unchanged_properties_snapshot(self):
     nid = str(uuid.uuid4())
     a = Test(nid)
     value = '++ VALUE ++'
     with g.session_scope() as s:
         a.key1 = value
         s.merge(a)
         s.commit()
         a = g.nodes(Test).ids(nid).one()
         a.key1 = value
         s.merge(a)
         s.commit()
         self.assertEqual(a._history.all(), [])
Beispiel #26
0
    def test_value_two_platforms(self):
        some_branch = Branch.create_if_possible('some-branch', 'Some Branch')
        some_platform = Platform.create_if_possible('some-platform',
                                                    'Some Platform')
        other_platform = Platform.create_if_possible('other-platform',
                                                     'Other Platform')
        some_test = Test.update_or_insert('some-test', some_branch,
                                          some_platform)

        self._assert_single_test(ManifestJSONGenerator().value(), some_branch,
                                 some_platform, some_test)

        some_test = Test.update_or_insert('some-test', some_branch,
                                          other_platform)
        self.assertEqualUnorderedList(
            some_test.platforms,
            [some_platform.key(), other_platform.key()])

        value = ManifestJSONGenerator().value()
        expected_platform_ids = [some_platform.id, other_platform.id]
        self.assertEqualUnorderedList(value.keys(),
                                      ['branchMap', 'platformMap', 'testMap'])
        self.assertEqualUnorderedList(
            value['branchMap'], {
                some_branch.id: {
                    'name': some_branch.name,
                    'testIds': [some_test.id],
                    'platformIds': expected_platform_ids
                }
            })
        self.assertEqual(
            value['platformMap'], {
                some_platform.id: {
                    'name': some_platform.name,
                    'branchIds': [some_branch.id],
                    'testIds': [some_test.id]
                },
                other_platform.id: {
                    'name': other_platform.name,
                    'branchIds': [some_branch.id],
                    'testIds': [some_test.id]
                }
            })
        self.assertEqual(
            value['testMap'], {
                some_test.id: {
                    'name': some_test.name,
                    'branchIds': [some_branch.id],
                    'platformIds': expected_platform_ids
                }
            })
Beispiel #27
0
 def test_set_query_result_attribute(self):
     new = {'key1': 'first property', 'key2': 'first pass'}
     node = Test(self.nid)
     node.key2 = new['key2']
     with g.session_scope() as session:
         session.merge(node)
     with g.session_scope() as session:
         queried = g.nodes().ids(self.nid).one()
         queried.key1 = new['key1']
         session.merge(queried)
     with g.session_scope() as session:
         expected = _props(Test, new)
         self.assertEqual(g.nodes().ids(self.nid).one().properties,
                          expected)
Beispiel #28
0
def create_test_backup(request):
    test_obj = json.loads(request.body)
    test = Test()
    #import pdb; pdb.set_trace()
    if request.user.is_authenticated():
        owner = User_Profile.objects.filter(user = request.user)
        test.owner = owner[0]
        test.test_name = test_obj['PRE_TEST']['test_name']
        #test.subject = test_obj['PRE_TEST'].subject
        #test.target_exam = test_obj['PRE_TEST'].target_exam
        #test.topics = test_obj['PRE_TEST'].topics_included
        test.total_time = test_obj['PRE_TEST']['total_time']
        test.pass_criteria = test_obj['PRE_TEST']['pass_criteria']
        test.assoicated_class = Class.objects.get(pk=test_obj['CLASS_INFO'])
        test.save()
        try:
            for item in test_obj['QUESTIONS']:
                question = Question()
                question.question_text = item['question_text']
                question.explanation = item['explanation']
                question.options = json.dumps(item['options'])
                question.hint = item['hint']
                question.difficulty = item['difficulty_level']
                question.points = item['points']
                question.owner = owner[0]
                #question.target_exam = test.target_exam
                #question.subject = test.subject
                #question.topic = item.topic
                question.save()
                test.questions.add(question)
            data = {"status" : "success"}
            return JsonResponse(data)
        except Exception, e:
            raise e
Beispiel #29
0
def save_test(request):
    print 'POST: ', request.POST
    rule = None
    if request.POST['pattern']:
        rule = Rule(pattern=request.POST['pattern'], replacement=request.POST['replacement'])
        rule.save()
    if rule:
        test = Test(input=request.POST['input'], output=request.POST['output'], rule=rule)
    else:
        test = Test(input=request.POST['input'], output=request.POST['output'])
    test.save()
    response_data = {}

    return HttpResponse(simplejson.dumps(response_data), mimetype="application/json")
Beispiel #30
0
    def get(self, in_test_id=None):
        template_values = get_template_values( self )
        user = users.get_current_user()
        try:
            entity = Entity.query( Entity.id == user.user_id() ).get()
            if not entity.display_name: # It's only slightly possible to have a user with no display_name
                self.redirect('/login')
        except:
            self.redirect('/login')
        else:
            test_query = Test.query( ancestor = ndb.Key('Entity', user.user_id() ) )
            if len(test_query.fetch()) > 0:
                if in_test_id:
                    in_query = test_query.filter( Test.id == in_test_id ).fetch(1)
                    try: # The test exists
                        template_values = add_test_to_template( template_values, in_query[0] )
                    except IndexError: # The test does not exist
                        self.redirect("/")

            potential_groups = set(
                itertools.chain( entity.test_groups, default_groups )
            )
            print potential_groups
            grouped_marks = get_grouped_marks( entity.id )

            # Add groups with levels for level dropdown
            template_values['user_levels'] = json.dumps( grouped_marks )

            # Add list of groups for group dropdown
            template_values['user_groups'] = []
            for group in grouped_marks:
                group_test_query = Test.query( Test.group == group['group'] ).order(-Test.level).fetch()
                try:
                    threshold = group_test_query[0]
                except:
                    threshold = 0
                print threshold
                for mark in grouped_marks:
                    potential_groups = potential_groups - set(group['group'])
                    if mark['group'] == group and mark["level"] >= threshold:
                        template_values['user_groups'].append( group )
            for group in potential_groups:
                template_values['user_groups'].append( group )

            if template_values["user_groups"] == []:
                template_values['error'] = "You may only create a test in a new category."

            path = os.path.join( os.path.dirname(__file__), os.path.join( template_dir, 'create.html' ) )
            self.response.out.write( template.render( path, template_values ))
        return
Beispiel #31
0
def start_exp():
    """
        Serves up the experiment applet.
    """
    print('prolific_id' in request.args)

    print('Start Expe')

    if not ('prolific_id' in request.args) and (
            'study_id'
            in request.args) and ('participant_id'
                                  in request.args) and ('longit_id'
                                                        in request.args):
        raise ExperimentError(
            'prolific_study_participant_longit_id_not_set_in_exp_url')

    prolific_id = request.args['prolific_id']
    study_id = request.args['study_id']
    participant_id = request.args['participant_id']
    longit_id = request.args['longit_id']

    print(
        ("Prolific ID: {0}, Study ID: {1}, Participant ID: {2}, Longit ID: {3}"
         ).format(prolific_id, study_id, participant_id, longit_id))

    # Filter for prolific id and longit id in the DB: check first to see if they exist.
    matches = Test.query.\
                        filter(Test.prolific_id == prolific_id).\
                        filter(Test.longit_id == longit_id).\
                        all()
    # print(matches)
    numrecs = len(matches)
    if numrecs == 0:  # is not in the DB -> create a record in the DB
        part = Test(prolific_id, study_id, participant_id, longit_id)

        print("No match. Status is", part.status)

        part.status = STARTED
        part.beginexp = datetime.datetime.now()
        part.prolific_id = prolific_id
        part.study_id = study_id
        part.longit_id = int(longit_id)
        part.participant_id = int(participant_id)

        BaseObject.check_and_save(part)

        result = dict({"success": "yes"})

    else:
        part = matches[0]
        print("Participant id {0} matched in the DB! Status is {1}".format(
            participant_id, part.status))

    # Start the task
    return render_template('ps_dev_exp.html',
                           study_id=study_id,
                           participant_id=participant_id,
                           prolific_id=prolific_id,
                           longit_id=longit_id)
Beispiel #32
0
def _create_results(branch, platform, builder, test_name, values):
    results = []
    for i, value in enumerate(values):
        build = Build(branch=branch,
                      platform=platform,
                      builder=builder,
                      buildNumber=i,
                      revision=100 + i,
                      timestamp=datetime.now())
        build.put()
        result = TestResult(name=test_name, build=build, value=value)
        result.put()
        Test.update_or_insert(test_name, branch, platform)
        results.append(result)
    return results
Beispiel #33
0
def create_test(request):
	c=None
	if request.method=='POST':
		testname = request.POST.get('testname','')
		number = request.POST.get('q_number','')
		if 'course' in request.session:
			c = Course.objects.get(name=request.session['course'])
		if c :
			t = Test(name=testname,course = c.id ,question_number=number)
			t.save()
			c.number_test+=1
			c.save()
			return HttpResponseRedirect(reverse('teacher_course',args=(c.name,)))
	else :
		return HttpResponse('wrong method')
Beispiel #34
0
    def post(self):
        self.response.headers['Content-Type'] = 'text/plain; charset=utf-8'

        try:
            payload = json.loads(self.request.body)
            hide = payload['hide']
        except:
            self.response.out.write("Failed to parse the payload: %s" % self.request.body)
            return

        if 'platform' in payload:
            model = Platform.get_by_key_name(payload['platform'])
        elif 'test' in payload:
            model = Test.get_by_key_name(payload['test'])
        else:
            self.response.out.write('Not supported')
            return

        if not model:
            self.response.out.write('Could not find the model')
            return

        model.hidden = hide
        model.put()
        schedule_dashboard_update()
        schedule_manifest_update()

        self.response.out.write('OK')
Beispiel #35
0
    def post( self, in_test_id ):
        path = urlparse.urlsplit(self.request.referrer).path
        author_id = self.request.get("author_id")
        test_id = self.request.get("test_id")
        mark_id = self.request.get("mark_id")
        address = self.request.get("mark_address")
        comment = self.request.get("comment")
        mark = self.request.get("mark")

        author_entity = Entity.query( Entity.id == author_id ).get()
        test_entity = Test.query( Test.id == test_id ).get()
        mark_entity = Mark.query( ancestor = ndb.Key("Entity", mark_id) )
        mark_entity = mark_entity.filter( Mark.test.id == test_id ).get()

        mark_entity.marker_entity = author_entity
        mark_entity.test = test_entity
        mark_entity.comment = comment
        mark_entity.mark = int(mark)
        test_entity.total_score += mark_entity.mark
        test_entity.num_marked += 1
        mark_entity.modified = datetime.datetime.now()
        mark_entity.complete = True
        mark_entity.put()
        send_email( address, test_entity, "Answer-Response")
        test_entity.put()
        self.redirect( path )
        return
Beispiel #36
0
    def post(self):
        test_id = self.request.get( 'test_id' )
        author_id = self.request.get( 'author_id' )

        user = users.get_current_user()
        if user:
            test = Test.query( Test.id == test_id ).get()
            mark_query = Mark.query( ancestor = ndb.Key("Entity", user.user_id() ) )
            mark_query = mark_query.filter( Mark.test.id == test.id )

            this_mark = mark_query.get()

            if this_mark == None:
                print "IndexError"
                this_mark = Mark( parent = ndb.Key("Entity", user.user_id() ) )
                this_mark.test = test
                this_mark.created = datetime.datetime.now()
                this_mark.mark = None
                this_mark.rated = False
                this_mark.rating = 0
                test.times_taken += 1
                test.put()

            this_mark.response = self.request.get( 'response' )
            this_mark.complete = False
            this_mark.modified = datetime.datetime.now()
            this_mark.id = test_id + user.user_id()
            this_mark.marker_entity = Entity.query( Entity.id == author_id ).get()
            this_mark.taker_entity = Entity.query( Entity.id == user.user_id() ).get()
            send_email( this_mark.marker_entity.user.email() , test,  "Test-Answer")
            this_mark.put()

        self.redirect( '/t/%s' % test_id )
        return
Beispiel #37
0
    def get(self):
        self.response.headers['Content-Type'] = 'application/json; charset=utf-8';
        cache = memcache.get('dashboard')
        if cache:
            self.response.out.write(cache)
            return

        webkit_trunk = Branch.get_by_key_name('webkit-trunk')

        # FIXME: Determine popular branches, platforms, and tests
        dashboard = {
            'defaultBranch': 'WebKit trunk',
            'branchToId': {webkit_trunk.name: webkit_trunk.id},
            'platformToId': {},
            'testToId': {},
        }

        for platform in Platform.all():
            dashboard['platformToId'][platform.name] = platform.id

        for test in Test.all():
            dashboard['testToId'][test.name] = test.id

        result = json.dumps(dashboard)
        self.response.out.write(result)
        memcache.add('dashboard', result)
Beispiel #38
0
    def test_update_incrementally(self):
        some_branch = Branch.create_if_possible('some-branch', 'Some Branch')
        some_platform = Platform.create_if_possible('some-platform', 'Some Platform')
        some_builder = Builder.get(Builder.create('some-builder', 'Some Builder'))
        some_test = Test.update_or_insert('some-test', some_branch, some_platform)
        self.assertThereIsNoInstanceOf(Runs)

        timestamps = [datetime.now(), datetime.now()]
        builds, results = self._create_results(some_branch, some_platform, some_builder, 'some-test', [50.0, 52.0], timestamps)
        runs = Runs.update_or_insert(some_branch, some_platform, some_test)
        self.assertOnlyInstance(runs)
        self.assertEqual(json.loads('[' + runs.json_runs + ']'),
            [[5, [4, 0, 100, None], mktime(timestamps[0].timetuple()), 50.0, 0, [], None, None],
            [7, [6, 1, 101, None], mktime(timestamps[1].timetuple()), 52.0, 0, [], None, None]])
        self.assertEqual(json.loads('{' + runs.json_averages + '}'), {"100": 50.0, "101": 52.0})
        self.assertEqual(runs.json_min, 50.0)
        self.assertEqual(runs.json_max, 52.0)

        timestamps.append(datetime.now())
        builds, results = self._create_results(some_branch, some_platform, some_builder, 'some-test', [48.0],
            timestamps[2:], starting_revision=102)
        runs.update_incrementally(builds[0], results[0])

        self.assertOnlyInstance(runs)
        self.assertEqual(json.loads('[' + runs.json_runs + ']'),
            [[5, [4, 0, 100, None], mktime(timestamps[0].timetuple()), 50.0, 0, [], None, None],
            [7, [6, 1, 101, None], mktime(timestamps[1].timetuple()), 52.0, 0, [], None, None],
            [9, [8, 0, 102, None], mktime(timestamps[2].timetuple()), 48.0, 0, [], None, None]])
        self.assertEqual(json.loads('{' + runs.json_averages + '}'), {"100": 50.0, "101": 52.0, "102": 48.0})
        self.assertEqual(runs.json_min, 48.0)
        self.assertEqual(runs.json_max, 52.0)
Beispiel #39
0
    def test_to_json_with_results(self):
        some_branch = Branch.create_if_possible('some-branch', 'Some Branch')
        some_platform = Platform.create_if_possible('some-platform', 'Some Platform')
        some_builder = Builder.get(Builder.create('some-builder', 'Some Builder'))
        some_test = Test.update_or_insert('some-test', some_branch, some_platform)
        builds, results = self._create_results(some_branch, some_platform, some_builder, 'some-test', [50.0, 51.0, 52.0, 49.0, 48.0])

        value = json.loads(Runs.update_or_insert(some_branch, some_platform, some_test).to_json())
        self.assertEqualUnorderedList(value.keys(), ['test_runs', 'averages', 'min', 'max', 'unit', 'date_range', 'stat'])
        self.assertEqual(value['stat'], 'ok')
        self.assertEqual(value['min'], 48.0)
        self.assertEqual(value['max'], 52.0)
        self.assertEqual(value['unit'], None)
        self.assertEqual(value['date_range'], None)  # date_range is never given

        self.assertEqual(len(value['test_runs']), len(results))
        for i, run in enumerate(value['test_runs']):
            result = results[i]
            self.assertEqual(run[0], result.key().id())
            self.assertEqual(run[1][1], i)  # Build number
            self.assertEqual(run[1][2], 100 + i)  # Revision
            self.assertEqual(run[1][3], None)  # Supplementary revision
            self.assertEqual(run[3], result.value)
            self.assertEqual(run[6], some_builder.key().id())
            self.assertEqual(run[7], None)  # Statistics
Beispiel #40
0
    def test_chart_params_with_value(self):
        some_branch = Branch.create_if_possible('some-branch', 'Some Branch')
        some_platform = Platform.create_if_possible('some-platform', 'Some Platform')
        some_builder = Builder.get(Builder.create('some-builder', 'Some Builder'))
        some_test = Test.update_or_insert('some-test', some_branch, some_platform)

        start_time = datetime(2011, 2, 21, 12, 0, 0)
        end_time = datetime(2011, 2, 28, 12, 0, 0)
        results = self._create_results(some_branch, some_platform, some_builder, 'some-test',
            [50.0, 51.0, 52.0, 49.0, 48.0, 51.9, 50.7, 51.1],
            [start_time + timedelta(day) for day in range(0, 8)])

        # Use int despite of its impreciseness since tests may fail due to rounding errors otherwise.
        def split_as_int(string):
            return [int(float(value)) for value in string.split(',')]

        params = Runs.update_or_insert(some_branch, some_platform, some_test).chart_params(7)
        self.assertEqual(params['chxl'], '0:|Feb 21|Feb 22|Feb 23|Feb 24|Feb 25|Feb 26|Feb 27|Feb 28')
        self.assertEqual(split_as_int(params['chxr']), [1, 0, 57, int(52 * 1.1 / 5 + 0.5)])
        x_min, x_max, y_min, y_max = split_as_int(params['chds'])
        self.assertEqual(datetime.fromtimestamp(x_min), start_time)
        self.assertEqual(datetime.fromtimestamp(x_max), end_time)
        self.assertEqual(y_min, 0)
        self.assertEqual(y_max, int(52 * 1.1))
        self.assertEqual(split_as_int(params['chg']), [int(100 / 7), 20, 0, 0])

        params = Runs.update_or_insert(some_branch, some_platform, some_test).chart_params(14)
        self.assertEqual(params['chxl'], '0:|Feb 14|Feb 16|Feb 18|Feb 20|Feb 22|Feb 24|Feb 26|Feb 28')
        self.assertEqual(split_as_int(params['chxr']), [1, 0, 57, int(52 * 1.1 / 5 + 0.5)])
        x_min, x_max, y_min, y_max = split_as_int(params['chds'])
        self.assertEqual(datetime.fromtimestamp(x_min), datetime(2011, 2, 14, 12, 0, 0))
        self.assertEqual(datetime.fromtimestamp(x_max), end_time)
        self.assertEqual(y_min, 0)
        self.assertEqual(y_max, int(52 * 1.1))
        self.assertEqual(split_as_int(params['chg']), [int(100 / 7), 20, 0, 0])
Beispiel #41
0
    def post(self):
        self.response.headers['Content-Type'] = 'text/plain; charset=utf-8'

        log_id = int(self.request.get('id', 0))

        log = ReportLog.get_by_id(log_id)
        if not log or not log.commit:
            self.response.out.write("Not processed")
            return

        branch = log.branch()
        platform = log.platform()
        build = Build.get_or_insert_from_log(log)

        for test_name, result_value in log.results().iteritems():
            test = Test.update_or_insert(test_name, branch, platform)
            result = TestResult.get_or_insert_from_parsed_json(test_name, build, result_value)
            runs = Runs.get_by_objects(branch, platform, test)
            regenerate_runs = True
            if runs:
                runs.update_incrementally(build, result)
                regenerate_runs = False
            schedule_runs_update(test.id, branch.id, platform.id, regenerate_runs)

        log = ReportLog.get(log.key())
        log.delete()

        # We need to update dashboard and manifest because they are affected by the existance of test results
        schedule_dashboard_update()
        schedule_manifest_update()

        self.response.out.write('OK')
Beispiel #42
0
    def test_value_single_platform(self):
        some_branch = Branch.create_if_possible('some-branch', 'Some Branch')
        some_platform = Platform.create_if_possible('some-platform', 'Some Platform')
        self.assertEqual(ManifestJSONGenerator().value(), {'branchMap': {}, 'platformMap': {}, 'testMap': {}})

        some_test = Test.update_or_insert('some-test', some_branch, some_platform)
        self._assert_single_test(ManifestJSONGenerator().value(), some_branch, some_platform, some_test)
def start_test(test_id):
    """
    Start a test.

    If an existing test_attempt that is not complete exists, it is returned.
    If not, if the user has access to the test, a new test attempt and section
    attempt(s) is created and returned.

    :param testID:
    :return: the id of the test attempt
    """

    try:
        attempt = (
            TestAttempt.query
            # can be made inner join because section attempts should
            # exist if question attempt exists
            .join(TestAttempt.section_attempts).options(
                contains_eager(TestAttempt.section_attempts)).filter(
                    TestAttempt.test_id == test_id).filter(
                        TestAttempt.user_id == current_user.id).one())

        if attempt.is_complete:
            return Error("Test is already completed", 403, "TAC001")()

        sorted_section_attempts = sorted(attempt.section_attempts,
                                         key=lambda x: x.id)

        current_section = (filter(lambda x: x.is_complete == False,
                                  sorted_section_attempts))

        # todo penalize the current_section by the value of
        # Pinger's time.

        current_section_id = list(current_section)[0].section_id

    except NoResultFound:  # didn't find existing attempt, create a new one

        if not Test.user_has_access(current_user, test_id):
            return Error("Purchase the Test", 400)()

        current_section_id = TestAttempt.setup_test_attempt(
            test_id, current_user.id)

    test = (Test.query.filter(Test.id == test_id).options(
        load_only(Test.allow_section_jumps)).one())

    # finally, update the cookie
    string = Pinger.push_data_from_data(
        test_id, current_section_id, test.allow_section_jumps == True,
        datetime.timestamp(datetime.now()) + Pinger.PING_GRACE, 0)

    resp = Response()
    resp.headers["ping"] = string

    AuditLog.log_start_test_event(user_id=current_user.id,
                                  test_id=test_id,
                                  current_section_id=current_section_id)

    return resp
Beispiel #44
0
def registration():
    form = RegistrationForm()
    if form.validate_on_submit():
        target = os.path.join(APP_ROOT, 'static/avatars/')
        if not os.path.isdir(target):
            os.makedirs(target)

        file = request.files['file']
        filename = secure_filename(file.filename)
        destination = '/'.join([target, filename])
        file.save(destination)
        '''
        new_user = User(username=form.username.data,
                        email=form.email.data,
                        planet=form.planet.data,
                        password=form.password.data)
        db.session.add(new_user)
        db.session.commit()
        '''
        new_user = Test(username=form.username.data,
                        email=form.email.data,
                        planet=form.planet.data,
                        avatar=file.read(),
                        password=form.password.data)
        db.session.add(new_user)
        db.session.commit()
        print(f'Account created for {form.username.data}!', 'success')

        return redirect(url_for('user', name=form.username.data))
    return render_template('register.html', title='Register', form=form)
def APITests():
    rdata = request.get_json() #allows to get JSON data from request example JSON data: {"title":"hello"}
    test_id = request.args.get('id') #get id from URL (/API/Tests/?id=<ID>)

    if request.method == 'GET': #define used method
        tests = Test.query.all() #get all tests
        jsonized = jsonify(tests=[(dict(id=test.id, title=test.title)) for test in tests]) #create list of tests
        return jsonized #return our list

    elif request.method == 'POST':
        title = rdata["title"] #get JSON "title"

        try: #try to add values into database, if you have same values entered, will force 403 error
            t = Test(title=title) #create new object
            db.session.add(t) #add to database
            db.session.commit() #commit changes

            return jsonify(created_id=t.id) #return id of created data (optional)
        except IntegrityError: #force error if data exists
            return pdenied

    elif request.method == 'PUT':
        new_title = rdata['title']
        try:
            db.session.query(Test).filter_by(id=test_id).update({"title": new_title}) #Update data
            db.session.commit()
            return OK
        except IntegrityError:
            return pdenied #force error if entered data is equal past data

    elif request.method == 'DELETE':

        Test.query.filter_by(id=test_id).delete() #delete by id(test_id)
        db.session.commit()
        return OK
def main(database_file):
    dao = PerformanceTestDAO(database_file)
    session = dao.get_session()
    for num_containers in (1, 5, 10, 20, 40, 60, 80, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600):
        test = Test(image_id='packettracer_xvfb_mount', volumes_from='ptdata', number_of_containers=num_containers, repetitions=1)
        session.add(test)
    session.commit()
Beispiel #47
0
def load_xls(file_location):
    data = parse_xls(file_location)
    for row in data:
        test = Test(row['SITEID'], row['GENDER'], row['ETHNICITY'],
                    int(row['AGE']))
        db_session.add(test)
    db_session.commit()
Beispiel #48
0
    def get(self):
        self.response.headers["Content-Type"] = "application/json; charset=utf-8"

        cache = memcache.get("dashboard")
        if cache:
            self.response.out.write(cache)
            return

        webkitTrunk = Branch.get_by_key_name("webkit-trunk")

        # FIXME: Determine popular branches, platforms, and tests
        dashboard = {
            "defaultBranch": "WebKit trunk",
            "branchToId": {webkitTrunk.name: webkitTrunk.id},
            "platformToId": {},
            "testToId": {},
        }

        for platform in Platform.all():
            dashboard["platformToId"][platform.name] = platform.id

        for test in Test.all():
            dashboard["testToId"][test.name] = test.id

        result = json.dumps(dashboard)
        self.response.out.write(result)
        memcache.add("dashboard", result)
Beispiel #49
0
    def test_update_incrementally(self):
        some_branch = Branch.create_if_possible('some-branch', 'Some Branch')
        some_platform = Platform.create_if_possible('some-platform', 'Some Platform')
        some_builder = Builder.get(Builder.create('some-builder', 'Some Builder'))
        some_test = Test.update_or_insert('some-test', some_branch, some_platform)
        self.assertThereIsNoInstanceOf(Runs)

        timestamps = [datetime.now(), datetime.now()]
        builds, results = self._create_results(some_branch, some_platform, some_builder, 'some-test', [50.0, 52.0], timestamps)
        runs = Runs.update_or_insert(some_branch, some_platform, some_test)
        self.assertOnlyInstance(runs)
        self.assertEqual(json.loads('[' + runs.json_runs + ']'),
            [[5, [4, 0, 100, None], mktime(timestamps[0].timetuple()), 50.0, 0, [], None, None],
            [7, [6, 1, 101, None], mktime(timestamps[1].timetuple()), 52.0, 0, [], None, None]])
        self.assertEqual(json.loads('{' + runs.json_averages + '}'), {"100": 50.0, "101": 52.0})
        self.assertEqual(runs.json_min, 50.0)
        self.assertEqual(runs.json_max, 52.0)

        timestamps.append(datetime.now())
        builds, results = self._create_results(some_branch, some_platform, some_builder, 'some-test', [48.0],
            timestamps[2:], starting_revision=102)
        runs.update_incrementally(builds[0], results[0])

        self.assertOnlyInstance(runs)
        self.assertEqual(json.loads('[' + runs.json_runs + ']'),
            [[5, [4, 0, 100, None], mktime(timestamps[0].timetuple()), 50.0, 0, [], None, None],
            [7, [6, 1, 101, None], mktime(timestamps[1].timetuple()), 52.0, 0, [], None, None],
            [9, [8, 0, 102, None], mktime(timestamps[2].timetuple()), 48.0, 0, [], None, None]])
        self.assertEqual(json.loads('{' + runs.json_averages + '}'), {"100": 50.0, "101": 52.0, "102": 48.0})
        self.assertEqual(runs.json_min, 48.0)
        self.assertEqual(runs.json_max, 52.0)
Beispiel #50
0
    def test_chart_params_with_value(self):
        some_branch = Branch.create_if_possible('some-branch', 'Some Branch')
        some_platform = Platform.create_if_possible('some-platform', 'Some Platform')
        some_builder = Builder.get(Builder.create('some-builder', 'Some Builder'))
        some_test = Test.update_or_insert('some-test', some_branch, some_platform)

        start_time = datetime(2011, 2, 21, 12, 0, 0)
        end_time = datetime(2011, 2, 28, 12, 0, 0)
        results = self._create_results(some_branch, some_platform, some_builder, 'some-test',
            [50.0, 51.0, 52.0, 49.0, 48.0, 51.9, 50.7, 51.1],
            [start_time + timedelta(day) for day in range(0, 8)])

        # Use int despite of its impreciseness since tests may fail due to rounding errors otherwise.
        def split_as_int(string):
            return [int(float(value)) for value in string.split(',')]

        params = Runs.update_or_insert(some_branch, some_platform, some_test).chart_params(7)
        self.assertEqual(params['chxl'], '0:|Feb 21|Feb 22|Feb 23|Feb 24|Feb 25|Feb 26|Feb 27|Feb 28')
        self.assertEqual(split_as_int(params['chxr']), [1, 0, 57, int(52 * 1.1 / 5 + 0.5)])
        x_min, x_max, y_min, y_max = split_as_int(params['chds'])
        self.assertEqual(datetime.fromtimestamp(x_min), start_time)
        self.assertEqual(datetime.fromtimestamp(x_max), end_time)
        self.assertEqual(y_min, 0)
        self.assertEqual(y_max, int(52 * 1.1))
        self.assertEqual(split_as_int(params['chg']), [int(100 / 7), 20, 0, 0])

        params = Runs.update_or_insert(some_branch, some_platform, some_test).chart_params(14)
        self.assertEqual(params['chxl'], '0:|Feb 14|Feb 16|Feb 18|Feb 20|Feb 22|Feb 24|Feb 26|Feb 28')
        self.assertEqual(split_as_int(params['chxr']), [1, 0, 57, int(52 * 1.1 / 5 + 0.5)])
        x_min, x_max, y_min, y_max = split_as_int(params['chds'])
        self.assertEqual(datetime.fromtimestamp(x_min), datetime(2011, 2, 14, 12, 0, 0))
        self.assertEqual(datetime.fromtimestamp(x_max), end_time)
        self.assertEqual(y_min, 0)
        self.assertEqual(y_max, int(52 * 1.1))
        self.assertEqual(split_as_int(params['chg']), [int(100 / 7), 20, 0, 0])
Beispiel #51
0
    def test_to_json_with_results(self):
        some_branch = Branch.create_if_possible('some-branch', 'Some Branch')
        some_platform = Platform.create_if_possible('some-platform', 'Some Platform')
        some_builder = Builder.get(Builder.create('some-builder', 'Some Builder'))
        some_test = Test.update_or_insert('some-test', some_branch, some_platform)
        builds, results = self._create_results(some_branch, some_platform, some_builder, 'some-test', [50.0, 51.0, 52.0, 49.0, 48.0])

        value = json.loads(Runs.update_or_insert(some_branch, some_platform, some_test).to_json())
        self.assertEqualUnorderedList(value.keys(), ['test_runs', 'averages', 'min', 'max', 'unit', 'date_range', 'stat'])
        self.assertEqual(value['stat'], 'ok')
        self.assertEqual(value['min'], 48.0)
        self.assertEqual(value['max'], 52.0)
        self.assertEqual(value['unit'], None)
        self.assertEqual(value['date_range'], None)  # date_range is never given

        self.assertEqual(len(value['test_runs']), len(results))
        for i, run in enumerate(value['test_runs']):
            result = results[i]
            self.assertEqual(run[0], result.key().id())
            self.assertEqual(run[1][1], i)  # Build number
            self.assertEqual(run[1][2], 100 + i)  # Revision
            self.assertEqual(run[1][3], None)  # Supplementary revision
            self.assertEqual(run[3], result.value)
            self.assertEqual(run[6], some_builder.key().id())
            self.assertEqual(run[7], None)  # Statistics
Beispiel #52
0
    def test_update_or_insert(self):
        some_branch = Branch.create_if_possible('some-branch', 'Some Branch')
        some_platform = Platform.create_if_possible('some-platform', 'Some Platform')
        some_builder = Builder.get(Builder.create('some-builder', 'Some Builder'))
        some_test = Test.update_or_insert('some-test', some_branch, some_platform)
        self.assertThereIsNoInstanceOf(Runs)

        runs = Runs.update_or_insert(some_branch, some_platform, some_test)
        self.assertOnlyInstance(runs)
        self.assertEqual(runs.json_runs, '')
        self.assertEqual(runs.json_averages, '')
        self.assertEqual(runs.json_min, None)
        self.assertEqual(runs.json_max, None)
        old_memcache_value = memcache.get(Runs._key_name(some_branch.id, some_platform.id, some_test.id))
        self.assertTrue(old_memcache_value)

        runs.delete()
        self.assertThereIsNoInstanceOf(Runs)

        builds, results = self._create_results(some_branch, some_platform, some_builder, 'some-test', [50.0])
        runs = Runs.update_or_insert(some_branch, some_platform, some_test)
        self.assertOnlyInstance(runs)
        self.assertTrue(runs.json_runs.startswith('[5, [4, 0, 100, null],'))
        self.assertEqual(json.loads('{' + runs.json_averages + '}'), {"100": 50.0})
        self.assertEqual(runs.json_min, 50.0)
        self.assertEqual(runs.json_max, 50.0)
        self.assertNotEqual(memcache.get(Runs._key_name(some_branch.id, some_platform.id, some_test.id)), old_memcache_value)
Beispiel #53
0
    def get(self, test_to_get=None):
        template_values = get_template_values( self )
        user = users.get_current_user()

        if not test_to_get:
            self.logger.debug("No test was provided for lookup")
            self.redirect('/')
            return
        else:
            try:
                test = Test.query( Test.id == test_to_get).fetch(1)[0]
            except IndexError:
                self.logger.debug("Invalid Test ID")
                self.redirect('/')
            else:
                if user:
                    template_values = add_entity_to_template(
                        template_values,
                        Entity.query( Entity.id == user.user_id() ).fetch(1)[0]
                    )
                    user_level = get_user_group_level(
                        get_grouped_marks( user.user_id() ),
                        test.group
                    )
                    if user_level == None:
                        user_level = 1

                    template_values['user_level'] = user_level
                    if user_level < test.level:
                        template_values['locked'] = True
                    try:
                        mark_query = Mark.query( ancestor = ndb.Key("Entity", user.user_id() ) )
                        mark = mark_query.filter( Mark.test.id == test.id ).fetch(1)[0]
                        template_values = add_mark_to_template( template_values, mark )
                        if (datetime.datetime.now() - mark.modified) < datetime.timedelta(hours=24) or mark.complete:
                            template_values['locked'] = True
                    except IndexError:
                        self.logger.debug( "No mark found" )
                        template_values = add_test_to_template( template_values, test )
                    finally:
                        if test.author_id == user.user_id():
                            template_values['is_test_marker'] = True
                            template_values['locked'] = True
                            test_marker = Entity.query( Entity.id == user.user_id() ).get()
                            template_values['to_be_marked'] = get_to_be_marked( test_marker, test )
                            template_values['name'] = test_marker.display_name
                            template_values['current_user'] = user.user_id()
                else:
                    template_values['locked'] = True
                    template_values['visitor'] = True
                    logging.warning("User not found!")
                    template_values = add_test_to_template( template_values, test )


            finally:

                path = os.path.join( os.path.dirname(__file__), os.path.join( template_dir, 'test_detail.html') )
                self.response.out.write( template.render( path, template_values) )
        return
Beispiel #54
0
    def post(self):
        template_values = get_template_values( self )
        user = users.get_current_user()

        if self.request.get('next'):
            cursor = search.Cursor(web_safe_string=self.request.get('next'))
        else:
            cursor = search.Cursor()

        q = query = self.request.get("search-text").replace(',',"")
        order = self.request.get("search-order")
        completed = True if self.request.get("search-completed") == "on" else False

        template_values["query_values"] = {
            'query':query,
            'order':order,
            'completed':completed,
        }

        if order == "rating":
            sort_exp = search.SortExpression( expression='rating', direction=search.SortExpression.DESCENDING, default_value=0)
        elif order == "times_taken":
            sort_exp = search.SortExpression( expression='times_taken', direction=search.SortExpression.DESCENDING, default_value=0)
        elif order == "date_inc":
            sort_exp = search.SortExpression( expression='date', direction=search.SortExpression.DESCENDING, default_value=0)
        elif order == "date_dec":
            sort_exp = search.SortExpression( expression='date', direction=search.SortExpression.ASCENDING, default_value=0)
        elif order == "level_dec":
            sort_exp = search.SortExpression( expression='level', direction=search.SortExpression.DESCENDING, default_value=0)
        elif order == "level_inc":
            sort_exp = search.SortExpression( expression='level', direction=search.SortExpression.ASCENDING, default_value=0)

        query_options = search.QueryOptions(
            limit = self.page_depth,
            cursor = cursor,
            sort_options = search.SortOptions(expressions=[sort_exp,]),
        )

        query_obj = search.Query(query_string=query, options=query_options)
        results = search.Index(name="tests").search(query=query_obj)
        template_values["query_results"] = []

        for document in results:
            test = Test.query( Test.id == document.doc_id ).get()
            if completed and user:
                # If the "Hide completed" checkbox is selected by the user
                if Mark.query( Mark.taker_entity.id == user.user_id(), Mark.test.id == test.id ).get() != None :
                    # And a Mark has been created
                    continue # Don't add it to the list.
                    # If this continue is active, this selects out TAKEN tests
                    # Otherwise , this if statement selects out MARKED tests
                    if Mark.query( Mark.complete == False ).get() == None:
                        # And the Test has been marked as completed for this user.
                        continue # Don't add it to the list.
            template_values["query_results"].append( test )

        path = os.path.join( os.path.dirname(__file__), os.path.join( template_dir, 'main.html' ) )
        self.response.out.write( template.render( path, template_values ))
        return
Beispiel #55
0
def send_presses(request, instance_name):
    instance = get_object_or_404(ExperimentInstance, name=instance_name)
    sessions = Session.objects.filter(instance=instance)
    searched_session = 0
    _dict = request.POST.copy()
    for session in sessions:
        tests = Test.objects.filter(session=session)
        if len(tests) < instance.definition.session_length:
            searched_session = session
    new_test = Test(session=searched_session, number=_dict['config'])
    new_test.save()
    del(_dict['config'])
    print _dict
    for i in _dict:
        new_press = Press(test=new_test, key_number=int(i), time=int(_dict[i]), correct=True)
        new_press.save()
    return JsonResponse({'ok': 'ok'})
Beispiel #56
0
def student_details(test_id):
    test = Test.get_by_id(test_id)
    if request.method == "POST":
        data = request.get_json(force=False, silent=False, cache=False) 
        test.student_data = data
        test.put()
    student_data = json.dumps(test.student_data)
    return render_template('student_details.html', test_id = test_id, test = test, student_data = student_data)
Beispiel #57
0
    def get(self):
        self.response.headers['Content-Type'] = 'application/json'

        test_id, branch_id, platform_id = _get_test_branch_platform_ids(self)
        runs = PersistentCache.get_cache(Test.cache_key(test_id, branch_id, platform_id))
        if runs:
            self.response.out.write(runs)
        else:
            schedule_runs_update(test_id, branch_id, platform_id)
Beispiel #58
0
    def get(self):
        self.response.headers['Content-Type'] = 'application/json; charset=utf-8'

        try:
            testId = int(self.request.get('id', 0))
            branchId = int(self.request.get('branchid', 0))
            platformId = int(self.request.get('platformid', 0))
        except TypeError:
            # FIXME: Output an error here
            testId = 0
            branchId = 0
            platformId = 0

        # FIXME: Just fetch builds specified by "days"
        # days = self.request.get('days', 365)

        cacheKey = Test.cacheKey(testId, branchId, platformId)
        cache = memcache.get(cacheKey)
        if cache:
            self.response.out.write(cache)
            return

        builds = Build.all()
        builds.filter('branch =', modelFromNumericId(branchId, Branch))
        builds.filter('platform =', modelFromNumericId(platformId, Platform))

        test = modelFromNumericId(testId, Test)
        testName = test.name if test else None
        test_runs = []
        averages = {}
        values = []
        timestamps = []

        for build in builds:
            results = TestResult.all()
            results.filter('name =', testName)
            results.filter('build =', build)
            for result in results:
                builderId = build.builder.key().id()
                posixTimestamp = mktime(build.timestamp.timetuple())
                test_runs.append([result.key().id(),
                    [build.key().id(), build.buildNumber, build.revision],
                    posixTimestamp, result.value, 0, [], builderId])
                # FIXME: Calculate the average; in practice, we wouldn't have more than one value for a given revision
                averages[build.revision] = result.value
                values.append(result.value)
                timestamps.append(posixTimestamp)

        result = json.dumps({
            'test_runs': test_runs,
            'averages': averages,
            'min': min(values) if values else None,
            'max': max(values) if values else None,
            'date_range': [min(timestamps), max(timestamps)] if timestamps else None,
            'stat': 'ok'})
        self.response.out.write(result)
        memcache.add(cacheKey, result)
Beispiel #59
0
def update_test(test_id):
    test = Test.get_by_id(test_id)
    if request.method == "POST":
        data = request.get_json(force=False, silent=False, cache=False)
        test.test_data = data
        #test.test_data = request.get_json(force=False, silent=False, cache=False);
        test.put()
    new_data = json.dumps(test.test_data)
    return render_template('update_test.html', test=test, mc_data = new_data, bad_test = test.test_data)
Beispiel #60
0
    def test_to_json_with_unit(self):
        some_branch = Branch.create_if_possible('some-branch', 'Some Branch')
        some_platform = Platform.create_if_possible('some-platform', 'Some Platform')
        some_builder = Builder.get(Builder.create('some-builder', 'Some Builder'))
        some_test = Test.update_or_insert('some-test', some_branch, some_platform, 'runs/s')
        builds, results = self._create_results(some_branch, some_platform, some_builder, 'some-test', [50.0, 51.0, 52.0, 49.0, 48.0])

        value = json.loads(Runs.update_or_insert(some_branch, some_platform, some_test).to_json())
        self.assertEqual(value['unit'], 'runs/s')