def test_get_push_setting(self, mock_verify_id_token): """Should return push setting json response.""" mock_time = pendulum.datetime(2020, 5, 21, 12) pendulum.set_test_now(mock_time) # insert user_1 mock_verify_id_token.return_value = dict(uid=mock_user_1["uid"]) response_1 = create_user_1(self.app) self.assertEqual(response_1.status_code, 200) response = self.app.get("/users/{user_id}/setting/push".format( user_id=response_1.get_json().get("_id")), headers=dict(uid=mock_user_1["uid"]), content_type="application/json") data = response.get_json() self.assertEqual(response.status_code, 200) self.assertEqual(data.get("poke"), True) self.assertEqual(data.get("request"), True) self.assertEqual(data.get("comment"), True) self.assertEqual(data.get("high_rate"), True) self.assertEqual(data.get("match"), True) self.assertEqual(data.get("favorite_comment"), True) self.assertEqual(data.get("conversation"), True) self.assertEqual(data.get("lookup"), True)
def test_option_order_add_all_orders(): broker = Broker() order = OptionOrder( symbol="nifty", spot=17144, expiry=923, step=50, contracts=[(0, "c", "b", 50), (0, "p", "b", 50)], broker=broker, ) known = pendulum.datetime(2021, 1, 1, 10) pendulum.set_test_now(known) orders = [ Order( symbol="NIFTY92317150CE", side="buy", quantity=50, exchange="NSE", timezone="Asia/Kolkata", order_type="MARKET", ), Order( symbol="NIFTY92317150PE", side="buy", quantity=50, exchange="NSE", timezone="Asia/Kolkata", order_type="MARKET", ), ] order.add_all_orders(exchange="NSE", timezone="Asia/Kolkata") for i in range(len(orders)): order.orders[i].internal_id = orders[i].internal_id pendulum.set_test_now() assert order.orders == orders
def test_wait_until_tomorrow_morning(fixed_day): after_midday = fixed_day.at(hour=10, second=1) pendulum.set_test_now(after_midday) tomorrow_morning = fixed_day.add(days=1).at(hour=7) event = greetings.Event.next() assert pendulum.now() + event.until == tomorrow_morning assert event.func == greetings.send_congrats
def monday_10_am_utc(): dt = pendulum.parse("2019-02-04T10:00:00", tz="UTC") pendulum.set_test_now(dt) yield dt pendulum.set_test_now()
def test_list_users_within_distance(self, mock_verify_id_token): """There must not be recommended users because anotehr users contacts contain my number.""" mock_time = pendulum.datetime(2020, 5, 21, 12) pendulum.set_test_now(mock_time) # insert user_1 mock_verify_id_token.return_value = dict(uid=mock_user_1["uid"]) response_1 = create_user_1(self.app) self.assertEqual(response_1.status_code, 200) # insert user_2 mock_verify_id_token.return_value = dict(uid=mock_user_2["uid"]) response_2 = create_user_2(self.app) self.assertEqual(response_2.status_code, 200) User.objects(uid=mock_user_1["uid"]).update(available=True) User.objects(uid=mock_user_2["uid"]).update(available=True) user_1 = User.objects(uid=mock_user_1["uid"]).first() user_2 = User.objects(uid=mock_user_2["uid"]).first() Contact(owner=user_2, phones=[user_1.phone], last_updated_at=pendulum.now().int_timestamp).save() response = self.app.get("/users/{user_id}/distance/10".format( user_id=response_1.get_json().get("_id")), headers=dict(uid=mock_user_1["uid"]), content_type="application/json") self.assertEqual(response.status_code, 500) recommendation = Recommendation.objects.first() self.assertEqual(len(recommendation.user_ids), 0)
def test_wait_until_morning(fixed_day): night = fixed_day.at(hour=1) pendulum.set_test_now(night) morning = fixed_day.at(hour=7) event = greetings.Event.next() assert pendulum.now() + event.until == morning assert event.func == greetings.send_congrats
def test_wait_until_midday(fixed_day): after_morning = fixed_day.at(hour=7, second=1) pendulum.set_test_now(after_morning) midday = fixed_day.at(hour=10) event = greetings.Event.next() assert pendulum.now() + event.until == midday assert event.func == greetings.send_report
def test_ordering_flow_tasks_with_interval_seconds( pendulum_utcnow, flowitem_model, flowmasterdata_items_to_csv_notebook): with mock.patch("flowmaster.service.iter_active_notebook_filenames" ) as a100, mock.patch( "flowmaster.service.get_notebook") as b100: a100.return_value = flowmasterdata_items_to_csv_notebook.name b100.return_value = ( True, None, None, flowmasterdata_items_to_csv_notebook, None, ) from flowmaster.operators.base.work import ordering_flow_tasks all_tasks = [] for _ in range(4): tasks = list(ordering_flow_tasks()) all_tasks += tasks assert len(tasks) == 1 pendulum_utcnow += dt.timedelta(seconds=60) pendulum.set_test_now(pendulum_utcnow) assert len(all_tasks) == 4
def test_finds_2_recipients(conn: connection) -> None: chosen_user = conftest.users[7] test_now = pendulum.instance(chosen_user.birthday, tz=config.tz).add(years=conftest.age) pendulum.set_test_now(test_now) recipients = greetings.todays_recipients(conn) assert len(recipients) == 2
def mock_time(): try: fake_time = request.values.get('now') now = pendulum.parse(fake_time) pendulum.set_test_now(now) except: pass
def test_verify_fail_due_to_duplicate_phone(self, get_user, verify_id_token): class MockUser: email = "*****@*****.**" verify_id_token.return_value = dict(uid=mock_user_1["uid"]) get_user.return_value = MockUser() create_user_1(self.app) # Create testing datetime known = pendulum.datetime(2001, 5, 21, 12) pendulum.set_test_now(known) response = self.app.put("/verifications/sms", data=dict(phone="+821022889311", expired_at="990446400", sms_code="291455")) json_data = response.get_json() self.assertEqual(json_data.get("verified"), True) phone = json_data["phone"] sms_code = json_data["sms_code"] sms_token = json_data["sms_token"] response = self.app.get( "/users/phone/{phone}/sms_code/{sms_code}/sms_token/{sms_token}". format(phone=phone, sms_code=sms_code, sms_token=sms_token)) json_data = response.get_json() email, is_exists = json_data["email"], json_data["is_exists"] self.assertEqual(email, "*****@*****.**") self.assertEqual(is_exists, True)
def test_update_request_accepted(self, mock_send, mock_verify_id_token): """Should have response become 1 after the update.""" # set mock time mock_time = pendulum.datetime(2020, 5, 21, 12) pendulum.set_test_now(mock_time) # create 2 users mock_verify_id_token.return_value = dict(uid=mock_user_1["uid"]) response_1 = self.app.post( "/users", data=json.dumps(mock_user_1), headers=dict(uid=mock_user_1["uid"]), content_type="application/json") response_1 = self.app.put( "/users/profile", data=json.dumps(mock_user_1), headers=dict(uid=mock_user_1["uid"]), content_type='application/json') mock_verify_id_token.return_value = dict(uid=mock_user_2["uid"]) response_2 = self.app.post( "/users", data=json.dumps(mock_user_2), headers=dict(uid=mock_user_2["uid"]), content_type="application/json") response_2 = self.app.put( "/users/profile", data=json.dumps(mock_user_2), headers=dict(uid=mock_user_2["uid"]), content_type='application/json') # 1: user_from, 2: user_to user_1, user_2 = response_1.get_json(), response_2.get_json() # set mock id token mock_verify_id_token.return_value = dict(uid=user_1["uid"]) # create a request response = self.app.post("/requests/user_to/{user_id}/type/{type}".format( user_id=user_2["id"], type=1), headers=dict(uid=user_1["uid"])) self.assertEqual(mock_send.call_count, 1) self.assertEqual(response.status_code, 200) req = Request.objects.first() # update a request with response 1 (yes) response = self.app.put( "/requests/{rid}/response/{response}".format( rid=req["id"], response=1), headers=dict(uid=user_2["uid"])) # assert request updated_request = Request.objects.first() self.assertEqual(response.status_code, 200) self.assertEqual(updated_request.response, 1) self.assertEqual(updated_request.responded_at, pendulum.now().int_timestamp) self.assertEqual(mock_send.call_count, 2) # chat room must be created when accepted. chat_room = ChatRoom.objects.first() member_1, member_2 = chat_room.members[0], chat_room.members[1] self.assertEqual(user_1["uid"], member_1["uid"]) self.assertEqual(user_2["uid"], member_2["uid"]) self.assertEqual(chat_room.created_at, pendulum.now().int_timestamp)
def tearDown(self): pendulum.set_test_now() pendulum.set_formatter() pendulum.set_locale('en') LocalTimezone.set_local_timezone() Pendulum.reset_to_string_format() Date.reset_to_string_format() Time.reset_to_string_format() Pendulum.set_transition_rule(Timezone.POST_TRANSITION)
def setup(): pendulum.set_local_timezone(pendulum.timezone("America/Toronto")) yield pendulum.set_test_now() pendulum.set_locale("en") pendulum.set_local_timezone() pendulum.week_starts_at(pendulum.MONDAY) pendulum.week_ends_at(pendulum.SUNDAY)
def test_processed_orders_stream_slices(patch_incremental_base_class, now, stream_state, slice_count, expected_from_date, expected_to_date): start_date = date(2050, 1, 1) pendulum.set_test_now(pendulum.parse(now if now else start_date)) stream = ProcessedOrders(start_date=start_date) stream_slices = list(stream.stream_slices(stream_state)) assert len(stream_slices) == slice_count assert stream_slices[0]["FromDate"] == expected_from_date assert stream_slices[-1]["ToDate"] == expected_to_date
def test_log_client_online(): current_time = pendulum.now() pendulum.set_test_now(current_time) clients = list(parse_logs(testlog_path))[0].clients old_onlinetime = int(clients['1'].onlinetime.total_seconds()) pendulum.set_test_now(current_time.add(seconds=2)) # add 2s to .now() clients = list(parse_logs(testlog_path))[0].clients assert int(clients['1'].onlinetime.total_seconds()) == old_onlinetime + 2
def test_stream_slices(patch_incremental_base_class, now, stream_state, slice_count, expected_from_date, expected_to_date): start_date = date(2050, 1, 1) pendulum.set_test_now(pendulum.parse(now if now else start_date)) stream = IncrementalFlexportStream(start_date=start_date) stream_slices = list(stream.stream_slices(stream_state)) assert len(stream_slices) == slice_count assert stream_slices[0]["from"] == expected_from_date assert stream_slices[-1]["to"] == expected_to_date
def test_update_request_declined(self, mock_send, mock_verify_id_token): """Should have response become 0 after the update.""" # set mock time mock_time = pendulum.datetime(2020, 5, 21, 12) pendulum.set_test_now(mock_time) # create 2 users mock_verify_id_token.return_value = dict(uid=mock_user_1["uid"]) response_1 = self.app.post( "/users", data=json.dumps(mock_user_1), headers=dict(uid=mock_user_1["uid"]), content_type="application/json") response_1 = self.app.put( "/users/profile", data=json.dumps(mock_user_1), headers=dict(uid=mock_user_1["uid"]), content_type="application/json") mock_verify_id_token.return_value = dict(uid=mock_user_2["uid"]) response_2 = self.app.post( "/users", data=json.dumps(mock_user_2), headers=dict(uid=mock_user_2["uid"]), content_type="application/json") response_2 = self.app.put( "/users/profile", data=json.dumps(mock_user_2), headers=dict(uid=mock_user_2["uid"]), content_type="application/json") # 1: user_from, 2: user_to user_from, user_to = \ response_1.get_json(), response_2.get_json() # set mock id token mock_verify_id_token.return_value = dict(uid=user_from["uid"]) # create a request response = self.app.post( "/requests/user_to/{user_id}/type/{type}".format( user_id=user_to["id"], type=1), headers=dict(uid=user_from["uid"])) req = Request.objects.first() self.assertEqual(response.status_code, 200) self.assertEqual(mock_send.call_count, 1) # should be called when created # update a request with response 0 (No!) response = self.app.put( "/requests/{rid}/response/{response}".format( rid=req["id"], response=0), headers=dict(uid=user_to["uid"])) # assert updated_request = Request.objects.first() self.assertEqual(response.status_code, 200) self.assertEqual(updated_request.response, 0) self.assertEqual(mock_send.call_count, 1) # should be not called when declined self.assertEqual(updated_request.responded_at, pendulum.now().int_timestamp)
def test_create_message(self, send, verify_id_token): from firebase_admin import messaging messaging.send = lambda x: x # set mock function to messaging.send mock_time = pendulum.datetime(2020, 5, 21, 12) pendulum.set_test_now(mock_time) # insert user1 verify_id_token.return_value = dict(uid=mock_user_1["uid"]) create_user_1(self.app) # insert user2 verify_id_token.return_value = dict(uid=mock_user_2["uid"]) create_user_2(self.app) # open chat room with user1 and user2 users = User.objects.all() user_1, user_2 = users[0], users[1] conversation = Conversation( title=None, participants=[user_1, user_2], references=[user_1, user_2], created_at=pendulum.now().int_timestamp).save() first_message = "first_message 1" second_message = "second_message 2" # insert message_1 response = self.app.post( "/conversations/{conversation_id}/messages/{message}".format( conversation_id=conversation.id, message=first_message), headers=dict(uid=user_1.uid), content_type='application/json') self.assertEqual(response.status_code, 200) # insert message_2 response = self.app.post( "/conversations/{conversation_id}/messages/{message}".format( conversation_id=conversation.id, message=second_message), headers=dict(uid=user_1.uid), content_type='application/json') self.assertEqual(response.status_code, 200) conversation = Conversation.objects.first() # assert embedded_messages messages = conversation.messages self.assertEqual(len(messages), 2) self.assertEqual(str(messages[0].user_id), str(user_1.id)) self.assertEqual(messages[0].message, first_message) self.assertEqual(str(messages[1].user_id), str(user_1.id)) self.assertEqual(messages[1].message, second_message)
def test_finds_recipient(conn: connection) -> None: chosen_user = conftest.users[0] test_now = pendulum.instance(chosen_user.birthday, tz=config.tz).add(years=conftest.age) pendulum.set_test_now(test_now) recipients = greetings.todays_recipients(conn) assert len(recipients) == 1 recipient = recipients[0] assert recipient.nick == chosen_user.slack_nick assert recipient.slack_id == chosen_user.slack_id assert recipient.age == conftest.age
def test_issue2(self): # Create testing datetime known = pendulum.datetime(2001, 5, 21, 12) pendulum.set_test_now(known) phone, expired_at = "+821022889311", pendulum.now().int_timestamp sms_code = hash_service.get_sms_code(phone, expired_at) self.assertEqual(sms_code, "291455") result = issue("+821022889311") expired_at = result.get("expired_at") self.assertEqual(expired_at, 990447000)
def test_test_now(): now = pendulum.datetime(2000, 11, 10, 12, 34, 56, 123456) pendulum.set_test_now(now) assert pendulum.has_test_now() assert now == pendulum.get_test_now() assert_datetime(pendulum.now(), 2000, 11, 10, 12, 34, 56, 123456) pendulum.set_test_now() assert not pendulum.has_test_now() assert pendulum.get_test_now() is None
def test_set_test_now_is_global(self): now = pendulum.create(2000, 11, 10, 12, 34, 56, 123456) pendulum.set_test_now(now) self.assertEqual(now, pendulum.get_test_now()) self.assertEqual(now, pendulum.Pendulum.get_test_now()) self.assertEqual(now.date(), pendulum.Date.get_test_now()) self.assertEqual(now.time(), pendulum.Time.get_test_now()) self.assertPendulum(pendulum.Pendulum.now(), 2000, 11, 10, 12, 34, 56, 123456) self.assertDate(pendulum.Date.today(), 2000, 11, 10) self.assertTime(pendulum.Time.now(), 12, 34, 56, 123456)
def freeze_time(time=None, device=None): # Get current time if not provided if time is None: time = pendulum.now() # Freeze a single device if device is not None: with freeze_device_time(device, time) as time: yield time return # Parse time global __freeze_time_task if isinstance(time, str): time = pendulum.parse(time) # Save previous context previous_task = __freeze_time_task previous_time = pendulum.get_test_now() # Get current trio task try: current_task = trio.lowlevel.current_task() except RuntimeError: current_task = None # Ensure time has not been frozen from another coroutine assert previous_task in (None, current_task) try: # Set new context __freeze_time_task = current_task pendulum.set_test_now(time) try: from libparsec.types import freeze_time as _Rs_freeze_time except ImportError: pass else: _Rs_freeze_time(time) yield time finally: # Restore previous context __freeze_time_task = previous_task pendulum.set_test_now(previous_time) try: from libparsec.types import freeze_time as _Rs_freeze_time except ImportError: pass else: _Rs_freeze_time(previous_time)
def test_update_request_accepted(self, mock_send, mock_verify_id_token): """Should have response become 1 after the update.""" # set mock time mock_time = pendulum.datetime(2020, 5, 21, 12) pendulum.set_test_now(mock_time) # create 2 users mock_verify_id_token.return_value = dict(uid=mock_user_1["uid"]) response_1 = create_user_1(self.app) mock_verify_id_token.return_value = dict(uid=mock_user_2["uid"]) response_2 = create_user_2(self.app) # 1: user_from, 2: user_to user_1, user_2 = response_1.get_json(), response_2.get_json() user_1 = User.objects.get_or_404(id=user_1["_id"]) user_2 = User.objects.get_or_404(id=user_2["_id"]) # set mock id token mock_verify_id_token.return_value = dict(uid=user_1["uid"]) # create a request response = self.app.post("/requests/user_to/{user_id}/type/{type}".format( user_id=str(user_2["id"]), type=1), headers=dict(uid=user_1["uid"])) self.assertEqual(mock_send.call_count, 1) self.assertEqual(response.status_code, 200) req = Request.objects.first() # update a request with response 1 (yes) response = self.app.put( "/requests/{rid}/response/{response}".format( rid=req["id"], response=1), headers=dict(uid=user_2["uid"])) # assert request updated_request = Request.objects.first() self.assertEqual(response.status_code, 200) self.assertEqual(updated_request.response, 1) self.assertEqual(updated_request.responded_at, pendulum.now().int_timestamp) self.assertEqual(mock_send.call_count, 2) # chat room must be created when accepted. conversation = Conversation.objects.first() member_1, member_2 = conversation.participants[0], conversation.participants[1] self.assertEqual(user_1["uid"], member_1["uid"]) self.assertEqual(user_2["uid"], member_2["uid"]) self.assertEqual(conversation.created_at, pendulum.now().int_timestamp)
def test_verify_success(self, verify_id_token): verify_id_token.return_value = dict(uid=mock_user_1["uid"]) create_user_1(self.app) # Create testing datetime known = pendulum.datetime(2001, 5, 21, 12) pendulum.set_test_now(known) response = self.app.put("/verifications/sms", data=dict(phone="+821022881234", expired_at="990446400", sms_code="174522"), headers=dict(uid=mock_user_1["uid"])) json_data = response.get_json() self.assertEqual(json_data.get("verified"), True)
def test_issue(self, verify_id_token): verify_id_token.return_value = dict(uid=mock_user_1["uid"]) create_user_1(self.app) # Create testing datetime known = pendulum.datetime(2001, 5, 21, 12) pendulum.set_test_now(known) response = self.app.post("/verifications/sms", data=dict(phone="+821022889311")) json_data = response.get_json() expired_at = json_data.get("expired_at") expired_at_to_verify = pendulum.now().int_timestamp + (60 * 10) self.assertEqual(expired_at, expired_at_to_verify)
def test_verify_failed3(self, verify_id_token): verify_id_token.return_value = dict(uid=mock_user_1["uid"]) create_user_1(self.app) # Create testing datetime known = pendulum.datetime(2001, 5, 23, 12) pendulum.set_test_now(known) response = self.app.put("/verifications/sms", data=dict(phone="+821022889311", expired_at="990446400", sms_code="291455"), headers=dict(uid=mock_user_1["uid"])) json_data = response.get_json() verified, reason = json_data["verified"], json_data["reason"] self.assertEqual(verified, False) self.assertEqual(reason, "SMS_CODE가 만료 되었습니다.")
def test_set_test_now_can_be_overridden(self): now = pendulum.create(2000, 11, 10, 12, 34, 56, 123456) pendulum.set_test_now(now) dt = pendulum.create(2001, 12, 11, 1, 2, 3, 987654) pendulum.Pendulum.set_test_now(dt) pendulum.Date.set_test_now(dt) pendulum.Time.set_test_now(dt) self.assertEqual(now, pendulum.get_test_now()) self.assertEqual(dt, pendulum.Pendulum.get_test_now()) self.assertEqual(dt.date(), pendulum.Date.get_test_now()) self.assertEqual(dt.time(), pendulum.Time.get_test_now()) self.assertPendulum(pendulum.Pendulum.now(), 2001, 12, 11, 1, 2, 3, 987654) self.assertDate(pendulum.Date.today(), 2001, 12, 11) self.assertTime(pendulum.Time.now(), 1, 2, 3, 987654)
def test_verify_failed2(self, verify_id_token): verify_id_token.return_value = dict(uid=mock_user_1["uid"]) create_user_1(self.app) # Create testing datetime known = pendulum.datetime(2001, 5, 21, 12) pendulum.set_test_now(known) response = self.app.put("/verifications/sms", data=dict(phone="INVALID_PHONE_NUMBER", expired_at="990446400", sms_code="957822"), headers=dict(uid=mock_user_1["uid"])) json_data = response.get_json() verified, reason = json_data["verified"], json_data["reason"] self.assertEqual(verified, False) self.assertEqual(reason, "유효하지 않은 SMS_CODE 입니다.")