Tutorial: 11 - Environment Switching / Custom mitmproxy Commands

11 - Environment Switching / Custom mitmproxy Commands

We use mitmproxy to enable our network capture when enableProxy is active - it's a very powerful tool.

If the built-in urlRewrites and blockPatterns settings don't cover your needs, you can manually use this rewrite functionality (or other feature) in your tests for environments switching using the extraProxyCommands.

Like all runner settings, extraProxyCommands can be added to either the specific test, or to all tests. In this example, the environment will be switched to 'qa', because the test-specific extraProxyCommands string overrides the runner-level setting with the same name:

// the runner configuration object
module.exports = {

  specs: [
    {
      testFile: 'tests/examples/switch-tiq-environment-to-qa.js',
      // switch to qa for this test only (overriding the runner-level switch to 'dev')
      extraProxyCommands: '--map-remote @tags\.tiqcdn\.com\/utag\/tealium-solutions\/test-example\/prod\/utag\.js@\/prod\/@/qa/' 
    },
    {
      testFile: 'tests/examples/switch-tiq-environment-to-dev.js',
    }
  ],

  summaryReportTitle: 'URL Rewrite POC',

  runRemotely: true,

  enableProxy: true,
  // environment switch TiQ from prod to dev (can be overridden by a test-specific string)
  extraProxyCommands: '--map-remote @tags\.tiqcdn\.com\/utag\/tealium-solutions\/test-example\/prod\/utag\.js@\/prod\/@/dev/',

  showDurations: true
}

That example command will cause your test run to use the qa version instead of prod for the utag.js file for tealium-solutions/test-example.

It could have also been implemented using the urlRewrites option:

      // ...
      urlRewrites: [{
        'pattern': 'tags.tiqcdn.com/utag/tealium-solutions/test-example/prod/utag.js',
        'type': 'string',
        'target': '/prod/',
        'replacement': '/qa/'
      }]
      // ... 

You can add more than one command to that string, and they'll be passed into the Proxy.

Be careful, syntax errors in this command can lead to confusing network-access-based test failures.

mitmproxy's documentation for that functionality (and much more) is here.