Duplicate Variable and Scopes

I had fallen in a variable scope pitfall.
Recently I came back to request that were added months ago. And I try them as they were saved. Everything was looking good. As a sanity test, I checked the request in the console, and then I knew something was broken. A few entries were send empty even if I set them in pre-req script.

Investigation #1 Variable scopes are not implemented equally.
You have additional info about variable that you will use and you see each of them in URL/ PATH input. Like this:
image
But in Test text area you only have this


As I were not aware when sth was save in each of the scopes I found my pitfall.

This additional β€˜scope’ info was recently added, so step in right direction but not in all places you know what variable you will use. For now remember that :point_right: appearance of two suggested variable portends trouble.

Investigation #2 Cannot see the difference
As you cannot see the difference just looking at the code. Everything is just orange and say different current values. I cannot spot which were in two or more scopes without placing cursor and hitting ctrl+space.

Solution #1
Well established process and common names for variables.
I use prefixes for different kind of variables

  • r. for random created in pre-req
  • d. for dictionary and other constant.

This allow for fast typing with autocomplete.
Second benefit - I can Nuke it when it grows or I lost myself like today.

Like that:

function wipeCollection() {
    const clean = _.keys(pm.collectionVariables.toObject())
    _.each(clean, (arrItem) => {
        if (arrItem.startsWith("r.")) {
            pm.collectionVariables.unset(arrItem)
        }
    })
}
wipeCollection() 

function wipeGloabls() {
    const clean = _.keys(pm.globals.toObject())
    _.each(clean, (arrItem) => {
        if (arrItem.startsWith("r.")) {
            pm.globals.unset(arrItem)
        }
    })
}
wipeGloabls()

You can add ENV scope also If you need.

Question
This is easily to fix when you know about the problem.
But investigation from checking response body , pre-req js script, other request that set those variables and so one took me like 2h.

Do you have a better way to check which variables are duplicated???
My way is rather a final solution than a fix.

In JS part - test, pre-req you can specify which scope you want to use but in Body and URL Path you will use variable according to Variable scopes.

ps. If you think this should be in different place of the forum - lets be it. :trophy: Community Showcase

The function that you created looks very familiar :wink:

It’s good to embrace the best code snippets posted on the forum :wink:
I had to search, but first version was made by you, like a year ago :slight_smile:

1 Like

I’m glad that people are finding these things in the fourm and adapting them to their context!

It’s really great to see :heart:

1 Like