def seed_polls(num_entries=10, choice_min=2, choice_max=5, overwrite = False): """ Seeds num_entries poll with random users as owners Each poll will be seeded with # choices from choice_min to choice_max """ if overwrite: print("over writing poll") Poll.objects.all().delete() users = list(User.objects.all()) count = 0 for _ in range(num_entries): p = Poll( owner = random.choice(users), text=fake.paragraph(), pub_date=datetime.datetime.now() ) p.save() num_choices = random.randrange(choice_min,choice_max+1) for _ in range(num_choices): c = Choice( poll=p, choice_text=fake.sentence() ) c.save() count += 1 perecent_complete = count / num_entries * 100 print( "Addind {} new poll: {:.2f}%".format( num_entries, perecent_complete ), end='\r', flush=True ) print()
def pollSave(request): # if request.method == 'POST': # if not request.POST.get('subject', ''): # errors.append('Enter a subject.') # if not request.POST.get('message', ''): # errors.append('Enter a message.') # if request.POST.get('email') and '@' not in request.POST['email']: # errors.append('Enter a valid e-mail address.') # if not errors: # send_mail( # request.POST['subject'], # request.POST['message'], # request.POST.get('email', '*****@*****.**'), # ['*****@*****.**'], # ) # return HttpResponseRedirect('/contact/thanks/') title = request.POST.get('title', '') remark = request.POST.get('remark', '') poll = Poll(title=title, remark=remark, createTime=datetime.now()) poll.save() itemIds = request.POST.get('item_ids', '') ids = itemIds.split(',') for id in ids: pollItem = PollItem(title=request.POST.get('item_title' + id, ''), poll=poll) pollItem.save() return render_to_response('pollSave.html')
def test_that_data_from_poll_should_have_all_the_neccessary_fields(self): question = "is this really a poll ? or a pool ? or a loop?" name = "this is a poll" an_hour_ago = datetime.datetime.now() - datetime.timedelta(hours=1) default_response = "thanks" poll = Poll(name=name, question=question, id=12, type="t", start_date=an_hour_ago, default_response=default_response, response_type="a") expected_poll_data = { "id": "12", "question": question, "name": name, "language": None, "question_voice": None, "start_date": an_hour_ago.strftime(self.view.get_datetime_format()), "end_date": None, "is_registration": False, "type": "t", "is_registration_end": False, "default_response": default_response, "default_response_voice": None, "response_type": "allow_all" } self.assertDictEqual(expected_poll_data, self.view.get_data_from_poll(poll))
def convert_polls(self): self.clear_polls() cursor = connection.cursor() cursor.execute("SELECT * FROM smf_polls") rows = cursor.fetchall() for row in rows: try: profile = Profile.objects.get(old_user_id=row[7]) try: poll = Poll() poll.old_poll_id = row[0] poll.user = profile.user poll.username = row[8] poll.question = row[1] if row[2] == 1: poll.locked = True poll.expires_on = self.fix_epoch(row[4]) if row[5] == 0: poll.hide_results_until_vote = False if row[6] == 0: poll.allow_changing_votes = False poll.allow_changing_votes = False if row[9] == 1: poll.allow_changing_votes = True poll.hide_results_until_expored = False poll.save() except Exception, e: print "Could not save poll: %s" % (str(e)) except Profile.DoesNotExist, e: pass
def post(self, request): title = request.data.get('title') text = request.data.get('text') link = request.data.get('link', 'No link') user = request.user close_date = request.data.get('closeDate', '2424-2-2') if not close_date: close_date = '2424-2-2' participants = request.data.get('participants', []) selects = request.data.get('selects') meeting = Meeting(title=title, text=text, owner=user) meeting.save() poll = Poll(title=title, text=text, meeting=meeting) if close_date: poll.date_close = datetime.datetime.strptime( close_date, '%Y-%m-%d') poll.save() meetingParticipant = MeetingParticipant(meeting=meeting, participant=user) meetingParticipant.save() link += str(poll.id) self.create_participants(meeting, participants, user) self.createOptions(poll, selects) check_poll_close(poll) poll_json = serializers.serialize('json', [poll]) send_email_create_poll(user, title, link, participants) try: return HttpResponse(poll_json, content_type='application/json') except Exception as e: print(e) return HttpResponse404Error("This poll doesn\'t exist.")
def get_mocked_step_with_poll_question(self, question, script_slug='registration_script'): mocked_poll = Poll() mocked_poll.question = question poll_step = ScriptStep() poll_step.poll = mocked_poll poll_step.script = Script(slug=script_slug) return poll_step
def test_get_polls(self, app): with app.app_context(): now = datetime.now() p = Poll(id=None, name="Nom", date=now) p.save() p = Poll(id=None, name="Nom #2", date=now) p.save() new_poll = Poll.get_polls() assert new_poll[0].id == 1 assert new_poll[0].name == "Nom" assert new_poll[0].date == str(now) assert new_poll[1].id == 2 assert new_poll[1].name == "Nom #2" assert new_poll[1].date == str(now)
def test_that_if_the_response_is_not_accepted_the_script_steps_are_not_checked( self): self.view.get_poll = Mock(return_value=Poll()) self.view.get_incoming_response = Mock() self.view.process_poll_response = Mock(return_value=(False, "")) self.view.create_json_response = Mock() fake_process_registration = Mock() self.view.process_registration_steps = fake_process_registration self.view.post(self, None, **{'poll_id': "12"}) assert not fake_process_registration.called
def test_get_poll_by_id(self, app): with app.app_context(): now = datetime.now() p = Poll(id=None, name="Nom", date=now) p.save() new_poll = Poll.get_poll_by_id(1) assert new_poll.id == 1 assert new_poll.name == "Nom" assert new_poll.date == str(now)
def test_index(self, app, client): with app.app_context(): now = datetime.now() p = Poll(id=None, name="Mon premier sondage", date=now) p.save() response = client.get("/") assert response.status_code == 200 assert b"Aucuns sondages actifs" not in response.data assert b"Mon premier sondage" in response.data
def test_should_choose_batch_status_based_on_feature_flag(self): p = Poll() self.assertEqual(p.get_start_poll_batch_status(), "Q") settings.FEATURE_PREPARE_SEND_POLL = True self.assertEqual(p.get_start_poll_batch_status(), "P") settings.FEATURE_PREPARE_SEND_POLL = False self.assertEqual(p.get_start_poll_batch_status(), "Q")
def test_save_inserts_row(self, app): with app.app_context(): now = datetime.now() p = Poll(id=None, name="Nom", date=now) p.save() new_poll = get_db().execute( "SELECT id, name, date FROM polls WHERE id = ?", [1]).fetchone() assert new_poll[0] == 1 assert new_poll[1] == "Nom" assert new_poll[2] == str(now)
def setUp(self): self.queue = Queue(title='TestQueue', auth=False) self.queue.save() self.poll = Poll(title='TestPoll', queue=self.queue, polltype=0, startdate=datetime.now()) self.poll.save() self.item = self.poll.item_set.create(userbox=False, value='One', index=0) self.client = Client()
def test_that_valid_get_request_returns_poll_summary(self): backend = Backend(name="test") self.view.get_connection = Mock(return_value=Connection(identity="77777", backend=backend)) self.view.get_backend = Mock(return_value=backend) self.view.contact_exists = Mock(return_value=True) self.view.get_poll = Mock(return_value=Poll(question="Testing?")) poll_summary = {"total": 1, "responses": [{"name": "T", "count": 1}]} self.view.get_poll_summary = Mock(return_value=poll_summary) expected_data = { "success": True, "poll_result": poll_summary } response = self.get_http_response_from_view(self.build_kwargs("my_backend","77777","12"), self.view) data = json.loads(response.content) self.assertEquals(200,response.status_code) self.assertDictEqual(expected_data, data)
def test_that_retrieves_poll_data_from_step_of_script_progress(self): fake_connection = Mock() fake_connection.return_value = self.build_connection(None) self.view.get_connection = fake_connection self.view.get_script_progress = Mock(return_value=ScriptProgress( script=Script(slug="ureport_autoreg2"))) fake_get_next_step = Mock(return_value=ScriptStep( poll=Poll(name="test poll", question="Is it working?"))) self.view.get_current_step = fake_get_next_step self.view.get_backend = Mock(return_value=Backend(name="my_backend")) response = self.get_http_response_from_view( { "backend": "my_backend", "user_address": "77777" }, self.view) data = json.loads(response.content) self.assertEqual(True, data['poll']['is_registration'])
def test_get_number_of_votes(self, app): with app.app_context(): now = datetime.now() p = Poll(id=None, name="Nom", date=now) p.save() assert p.number_of_votes() == 0 c1 = Choice(id=None, choice="Premier choix", poll=p) c1.save() c2 = Choice(id=None, choice="Deuxième choix", poll=p) c2.save() assert p.number_of_votes() == 0 c1.cast_vote() c1.cast_vote() c2.cast_vote() assert p.number_of_votes() == 3
def poll_creation_form(request): if request.method == "POST": poll_form = PollForm(request.POST) content = {"form": poll_form} if poll_form.is_valid(): poll = Poll(poll_name=poll_form.cleaned_data["poll_name"], start_date=poll_form.cleaned_data["start_date"], manager=request.user.email, end_date=poll_form.cleaned_data["end_date"]) poll.save() poll.member.add(request.user) return redirect("pollhome.page") else: return render(request, "poll/poll_form.html", content) else: poll_form = PollForm() content = {"form": poll_form} return render(request, "poll/poll_form.html", content)
def polls_new(): poll = Poll(None, '', None) return views.new_poll(poll)
def add_poll( request ): errors = [] if request.method == 'POST': word = re.compile( r'\s*\w+\s*' ) title = request.POST.get( 'title', '' ) if not title or not word.search( title ): errors.append( 'Need to add a title.' ) else: single_choice_str = request.POST.get( 'is_single_choice', '' ) is_single_choice = True if not single_choice_str: is_single_choice = False count = 0 options = [] for key, value in request.POST.items(): if key.startswith( 'option' ): if word.search( value ): count += 1 options.append({ 'key': key, 'value':value }) if count < 2: errors.append( 'Need 2 or more options.' ) else: poll = Poll( user= request.user, title= title, is_single_choice= is_single_choice ) poll.save() def sortById( element ): theKey = element[ 'key' ] theId = re.match( r'\w+(?P<id>\d+)', theKey ) return theId.group( 'id' ) options.sort( key= sortById ) for aOption in options: poll.option_set.create( text= aOption[ 'value' ] ) return HttpResponseRedirect( poll.get_url() ) context = { 'errors': errors, 'initial_options': range( 1, 4 ), 'title_length': POLL_TITLE_LENGTH, 'option_length': OPTION_TEXT_LENGTH } return render( request, 'add_poll.html', context )
def poll(uuid=None): if request.method == "POST": question = request.form.get("questionTitle", None) answers = request.form.getlist("answer") max_selection_limit = request.form.get("maxSelectionLimit", 1) access_key = generate_access_key() # Sanity check if question is None or answers is None: abort(422) try: max_selection_limit = int(max_selection_limit) except Exception as e: abort(422) if len(question) < 1 or len( answers ) < 1 or max_selection_limit < 1 or max_selection_limit > len(answers): abort(422) try: question = escape(question) answer_objects = [Answer(text=escape(ans)) for ans in answers] except Exception as e: abort(422) new_poll = Poll(question=question, access_key=access_key, max_selection_limit=max_selection_limit, answers=answer_objects) db.session.add(new_poll) db.session.commit() new_uuid = new_poll.uuid return redirect(url_for("poll.share", uuid=new_uuid)) elif request.method == "GET": # User has voted before, help him/her check the answers. user_uuid = request.cookies.get("uuid") voted_answers = None try: poll = Poll.query.filter_by(uuid=uuid).first() except Exception as e: abort(422) if poll is None: abort(404) answers = [ans.to_json() for ans in poll.answers] if user_uuid is not None: voted_answers_obj_list = Vote.query.filter_by( voter=user_uuid, poll_id=poll.id).all() voted_answers = {} for obj in voted_answers_obj_list: voted_answers[obj.answer_id] = True # Add checked in answers for ans in answers: if user_uuid is not None and ans["id"] in voted_answers: ans["checked"] = True else: ans["checked"] = False variables = { "question": poll.question, "max_limit": poll.max_selection_limit, "answers": answers, "voted_answers": voted_answers, "poll_id": poll.id, "result_link": "/result/{}".format(poll.uuid) } print(variables) return render_template("poll.html", **variables)
def create_new_poll_from_post_data(cls, post_data, date): poll = Poll(id=None, name=post_data['name'], date=date) poll.save() return poll