Created
December 21, 2024 15:43
-
-
Save alexandreelise/b6803c63da5fa777b87df3819f7113ab to your computer and use it in GitHub Desktop.
An example of heavily automated, optimized, effective Postman collection level pre-request script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Remove collection name from the breadcrumb | |
pm.execution.location.splice(0, 1); | |
// Remove the last element as it is the request and we don't need it | |
pm.execution.location.pop(); | |
let currentLocation = pm.execution.location.map(item => item.replace(/^((\d+\.\d*)(\s+))/, '').toLowerCase().split(' ').join('_')).join('_') || pm.variables.replaceIn('{{$uuid}}'); | |
console.log('computed current location', currentLocation); | |
// set collection level current location to use it in all request and responses in this collection and it also mean it is self-contained | |
pm.collectionVariables.set('computed_current_location', currentLocation); | |
// If no Joomla API }Token provided do not continue | |
pm.test(`Pre-request setting default headers for ${currentLocation}`, () => { | |
if (!pm.variables.get('auth_apikey')) { | |
pm.expect.fail('This failed because no Joomla API Token provided'); | |
} | |
}); | |
pm.test(`Pre-request setting default headers for ${currentLocation}`, () => { | |
let method = pm.request.method; | |
const allowedHttpAcceptHeader = ['application/vnd.api+json']; | |
const allowedHttpContentTypeHeader = ['application/json']; | |
const defaultHttpAcceptHeader = pm.variables.get('default_http_accept_header_value') || 'application/vnd.api+json'; | |
const defaultHttpContentTypeHeader = pm.variables.get('default_http_accept_header_value') || 'application/json'; | |
// Verify that the variables are in allowed lists | |
pm.expect(allowedHttpAcceptHeader).to.include(defaultHttpAcceptHeader); | |
pm.expect(allowedHttpContentTypeHeader).to.include(defaultHttpContentTypeHeader); | |
// If not in allowed list stop here | |
if (!allowedHttpAcceptHeader.includes(defaultHttpAcceptHeader) || !allowedHttpContentTypeHeader.includes(defaultHttpContentTypeHeader)) { | |
pm.expect.fail('This failed because provided Accept header or Content-Type header is not allowed'); | |
} | |
if (!['OPTIONS', 'HEAD', 'DELETE', 'TRACE'].includes(method) && !pm.request.headers.has('Accept', defaultHttpAcceptHeader)) { | |
pm.request.headers.append('Accept', defaultHttpAcceptHeader); | |
} | |
if (['POST', 'PATCH', 'PUT'].includes(method)) { | |
if (!pm.request.headers.has('Content-Type', defaultHttpContentTypeHeader)) { | |
pm.request.headers.append('Content-Type', defaultHttpContentTypeHeader); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment