Django REST API UNIT Testing [3/3]

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello guys welcome back so this is the last video of our three part video section for creating a secure and well tested jungle restful api so in this last video we're going to look at rest api unit testing right so what i'm going to do is if not get to the api folder there's a test file that you see there so let's start by deleting or removing this test file right so i'm going to remove this test file inside the api folder just create a new folder called tests so the reason why i'm creating a new folder is if i'm going to have multiple api uh or multiple a per unit test that i want to run all the test files i'm going to put them inside this test folder so after you have done that just go ahead and quickly create a new test file so the test file is going to be called test underscore customer and that's called api dot py right so once i've created my test file the next thing that you probably need to do is you need to actually go ahead and create your init a file inside the test folder so the reason why we're creating an init so it's called underscore underscore init underscore underscore dot py so if you don't create this file uh when the test runner runs it will actually skip this file because it won't be recognized so you need to initialize your test folder because it's a new folder so once you have done that right let's go ahead and navigate to the newly created test file so what you want to do here is we want to actually go ahead and write some unit testing on our endpoints right so if you go to the api urls you actually see that we have the customers and then they get customers by id right so we want to write some unit testing on these views right so which means the customer view and the customer data view right so in this case i'm going to start by uh writing a unit testing for uh using a simple test case right because for our api unit testing uh we're going to use the api test case right but in this case i want to start by writing a simple jungle unit test right so i'm going to use simple test case for that so just quickly go ahead and write so this unit test is simply going to uh test our urls so i'm going to call it api urls test right then it's going to extend from simple simple tests case right like so right so so i just want to start so that you guys before i start writing the unit testing you know where we're coming from and what we're trying to achieve right so the next thing that i probably need to do is i need to import my simple test case so from jungle dot test import simple i mean simple test case simple tests yes right so once i have that imported right so in this case i simply want to test the urls right for example i want to test if this for example this customer uh url is resolved right so how do i mean by that so the unit testing that i'm going to write here the jungle unit testing it is going to test uh whether this uh if a client is this url api slash customers forward slash is it's it's supposed to resolve we're supposed to actually go ahead and run or or redirect to the customer view right so i that's the test that i want to run right so for us to be able to do that um we need to import the reverse and the and there is resolve function from jungle urls so from jungle dot urls import so we're going to import the reverse function right and then the result function so what this reverse function does is it actually uh go ahead and give you an absolute url so what do i mean by that right so let me so so now that i have my class right now that i have my class right the next thing that you need to do is you actually need to define your test case right so when the test runner runs right it actually uh looks for a file uh with with well with the name that start with tests right or folder that status test right so when the test runner runs it actually looks it actually see this folder called test then it goes into this folder then it looks for file that started test then it actually go ahead and run this file then while let's see it's in this file it will look for a test case that starts with test right so you have to uh note this uh your your your function or the name of your test case has to start with test right so this test case i'm going to call it get and get customers right is resolved right so since inside the class we need to reference it with self right so let's let's let's now pinpoint our url right so our url is uh we need to reverse it right so the way we reverse the arl because i said like i mentioned earlier the reverse a function is used to get an absolute a path right for urls so because here um so if you go to our urls right uh in our api urls you actually see that uh all the part that we have defined we've given them a specific name right so for us to actually get the absolute part of these customers for example the absolute path will be forward slash api forward slash customers then forward slash at the end so for us to be able to get the absolute url of this path we need to resolve it by its name right so this is a name customer so we'll go to a test case right so we want to reverse uh the customer right so let's actually go ahead and do this so what we are expecting right for example if i actually go ahead and print this out right so that you guys will see let's go ahead and print this out if i print this out right and then i run my test case we are supposed to get an absolute path for this customer so let's test it out so to uh to actually run your unit testing uh first of all you need to make sure that [Music] your future environment is up so i'm going to say pp and v shell right in terminal right so this is just activating my visual environment right then i navigate to my folder and i clear the terminal so my visual environment is now activated so to run the unit testing is simply say manage dot py test right so if you hit this command what the jungle test runner do is it actually looks for every uh test file in all the apps that we have so in this case it doesn't look for a test file in the api uh in the secure um in the in the business uh where's the business yeah this one in the business app it will actually look for the api but in this case you don't want to test the business app right we simply want to test um the api uh app only right so to do that you need to provide the name of the app at the end so in this case we want to test the api app right so once you have you have done that right as you can see actually it's not saying it is run one test right and then there are no errors right so you can actually see that at this line it is printed the absolute path right of our url right this slash api slash customers so this is how you get the url right so after you have done this right our test is not yet complete even though it's saying it is the rain one test but our test is not complete right so to complete our tests we need to write we need to write some assessions right so basically uh the the simple test case it actually comes with the self dots uh we can use a set equals so what a set means is we want to say so it's more or less like a declarative statement where we are saying uh the uh url that is being right so we later on need to resolve this url right so if you resolve this url so let me go to urls.py right so if we resolve this url right we need to actually make sure that it's it's actually going to refer or reference a cast a class or a view called view which is a class right so how can we do that right so we can do that through resolve right so we want to declare that the resolved url is going to be equal to the customer view as a class right so okay so before i resolve let me just let me just start by printing uh the resolved urls so that you see what you mean right so if i print um the resolved right i want to run the resolve and then i print the url right then i save then i run my tests right i want to see i want you to see you guys see what is being produced right so in the resolve we can actually see that it is if it is produced a resolver measure a resolver mesh right so inside this uh inside this resolver mesh you can actually see that we have something called a function right we have the arguments we have the keyword arguments we have the url name right which is the name of the url customer right and then we have the fnams we have the spaces the root right so this is the absolute root right so so what this resolve does it actually resolve the path right and then gives you what uh what what things they expected or what things are declared in that in that part for example the view name right so since everything is a function uh in python you can actually see that um our class here the or the uh the view name is being referenced under the function parameter right so this is the function dot api dot views and then the class name so we want to resolve if this class name if this url is going to run this customer view right so how do you do that so to do that we simply go ahead and write our session here right so for our assistant we're simply going to say resolve right resolve url right then so we want to get uh the uh the name of the class that is being the or the name of the view that is going to be run right so we get it by the function name right so if you type the function name right it will give us the actual class right it will actually uh it will give us the actual class right so for example if i print this so if i say resolve url dot func like so it it's supposed to give us so let me comment this out a bit it's supposed to it's supposed to actually give us uh the uh the class name right of this url so as you can see it's now saying uh function then the customer view and then the object of that class you can actually see that it's now giving us the the customer so which means uh for our resolve right so i'm going back to my assertion right i'm going to say assertion dot func right for function right dot view underscore class so this is how we get the the the name of the class you say view underscore class like this then dot comma right so what do you want to accept it what do i said that uh whatever the result function is going to be equal to because we know that it's supposed to run the customer view that's all so we need to we might need to import the customer view so let's quickly go ahead and import the customer view so from uh api dot views right so from the api app dot views import customer field like so right so like this so we don't need this print function anymore because you know you guys know so the this is our session so let's quickly go ahead and run our session all right so we can actually see that now the test is uh the test has passed one test right and then there are no issues so this is how you actually go ahead and write some unit testing some jungle unit testing for your urls right so in this in this tutorial we are not going to write some unit testing for everything for the jungle we were simply going to focus on the api unit testing but in uh if you guys want a video uh or now we can actually write some jungle unit testing whereby we'll be testing the models uh the videos um the urls and etc you guys just let me know in the comments down below so that i can actually go ahead and make a video for that so in this case this is how you write some url unit testing in jungle right so now let's quickly go ahead and move on to um our main purpose of this video so we want to write some unit testing for our api right so in this uh in this case you have noticed that we've been using the api test case right so for the rest api we use something called an api um we've been using a simple test case but in this case we'll now want to use a test case called api test case right so the api test case allows us to actually go ahead and write some unit testing for our uh rest api so first of all just quickly let's quickly go ahead and create the class so the class that we now need to create we can actually do it in this file so it's going to be called customer api field api view right api view yes right this is the name um this is the name of this name of my class right and then i'm going to extend from the api test from the api test case okay my typing is off today all right so i want to import this api test case right so how do we import it right so we're going to import it from the rest framework right so we're going to say from rest from work right dot test right import api tests yes right so the api test case it actually comes with an http client called the api client right so here we don't need to actually explicitly define it because there's something called an api client right like this api client but the class by this api test case class it comes with this api client right because for us to be able to write our request for example the get request they put the delete request we need to use an http client so in this case we'll be using uh the api test case comes with this api client so we don't need to explicitly uh bring it on because we are going to uh it's going we're going to use the one that comes with the api test case right so inside this test case what do you want to do right so in this um interface we need to actually go ahead and reverse uh our url right so we're going to say customers right so the view so so this is for the first view right so we are simply we're going to write some unit testing for the customer view then later on write the unit testing for the customer detail view right so we're starting with the customer view right so inside the customer view right we have our url are called customers right um our url scrolls uh slash customers with a name called custom right so let's simply go ahead and bring it up so we're going to say customer urls is equals to then we reverse to get the absolute path like what we did at the top here and customer like this so now that we have an absolute path what do you want to do right so since this is an api unit testing right there's uh there are some couple of things that we need to do right so for example um uh you can actually note that the our endpoints right so if you go to the urls right you can actually know that the customer view if you go to the api views you can actually note that the customer views these customer views are secured right which means we need to uh somewhere providing a token or an authentication to our client request headers right so like i said the api view comes with an api client right so when you write the request we need to as some way somehow to actually go ahead and provide an authorization header uh with a beta token uh to our uh uh client right so that will be able to make the get requests or the post request is specifically for this customer api view right so to do that django um uh there's a function that you can actually go ahead and make use of our code a setup right so these are more or less like some context manager right which actually go ahead and manage the resources for us right so there's a function called uh setup right so what this setup does is everything that you want to set up so like in this case we're going to say we're going to first of all we need to create a user for our client right once we have created a user then after creating user then we need to uh to create a token right a a token then after creating a token then we need to actually assign that token to our authorization um uh header on our on our client right so first of all we need to do that in the setup right then there's a teardown right for example like i said these are contest context managers right when we need to set up every time you run you run a test case or a test uh class you need to set up and then tear down in in terms of managing the resources right so in the in the in the setup right so before we write our test cases we need to get this out of the way right so let's let's let's quickly go ahead and create the the the user so we're going to use the user right the self.user is equals to user so we need to bring in the user from the uh auth modules right so let's quickly go ahead and do that so we're going to say from django dot contrib right dot auth dot models import user right so after we have imported the user the next thing that we need to do like i said we also need to create a token right so we need to uh bring the token from restroom so from junk from rest from work well from restful mic uh dot auth token dot models import right import token right so after you have imported the token um later on i need to import the status so i'm simply going to import everything that we're going to use in our test cases so from rest framework um import status right because we're going to use the status for example to to asset that maybe if it is a 200 uh response or two or one we need to use the status so that we'll be able to make our sessions right then after that uh the last thing that maybe you probably need to import i think i think this will do for now so let's quickly go ahead and create our user so to create our user we simply say user dot object right dot create create user right then we provide the username right so in this case we're going to say maybe username is that bin then we need to provide the password right password and say some uh uh password right so now that you've created our user what do you want to do right the next thing after creating a user like what we're doing manually we need to create a token right so let's create the token right so the token will be equal to let's use the token class dot objects dot objects objects dot create right so in this case we want to create a token by assigning uh by provider by so remember when we created a token in the last time we were actually providing some credentials so that it will be able young will be able to generate the token right so here we are simply providing the user that we've created so that it will be able to generate the token right so now uh now that we have uh the token what do we need to do next right so the next step will be actually to assign uh the token uh to assign the token to our authorization authorization header of our client right so in this case like i said before the api test case comes with an api client right so to use the api client you simply say a self-taught client right so the use of the token or um uh all these are coming from uh from the test case right so self dot client right we're using we're now using the api client right so self.client right so let's let's let's let's assign the authorization here so use a method called credentials right then we assign http underscore authorization right authorization so remember for our token right we need to provide the token right so remember we use the token keyword for rest uh token then we add itself dot token that we just generated then to get the actual uh string of the token or you use the key right dot key like this right so this is our setup setup method right so um after that for context management remember i said we also have a teardown right a teardown uh method right so in this in this in this case i'm not going to use this uh teardown the reason why because is every time you write a unit test or you run a unit test right what django does if it's involving the database it actually creates a volatile database right which means uh when the database is created after the test is completed right that database will be teared down automatically right so there's no need to actually go ahead and implement something down here because that is being automatically done uh by our jungle restroom otherwise if you're using other libraries uh there will be need for actually managing the context using this teardown so i'm not going to implement anything for now right so now let's write our test case right so for our test case we're going to say uh we want to test if they get customer uh if the guests they get uh sorry get customers um uh authenticated right so we want to test uh if we were actually able to uh run some get customers uh a query right on our ap on our customer customer view right so let's do it so now we need the response right so now let's let's write our requests so we need a response so we're simply going to say response it goes through now let's use the client to write the request so we're going to say self.client so in this case the self decla our client already has the authorization headers and everything that we need right so we are going to say so dot client right and then we want to write specifically a get request right for this one right so inside our get request then we need to actually go ahead and pass the url so self dot customer urls all right like this so it's not customer let's say customer url right like this right so once you have done this right now that uh response so now that our client is assigned a get request to our url let's let's try to assert it right so self. we're going to use the method asset equal right set equal so what do you want to asset so we want to accept that the response right this is now get request the response dot status right the status code that we're going to get is equal to the status dot http right http underscore 200 underscore okay right so this is what we are setting right so we're simply setting that uh this request is going to be successful why because we've provided some authorization headers and we're going to create a 200 response this is our this is what we want to set so let's quickly go ahead and save this and write and run our test right so manage.py test api like this all right so you can actually see that our test has worked right it has run two tests and both of them were successful so this is the first one and then this is the second one and then the first one was on the urls right so as a rule of thumb remember every time you write unit tests you need to actually go ahead and mess up with this so let's say i say 401 right so we need to actually see if our unit testing are working so every time you need to actually go ahead and mess up mess around with these assessions so that you can access that it's behaving as expected right so you can actually see that we know we're now getting an error it ran two tests but one is failed right so uh the one that is filled it's it's this one one hour session it's expecting 200 yet we've provided 401 right so which means our session is working and also one thing like i had mentioned earlier we don't need the date down as you can see it's actually at the beginning of the test it has said creating a test database right so here it is created a test database but after the test is run it it's not destroying the database all right the database so you don't need to implement the teardown because everything will be automatically done for you right so for our you for the guest to get customer url that was authenticated this has worked right so the next test that we need to do is we need to test if we if we can actually uh do a get a request for an authenticated uh an authenticated um and an authenticated authenticated this will definitely twist your time okay and authenticated requests right so so for us so remember uh everything is being done in the tier so which means every every time we run our unit testing the setup will uh set our authorization header um with the token right but here now since this method or since this test class uh test case is in this test class how can you actually go ahead and remove this authorization header right so to remove it right not to worry the rest framework comes with um a method right so i'm going to use the client so i'm going to say first of all i need to remove the authorization header so i'm going to say self.client right it comes with a method called force right force authentication um or then t right force authenticate like this right then you simply go ahead and pass your user and assign a user to none and then the token to none as well right or either one of them right so if you set this to none it actually means that we have removed the authorization header for specifically this function uh on our client right so now let's try to actually go ahead and run our unit test so i'm simply going to copy these two right because it's the same i'm simply going to copy this and paste them here uh but in this case now the status code that we're expecting is no longer 200 right so we're now expecting that we'll get a 401 401 which means we haven't provided some authentication but for now for the purpose of testing i'm going to test it with the 200 right and it's supposed to fail on this test case so let me clear my terminal and run the uh test again all right so you can actually see that it is run three tests but one is filled right so which one so it has failed uh this one that's just an error we were saying it's it's status 200 yet we have removed the authorization headers supposed to be a 401 right so in this case our unit testing is working so let's quickly go ahead and correct it to 401 all right so once you've done that it actually means that your client is now being saved right and then everything is working fine right so this is this this was just for the get requests right so now let's quickly go ahead and implement the post request right so let's quickly go ahead and test write test posts underscore customer right uh undersold customer and then this one is going to be you're going to provide is authenticated right then we'll pass itself like so right so the first thing that we need is the data for our customer right so the data that we need we need the title okay so for the data we need the title then for the title i'm going to say next um then the name so this is just the name right so i'm going to say peter then the last name right i'm going to say parker then the gender right the gender remember we had our status choice with the gender then the status right remember for the status uh on our manager we had the status uh whether it was a draft or a published so in this case i'm simply going to say uh published right also for the keyword it was small caps right so this is the data that we want to post right so now let's quickly go ahead and write our post requests right so for our first request i'm simply going to say self.client right then i'm simply going to say dot in this case it's a post request right then we'll assign the url so customer url then we assign the data right and then pairs maybe the format so the format is going to be json right so these are post requests right so after you've written our post requests let's now write our sessions so we need to say asset self.set equal right so in this case we are expecting that since it's um uh since this one is this client is authenticated we're expecting a status code of 201 is created right so status dot um http underscore 201 underscore created right so these are the rest setters right so this is the first accession so you can actually go ahead and write as many sessions as you want there's no limit right so you can actually go ahead and say a set equal so the more sessions the better because your app will be more robust since you have you they've maybe exhausted some more test cases right so if you write as many as sessions as possible it's actually recommended right so here i'm going to say the response dot data so remember each and every time each and every time you uh you make a post request it actually returns the user that you have posted so in this case i'm simply going to say the response is going to have a name called peter right so i've written some two assistants let me go ahead and save this and clear my terminal and rerun the test all right so as you can see it is run four tests and then all the tests is actually passed right so let's let's try to mess around maybe with the name here let's say let's say let's put john right and test it out so put john and then run our api testing again all right so it is four tests but one is failed right so it's peter for john right so which means our session our post request is working as xp as expected right all right so if uh our post requests um is working right so the next uh the next the next one uh that we need to write is for an authenticated right so i'm not going to write so you guys i'm going to simply uh leave this leave this for you for the unauthenticated you guys you can actually go ahead and make a pull request and write the on authenticated so just quickly go ahead you can make a pull request and do that as your assignment um so the link in the uh the link is in the description below for the actually uh for the for the repository right so the repository it actually has a description it is everything i'll show you at the end of the video all right so by now i think uh this customer view i think we are done with it right so let's move on to the next uh to uh to the customer detail view right so let's write some unit testing for that one all right so class customer detail api view yes right so remember you need to uh extend your api test case for you to get all the nitty gritties right so in this in this in this case now right so in this case now what do you want to do right so if you go on to our views right we have a get request right so for our get requests uh we have a get request then we have a put request and we have a delete right so in these two requests we first initially need to actually uh pre insert some data so that we'll be able to write some get requests so we need to use both of the views right so if you go to the urls you can actually see that for our get request this uh this the second one is actually accepting is actually taking an id right then the first one it doesn't right but we need both of these urls why because for us to to do some delay some get requests we need to actually pre-populate the table first right so what i'm simply going to do here is i'm simply going to paste the first one right the customer urls right and then i paste it here right and then we need the second one right so the second one i'm going to call it customer because this is just for a single thing customer instead of customers i'm going to say customer url then i reverse the function so for the reverse function of this one uh it's it's actually uh it's called customer customer detail right that's the name of it right customer detail all right so that's the name of it customer detail like this but if i try to run this uh the test here i actually have an error why because the error that will receive is the customer if you go back to the urls this one is expecting a parameter right so which means for our universe url we need a way to actually provide a parameter right so if i test this out okay so let me let me simply go ahead and clear my terminal and run so that you guys will see the error that we get all right so it's saying run one test and one one field right so where is the failure right so the failure is saying uh for our url pattern um the customer detail with no arguments not found so which means we need a way to actually provide arguments to our urls so without arguments uh it won't work so we need to provide an argument so let's quickly go ahead and provide arguments so the way you provide argument uh the reverse function comes with an axe comes within ads so the argument that we'll be expecting in this case is we need to provide an id so let's just provide an id one right so after you've provided the id right we need to write your setup right so in this case uh let me simply go ahead and copy the setup that we had before right so the setup that we're going to have is this one right so remember we need to pre-populate the data right so inside our setup i'm going to create the user i'm going to create the token then i'm going to assign the authorization token right and then maybe lastly i need to pre-insert a user right so here i'm going to put a comment uh saving user saving user like so right so once uh so the user that i want to save right i can copy the data here right so i can copy this data right so once i've copied this data then i can make my post request right so let me simply go ahead and copy everything here right so i'm simply using uh the same data like so so we are using the customer url that we brought in here so that will be able to make the possible question right so maybe for for the so that you guys will see that it's different um let me actually go ahead and put a different um i'm going to say bruce banner like this right and it's published so that you guys you see the difference so that you see that it's actually running two different classes all right so now after we have done that uh the next thing that we probably need to do now is to actually go ahead and create our um our test cases right so the first test case that we need is we need to actually go ahead and uh test uh get uh test guest customer authenticated right authenticated then we need to provide itself like so so for our test customer authenticated we need a response right so let's write the let's write our requests so we're going to say self.client dot get right so in this case uh we are now using the uh the new uh url right this one with with an argument because we want to get the customer by the id so we write that right so after we have made the uh the get request the next thing that we need to do is to provide our session so i'm going to say asset right i set equal then response dot status underscore code right so for our status code in this case i'm going to say 200. um right i'm going to say 200 because we're going to get the data right then the second a session i'm going to say asset set equal right then response dot data right the data then the name so in this case the name is going to be ros right because we have a posted a proceed right so the response is going to be 200 which means our get request is going to work so let's quickly go ahead and run our test so clear this out then i'll run the test after we have run the tests uh you can actually see that it has ran five tests and one test has failed right so which uh where is the failure customer url is not defined all right i forgot since this one is an instance of a class i need to refer it by the instance name right so i need to put self here alright so this is an instance variable so my bit guys right so let's rerun the test again all right so as you can see uh it has run the five tests and all of them um you have passed right so this is how you do the get requests right so for the unauthenticated user you can actually go ahead and do the same thing um but you're expecting to get a 401 so instead of typing this all out i'm simply going to copy and paste this and i'm going to say to change the name of our test case so in this case it's now unauthenticated then to provide some an authentication we need to use the force authenticate function right so let's use the force authenticate function to actually remove uh the user then we get right so in this case um we are not going we are not going to get a status 200 because this is an authenticated user we expecting get a 401 right so let's save this up and let's rerun the test all right so as you can see it has run the two tests right so the last test that i'm going to run for this tutorial is i'm going to run the test delete test delete customer right for the authenticated request right so for the let's quickly go ahead and write our our requests our delete requests so we use the delete method um then the self dot customer url right so and let's quickly go ahead and write our session i set set equal right so for the assession we're going to expect it to have a status uh code a status code of 204 no content right so remember when you write our delete requests it actually returns a 204 status code right so http all right http underscore 204 underscore no content right because after hitting the the delete request remember it actually returns a two or four meaning uh it returns an empty object right so let's run the tests all right so i can actually see that it has ran seven tests and all of them here have passed all right so the last uh test for this uh for this one was the put request so like i said you guys can actually go ahead and do it so if you have reached this far and if you've managed to make these requests congratulations guys this is how you do some api unit testing in jungle rest framework so this is how you actually go ahead and do that so thank you guys for watching the video and don't forget to like and subscribe to the channel just to support the channel so i think now i think i can actually go ahead and show you uh the the github for those who want to be making the pull requests so the link for the github is actually in the comment down below um just just go ahead and check it out in the description of the video this is the length of the github so what i've done to the github is i've actually written some sort of a documentation to this whole three part tutorial so it's actually a long documentation where if you don't want to watch the video you can actually go ahead and read it out so just make sure that you visit it if you find it helpful so it's actually documentation with everything that you need to know about this whole three-part video course so naturally go ahead and like you can style it you can fork it you can use it as you wish but this is it so again you're actually free to make some pull requests to actually do those tests that way so that it can be a contributor to this one so this was it guys uh thank you for taking your time watching this video i know that this was long i'm looking forward to the next video cheers
Info
Channel: StackDev IO
Views: 11,655
Rating: undefined out of 5
Keywords:
Id: z6_v1UQ9Ht0
Channel Id: undefined
Length: 46min 26sec (2786 seconds)
Published: Thu Jul 01 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.