def test_buscar_por_parlamentar(self): parlamentar_1 = Parlamentar(id='1', cargo='BR1') parlamentar_2 = Parlamentar(id='2', cargo='BR1') parlamentar_3 = Parlamentar(id='1', cargo='BR2') relatorio_1 = Relatorio(parlamentar=parlamentar_1, data_inicial=datetime(2019, 1, 1)).save() relatorio_2 = Relatorio(parlamentar=parlamentar_2, data_inicial=datetime(2019, 1, 1)).save() relatorio_3 = Relatorio(parlamentar=parlamentar_3, data_inicial=datetime(2019, 1, 1)).save() relatorio_4 = Relatorio(parlamentar=parlamentar_1, data_inicial=datetime(2019, 1, 1)).save() relatorio_5 = Relatorio(parlamentar=parlamentar_3, data_inicial=datetime(2019, 1, 1)).save() relatorio_6 = Relatorio(parlamentar=parlamentar_2, data_inicial=datetime(2019, 1, 1)).save() actual = Relatorios().buscar_por_parlamentar('BR1', '1') expected = [relatorio_1.to_dict(), relatorio_4.to_dict()] self.assertEqual(len(actual), len(expected))
def test_obter_relatorio_json_inexistente_por_periodos_diferentes( self, mock_model_selector ): parlamentar = Parlamentar(id='1', cargo='BR1') brasilia_tz = pytz.timezone('America/Sao_Paulo') relatorio_inicial = Relatorio( parlamentar=parlamentar, data_final=brasilia_tz.localize(datetime(2019, 6, 29)), data_inicial=brasilia_tz.localize(datetime(2019, 6, 15)) ).save() relatorio_gerado = Relatorio( parlamentar=parlamentar, data_final=datetime(2019, 6, 29), data_inicial=datetime(2019, 6, 22) ) class FakeModel: def obter_relatorio(self, *args, **kwargs): return relatorio_gerado mock_model_selector.return_value = FakeModel actual_response = Relatorios().obter_relatorio('1', '2019-06-29', 'BR1', periodo=7) actual_response['_id'] = 'id' relatorio_gerado.pk = 'id' self.assertEqual(mock_model_selector.call_count, 1) self.assertEqual(actual_response, relatorio_gerado.to_dict())
def test_send_push_notification_message_too_big_sucess(self, mock_urllib3): def assert_equal(actual, expected): self.assertEqual(actual, expected) class FakePoolManager: def __init__(self, *args, **kwargs): FakePoolManager.call_count = 0 def request(self, method, url, headers, body): class responseFail(): status = 200 data = json.dumps({ 'results': [{ 'error': 'MessageTooBig' }] }).encode('utf-8') class responseSucess(): status = 200 data = json.dumps({ 'results': [{ 'id': '123' }] }).encode('utf-8') FakePoolManager.call_count += 1 assert_equal(method, "POST") assert_equal(url, "https://fcm.googleapis.com/fcm/send") if 'reportsIds' in body.decode('utf-8'): return responseSucess() return responseFail() data_inicial = datetime(2019, 10, 12) data_final = datetime(2019, 10, 19) parlamentar1 = Parlamentar(id='1', cargo='BR1', nome='AMANDA') relatorio1 = Relatorio( id="123", parlamentar=parlamentar1, data_final=data_final, data_inicial=data_inicial, proposicoes=[ Proposicao(id="1"), Proposicao(id="2"), Proposicao(id="3"), Proposicao(id="4") ], eventos_presentes=[Evento(id="1"), Evento(id="2")], eventos_previstos=None, eventos_ausentes=[Evento(id="4"), Evento(id="5"), Evento(id="6")]) mock_urllib3.side_effect = FakePoolManager result = send_push_notification("token", [relatorio1.to_dict()]) self.assertTrue(mock_urllib3.called) self.assertEqual(2, mock_urllib3.side_effect.call_count) self.assertTrue(result)
def test_generate_reports_multiplos_parlamentares( self, mock_send_email ): brasilia_tz = pytz.timezone('America/Sao_Paulo') agora = datetime.now() data_final = datetime(agora.year, agora.month, agora.day) data_final = brasilia_tz.localize(data_final) data_inicial = data_final - timedelta(days=7) parlamentar1 = Parlamentar(id='1', cargo='BR1') parlamentar2 = Parlamentar(id='2', cargo='BR2') parlamentar3 = Parlamentar(id='3', cargo='BR1') relatorio1 = Relatorio( parlamentar=parlamentar1, data_final=data_final, data_inicial=data_inicial ).save().reload() relatorio2 = Relatorio( parlamentar=parlamentar2, data_final=data_final, data_inicial=data_inicial ).save().reload() relatorio3 = Relatorio( parlamentar=parlamentar3, data_final=data_final, data_inicial=data_inicial ).save().reload() mock_send_email.return_value = True user = [User( username='******', password='******', email='*****@*****.**', inscricoes=Inscricoes( parlamentares=[parlamentar1, parlamentar2, parlamentar3], intervalo=7 ) )] generate_reports(user, data_final=agora) mock_send_email.assert_called_once_with( "*****@*****.**", [relatorio1.to_dict(), relatorio2.to_dict(), relatorio3.to_dict()], dates=ANY )
def test_obter_relatorio_json_existente(self): brasilia_tz = pytz.timezone('America/Sao_Paulo') parlamentar = Parlamentar(id='1', cargo='BR1') relatorio = Relatorio( parlamentar=parlamentar, data_final=brasilia_tz.localize(datetime(2019, 1, 8)), data_inicial=brasilia_tz.localize(datetime(2019, 1, 1)), ).save() actual_response = Relatorios().obter_relatorio( '1', '2019-01-08', 'BR1', periodo=7) self.maxDiff = None self.assertEqual( brasilia_tz.normalize(actual_response['dataFinal'].replace(tzinfo=pytz.UTC)), relatorio.to_dict()['dataFinal'] ) actual_response['dataFinal'] = relatorio.to_dict()['dataFinal'] self.assertEqual( brasilia_tz.normalize(actual_response['dataInicial'].replace(tzinfo=pytz.UTC)), relatorio.to_dict()['dataInicial'] ) actual_response['dataInicial'] = relatorio.to_dict()['dataInicial'] self.assertEqual(actual_response, relatorio.to_dict())
def test_send_push_notification_invalid_json_response(self, mock_urllib3): def assert_equal(actual, expected): self.assertEqual(actual, expected) class FakePoolManager: def __init__(self, *args, **kwargs): FakePoolManager.call_count = 0 def request(self, method, url, headers, body): class response(): status = 401 data = '<HTML><HEAD><TITLE>Invalid (legacy) Server-key delivered or Sender is not authorized to perform request.</TITLE></HEAD><BODY BGCOLOR="#FFFFFF" TEXT="#000000"><H1>Invalid (legacy) Server-key delivered or Sender is not authorized to perform request.</H1><H2>Error 401</H2></BODY></HTML>'.encode( 'utf-8') FakePoolManager.call_count += 1 assert_equal(method, "POST") assert_equal(url, "https://fcm.googleapis.com/fcm/send") return response() data_inicial = datetime(2019, 10, 12) data_final = datetime(2019, 10, 19) parlamentar1 = Parlamentar(id='1', cargo='BR1', nome='AMANDA') relatorio1 = Relatorio( id="123", parlamentar=parlamentar1, data_final=data_final, data_inicial=data_inicial, proposicoes=[ Proposicao(id="1"), Proposicao(id="2"), Proposicao(id="3"), Proposicao(id="4") ], eventos_presentes=[Evento(id="1"), Evento(id="2")], eventos_previstos=None, eventos_ausentes=[Evento(id="4"), Evento(id="5"), Evento(id="6")]) mock_urllib3.side_effect = FakePoolManager result = send_push_notification("token", [relatorio1.to_dict()]) self.assertTrue(mock_urllib3.called) self.assertEqual(1, mock_urllib3.side_effect.call_count) self.assertFalse(result)
def test_obter_relatorio_json_inexistente_funcao_sem_erro( self, mock_model_selector ): parlamentar = Parlamentar(id='1', cargo='BR1') relatorio = Relatorio(parlamentar=parlamentar, data_final=datetime(2019, 1, 1)) class FakeModel: def obter_relatorio(self, *args, **kwargs): return relatorio mock_model_selector.return_value = FakeModel actual_response = Relatorios().obter_relatorio('1', '2019-01-01', 'BR1', periodo=7) actual_response['_id'] = 'id' relatorio.pk = 'id' self.assertEqual(mock_model_selector.call_count, 1) self.assertEqual(actual_response, relatorio.to_dict())
def test_generate_reports_send_to_active_devices_only( self, mock_send_email, mock_send_push_notification ): brasilia_tz = pytz.timezone('America/Sao_Paulo') agora = datetime(2019, 6, 29) data_final = datetime(agora.year, agora.month, agora.day) data_final = brasilia_tz.localize(data_final) parlamentar = Parlamentar(id='1', cargo='BR1') relatorio = Relatorio( parlamentar=parlamentar, data_final=data_final, data_inicial=data_final - timedelta(days=7) ).save().reload() mock_send_email.return_value = True users = [ User( username='******', password='******', email='*****@*****.**', inscricoes=Inscricoes( parlamentares=[parlamentar], intervalo=7 ), devices=[ UserDevice(id="device1", token="token1", name="name1", active=True), UserDevice(id="device2", token="token2", name="name2", active=False), UserDevice(id="device3", token="token3", name="name3", active=True), UserDevice(id="device4", token="token4", name="name4", active=False), ] ), ] generate_reports(users, data_final=agora) self.assertEqual(mock_send_push_notification.call_count, 2) mock_send_push_notification.assert_has_calls( [ call("token1", [relatorio.to_dict()]), call("token3", [relatorio.to_dict()]) ] )
def test_generate_reports_multiplos_intervalos( self, mock_send_email ): brasilia_tz = pytz.timezone('America/Sao_Paulo') agora = datetime(2019, 6, 29) data_final = datetime(agora.year, agora.month, agora.day) data_final = brasilia_tz.localize(data_final) parlamentar1 = Parlamentar(id='1', cargo='BR1') relatorio1 = Relatorio( parlamentar=parlamentar1, data_final=data_final, data_inicial=data_final - timedelta(days=7) ).save().reload() relatorio2 = Relatorio( parlamentar=parlamentar1, data_final=data_final, data_inicial=data_final - timedelta(days=14) ).save().reload() relatorio3 = Relatorio( parlamentar=parlamentar1, data_final=data_final, data_inicial=data_final - timedelta(days=28) ).save().reload() mock_send_email.return_value = True users = [ User( username='******', password='******', email='*****@*****.**', inscricoes=Inscricoes( parlamentares=[parlamentar1], intervalo=7 ) ), User( username='******', password='******', email='*****@*****.**', inscricoes=Inscricoes( parlamentares=[parlamentar1], intervalo=14 ) ), User( username='******', password='******', email='*****@*****.**', inscricoes=Inscricoes( parlamentares=[parlamentar1], intervalo=28 ) ) ] generate_reports(users, data_final=agora) self.assertEqual(mock_send_email.call_count, 3) mock_send_email.assert_has_calls( [ call("*****@*****.**", [relatorio1.to_dict()], dates=ANY), call("*****@*****.**", [relatorio2.to_dict()], dates=ANY), call("*****@*****.**", [relatorio3.to_dict()], dates=ANY) ] )
def test_send_push_notification_success(self, mock_urllib3): def assert_equal(actual, expected): self.assertEqual(actual, expected) data_inicial = datetime(2019, 10, 12) data_final = datetime(2019, 10, 19) parlamentar1 = Parlamentar(id='1', cargo='BR1', nome='AMANDA') relatorio1 = Relatorio( id="123", parlamentar=parlamentar1, data_final=data_final, data_inicial=data_inicial, proposicoes=[ Proposicao(id="1"), Proposicao(id="2"), Proposicao(id="3"), Proposicao(id="4") ], eventos_presentes=[Evento(id="1"), Evento(id="2")], eventos_previstos=None, eventos_ausentes=[Evento(id="4"), Evento(id="5"), Evento(id="6")]) expected_reports = [{ "_id": "123", "parlamentar": parlamentar1.to_dict(), "mensagem": None, "dataInicial": str(data_inicial), "dataFinal": str(data_final), "orgaos": 0, "proposicoes": 4, "eventosPresentes": 2, "eventosAusentes": 3, "eventosPrevistos": 0, "presencaRelativa": "100.00%", "presencaTotal": "40.00%", "eventosAusentesEsperadosTotal": 0 }] class FakePoolManager: def __init__(self, *args, **kwargs): pass def request(self, method, url, headers, body): class response(): status = 200 data = json.dumps({ 'results': [{ 'id': '123' }] }).encode('utf-8') assert_equal(method, "POST") assert_equal(url, "https://fcm.googleapis.com/fcm/send") assert_equal( json.loads(body.decode('utf-8'))["data"]["reports"], expected_reports) return response() mock_urllib3.side_effect = FakePoolManager reports = [relatorio1.to_dict()] result = send_push_notification("token", reports) self.assertTrue(mock_urllib3.called) self.assertTrue(result) self.assertEqual([relatorio1.to_dict()], reports)