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()
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)
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])
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")
def test_property_merge(self): node = Test('a') node.key1 = 'first' node.key2 = 'first' with g.session_scope() as session: session.merge(node) node = Test('a') node.key1 = 'second' node.key1 = 'third' with g.session_scope() as session: session.merge(node) with g.session_scope() as session: node = g.nodes(Test).ids('a').one() self.assertEqual(node.key1, 'third') self.assertEqual(node.key2, 'first')
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'))
def test_custom_insert_hooks(self): """Test that all custom insert hooks are called.""" self._clear_tables() node_id = 'test_insert' def add_key1(target, session, *args, **kwargs): target.key1 = 'value1' def add_key2(target, session, *args, **kwargs): target.key2 = 'value2' Test._session_hooks_before_insert = [ add_key1, add_key2, ] try: with g.session_scope() as s: test = Test(node_id) s.merge(test) with g.session_scope(): test = g.nodes(Test).ids(node_id).one() self.assertEqual(test.key1, 'value1') self.assertEqual(test.key2, 'value2') finally: Test._session_hooks_before_insert = []
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()
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 handle_test(): """ Create person and retrieve all persons """ # POST request if request.method == 'POST': body = request.get_json() # if body is None: # raise APIException("You need to specify the request body as a json object", status_code=400) # if 'testStatus' not in body: # raise APIException('You need to specify the test', status_code=400) test1 = Test(name=body['name']) db.session.add(test1) db.session.commit() return "ok", 200 # GET request if request.method == 'GET': all_people = Test.query.all() all_people = list(map(lambda x: x.serialize(), all_people)) return jsonify(all_people), 200 return "Invalid Method", 404
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'))
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 test_custom_delete_hooks(self): """Test that all custom pre-delete hooks are called.""" self._clear_tables() node_id = 'test_update' new_node_id1 = 'pre-delete-1' new_node_id2 = 'pre-delete-2' def add_new_node1(target, session, *args, **kwargs): session.merge(Test(new_node_id1)) def add_new_node2(target, session, *args, **kwargs): session.merge(Test(new_node_id2)) Test._session_hooks_before_delete = [ add_new_node1, add_new_node2, ] try: with g.session_scope() as s: assert not g.nodes(Test).ids(node_id).first() test = Test(node_id) test = s.merge(test) s.commit() s.delete(test) with g.session_scope(): g.nodes(Test).ids(new_node_id1).one() g.nodes(Test).ids(new_node_id2).one() self.assertFalse(g.nodes(Test).ids(node_id).scalar()) finally: Test._session_hooks_before_delete = []
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()
def test_custom_hooks_are_class_local(self): """Test that all custom hooks affect single classes.""" self._clear_tables() node_id = 'test_locality' def bad_hook(target, session, *args, **kwargs): raise RuntimeError Test._session_hooks_before_insert = [ bad_hook, ] try: with self.assertRaises(RuntimeError): with g.session_scope() as s: test = Test(node_id) s.merge(test) with g.session_scope() as s: foo = Foo(node_id) s.merge(foo) with g.session_scope(): foo = g.nodes(Foo).ids(node_id).one() self.assertEqual(foo.bar, None) self.assertEqual(foo.baz, None) finally: Test._session_hooks_before_insert = []
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
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)
def test_neomodel(): # Test connection object current_app.logger.debug("graph db object: %s" % neomodel.graph_db) # Create a new node test = Test(name="just a test").save() current_app.logger.info("created test object: %s" % test) return test.name
def __init__(self, scan): self.scan = scan self.test = Test(scan_id=self.scan.id, name="SSLAPI", status=1, started_date=datetime.utcnow()) db_session.add(self.test) db_session.commit()
def test_source_insert_5(self): s5 = Test(title='mybook5', publisher_name='publisher5') session.add(s5) r5 = session.query(Test).filter_by(title='mybook5').one() self.assertEqual(str(r5.publisher_name), 'publisher5') session.query(Test).filter_by(title='mybook5').delete() session.commit()
def test_source_insert_8(self): s8 = Test(title='mybook8', publisher_name='publisher8') session.add(s8) r8 = session.query(Test).filter_by(title='mybook8').one() self.assertEqual(str(r8.publisher_name), 'publisher8') session.query(Test).filter_by(title='mybook8').delete() session.commit()
def test_relationship_population_constructer(self): a = Test('a') b = Foo('b') e = Edge2(src=a, dst=b) with g.session_scope() as s: a, b = map(s.merge, (a, b)) e2 = s.query(Edge2).src('a').dst('b').one() e = a._Edge2_out[0] self.assertEqual(e2, e)
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')
def test_source_insert_7(self): s7 = Test(title='mybook7', publisher_name='publisher7') session.add(s7) r7 = session.query(Test).filter_by(title='mybook7').one() self.assertEqual(str(r7.publisher_name), 'publisher7') session.query(Test).filter_by(title='mybook7').delete() session.commit()
def test_source_insert_6(self): s6 = Test(title='mybook6', publisher_name='publisher6') session.add(s6) r6 = session.query(Test).filter_by(title='mybook6').one() self.assertEqual(str(r6.publisher_name), 'publisher6') session.query(Test).filter_by(title='mybook6').delete() session.commit()
def load_test(): for f in glob.glob(os.path.join(data_dir, 'test*.csv')): df = pd.read_csv(f) for ix, row in df.iterrows(): test = Test(test_code=row['testCode'], name=row['name'], unit=row['unit']) session.add(test) session.commit()
def test_source_insert_4(self): s4 = Test(title='mybook4', publisher_name='publisher4') session.add(s4) r4 = session.query(Test).filter_by(title='mybook4').one() self.assertEqual(str(r4.publisher_name), 'publisher4') session.query(Test).filter_by(title='mybook4').delete() session.commit()
def test_source_insert_3(self): s3 = Test(title='mybook3', publisher_name='publisher3') session.add(s3) r3 = session.query(Test).filter_by(title='mybook3').one() self.assertEqual(str(r3.publisher_name), 'publisher3') session.query(Test).filter_by(title='mybook3').delete() session.commit()
def test_source_insert_2(self): s2 = Test(title='mybook2', author_name='author2') session.add(s2) session.commit() r2 = session.query(Test).filter_by(title='mybook2').one() self.assertEqual(str(r2.author_name), 'author2') session.query(Test).filter_by(title='mybook2').delete() session.commit()
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"}