212 lines
6.1 KiB
Python
212 lines
6.1 KiB
Python
#!/usr/bin/env python
|
|
"""
|
|
Script de teste da integração com API de Suprimentos.
|
|
Execute com: python test_api_integration.py
|
|
"""
|
|
|
|
import os
|
|
import sys
|
|
import django
|
|
from django.conf import settings
|
|
|
|
# Setup Django
|
|
sys.path.insert(0, os.path.dirname(__file__))
|
|
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'aprovacao_pedidos.settings')
|
|
django.setup()
|
|
|
|
from home.views import get_api_suprimentos_data, merge_api_with_sql_data
|
|
from django.conf import settings
|
|
|
|
def test_api_connection():
|
|
"""Testa a conexão com a API de Suprimentos."""
|
|
print("=" * 60)
|
|
print("TESTE 1: Conexão com a API de Suprimentos")
|
|
print("=" * 60)
|
|
|
|
# Verificar se token está configurado
|
|
api_config = settings.API_SUPRIMENTOS_CONFIG
|
|
token = api_config.get('TOKEN', '')
|
|
|
|
if not token:
|
|
print("❌ ERRO: Token não configurado no .env")
|
|
print(" Crie um arquivo .env com: API_SUPRIMENTOS_TOKEN=seu_token")
|
|
return False
|
|
|
|
print(f"✓ Token encontrado: {token[:20]}...")
|
|
print(f"✓ URL Detalhe: {api_config.get('DETALHE_URL')}")
|
|
print(f"✓ URL Implantação: {api_config.get('IMPLANTACAO_URL')}")
|
|
|
|
# Tentar buscar dados
|
|
print("\n📡 Conectando à API...")
|
|
api_data = get_api_suprimentos_data()
|
|
|
|
if api_data is None:
|
|
print("❌ Falha ao conectar com a API (verifique token e conexão de rede)")
|
|
return False
|
|
|
|
if isinstance(api_data, list) and len(api_data) > 0:
|
|
print(f"✓ Sucesso! {len(api_data)} registros obtidos da API")
|
|
|
|
# Mostrar exemplo de registro
|
|
first_record = api_data[0]
|
|
print("\nExemplo de registro da API:")
|
|
for key in ['PDV', 'SKU', 'quantidade', 'Quantidade']:
|
|
if key in first_record:
|
|
print(f" - {key}: {first_record[key]}")
|
|
|
|
return True
|
|
else:
|
|
print("⚠️ API retornou lista vazia")
|
|
return False
|
|
|
|
def test_data_merge():
|
|
"""Testa o merge de dados SQL + API."""
|
|
print("\n" + "=" * 60)
|
|
print("TESTE 2: Merge de dados (SQL + API)")
|
|
print("=" * 60)
|
|
|
|
# Dados de exemplo do SQL
|
|
sql_data = [
|
|
{
|
|
'PDV': '2001',
|
|
'SKU': 'ABC123',
|
|
'Descricao_PDV': 'Loja Centro',
|
|
'Estoque_Total': 150,
|
|
'sugestao_Compra_Total': 30
|
|
},
|
|
{
|
|
'PDV': '2002',
|
|
'SKU': 'XYZ789',
|
|
'Descricao_PDV': 'Loja Norte',
|
|
'Estoque_Total': 80,
|
|
'sugestao_Compra_Total': 15
|
|
}
|
|
]
|
|
|
|
# Dados de exemplo da API
|
|
api_data = [
|
|
{
|
|
'PDV': '2001',
|
|
'SKU': 'ABC123',
|
|
'quantidade': 45,
|
|
'status': 'pendente'
|
|
},
|
|
{
|
|
'PDV': '2003',
|
|
'SKU': 'QWE456',
|
|
'quantidade': 20,
|
|
'status': 'pendente'
|
|
}
|
|
]
|
|
|
|
print(f"Registros SQL: {len(sql_data)}")
|
|
print(f"Registros API: {len(api_data)}")
|
|
|
|
# Fazer merge
|
|
merged = merge_api_with_sql_data(sql_data, api_data)
|
|
|
|
print(f"\nResultado após merge: {len(merged)} registros")
|
|
|
|
for row in merged:
|
|
pdv = row.get('PDV')
|
|
sku = row.get('SKU')
|
|
sugestao = row.get('sugestao_analista')
|
|
presente = row.get('dados_api_presentes')
|
|
|
|
status = "✓ API" if presente else "- SQL"
|
|
print(f" {status} | PDV: {pdv}, SKU: {sku}, Sugestão: {sugestao}")
|
|
|
|
# Verificar se o merge funcionou
|
|
encontrou_match = any(row.get('dados_api_presentes') for row in merged)
|
|
if encontrou_match:
|
|
print("\n✓ Merge funcionando corretamente!")
|
|
return True
|
|
else:
|
|
print("\n⚠️ Nenhum match encontrado (PDV/SKU diferentes)")
|
|
return True
|
|
|
|
def test_full_integration():
|
|
"""Testa a integração completa."""
|
|
print("\n" + "=" * 60)
|
|
print("TESTE 3: Integração Completa")
|
|
print("=" * 60)
|
|
|
|
# Buscar dados da API
|
|
api_data = get_api_suprimentos_data()
|
|
|
|
if not api_data:
|
|
print("⚠️ API não disponível para teste completo")
|
|
return False
|
|
|
|
print(f"✓ Dados da API carregados: {len(api_data)} registros")
|
|
|
|
# Simular dados do SQL
|
|
sql_sample = [
|
|
{
|
|
'PDV': str(api_data[0].get('PDV', '')) if api_data else '0',
|
|
'SKU': str(api_data[0].get('SKU', '')) if api_data else '0',
|
|
'Estoque_Total': 100,
|
|
}
|
|
]
|
|
|
|
merged = merge_api_with_sql_data(sql_sample, api_data)
|
|
|
|
if merged[0].get('dados_api_presentes'):
|
|
print("✓ Merge bem-sucedido!")
|
|
print(f" - sugestao_analista: {merged[0].get('sugestao_analista')}")
|
|
return True
|
|
else:
|
|
print("⚠️ Sem matches (pode ser esperado com dados de exemplo)")
|
|
return True
|
|
|
|
def main():
|
|
"""Executa todos os testes."""
|
|
print("\n🧪 TESTES DE INTEGRAÇÃO COM API DE SUPRIMENTOS\n")
|
|
|
|
results = []
|
|
|
|
# Teste 1
|
|
try:
|
|
results.append(("Conexão com API", test_api_connection()))
|
|
except Exception as e:
|
|
print(f"\n❌ Erro no Teste 1: {e}")
|
|
results.append(("Conexão com API", False))
|
|
|
|
# Teste 2
|
|
try:
|
|
results.append(("Merge de dados", test_data_merge()))
|
|
except Exception as e:
|
|
print(f"\n❌ Erro no Teste 2: {e}")
|
|
results.append(("Merge de dados", False))
|
|
|
|
# Teste 3
|
|
try:
|
|
results.append(("Integração completa", test_full_integration()))
|
|
except Exception as e:
|
|
print(f"\n❌ Erro no Teste 3: {e}")
|
|
results.append(("Integração completa", False))
|
|
|
|
# Resumo
|
|
print("\n" + "=" * 60)
|
|
print("RESUMO DOS TESTES")
|
|
print("=" * 60)
|
|
|
|
for test_name, passed in results:
|
|
status = "✓ PASSOU" if passed else "❌ FALHOU"
|
|
print(f"{status}: {test_name}")
|
|
|
|
total_passed = sum(1 for _, passed in results if passed)
|
|
total = len(results)
|
|
|
|
print(f"\nTotal: {total_passed}/{total} testes passaram")
|
|
|
|
if total_passed == total:
|
|
print("\n🎉 Todos os testes passaram! Integração pronta para usar.")
|
|
return 0
|
|
else:
|
|
print("\n⚠️ Alguns testes falharam. Verifique a configuração.")
|
|
return 1
|
|
|
|
if __name__ == '__main__':
|
|
sys.exit(main())
|