Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tests: attach JSON mocks as attachments #348

Merged
merged 2 commits into from
Jul 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 18 additions & 114 deletions integration-test/helpers/harness.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
import {mkdtempSync, readFileSync} from 'fs'
import {readFileSync} from 'fs'
import {join} from 'path'
import {tmpdir} from 'os'
import {devices} from 'playwright'
import {chromium, firefox} from '@playwright/test'
import {macosContentScopeReplacements, iosContentScopeReplacements} from './mocks.webkit.js'

const DATA_DIR_PREFIX = 'ddg-temp-'
import {validPlatform} from './utils.js'

/**
* @param {import("@playwright/test").Page} page
Expand All @@ -28,42 +24,6 @@ export async function setupMockedDomain (page, domain) {
})
}

/**
* Launch a chromium browser with the test extension pre-loaded.
*
* @param {typeof import("@playwright/test").test} test
*/
export function withChromeExtensionContext (test) {
return test.extend({
context: async ({ browserName }, use, testInfo) => {
// ensure this test setup cannot be used by anything other than chrome
testInfo.skip(testInfo.project.name !== 'extension')

const tmpDirPrefix = join(tmpdir(), DATA_DIR_PREFIX)
const dataDir = mkdtempSync(tmpDirPrefix)
const browserTypes = { chromium, firefox }
const launchOptions = {
devtools: true,
headless: false,
viewport: {
width: 1920,
height: 1080
},
args: [
'--disable-extensions-except=integration-test/extension',
'--load-extension=integration-test/extension'
]
}
const context = await browserTypes[browserName].launchPersistentContext(
dataDir,
launchOptions
)
await use(context)
await context.close()
}
})
}

