I need to test a function with a async function inside, but I do not know how to mock the async function.
matching_ingr_zingr.py
def first_table(ingredient_raw, ingredient_extracted, ingredient_processed):
ingredient_body, table_rows_I = [], []
for idx, ing_extr in enumerate(ingredient_extracted):
ingr_extr = " ".join(list(set(ing_extr.split())))
ext_ing_st = stemization(ingredient_extracted[idx])
try:
# # ======== MULTI-SEARCH
ingredient_body = format_for_batch_search(ingr_extr, ingredient_raw[idx], ext_ing_st)
res = asyncio.run(batch_search_v2(ingredient_body))
except BaseException:
res = 'Não retornou nada do Banco de Dados'
continue
result_search_clean, score, zingr_id = eliminate_duplicates_search(res)
for l in range(len(result_search_clean)):
proc_zing = text_normalization(result_search_clean[l])
table_rows_I.append({'Raw_Ingred': ingredient_raw[idx],
'Zapl_Ingre': result_search_clean[l],
'Proc_Ingre': ingredient_processed[idx],
'Extr_Ingre': ingredient_extracted[idx],
'Score_Elas': score[l],
'Ext_Ing_St': ext_ing_st,
'Proc_Zingr': proc_zing,
'Stem_Zingr': stemization(proc_zing),
'Zingred_id': zingr_id[l]})
return table_rows_I
The line to be mocked is asyncio.run(batch_search_v2(ingredient_body)) in the above code. To test the function first_table() I write the test below:
test_matching_ingr_zingr.py
#pytest.mark.asyncio
def test_first_table_entrada_correta(mocker):
ingredient_raw = ['Colher de açaí 2colher(es) de sopa']
ingredient_extracted = ('acai',)
ingredient_processed = ('colher acai colheres sopa',)
result_expected = table_rows_result
# mock mocking uma função assincrona (asynchronous function)
mocker.patch('src.services.matching_ingr_zingr.batch_search_v2', return_value=async_res)
# mocker.patch('src.services.matching_ingr_zingr.batch_search_v2', return_value=async_res)
result = first_table(ingredient_raw, ingredient_extracted, ingredient_processed)
assert result == result_expected
The variable table_rows_result is imported from another file to test.
Can anyone help me to learn how to do mock this async function, I want to test the first_table() but I dont want to acess the DB by batch_search_v2() async function.
The estructure of async_res is a list of tuples with lenght 3:
async_res = [('polpa de açaí', 9.626554, 2779),
('açaí', 8.914546, 1764),
('sopa de cebola', 8.442016, 388405)]
As described
#pytest.mark.asyncio
def test_first_table_entrada_correta(mocker):
async_res = [('polpa de açaí', 9.626554, 2779),
('açaí', 8.914546, 1764),
('sopa de cebola', 8.442016, 388405)]
with mock.patch(asyncio.run) as mock_async:
mock_async.configure_mock(return_value=async_res)
ingredient_raw = ['Colher de açaí 2colher(es) de sopa']
ingredient_extracted = ('acai',)
ingredient_processed = ('colher acai colheres sopa',)
result_expected = table_rows_result
result = first_table(ingredient_raw, ingredient_extracted, ingredient_processed)
assert result == result_expected
Related
I'm building a little app to generate a word document with several tables, since this process takes a little long to finish I'd like to add a progress bar to, make it a little less boring the wait for the user, so far I manage to make the following method:
def loading_screen(self,e,data_hold=None):
"""
Generates a progress bart to display elapset time
"""
loading = Toplevel()
loading.geometry("300x50")
#loading.overrideredirect(True)
progreso = Progressbar(loading,orient=HORIZONTAL,length=280,mode="determinate")
progreso.pack()
progreso.start(10)
#progreso.destroy()
This method is supposed to run right after the user clicks a button of the next Toplevel.
def validate_data(self):
"""
genera una venta para validar los datos ingresadados y hacer cualquier correccion
previa a la generacion de los depositos finales
"""
if self.datos:
venta = Toplevel()
venta.title("Listado de depositos por envasadora")
venta.geometry("600x300")
columnas = ["ID","Banco","Monto","Envasadora"]
self.Tree_datos = ttk.Treeview(venta,columns=columnas,show="headings")
self.Tree_datos.pack()
for i in columnas:
self.Tree_datos.heading(i,text=i)
for contact in self.datos:
self.Tree_datos.insert('', END, values=contact)
self.Tree_datos.column("ID",width=20)
#Tree_datos.column("Banco",width=100)
imprimir_depositos = Button(venta,text="Generar Depositos",command=self.generar_depositos)
imprimir_depositos.pack(fill=BOTH,side=LEFT)
editar_deposito = Button(venta,text="Editar seleccion",command=self.edit_view)
editar_deposito.pack(fill=BOTH,side=RIGHT)
imprimir_depositos.bind("<Button-1>",self.loading_screen)
#return get_focus ()
def get_focus(e):
self.valor_actualizado = self.Tree_datos.item(self.Tree_datos.focus()) ["values"]
self.Tree_datos.bind("<ButtonRelease-1>",get_focus)
else:
messagebox.showinfo(message="No hay datos que mostra por el momento",title="No hay datos!")
The command that generates the doc file is this (along with other methods that are not relevant for now I guess):
def generar_depositos(self):
documento = Document()
add_style = documento.styles ["Normal"]
font_size = add_style.font
font_size.name = "Calibri"
font_size.size = Pt(9)
table_dict = {"BPD":self.tabla_bpd,"BHD":self.tabla_bhd,"Reservas":self.tabla_reservas}
self.tabla_bhd(documento,"La Jagua","2535")
#for banco,env,deposito in datos_guardados:
#table_dict [banco] (documento,env,deposito)
# documento.add_paragraph()
self.set_doc_dimx(documento,margen_der=0.38,margen_izq=0.9,margen_sup=0.3,margen_infe=1)
sc = documento.sections
for sec in sc:
print(sc)
documento.save("depositos.docx")
So basically what I want is to display the animated progress bar while this method is running, I read about threading but I don't how to implement it on my code.
This code returns a JSON datas in my localhost from pokeAPI (https://pokeapi.co/) already filtered. But everytime I reload the page my dictionary gets duplicated and I just want the original always. PS: the red mark on the picture shows the original dictionary and the rest of it is wrong.
#listas auxiliares
tipo = [] #aux tipo
habil = [] #aux habilidade
lista_hab = []
lista_tipo = []
lista_todos = []
lista_aux = []
#dicionários
dicio_stat = {}
dicio_todos = {}
dicio_aux = {}
def pokemons(request):
for i in range(1, 10):
url = f"https://pokeapi.co/api/v2/pokemon/{i}"
requisicao = requests.get(url)
try:
lista = requisicao.json()
except ValueError:
print("ERRO TIPO")
dicio = {
'ID': lista['id'],
'Nome': lista['name'],
'Tipo': lista_tipo,
'Peso': lista['weight'],
'Altura': lista['height'],
'Habilidades': lista_hab,
'Estatisticas': dicio_stat,
'Link_img': lista['sprites']['other']['official-artwork']['front_default']
}
for a in lista['abilities']:
#dic_abi[i['ability']['name']] = i['ability']['url']
habil.append(a['ability']['name'])
dicio['Habilidades'] = habil[:]
lista_hab.append(dicio.copy())
for s in lista['stats']:
dicio_stat[s['stat']['name']] = s['base_stat']
for t in lista['types']:
#dic_type[i['type']['name']] = i['type']['url']
tipo.append(t['type']['name'])
dicio['Tipo'] = tipo[:]
lista_tipo.append(dicio.copy())
dicio_aux = dicio.copy()
lista_aux.append(dicio_aux)
dicio_todos['pokemons'] = lista_aux
habil.clear()
tipo.clear()
dicio.clear()
return JsonResponse(dicio_todos)
JSON
this issue appear when I put promedios[x] = float(punteos / 3), if suppose to x is in for outside have a int value like possition. I modified the code with the new changes
def alumno(nombre, apellido):
print('Nombre: ', nombre, 'Apellido: ', apellido)
def promedio(a,b,c):
promedio1 = int(a+b+c)/3
#return promedio1
print(promedio1)
nombre = input('ingrese nombre: ')
apellido = input('ingrese apellido: ')
alumno(nombre,apellido)
print()
#promedio(1,2,3)
print('Ingrese los punteos de las Materias:')
punteo = 0
materias = 5
for x in range(0, materias):
punteos = 0
notas = 3
promedio1 = 0
promedios = []
xx = 1
for y in range(0, notas):
punteo = int(input("Ingrese punteo de la Materia "+str(x+1)+" punteo "+str(y+1)+": "))
punteos = int(punteos + punteo)
promedio1 = float(punteos/3)
promedios.append(promedio1)
print('El promedio de la materia ',x+1,' es ',promedio1)
print(promedios[x])
As long as you have done promedios = 0 and no longer modify the variable promedios before the line of code promedios[x] = float(punteos / 3), promedios is an int at that line.
However, doing promedios[x] = ... calls the __setitem__ method of variable promedios, which is of type int and of course does not support such item assignment.
Types like list, dict support item assignment, by the way.
You need to start with an empty list:
promedios = []
And then append to it:
promedios.append(float(punteos / 3))
I am getting Rollbacks automatically.
Here is my code:
#socketio.on('update2')
def update_table_infocorp(trigger):
checknotprocess = Infocorp.query.filter(Infocorp.Procesado == False)
for row in checknotprocess:
getidentityuser = Usuarios.query.filter(Usuarios.id_user == row.id_user).first()
getidentityconsulta = Consolidado.query.filter(Consolidado.id_user == row.id_user and
(Consolidado.numdocumento == getidentityuser.numdocumento)).first()
if not getidentityconsulta:
# print("No se encontro la consulta relacionada al usuario.")
test = True
else:
sentinelresult = getsentinel(getidentityuser.tipodocumento, getidentityuser.numdocumento, row.id_consulta,
getidentityconsulta.solicitudes_id)
print(getidentityconsulta.solicitudes_id)
print(getidentityuser.tipodocumento)
if sentinelresult == True:
continue
else:
print("Ocurrio un error")
resultadoquery = Infocorp.query.filter(Infocorp.Procesado == True)
datatransform = InfocorpSchema(many=True)
datatransformresult = datatransform.dump(resultadoquery)
emit('nuevatableinfocorp', datatransformresult, broadcast=True)
And those are my logs:
I hope you will be able to help me because it is affecting other systems that use the same database.
I have made a function that extracts Gpe but it doesn't work.
The error generated is "invalid syntax" in the line that i will underline with * * in the code.
def EstraiLuoghi(frasi):
TokensTOT = []
TokensPOStot = []
NamedGPE = []
for frase in frasi:
tokens=nltk.word_tokenize(frase)
tokensPOS=nltk.pos_tag(tokens)
analisi=nltk.ne_chunk(tokensPOS)
for nodo in analisi:
NE=''
if hasattr(nodo, 'label'):
if nodo.label() in ["GPE"]:
for partNE in nodo.leaves():
NE=NE+' '+partNE[0]
NamedGPE.append(NE)
TokensTOT=TokensTOT+tokens
TokensPOStot=TokensPOStot+tokensPOS
return TokensTOT, TokensPOStot, NamedGPE
TokensTOT1, TokensPOStot1, NamedGPEC1 = EstraiLuoghi(frasi1)********
freqGPEC1 = nltk.FreqDist(NamedGPEC1)
luoghiOrdinatiC1 = freqGPEC1.most_common(20)
TokensTOT2, TokensPOStot2, NamedGPEC2 = EstraiLuoghi(frasi2)
freqGPEC2 = nltk.FreqDist(NamedGPEC2)
luoghiOrdinatiC2 = freqGPEC2.most_common(20)