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

fix: correctly generate test x request id for each test in one browser #825

Merged
merged 1 commit into from
Jan 16, 2024
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
4 changes: 2 additions & 2 deletions src/browser/browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@ module.exports = class Browser {
constructor(config, opts) {
this.id = opts.id;
this.version = opts.version;
this.testXReqId = opts.testXReqId;

this._config = config.forBrowser(this.id);
this._debug = config.system.debug;
this._session = null;
this._callstackHistory = null;
this._state = {
...opts.state,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поле теперь прокидываю в state. Посчитал, что нет необходимости в отдельном поле.

isBroken: false,
};
}
Expand Down Expand Up @@ -93,7 +93,7 @@ module.exports = class Browser {

if (!req.headers["X-Request-ID"]) {
req.headers["X-Request-ID"] = `${
this.testXReqId
this.state.testXReqId
}${X_REQUEST_ID_DELIMITER}${crypto.randomUUID()}`;
}

Expand Down
3 changes: 1 addition & 2 deletions src/browser/existing-browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ module.exports = class ExistingBrowser extends Browser {

quit() {
this._meta = this._initMeta();
this._state = { isBroken: false };
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот это бесполезная строка была. Решил удалить ее.

}

async prepareScreenshot(selectors, opts = {}) {
Expand Down Expand Up @@ -169,7 +168,7 @@ module.exports = class ExistingBrowser extends Browser {
return {
pid: process.pid,
browserVersion: this.version,
testXReqId: this.testXReqId,
testXReqId: this.state.testXReqId,
...this._config.meta,
};
}
Expand Down
12 changes: 10 additions & 2 deletions src/runner/test-runner/regular-test-runner.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ module.exports = class RegularTestRunner extends Runner {
sessionCaps: this._browser.capabilities,
sessionOpts: this._browser.publicAPI.options,
file: this._test.file,
testXReqId: this._browser.testXReqId,
state: this._browser.state,
});
}

Expand All @@ -82,7 +82,15 @@ module.exports = class RegularTestRunner extends Runner {

async _getBrowser() {
try {
this._browser = await this._browserAgent.getBrowser({ testXReqId: crypto.randomUUID() });
const state = { testXReqId: crypto.randomUUID() };

this._browser = await this._browserAgent.getBrowser({ state });

// use correct state for cached browsers
if (this._browser.state.testXReqId !== state.testXReqId) {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Бага исправляется за счет этого куска кода. Сюда из браузер пулов может прилететь закешированный браузер в котором находится свой testXReqId и мне его нужно переопределить.

Мне этот if не очень нравится, но нормального решения не нашел. Пытался прокидывать state через массу браузер пулов (cached, limited, basic, ...), но выглядит очень топорно и сложно. Поэтому решил остановится на этом варианте.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а как эти testXReqId-ы вообще могут совпасть, если ты в state-е его новый генеришь?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Они не совпадают. Проблема возникает когда используется 1 инстанс браузера на N тестов. В первом тесте выполняется генерация testXReqId и запись его в состояние браузера. А следующий тест уже использует существующий инстанс браузера в котором имеется testXReqId от первого теста. В итоге testXReqId от второго теста никуда не попадает. Т.е. он генерится, но из cached пула возвращается существующий браузер.

Как вариант можно выполнять applyState внутри этого самого caching пула.

this._browser.applyState(state);
}

this._test.sessionId = this._browser.sessionId;

return this._browser;
Expand Down
2 changes: 1 addition & 1 deletion src/worker/hermione.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export interface WorkerRunTestOpts {
sessionId: string;
sessionCaps: WdioBrowser["capabilities"];
sessionOpts: WdioBrowser["options"];
testXReqId: string;
state: Record<string, unknown>;
}

export interface AssertViewResultsSuccess {
Expand Down
4 changes: 2 additions & 2 deletions src/worker/runner/browser-agent.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@ module.exports = class BrowserAgent {
this._pool = pool;
}

getBrowser({ sessionId, sessionCaps, sessionOpts, testXReqId }) {
getBrowser({ sessionId, sessionCaps, sessionOpts, state }) {
return this._pool.getBrowser({
browserId: this.browserId,
browserVersion: this.browserVersion,
sessionId,
sessionCaps,
sessionOpts,
testXReqId,
state,
});
}

Expand Down
4 changes: 2 additions & 2 deletions src/worker/runner/browser-pool.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ module.exports = class BrowserPool {
this._calibrator = new Calibrator();
}

async getBrowser({ browserId, browserVersion, sessionId, sessionCaps, sessionOpts, testXReqId }) {
async getBrowser({ browserId, browserVersion, sessionId, sessionCaps, sessionOpts, state }) {
const browser = Browser.create(this._config, {
id: browserId,
version: browserVersion,
testXReqId,
state,
emitter: this._emitter,
});

Expand Down
4 changes: 2 additions & 2 deletions src/worker/runner/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,12 @@ module.exports = class Runner extends AsyncEmitter {
]);
}

async runTest(fullTitle, { browserId, browserVersion, file, sessionId, sessionCaps, sessionOpts, testXReqId }) {
async runTest(fullTitle, { browserId, browserVersion, file, sessionId, sessionCaps, sessionOpts, state }) {
const tests = await this._testParser.parse({ file, browserId });
const test = tests.find(t => t.fullTitle() === fullTitle);
const browserAgent = BrowserAgent.create({ id: browserId, version: browserVersion, pool: this._browserPool });
const runner = TestRunner.create(test, this._config.forBrowser(browserId), browserAgent);

return runner.run({ sessionId, sessionCaps, sessionOpts, testXReqId });
return runner.run({ sessionId, sessionCaps, sessionOpts, state });
}
};
4 changes: 2 additions & 2 deletions src/worker/runner/test-runner/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ module.exports = class TestRunner {
this._browserAgent = browserAgent;
}

async run({ sessionId, sessionCaps, sessionOpts, testXReqId }) {
async run({ sessionId, sessionCaps, sessionOpts, state }) {
const test = this._test;
const hermioneCtx = test.hermioneCtx || {};

let browser;

try {
browser = await this._browserAgent.getBrowser({ sessionId, sessionCaps, sessionOpts, testXReqId });
browser = await this._browserAgent.getBrowser({ sessionId, sessionCaps, sessionOpts, state });
} catch (e) {
throw Object.assign(e, { hermioneCtx });
}
Expand Down
15 changes: 3 additions & 12 deletions test/src/browser/existing-browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ describe("ExistingBrowser", () => {
});

it('should extend meta-info with "testXReqId" field', () => {
const browser = mkBrowser_({}, { testXReqId: "12345" });
const browser = mkBrowser_({}, { state: { testXReqId: "12345" } });

assert.propertyVal(browser.meta, "testXReqId", "12345");
});
Expand Down Expand Up @@ -179,10 +179,10 @@ describe("ExistingBrowser", () => {

it('should add "X-Request-ID" header', async () => {
crypto.randomUUID.returns("67890");
const testXReqId = "12345";
const state = { testXReqId: "12345" };
const request = { headers: {} };

await initBrowser_(mkBrowser_({}, { testXReqId }));
await initBrowser_(mkBrowser_({}, { state }));

const { transformRequest } = webdriverio.attach.lastCall.args[0];
transformRequest(request);
Expand Down Expand Up @@ -1073,15 +1073,6 @@ describe("ExistingBrowser", () => {
});

describe("quit", () => {
it("should overwrite state field", async () => {
const browser = await initBrowser_();
const state = browser.state;

browser.quit();

assert.notEqual(state, browser.state);
});

it("should keep process id in meta", async () => {
const browser = await initBrowser_();
const pid = browser.meta.pid;
Expand Down
4 changes: 2 additions & 2 deletions test/src/browser/new-browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -224,10 +224,10 @@ describe("NewBrowser", () => {

it('should add "X-Request-ID" header', async () => {
crypto.randomUUID.returns("67890");
const testXReqId = "12345";
const state = { testXReqId: "12345" };
const request = { headers: {} };

await mkBrowser_({}, { testXReqId }).init();
await mkBrowser_({}, { state }).init();

const { transformRequest } = webdriverio.remote.lastCall.args[0];
transformRequest(request);
Expand Down
7 changes: 2 additions & 5 deletions test/src/browser/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,11 @@ function createBrowserConfig_(opts = {}) {
};
}

exports.mkNewBrowser_ = (configOpts, opts = { id: "browser", version: "1.0", testXReqId: "" }) => {
exports.mkNewBrowser_ = (configOpts, opts = { id: "browser", version: "1.0", state: {} }) => {
return NewBrowser.create(createBrowserConfig_(configOpts), opts);
};

exports.mkExistingBrowser_ = (
configOpts,
opts = { id: "browser", version: "1.0", testXReqId: "", emitter: "emitter" },
) => {
exports.mkExistingBrowser_ = (configOpts, opts = { id: "browser", version: "1.0", state: {}, emitter: "emitter" }) => {
return ExistingBrowser.create(createBrowserConfig_(configOpts), opts);
};

Expand Down
26 changes: 20 additions & 6 deletions test/src/runner/test-runner/regular-test-runner.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,9 @@ describe("runner/test-runner/regular-test-runner", () => {

describe("run", () => {
it("should get browser before running test", async () => {
const testXReqId = "12345";
crypto.randomUUID.returns(testXReqId);
BrowserAgent.prototype.getBrowser.withArgs({ testXReqId }).resolves(
const state = { testXReqId: "12345" };
crypto.randomUUID.returns(state.testXReqId);
BrowserAgent.prototype.getBrowser.withArgs({ state }).resolves(
stubBrowser_({
id: "bro",
version: "1.0",
Expand All @@ -100,7 +100,7 @@ describe("runner/test-runner/regular-test-runner", () => {
publicAPI: {
options: { foo: "bar" },
},
testXReqId,
state,
}),
);
const workers = mkWorkers_();
Expand All @@ -116,11 +116,25 @@ describe("runner/test-runner/regular-test-runner", () => {
sessionId: "100500",
sessionCaps: { browserName: "bro" },
sessionOpts: { foo: "bar" },
testXReqId,
state,
}),
);
});

it("should modify state if 'testXReqId' is not actual", async () => {
const state = { testXReqId: "12345" };
crypto.randomUUID.returns(state.testXReqId);
const browser = stubBrowser_({
state: { testXReqId: "67890" },
});
BrowserAgent.prototype.getBrowser.withArgs({ state }).resolves(browser);
const workers = mkWorkers_();

await run_({ workers });

assert.calledWith(browser.applyState.firstCall, state);
});

it("should run test in workers", async () => {
const test = new Test({
file: "foo/bar",
Expand Down Expand Up @@ -517,7 +531,7 @@ describe("runner/test-runner/regular-test-runner", () => {
},
});

assert.calledOnceWith(browser.applyState, { foo: "bar" });
assert.calledWith(browser.applyState, { foo: "bar" });
assert.callOrder(browser.applyState, BrowserAgent.prototype.freeBrowser);
});

Expand Down
8 changes: 4 additions & 4 deletions test/src/worker/runner/browser-agent.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ describe("worker/browser-agent", () => {
sessionId: "100-500",
sessionCaps: "some-caps",
sessionOpts: "some-opts",
testXReqId: "12345",
state: {},
})
.returns({ some: "browser" });
const browserAgent = BrowserAgent.create({ id: "bro-id", version: null, pool: browserPool });
Expand All @@ -26,7 +26,7 @@ describe("worker/browser-agent", () => {
sessionId: "100-500",
sessionCaps: "some-caps",
sessionOpts: "some-opts",
testXReqId: "12345",
state: {},
});

assert.deepEqual(browser, { some: "browser" });
Expand All @@ -40,7 +40,7 @@ describe("worker/browser-agent", () => {
sessionId: "100-500",
sessionCaps: "some-caps",
sessionOpts: "some-opts",
testXReqId: "12345",
state: {},
})
.returns({ some: "browser" });
const browserAgent = BrowserAgent.create({ id: "bro-id", version: "10.1", pool: browserPool });
Expand All @@ -49,7 +49,7 @@ describe("worker/browser-agent", () => {
sessionId: "100-500",
sessionCaps: "some-caps",
sessionOpts: "some-opts",
testXReqId: "12345",
state: {},
});

assert.deepEqual(browser, { some: "browser" });
Expand Down
4 changes: 2 additions & 2 deletions test/src/worker/runner/browser-pool.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,12 @@ describe("worker/browser-pool", () => {
const browserPool = createPool({ config, emitter });
Browser.create.returns(stubBrowser({ browserId: "bro-id" }));

await browserPool.getBrowser({ browserId: "bro-id", browserVersion: "1.0", testXReqId: "12345" });
await browserPool.getBrowser({ browserId: "bro-id", browserVersion: "1.0", state: {} });

assert.calledOnceWith(Browser.create, config, {
id: "bro-id",
version: "1.0",
testXReqId: "12345",
state: {},
emitter,
});
});
Expand Down
4 changes: 2 additions & 2 deletions test/src/worker/runner/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,14 +130,14 @@ describe("worker/runner", () => {
sessionId: "100500",
sessionCaps: "some-caps",
sessionOpts: "some-opts",
testXReqId: "12345",
state: {},
});

assert.calledOnceWith(TestRunner.prototype.run, {
sessionId: "100500",
sessionCaps: "some-caps",
sessionOpts: "some-opts",
testXReqId: "12345",
state: {},
});
});
});
Expand Down
2 changes: 1 addition & 1 deletion test/src/worker/runner/test-runner/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ describe("worker/runner/test-runner", () => {
sessionId: "100500",
sessionCaps: "some-caps",
sessionOpts: "some-opts",
testXReqId: "12345",
state: {},
};

await runner.run(opts);
Expand Down
Loading