def test_time_type_setting(self): """Tests whether the time type can be set correctly.""" self.post = Post( title="Title", text="Text", user_id=1, topics=[Topic(tag_name="topic1"), Topic(tag_name="topic2")], id=1) # Difference between the two timestamps is in minutes. # So timetype should equal 0. self.post.timestamp = datetime(2018, 6, 29, 10, 00, 00) self.test_timestamp = datetime(2018, 6, 29, 10, 2, 00) self.post.get_minutes(input_time=self.test_timestamp) self.assertEqual(0, self.post.time_type) self.assertFalse(1 == self.post.time_type) # Difference between the two timestamps is in hours. # So timetype should equal 1. self.post.timestamp = datetime(2018, 6, 29, 10, 00, 00) self.test_timestamp = datetime(2018, 6, 29, 11, 2, 00) self.post.get_minutes(input_time=self.test_timestamp) self.assertEqual(1, self.post.time_type) self.assertFalse(2 == self.post.time_type) # Difference between the two timestamps is in hours. # So timetype should equal 1. self.post.timestamp = datetime(2018, 6, 29, 10, 00, 00) self.test_timestamp = datetime(2018, 6, 30, 11, 2, 00) self.post.get_minutes(input_time=self.test_timestamp) self.assertEqual(2, self.post.time_type) self.assertFalse(1 == self.post.time_type)
def test_submit(self): """Tests whether posts can be put inside the database.""" self.post = Post( title="Title", text="Text", user_id=1, topics=[Topic(tag_name="topic1"), Topic(tag_name="topic2")]) self.post.upvotes = 1 self.post.downvotes = 0 self.post.importance = 1 self.post.score = self.post.get_score() db.session.add(self.post) db.session.commit()
def test_downvoting(self): """Tests whether posts can be downvoted or not.""" self.post = Post( title="Title", text="Text", user_id=1, topics=[Topic(tag_name="topic1"), Topic(tag_name="topic2")], id=1) self.post.downvotes = 1 db.session.add(self.post) db.session.commit() self.post.downvotes += 1 db.session.commit()
def test_add_new_comment(self): """Tests whether a new comment can be added.""" self.post = Post( title="Title", text="Text", user_id=1, topics=[Topic(tag_name="topic1"), Topic(tag_name="topic2")], id=1) db.session.add(self.post) db.session.commit() self.comment = Comment(text="This is a test", post_id=self.post.id) db.session.add(self.comment) db.session.commit()
def create(): form = TopicForm() topic = Topic(name=form.name.data, description=form.description.data) db.session.add(topic) db.session.commit() flash('New Topic Added!') return redirect(url_for('topics.show', id=topic.id)) # redirect to the topic.show view for the newly created topic
def create_topic(): question = request.form['question'] answer = request.form['answer'] newTopic = Topic(question=question, answer=answer) db.session.add(newTopic) db.session.commit() return redirect('/manage')
def load_sentences(): """Load the content of data.yml into the English / Latin tables""" yaml = open('data/quiz_data.yml') data = ruamel.yaml.load(yaml, ruamel.yaml.RoundTripLoader) print data for topic_name, quiz in data.items(): topic = (Topic.query.filter_by(name=topic_name).first() or Topic(name=topic_name)) print topic topic.save() for quiz_name, sentences in quiz.items(): quiz = Quiz(name=quiz_name, topic=topic) print quiz quiz.save() for question, answers in sentences.items(): type = answers.pop(0)['type'] q = Sentence(type=type, text=question, quiz=quiz) for answer in answers: a = Sentence(text=answer, ) q.translations.append(a) a.translations.append(q) db.session.add(q) db.session.commit()
def test_can_delete_post(self): """Tests whether a post can be deleted.""" self.post = Post( title="Title", text="Text", user_id=1, topics=[Topic(tag_name="topic1"), Topic(tag_name="topic2")], id=99) db.session.add(self.post) db.session.commit() db.session.delete(self.post) db.session.commit() posts = self.assertIsNone(Post.query.filter_by(id=99).first())
def get_topic(topic): if bool(Topic.query.filter(Topic.name.contains(topic)).first()): return Topic.query.filter(Topic.name.contains(topic)).first() new_topic = Topic(name=topic) db.session.add(new_topic) db.session.commit() return new_topic
def test_can_fetch_post(self): """Tests whether posts can be fetched from the database.""" self.post = Post( title="Title", text="Text", user_id=1, topics=[Topic(tag_name="topic1"), Topic(tag_name="topic2")], id=1) self.post.upvotes = 1 self.post.downvotes = 0 self.post.importance = 1 self.post.score = self.post.get_score() db.session.add(self.post) db.session.commit() self.query = Post.query.filter_by(id=1).first() self.query = Post.query.filter_by(user_id=1).first()
def build_topic_2(): test_topic_2 = Topic( topic_id=2, body='A VR company is seeking computer vision experts', title=u'VR & AR', created_time=datetime.utcnow(), rate=150.0, expert_id=101) return test_topic_2
def add_topic(): form = new_topic_forme() if form.validate_on_submit(): data = form.data topic_s = Topic(topic_s=data["topic"], user_id=session["user_id"]) db.session.add(topic_s) db.session.commit() return redirect("/topic/") return render_template("home/new_topic.html", form=form)
def build_topic_1(): test_topic_1 = Topic( topic_id=1, body= 'Our company needs a real-time recommendation system, who can help us?', title=u'推荐系统求助', created_time=datetime.utcnow(), rate=100.0, expert_id=101) return test_topic_1
def test_check_topic_exists_func(self): """Tests whether check_topic_exists function work.""" self.test_topic_str = "test" self.test_topic = Topic(tag_name=self.test_topic_str) db.session.add(self.test_topic) db.session.commit() self.assertTrue(check_topic_exists(self.test_topic_str)) self.assertFalse(check_topic_exists("BEFALSE"))
def test_filter_comment(self): """Tests whether a comment can be filtered by post_id.""" self.post = Post( title="Title", text="Text", user_id=1, topics=[Topic(tag_name="topic1"), Topic(tag_name="topic2")], id=1) db.session.add(self.post) db.session.commit() self.comment = Comment(text="This is a test", post_id=self.post.id) db.session.add(self.comment) db.session.commit() comments = Comment.query.filter_by(post_id=self.post.id) for i in comments: self.assertEqual(i.text, self.comment.text)
def add_topic(): name = request.json['name'] news_id = request.json['news_id'] new_topic = Topic(name, news_id) db.session.add(new_topic) db.session.commit() return jsonify(id=new_topic.id, name=new_topic.name, news_id=new_topic.news_id)
def admin_add_topic(): new_data = request.get_json()['newData'] result = Topic.query.filter(Topic.name == new_data['name']).first() if result: return forbidden("已存在,不能重复添加") try: topic = Topic(name=new_data['name'], icon_name=new_data['icon_name']) db.session.add(topic) db.session.commit() return jsonify({'success': True, 'data': True}) except: db.session.rollback() return forbidden('添加失败')
def load_lessons(): """Load the content of products.yml into the Product table""" yaml = open('data/lessons.yml') data = ruamel.yaml.load(yaml, ruamel.yaml.RoundTripLoader) print data for topic_name, text in data.items(): topic = (Topic.query.filter_by(name=topic_name).first() or Topic(name=topic_name)) print topic topic.text = unicode(text) topic.save()
def test_insert_topic(self): ''' test to insert into a new topic and comment to database :return: None ''' contest = Contest() db.session.add(contest) user = User(username='******') db.session.add(user) db.session.commit() topic = Topic() topic.contest_id = contest.id topic.author_username = user.username db.session.add(topic) db.session.commit() self.assertTrue(topic.contest.id == contest.id) comment = TopicComment() comment.topic_id = topic.id db.session.add(comment) db.session.commit() self.assertTrue(topic.comments.first().id == comment.id) db.session.delete(topic) db.session.commit() self.assertTrue(TopicComment.query.count() == 0) topic = Topic() topic.contest_id = contest.id topic.author_username = user.username db.session.add(topic) db.session.commit() comment = TopicComment() comment.topic_id = topic.id db.session.add(comment) db.session.commit() db.session.delete(contest) db.session.commit() self.assertTrue(Topic.query.count() == 0)
def createtopic(): form = CreateTopicForm() if form.validate_on_submit(): topic = Topic.query.filter_by(name=form.name.data).first() if topic: flash('There is already a topic with this name') form.name.value = '' return render_template('createtopic.html', form=form) topic = Topic(name=form.name.data, description=form.description.data, owner=current_user) db.session.add(topic) db.session.commit() return render_template('topic.html', topic=topic) return render_template('createtopic.html', form=form)
def addTopic(user_id, title, body, group_id, public=True): """ Add a topic to the database and commit the changes. Returns the topic. args: user_id: int title: string body: string group_id: int public: boolean """ ## Initialize topic attributes topic = Topic(user_id=user_id,title=title,body=body,public=public,group_id=group_id) ## add new topic to the database and commit the change db.session.add(topic) db.session.commit() return topic
def addsensor(): if request.is_json: req_data = request.get_json() try: emailData = req_data["email"] sensorNameData = req_data["sensorName"] hostnameData = req_data["hostname"] ipData = req_data["ipAddress"] interfaceData = req_data["netInterface"] locationData = req_data["location"] companyData = req_data["company"] except Exception as err: print("[Error] : {}".format(err)) return nice_json( raise_json_code(400, "Variable Error, Please Fill All the Field")) try: sensor = Sensor(hostname=hostnameData, ip_address=ipData, net_interfaces=interfaceData, location=locationData, company=companyData, topic=Topic()) sensor.set_sensor_name(sensorNameData) user = User.objects.get({'_id': emailData}) user.add_sensor(sensor) user.save() except ValidationError as ve: print("[Error] : {}".format(ve.message)) return nice_json(raise_json_code(400, "Paramter Not Valid")) except DuplicateKeyError: print("[Error] : Duplicate email") return nice_json( raise_json_code( 400, "There is already user with that email address.")) return nice_json( raise_json_code_with_data(200, "Add Sensor Success", sensor.to_son().to_dict())) else: return nice_json( raise_json_code(400, "Please send proper request in json"))
def test_follow_topic(self): u = User(email='*****@*****.**', password='******') topic = Topic(name='history') db.session.add(u) db.session.add(topic) db.session.commit() self.assertFalse(u.is_following_topic(topic)) self.assertFalse(u in topic.followers) u.follow_topic(topic) db.session.add(u) db.session.commit() self.assertTrue(u.is_following_topic(topic)) self.assertTrue(u in topic.followers) u.unfollow_topic(topic) db.session.add(u) db.session.commit() self.assertFalse(u.is_following_topic(topic)) self.assertFalse(u in topic.followers)
def submit(): # The below code is ugly and so are you. """View function for the submit site, which contains a standard form. Creates initial variables for mutable variables like upvotes, downvotes and importance, to avoid any TypeErrors.""" form = SubmitForm() if form.validate_on_submit(): # Checks whether the topic exists, so as to not make identical topics. if check_topic_exists(form.topics.data): topic = Topic.query.filter_by(tag_name=form.topics.data).first() post = Post(title=form.title.data, text=form.text.data, user_id=current_user.id, topics=[topic]) elif not check_topic_exists(form.topics.data): post = Post(title=form.title.data, text=form.text.data, user_id=current_user.id, topics=[Topic(tag_name=form.topics.data)]) # Checks to see if post is link or url. if form.link.data == "": post.is_link = False else: post.is_link = True if form.link.data == "" and form.text.data == "": flash("Please input either a link or text, or both.") return redirect(url_for('submit')) post.upvotes = 1 post.link = form.link.data post.downvotes = 0 post.importance = 10 post.hotness = post.get_hotness() post.score = post.get_score() db.session.add(post) db.session.commit() flash('You have now made a post!') return redirect(url_for('index')) return render_template('submit.html', title='Submit', form=form)
def create_resource( *, session: Session = Depends(get_session), resource: ResourceCreate, current_user: User = Depends(deps.get_current_user), ): db_resource = Resource.from_orm(resource, {"user_id": current_user.id}) # get or create the topic topic_ids = [] new_topics = [] for topic in resource.topics: if t := session.exec(select(Topic).where( Topic.name == topic.lower())).one_or_none(): print(t) topic_ids.append(t) else: new = Topic(name=topic.lower()) new_topics.append(new)
def submit(): """View function for the submit site, which contains a standard form. Creates initial variables for mutable variables like upvotes, downvotes and importance, to avoid any TypeErrors.""" form = SubmitForm() if form.validate_on_submit(): post = Post(title=form.title.data, text=form.text.data, user_id=current_user.id, topics=[Topic(tag_name=form.topics.data)]) post.upvotes = 1 post.downvotes = 0 post.importance = 1 post.score = post.get_score() db.session.add(post) db.session.commit() flash('You have now made a post!') return redirect(url_for('index')) return render_template('submit.html', title='Submit', form=form)
def test_follow_question(self): u = User(email='*****@*****.**', password='******') topic = Topic(name='history') question = Question(title='how are you?') question.topics.append(topic) db.session.add(u) db.session.add(topic) db.session.add(question) db.session.commit() self.assertFalse(u.is_following_question(question)) self.assertFalse(u in question.followers) u.follow_question(question) db.session.add(u) db.session.commit() self.assertTrue(u.is_following_question(question)) self.assertTrue(u in question.followers) u.unfollow_question(question) db.session.add(u) db.session.commit() self.assertFalse(u.is_following_question(question)) self.assertFalse(u in question.followers)
def category(id): category = Category.query.get_or_404(id) form = TopicForm() if form.validate_on_submit(): topic = Topic(title=form.title.data, body=form.body.data, body_html=markdown(form.body.data), category_id=category.id) db.session.add(topic) db.session.commit() flash("The topic {} was to added to category {}".format( topic.title, category.title)) return redirect(url_for('main.category', id=id)) return render_template('category.html', category=category, add_topic_form=form)
def importDefaultTopic(): topicModel = Topic() path = "file/zhenX.docx" doc = docx.Document(path) paras = doc.paragraphs parastests = [p.text for p in paras if p.text.isspace() is False] for content in parastests: topic_list = content.split("\n") for topic in topic_list: topic = topic.strip() if topic.isspace() is False and topic != '': try: topic_arr = topic.strip().split(".") if topic_arr and len(topic_arr) > 0: topicModel.addNewTopic(topic_arr[1]) pass pass except Exception as err: print err.message print "wrong:" + topic.strip() pass pass
def test_basic_flow(self): topic = Topic(name="test topic") user = User(nickname="andrei", email="*****@*****.**") answers_1 = [Answer(text="Answer #1", is_correct=True), Answer(text="Answer #2", is_correct=False)] answers_2 = [Answer(text="Answer #3", is_correct=True), Answer(text="Answer #4", is_correct=False)] question_1 = Question(text="test question #1", topic=topic, author=user, answers=answers_1) question_2 = Question(text="test question #2", topic=topic, author=user, answers=answers_2) db.session.add(question_1) db.session.add(question_2) db.session.commit() user = User.query.first() #Checking question references assert Question.query.get(1).author.nickname == "andrei" assert Question.query.get(1).answers[0].text == "Answer #1" assert Question.query.get(1).topic.name == "test topic" #Checking topic references assert len(Topic.query.get(1).questions) == 2 #Checking user references assert len(User.query.get(1).questions) == 2 attempt = Attempt(timestamp = datetime.utcnow(), student_name="stefan", student_email="*****@*****.**", score=99.5) attempt.answers.append(Question.query.get(1).answers[0]) attempt.answers.append(Question.query.get(2).answers[1]) db.session.add(attempt) db.session.commit() #Checking answer refferences assert Answer.query.filter(Answer.text=="Answer #1").first().attempts[0].student_name == "stefan" assert Answer.query.filter(Answer.text=="Answer #1").first().question.text == "test question #1" #Checking attempt refferences assert len(Attempt.query.get(1).answers) == 2