Skip to content

Commit

Permalink
Add tests and detect WhatsApp Web updates (pedroslopez#686)
Browse files Browse the repository at this point in the history
* test setup, add initializer tests

* test sending messages

* add script to check latest version

* add github action

* use env vars

* configure environment with .env file

* add test for sticker name and author

* add DownloadManager model

* test chats and contacts

* test for number utility functions

* throw error if no remote id has been set

* Update .version
  • Loading branch information
pedroslopez authored Jul 16, 2021
1 parent 04d2308 commit a03cc41
Show file tree
Hide file tree
Showing 10 changed files with 574 additions and 6 deletions.
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
WWEBJS_TEST_SESSION_PATH=test_session.json
WWEBJS_TEST_REMOTE_ID=[email protected]
3 changes: 2 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@
"es6": true,
"node": true
},
"extends": "eslint:recommended",
"extends": ["eslint:recommended", "plugin:mocha/recommended"],
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"parserOptions": {
"ecmaVersion": 2020
},
"plugins": ["mocha"],
"ignorePatterns": ["docs"],
"rules": {
"indent": [
Expand Down
35 changes: 35 additions & 0 deletions .github/workflows/update.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
name: Update

on:
schedule:
- cron: "0/15 * * * *"
workflow_dispatch:

jobs:
update:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2
- name: Install node v14
uses: actions/setup-node@v2
with:
node-version: '14'
- name: Install dependencies
run: npm install
- run: cd ./tools/version-checker
- name: Run Updater
run: ./update-version
- name: Store WA Version
run: echo WA_VERSION=`cat ./.version` >> $GITHUB_ENV
- name: Create Pull Request
uses: peter-evans/create-pull-request@v3
with:
commit-message: Update supported WhatsApp Web version to v${{ env.WA_VERSION }}
title: Update WhatsApp Web Version (${{ env.WA_VERSION }})
body: |
A new version of WhatsApp Web has been detected!
Tests should be run against this new version before merging.
labels: WhatsApp Change
reviewers: pedroslopez
9 changes: 7 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"main": "./index.js",
"typings": "./index.d.ts",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"test": "mocha tests",
"shell": "node --experimental-repl-await ./shell.js",
"generate-docs": "node_modules/.bin/jsdoc --configure .jsdoc.json --verbose"
},
Expand Down Expand Up @@ -37,8 +37,13 @@
"sharp": "^0.28.3"
},
"devDependencies": {
"chai": "^4.3.4",
"dotenv": "^10.0.0",
"eslint": "^7.27.0",
"eslint-plugin-mocha": "^9.0.0",
"jsdoc": "^3.6.4",
"jsdoc-baseline": "^0.1.5"
"jsdoc-baseline": "^0.1.5",
"mocha": "^8.4.0",
"sinon": "^11.1.1"
}
}
8 changes: 5 additions & 3 deletions src/util/Injected.js
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,8 @@ exports.LoadUtils = () => {
};

window.WWebJS.getChat = async chatId => {
const chat = window.Store.Chat.get(chatId);
const chatWid = window.Store.WidFactory.createWid(chatId);
const chat = await window.Store.Chat.find(chatWid);
return await window.WWebJS.getChatModel(chat);
};

Expand Down Expand Up @@ -324,8 +325,9 @@ exports.LoadUtils = () => {
return res;
};

window.WWebJS.getContact = contactId => {
const contact = window.Store.Contact.get(contactId);
window.WWebJS.getContact = async contactId => {
const wid = window.Store.WidFactory.createWid(contactId);
const contact = await window.Store.Contact.find(wid);
return window.WWebJS.getContactModel(contact);
};

Expand Down
10 changes: 10 additions & 0 deletions tests/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
## Running tests

These tests require an authenticated WhatsApp Web session, as well as an additional phone that you can send messages to.

This can be configured using the following environment variables:
- `WWEBJS_TEST_SESSION`: A JSON-formatted string with the session details. Must include `WABrowserId`, `WASecretBundle`, `WAToken1` and `WAToken2`.
- `WWEBJS_TEST_SESSION_PATH`: Path to a JSON file that contains the session details. Must include `WABrowserId`, `WASecretBundle`, `WAToken1` and `WAToken2`.
- `WWEBJS_TEST_REMOTEID`: A valid WhatsApp ID that you can send messages to, e.g. `[email protected]`.

You *must* set `WWEBJS_TEST_REMOTEID` **and** either `WWEBJS_TEST_SESSION` or `WWEBJS_TEST_SESSION_PATH` for the tests to run properly.
417 changes: 417 additions & 0 deletions tests/client.js

Large diffs are not rendered by default.

40 changes: 40 additions & 0 deletions tests/helper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const path = require('path');
const Client = require('../src/Client');
const Util = require('../src/util/Util');

require('dotenv').config();

const remoteId = process.env.WWEBJS_TEST_REMOTE_ID;
if(!remoteId) throw new Error('The WWEBJS_TEST_REMOTE_ID environment variable has not been set.');

function getSessionFromEnv() {
const envSession = process.env.WWEBJS_TEST_SESSION;
if(envSession) return JSON.parse(envSession);

const envSessionPath = process.env.WWEBJS_TEST_SESSION_PATH;
if(envSessionPath) {
const absPath = path.resolve(process.cwd(), envSessionPath);
return require(absPath);
}

throw new Error('No session found in environment.');
}

function createClient({withSession, options: additionalOpts}={}) {
const options = {};
if(withSession) {
options.session = getSessionFromEnv();
}

return new Client(Util.mergeDefault(options, additionalOpts || {}));
}

function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

module.exports = {
sleep,
createClient,
remoteId
};
1 change: 1 addition & 0 deletions tools/version-checker/.version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
2.2126.10
55 changes: 55 additions & 0 deletions tools/version-checker/update-version
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#!/usr/bin/env node

const fs = require('fs');
const puppeteer = require('puppeteer');
const { DefaultOptions } = require('../../src/util/Constants');

const getLatestVersion = async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setUserAgent(DefaultOptions.userAgent);

await page.goto('https://web.whatsapp.com/', { waitUntil: 'load'});
await page.waitForSelector('.landing-header');

const version = await page.evaluate(() => window.Debug.VERSION);
await browser.close();

return version;
};

const getCurrentVersion = () => {
try {
const versionFile = fs.readFileSync('./.version');
return versionFile ? versionFile.toString() : null;
} catch(_) {
return null;
}
};

const updateVersion = async (oldVersion, newVersion) => {
const readmePath = '../../README.md';

const readme = fs.readFileSync(readmePath);
const newReadme = readme.toString().replaceAll(oldVersion, newVersion);

fs.writeFileSync(readmePath, newReadme);
fs.writeFileSync('./.version', newVersion);

};

(async () => {
const currentVersion = getCurrentVersion();
const version = await getLatestVersion();

console.log(`Current version: ${currentVersion}`);
console.log(`Latest version: ${version}`);

if(currentVersion !== version) {
console.log('Updating files...');
await updateVersion(currentVersion, version);
console.log('Updated!');
} else {
console.log('No changes.');
}
})();

0 comments on commit a03cc41

Please sign in to comment.