Search code examples
postmanpostman-testcase

How can I change variable value in runtime in Postman test?


I'm trying to use postman for some basic API security tests and I have this URL:

http://example.com/api/v1/users/{{userID}}

{{userID}} is set to some user on site, and I want to set three tests that check if request is valid, if request has IDOR and if request has SQL injection.

This is the idea:

// userID is set to 20 ( valid user )

pm.test("Initial valid request", function () {
    pm.expect(pm.response.text()).to.include("Peter"); });

 *CHANGE THE VALUE OF {{userID}} to 30 to test for IDOR*
 * URL should be set to http://example.com/api/v1/users/30 *

pm.test("IDOR protection valid", function () {
    pm.expect(pm.response.text()).to.include("User not found."); });

 *CHANGE THE VALUE OF {{userID}} to 20'or'1 to test for SQL injection*
 * URL should be set to http://example.com/api/v1/users/20'or'1 * 

pm.test("SQL injection test", function () {
    pm.expect(pm.response.text()).to.include("You have an error"); });

My question is how do I change the values of {{userID}} so that next request uses changed value and not the one from environment variables.

Thanks


Solution

  • From the docs:

    Tests will execute after the request runs

    So each test will run based on the one request. So doing something like the following in your test

    pm.collectionVariables.set('userID', 'IDOR*') 
    // or
    pm.variables.set('userID', 'IDOR*') 
    

    Won't have the effect you're after as it doesn't make a request per test.

    One potential way to solve this would be to have multiple requests, all of which have set the different variable values in the Pre-request Script. As an example, you might have a request that looks like this: enter image description here

    And then the related test: enter image description here