jeudi 23 janvier 2020

How to test views using RequestFactory() and pytest with Django 2.0+

I am getting familiar testing django views with RequestFactory() I currently have the views below, what is the best way to write the test for?

I want to understand how it works, if anybody could show me the proper way the write the tests for these three functions using RequestFactory and mocking the create function. (I would be able to learn for future references)

path in the detail function to test is currently crashing for not using the right url apparently.

views.py

def index(request):
    universities = University.objects.all()

    context = {'universities': universities}
    return render(request, 'core/index.html', context)


def detail(request, id):
    univ = get_object_or_404(University, id=id)

    context = {'univ':univ}
    return render(request, 'core/detail.html', context)


def create(request):
    if request.method == "POST":
        form = UniversityForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/')
    else:
        form = UniversityForm()
    context = {'form':form}
    return render(request, 'core/create.html', context)

test_views.py

def test_list_univeristy():
    request = RequestFactory().get('/')
    resp = index(request)

    assert resp.status_code == 200


def test_detail_university():
    path = reverse('detail', kwargs={'id':1})
    request = RequestFactory().get(path)
    resp = univ_detail(request)

    assert resp.status_code == 200

def test_create():
    pass

forms.py

class UniversityForm(forms.ModelForm):
    class Meta:
        model = University
        fields = ('name', 
            'state', 
            'created', 
            'is_active'
        )

urls.py

app_name = 'core'
urlpatterns = [
    path('', views.index, name='index'),    
    path('<int:id>/', views.detail, name='detail'),
    path('create/', views.create, name='create'),
]

Aucun commentaire:

Enregistrer un commentaire