Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
¿Cómo probar las vistas que usan la solicitud de publicación en Django?

aquí está mi punto de vista (simplificado):

 @login_required(login_url='/try_again') def change_bar(request): foo_id = request.POST['fid'] bar_id = request.POST['bid'] foo = models.Foo.objects.get(id=foo_id) if foo.value > 42: bar = models.Bar.objects.get(id=bar_id) bar.value = foo.value bar.save() return other_view(request)

Ahora me gustaría comprobar si esta vista funciona correctamente (en este modelo simplificado, si la instancia de Bar cambia de valor cuando debería). ¿Cómo lo hago?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Voy a suponer que te refieres a pruebas automatizadas en lugar de solo verificar que la solicitud posterior parece funcionar. Si se refiere a lo último, simplemente verifique ejecutando la solicitud y verificando los valores de Foo y Bar relevantes en un shell o en el administrador.

La mejor manera de enviar solicitudes POST es usando un Client . Asumiendo que el nombre de la vista es my_view :

 from django.test import Client from django.urls import reverse c = Client() c.post(reverse('my_view'), data={'fid':43, 'bid':20})

Pero aún necesita algunos datos iniciales en la base de datos, y debe verificar si se realizaron los cambios que esperaba. Aquí es donde podrías usar un TestCase :

 from django.test import TestCase, Client from django.urls import reverse FooBarTestCase(TestCase): def setUp(self): # create some foo and bar data, using foo.objects.create etc # this will be run in between each test - the database is rolled back in between tests def test_bar_not_changed(self): # write a post request which you expect not to change the value # of a bar instance, then check that the values didn't change self.assertEqual(bar.value, old_bar.value) def test_bar_changes(self): # write a post request which you expect to change the value of # a bar instance, then assert that it changed as expected self.assertEqual(foo.value, bar.value)

Una biblioteca que encuentro útil para configurar algunos datos para ejecutar las pruebas más fácilmente es FactoryBoy . Reduce el estándar cuando se trata de crear nuevas instancias de Foo o Bar con fines de prueba. Otra opción es escribir accesorios, pero me parece menos flexible si tus modelos cambian.

También recomendaría este libro si desea obtener más información sobre las pruebas en python. Está orientado a django, pero los principios se aplican a otros marcos y contextos.

editar: se agregaron consejos sobre factoryboy y enlace al libro

over 4 years ago · Santiago Trujillo Report

0

puede intentar poner declaraciones de "impresión" entre el código y ver si se guarda el valor correcto. También para actualizar en lugar de consultar con "get" y luego guardarlo (bar.save()), puede usar el método "filter" y "update".

 @login_required(login_url='/try_again') def change_bar(request): foo_id = request.POST['fid'] bar_id = request.POST['bid'] foo = models.Foo.objects.get(id=foo_id) if foo.value > 42: models.Bar.objects.filter(id=bar_id).update(value=foo.value) #bar.value = foo.value #bar.save() return other_view(request)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!