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

feat(testing): add e2e test for 'Go Home' button #2648

Merged
merged 23 commits into from
Feb 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
f0b5a57
feat: add playwright
jsjoeio Jan 26, 2021
c2f1a2d
feat: add test for login page
jsjoeio Jan 28, 2021
d7e41a3
fix: increase test timeout to 30000
jsjoeio Jan 28, 2021
3033c8f
feat: add test to visit go home in app menu
jsjoeio Jan 28, 2021
34c6ec4
feat: add globalSetup for testing
jsjoeio Feb 1, 2021
9eba2bd
fix(ci): update test job to use bin
jsjoeio Feb 1, 2021
236717e
fix: update modulePathIgnorePatterns for jest
jsjoeio Feb 1, 2021
ffdbf3a
feat: add test/videos & /screenshots to gitignore
jsjoeio Feb 2, 2021
9e3c8bd
feat: add step to upload test videos
jsjoeio Feb 2, 2021
e077f2d
refactor: update test script to check env var
jsjoeio Feb 4, 2021
b02d2fb
feat: add cookie utils for e2e tests
jsjoeio Feb 4, 2021
2dc56ad
refactor: manually add cookie goHome
jsjoeio Feb 4, 2021
d0eece3
refactor: add note to test.sh about --home
jsjoeio Feb 4, 2021
06af8b3
refactor: update goHome location in test
jsjoeio Feb 11, 2021
38d7718
refactor: use promises for goHome test
jsjoeio Feb 11, 2021
3fa460c
refactor: create helpers.ts & add Cookie
jsjoeio Feb 12, 2021
5857b25
chore: add todo regarding storage and cookies e2e
jsjoeio Feb 12, 2021
b0fd554
refactor: add constants.ts with PASSWORD, etc
jsjoeio Feb 12, 2021
d61bbc4
refactor(goHome): check url, remove timeout
jsjoeio Feb 12, 2021
6d4f814
Close context before browser
code-asher Feb 12, 2021
ef7e727
Fix unreadable wtfnode output
code-asher Feb 12, 2021
6685b3a
Move wtfnode setup to global setup
code-asher Feb 12, 2021
47a05c9
Gate wtfnode behind WTF_NODE env var
code-asher Feb 12, 2021
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
10 changes: 9 additions & 1 deletion .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ jobs:
test:
needs: linux-amd64
runs-on: ubuntu-latest
env:
PASSWORD: e45432jklfdsab
CODE_SERVER_ADDRESS: http://localhost:8080
steps:
- uses: actions/checkout@v1
- name: Download release packages
Expand All @@ -37,9 +40,14 @@ jobs:
- uses: microsoft/playwright-github-action@v1
- name: Install dependencies and run tests
run: |
node ./release-packages/code-server*-linux-amd64 &
./release-packages/code-server*-linux-amd64/bin/code-server --home $CODE_SERVER_ADDRESS/healthz &
yarn --frozen-lockfile
yarn test
- name: Upload test artifacts
uses: actions/upload-artifact@v2
with:
name: test-videos
path: ./test/videos
jsjoeio marked this conversation as resolved.
Show resolved Hide resolved

release:
runs-on: ubuntu-latest
Expand Down
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,6 @@ node-*
/lib/coder-cloud-agent
.home
coverage
**/.DS_Store
**/.DS_Store
test/videos
test/screenshots
12 changes: 12 additions & 0 deletions ci/dev/test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,18 @@ main() {
# information. We must also run it from the root otherwise coverage will not
# include our source files.
cd "$OLDPWD"
if [[ -z ${PASSWORD-} ]] || [[ -z ${CODE_SERVER_ADDRESS-} ]]; then
echo "The end-to-end testing suites rely on your local environment"
echo -e "\n"
echo "Please set the following environment variables locally:"
echo " \$PASSWORD"
echo " \$CODE_SERVER_ADDRESS"
echo -e "\n"
echo "Please make sure you have code-server running locally with the flag:"
echo " --home \$CODE_SERVER_ADDRESS/healthz "
echo -e "\n"
exit 1
fi
CS_DISABLE_PLUGINS=true ./test/node_modules/.bin/jest "$@"
}

Expand Down
10 changes: 9 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,16 @@
"lines": 40
}
},
"testTimeout": 30000,
"globalSetup": "<rootDir>/test/globalSetup.ts",
"modulePathIgnorePatterns": [
"<rootDir>/release"
"<rootDir>/lib/vscode",
"<rootDir>/release-packages",
"<rootDir>/release",
"<rootDir>/release-standalone",
"<rootDir>/release-npm-package",
"<rootDir>/release-gcp",
"<rootDir>/release-images"
]
}
}
2 changes: 1 addition & 1 deletion src/node/routes/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { rootPath } from "../constants"
import { authenticated, getCookieDomain, redirect, replaceTemplates } from "../http"
import { hash, humanPath } from "../util"