export async function withEmailProtectionExtensionSignedInAs (page, username) {
const [backgroundPage] = await page.context().backgroundPages()
await backgroundPage.evaluateHandle((personalAddress) => {
Expand Down Expand Up @@ -224,73 +184,6 @@ export function forwardConsoleMessages (page, _opts = {}) {
})
}

/**
* Launch a webkit browser with a user-agent that simulates our iOS application
* @param {typeof import("@playwright/test").test} test
*/
export function withIOSContext (test) {
return test.extend({
context: async ({ browser }, use, testInfo) => {
// ensure this test setup cannot be used by anything other than webkit browsers
testInfo.skip(testInfo.project.name !== 'webkit')

const context = await browser.newContext({
...devices['iPhone 13'],
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 DuckDuckGo/7 Safari/605.1.15'
})

await use(context)
await context.close()
}
})
}

/**
* Launch a webkit browser with a user-agent that simulates our iOS application
* @param {typeof import("@playwright/test").test} test
*/
export function withAndroidContext (test) {
return test.extend({
context: async ({ browser }, use, testInfo) => {
// ensure this test setup cannot be used by anything other than webkit browsers
testInfo.skip(testInfo.project.name !== 'android')

const context = await browser.newContext({
...devices.iPhone,
userAgent: 'Mozilla/5.0 (Linux; Android 12) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.88 DuckDuckGo/7 Mobile Safari/537.36'
})

await use(context)
await context.close()
}
})
}

/**
* Launch a chromium browser to simulates our Windows application
*
* Note: Autofill knows this is Windows via the isWindows string replacement
* @param {typeof import("@playwright/test").test} test
*/
export function withWindowsContext (test) {
return test.extend({
context: async ({ browser }, use, testInfo) => {
// ensure this test setup cannot be used by anything other than the Windows browser
testInfo.skip(testInfo.project.name !== 'windows')

const context = await browser.newContext({
...devices['Desktop Chrome']
})

await use(context)
for (let page of context.pages()) {
await addMocksAsAttachments(page, test)
}
await context.close()
}
})
}

/**
* @param {import("@playwright/test").Page} page
* @param {string} measureName
Expand Down Expand Up @@ -354,21 +247,32 @@ export async function mockedCalls (page, names = [], mustExist = true) {
*
* @param {import("@playwright/test").Page} page
* @param {typeof import("@playwright/test").test} test
* @param {import("@playwright/test").TestInfo} testInfo
* @returns {Promise<void>}
*/
async function addMocksAsAttachments (page, test) {
export async function addMocksAsAttachments (page, test, testInfo) {
const calls = await mockedCalls(page)
const platform = validPlatform(testInfo.project.name)
let index = 0
for (let call of calls) {
index += 1
const [name, params, response] = call
let [name, params, response] = call
const lines = [`name: ${name}`]
lines.push(`params: \n\n` + JSON.stringify(params, null, 2))
lines.push(`response: \n\n` + JSON.stringify(response, null, 2))
if (platform === 'android') {
lines.push('sent as json string: \n\n' + JSON.stringify(params))
params = JSON.parse(/** @type {any} */(params))
}
lines.push(`\n\nparams: \n\n` + JSON.stringify(params, null, 2))
lines.push(`\n\nresponse: \n\n` + JSON.stringify(response, null, 2))
test.info().attachments.push({
name: `mock ${index} ${name} params`,
name: `mock ${index} ${name} info`,
contentType: 'text/plain',
body: Buffer.from(lines.join('\n'))
})
test.info().attachments.push({
name: `mock ${index} params as JSON`,
contentType: 'text/json',
body: Buffer.from(JSON.stringify(params, null, 2))
})
}
}
6 changes: 2 additions & 4 deletions integration-test/helpers/mocks.windows.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,12 +141,10 @@ export function createWindowsMocks () {
window.__playwright_autofill.mocks.calls.push(JSON.parse(JSON.stringify(call)))
}
/**
* @param {any} request
* @param {any} _request
* @param {any} response
*/
function respond (name, request, response) {
const call = [name, request, response]
window.__playwright_autofill.mocks.calls.push(JSON.parse(JSON.stringify(call)))
function respond (name, _request, response) {
setTimeout(() => {
for (let listener of listeners) {
listener({
Expand Down
66 changes: 66 additions & 0 deletions integration-test/helpers/test-context.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import {validPlatform} from './utils.js'
import {join} from 'path'
import {tmpdir} from 'os'
import {mkdtempSync} from 'fs'
import {chromium, firefox} from '@playwright/test'
import {addMocksAsAttachments} from './harness.js'

const DATA_DIR_PREFIX = 'ddg-temp-'

/**
* A single place
* @param {typeof import("@playwright/test").test} test
*/
export function testContext (test) {
return test.extend({
context: async ({ browser, browserName }, use, testInfo) => {
// use `testInfo.project.name` is something we support.
const platform = validPlatform(testInfo.project.name)
let context

// first, create the context
switch (platform) {
case 'ios':
case 'android':
case 'macos':
case 'windows': {
context = await browser.newContext()
break
}
case 'extension': {
const tmpDirPrefix = join(tmpdir(), DATA_DIR_PREFIX)
const dataDir = mkdtempSync(tmpDirPrefix)
const browserTypes = { chromium, firefox }
const launchOptions = {
devtools: true,
headless: false,
viewport: {
width: 1920,
height: 1080
},
args: [
'--disable-extensions-except=integration-test/extension',
'--load-extension=integration-test/extension'
]
}
context = await browserTypes[browserName].launchPersistentContext(
dataDir,
launchOptions
)
}
}

// actually run the tests
await use(context)

// collect attachments (like mock calls) and append as attachments
// note: skipping the extension for now, since it's testing setup has fallen behind
if (platform !== 'extension') {
for (let page of context.pages()) {
await addMocksAsAttachments(page, test, testInfo)
}
}
await context.close()
}
})
}
13 changes: 13 additions & 0 deletions integration-test/helpers/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,17 @@ async function addTopAutofillMouseFocus (page, button) {
await page.mouse.move(x + 50, y + 15)
}

/**
* @param {any} stringInput
* @returns {Platform}
*/
export function validPlatform (stringInput) {
/** @type {Platform[]} */
const valid = ['extension', 'windows', 'ios', 'macos', 'android']
if (!valid.includes(stringInput)) {
throw new Error(`invalid platform: ${stringInput}`)
}
return stringInput
}

export {createAvailableInputTypes, stripDuckExtension, clickOnIcon, withDataType, addTopAutofillMouseFocus}
6 changes: 3 additions & 3 deletions integration-test/tests/email-autofill.android.spec.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import {
createAutofillScript,
forwardConsoleMessages,
withAndroidContext
forwardConsoleMessages
} from '../helpers/harness.js'
import {test as base} from '@playwright/test'
import {constants} from '../helpers/mocks.js'
import {emailAutofillPage, signupPage} from '../helpers/pages.js'
import {androidStringReplacements, createAndroidMocks} from '../helpers/mocks.android.js'
import {testContext} from '../helpers/test-context.js'

/**
* Tests for email autofill on android tooltipHandler
*/
const test = withAndroidContext(base)
const test = testContext(base)

test.describe('android', () => {
test.describe('when signed in', () => {
Expand Down
7 changes: 4 additions & 3 deletions integration-test/tests/email-autofill.extension.spec.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import {forwardConsoleMessages, withChromeExtensionContext, withEmailProtectionExtensionSignedInAs} from '../helpers/harness.js'
import {forwardConsoleMessages, withEmailProtectionExtensionSignedInAs} from '../helpers/harness.js'
import { test as base, expect } from '@playwright/test'
import {constants} from '../helpers/mocks.js'
import {emailAutofillPage} from '../helpers/pages.js'
import { stripDuckExtension } from '../helpers/utils.js'
import {testContext} from '../helpers/test-context.js'

/**
* Tests for email autofill in chrome extension.
*
* Special setup is needed to load the extension, see withChromeExtensionContext();
* Special setup is needed to load the extension, see testContext();
*/
const test = withChromeExtensionContext(base)
const test = testContext(base)

test.describe('chrome extension', () => {
test('should autofill the selected email', async ({page}) => {
Expand Down
6 changes: 3 additions & 3 deletions integration-test/tests/email-autofill.ios.spec.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import {
createAutofillScript,
forwardConsoleMessages,
withIOSContext
forwardConsoleMessages
} from '../helpers/harness.js'
import { test as base } from '@playwright/test'
import {constants} from '../helpers/mocks.js'
import {emailAutofillPage} from '../helpers/pages.js'
import {createWebkitMocks, iosContentScopeReplacements} from '../helpers/mocks.webkit.js'
import {testContext} from '../helpers/test-context.js'

/**
* Tests for email autofill on ios tooltipHandler
*/
const test = withIOSContext(base)
const test = testContext(base)

test.describe('ios', () => {
test('should autofill the selected email when email protection is enabled', async ({page}) => {
Expand Down
3 changes: 2 additions & 1 deletion integration-test/tests/email-autofill.macos.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ import {constants} from '../helpers/mocks.js'
import {emailAutofillPage, signupPage} from '../helpers/pages.js'
import {createWebkitMocks, macosContentScopeReplacements} from '../helpers/mocks.webkit.js'
import {createAvailableInputTypes, stripDuckExtension} from '../helpers/utils.js'
import {testContext} from '../helpers/test-context.js'

/**
* Tests for various auto-fill scenarios on macos
*/
const test = base.extend({})
const test = testContext(base)

test.describe('macos', () => {
test('should autofill the selected email', async ({page}) => {
Expand Down
7 changes: 4 additions & 3 deletions integration-test/tests/incontext-signup.extension.spec.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import {forwardConsoleMessages, withChromeExtensionContext, setupMockedDomain} from '../helpers/harness.js'
import {forwardConsoleMessages, setupMockedDomain} from '../helpers/harness.js'
import { test as base, expect } from '@playwright/test'
import {emailAutofillPage, incontextSignupPage, incontextSignupPageWithinIframe, incontextSignupPageEmailBottomPage, incontextSignupPageEmailTopLeftPage} from '../helpers/pages.js'
import {testContext} from '../helpers/test-context.js'

/**
* Tests for email autofill in chrome extension.
*
* Special setup is needed to load the extension, see withChromeExtensionContext();
* Special setup is needed to load the extension, see testContext();
*/
const test = withChromeExtensionContext(base)
const test = testContext(base)

test.describe('chrome extension', () => {
test('should allow user to sign up for Email Protection', async ({page, context}) => {
Expand Down
5 changes: 3 additions & 2 deletions integration-test/tests/login-form.android.spec.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import {constants} from '../helpers/mocks.js'
import {createAutofillScript, forwardConsoleMessages, withAndroidContext} from '../helpers/harness.js'
import {createAutofillScript, forwardConsoleMessages} from '../helpers/harness.js'
import {loginPage, loginPageWithFormInModal, loginPageWithText} from '../helpers/pages.js'
import {androidStringReplacements, createAndroidMocks} from '../helpers/mocks.android.js'
import {test as base} from '@playwright/test'
import {testContext} from '../helpers/test-context.js'

/**
* @typedef {import('../../src/deviceApiCalls/__generated__/validators-ts').GetAutofillDataResponse} GetAutofillDataResponse
Expand All @@ -13,7 +14,7 @@ import {test as base} from '@playwright/test'
/**
* Tests for email autofill on android tooltipHandler
*/
const test = withAndroidContext(base)
const test = testContext(base)

/**
* @param {import("@playwright/test").Page} page
Expand Down
Loading