enum Cookie {
export enum Cookie {
Key = "key",
}

Expand Down
3 changes: 3 additions & 0 deletions test/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const CODE_SERVER_ADDRESS = process.env.CODE_SERVER_ADDRESS || "http://localhost:8080"
export const PASSWORD = process.env.PASSWORD || "e45432jklfdsab"
export const STORAGE = process.env.STORAGE || ""
code-asher marked this conversation as resolved.
Show resolved Hide resolved
3 changes: 2 additions & 1 deletion test/e2e.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { chromium, Page, Browser } from "playwright"
import { CODE_SERVER_ADDRESS } from "./constants"

let browser: Browser
let page: Page
Expand All @@ -17,7 +18,7 @@ afterEach(async () => {
})

it("should see the login page", async () => {
await page.goto("http://localhost:8080")
await page.goto(CODE_SERVER_ADDRESS)
// It should send us to the login page
expect(await page.title()).toBe("code-server login")
})
34 changes: 34 additions & 0 deletions test/globalSetup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// This setup runs before our e2e tests
// so that it authenticates us into code-server
// ensuring that we're logged in before we run any tests
import { chromium } from "playwright"
import { CODE_SERVER_ADDRESS, PASSWORD } from "./constants"
import * as wtfnode from "./wtfnode"

module.exports = async () => {
console.log("\n🚨 Running Global Setup for Jest Tests")
console.log(" Please hang tight...")
const browser = await chromium.launch()
const context = await browser.newContext()
const page = await context.newPage()

if (process.env.WTF_NODE) {
wtfnode.setup()
}

await page.goto(CODE_SERVER_ADDRESS, { waitUntil: "domcontentloaded" })
// Type in password
await page.fill(".password", PASSWORD)
// Click the submit button and login
await page.click(".submit")

// Save storage state and store as an env variable
// More info: https://playwright.dev/docs/auth?_highlight=authe#reuse-authentication-state
const storage = await context.storageState()
process.env.STORAGE = JSON.stringify(storage)

await page.close()
await browser.close()
await context.close()
console.log("✅ Global Setup for Jest Tests is now complete.")
}
88 changes: 88 additions & 0 deletions test/goHome.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { chromium, Page, Browser, BrowserContext, Cookie } from "playwright"
import { hash } from "../src/node/util"
import { CODE_SERVER_ADDRESS, PASSWORD, STORAGE } from "./constants"
import { createCookieIfDoesntExist } from "./helpers"

describe("go home", () => {
let browser: Browser
let page: Page
let context: BrowserContext

beforeAll(async () => {
browser = await chromium.launch()
// Create a new context with the saved storage state
const storageState = JSON.parse(STORAGE) || {}

const cookieToStore = {
sameSite: "Lax" as const,
name: "key",
value: hash(PASSWORD),
domain: "localhost",
path: "/",
expires: -1,
httpOnly: false,
secure: false,
}

// For some odd reason, the login method used in globalSetup.ts doesn't always work
// I don't know if it's on playwright clearing our cookies by accident
// or if it's our cookies disappearing.
// This means we need an additional check to make sure we're logged in.
// We do this by manually adding the cookie to the browser environment
// if it's not there at the time the test starts
const cookies: Cookie[] = storageState.cookies || []
// If the cookie exists in cookies then
// this will return the cookies with no changes
// otherwise if it doesn't exist, it will create it
// hence the name maybeUpdatedCookies
//
// TODO(@jsjoeio)
// The playwright storage thing sometimes works and sometimes doesn't. We should investigate this further
// at some point.
// See discussion: https://github.com/cdr/code-server/pull/2648#discussion_r575434946

const maybeUpdatedCookies = createCookieIfDoesntExist(cookies, cookieToStore)
jsjoeio marked this conversation as resolved.
Show resolved Hide resolved

context = await browser.newContext({
storageState: { cookies: maybeUpdatedCookies },
recordVideo: { dir: "./test/videos/" },
})
})

afterAll(async () => {
// Remove password from local storage
await context.clearCookies()

await context.close()
await browser.close()
})

beforeEach(async () => {
page = await context.newPage()
})

// NOTE: this test will fail if you do not run code-server with --home $CODE_SERVER_ADDRESS/healthz
it("should see a 'Go Home' button in the Application Menu that goes to /healthz", async () => {
const GO_HOME_URL = `${CODE_SERVER_ADDRESS}/healthz`
// Sometimes a dialog shows up when you navigate
// asking if you're sure you want to leave
// so we listen if it comes, we accept it
page.on("dialog", (dialog) => dialog.accept())

// waitUntil: "domcontentloaded"
// In case the page takes a long time to load
await page.goto(CODE_SERVER_ADDRESS, { waitUntil: "domcontentloaded" })

// Click the Home menu
await page.click(".home-bar ul[aria-label='Home'] li")
// See the Go Home button
const goHomeButton = "a.action-menu-item span[aria-label='Go Home']"
expect(await page.isVisible(goHomeButton))

// Click it and navigate to /healthz
// NOTE: ran into issues of it failing intermittently
// without having button: "middle"
await Promise.all([page.waitForNavigation(), page.click(goHomeButton, { button: "middle" })])
expect(page.url()).toBe(GO_HOME_URL)
})
})
35 changes: 35 additions & 0 deletions test/helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Borrowed from playwright
export interface Cookie {
name: string
value: string
domain: string
path: string
/**
* Unix time in seconds.
*/
expires: number
httpOnly: boolean
secure: boolean
sameSite: "Strict" | "Lax" | "None"
}

/**
* Checks if a cookie exists in array of cookies
*/
export function checkForCookie(cookies: Array<Cookie>, key: string): boolean {
// Check for a cookie where the name is equal to key
return Boolean(cookies.find((cookie) => cookie.name === key))
}

/**
* Creates a login cookie if one doesn't already exist
*/
export function createCookieIfDoesntExist(cookies: Array<Cookie>, cookieToStore: Cookie): Array<Cookie> {
const cookieName = cookieToStore.name
const doesCookieExist = checkForCookie(cookies, cookieName)
if (!doesCookieExist) {
const updatedCookies = [...cookies, cookieToStore]
return updatedCookies
}
return cookies
}
38 changes: 38 additions & 0 deletions test/login.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { chromium, Page, Browser, BrowserContext } from "playwright"
import { CODE_SERVER_ADDRESS, PASSWORD } from "./constants"

describe("login", () => {
let browser: Browser
let page: Page
let context: BrowserContext

beforeAll(async () => {
browser = await chromium.launch()
context = await browser.newContext()
})

afterAll(async () => {
await browser.close()
})

beforeEach(async () => {
page = await context.newPage()
})

afterEach(async () => {
await page.close()
// Remove password from local storage
await context.clearCookies()
})

it("should be able to login", async () => {
await page.goto(CODE_SERVER_ADDRESS)
// Type in password
await page.fill(".password", PASSWORD)
// Click the submit button and login
await page.click(".submit")
// See the editor
const codeServerEditor = await page.isVisible(".monaco-workbench")
expect(codeServerEditor).toBeTruthy()
})
})
3 changes: 0 additions & 3 deletions test/socket.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,8 @@ import * as tls from "tls"
import { Emitter } from "../src/common/emitter"
import { SocketProxyProvider } from "../src/node/socket"
import { generateCertificate, tmpdir } from "../src/node/util"
import * as wtfnode from "./wtfnode"

describe("SocketProxyProvider", () => {
wtfnode.setup()

const provider = new SocketProxyProvider()

const onServerError = new Emitter<{ event: string; error: Error }>()
Expand Down
61 changes: 60 additions & 1 deletion test/util.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { JSDOM } from "jsdom"
import { Cookie } from "playwright"
// Note: we need to import logger from the root
// because this is the logger used in logError in ../src/common/util
import { logger } from "../node_modules/@coder/logger"
Expand All @@ -8,12 +9,16 @@ import {
getFirstString,
getOptions,
logError,
normalize,
plural,
resolveBase,
split,
trimSlashes,
normalize,
} from "../src/common/util"
import { Cookie as CookieEnum } from "../src/node/routes/login"
import { hash } from "../src/node/util"
import { PASSWORD } from "./constants"
import { checkForCookie, createCookieIfDoesntExist } from "./helpers"

const dom = new JSDOM()
global.document = dom.window.document
Expand Down Expand Up @@ -255,4 +260,58 @@ describe("util", () => {
expect(spy).toHaveBeenCalledWith("api: oh no")
})
})

describe("checkForCookie", () => {
it("should check if the cookie exists and has a value", () => {
const fakeCookies: Cookie[] = [
{
name: CookieEnum.Key,
value: hash(PASSWORD),
domain: "localhost",
secure: false,
sameSite: "Lax",
httpOnly: false,
expires: 18000,
path: "/",
},
]
expect(checkForCookie(fakeCookies, CookieEnum.Key)).toBe(true)
})
it("should return false if there are no cookies", () => {
const fakeCookies: Cookie[] = []
expect(checkForCookie(fakeCookies, "key")).toBe(false)
})
})

describe("createCookieIfDoesntExist", () => {
it("should create a cookie if it doesn't exist", () => {
const cookies: Cookie[] = []
const cookieToStore = {
name: CookieEnum.Key,
value: hash(PASSWORD),
domain: "localhost",
secure: false,
sameSite: "Lax" as const,
httpOnly: false,
expires: 18000,
path: "/",
}
expect(createCookieIfDoesntExist(cookies, cookieToStore)).toStrictEqual([cookieToStore])
})
it("should return the same cookies if the cookie already exists", () => {
const PASSWORD = "123supersecure"
const cookieToStore = {
name: CookieEnum.Key,
value: hash(PASSWORD),
domain: "localhost",
secure: false,
sameSite: "Lax" as const,
httpOnly: false,
expires: 18000,
path: "/",
}
const cookies: Cookie[] = [cookieToStore]
expect(createCookieIfDoesntExist(cookies, cookieToStore)).toStrictEqual(cookies)
})
})
})
Loading