Skip to content
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 .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ jobs:
timeout-minutes: 15
strategy:
matrix:
node-version: [20, 22]
node-version: [20, 22, 24, 26]
os: [ubuntu-latest, macos-latest, windows-latest]
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: latest
version: 10
- name: Setup Node.js
uses: actions/setup-node@v4
with:
Expand Down
45 changes: 27 additions & 18 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,42 +4,51 @@ import { test } from 'node:test'
import { fileURLToPath } from 'node:url'
import { threadCpuUsage } from '../index.js'

function validateResult (result) {
ok(result !== null)
ok(Number.isFinite(parseInt(result.user)))
ok(Number.isFinite(parseInt(result.system)))
ok(result.user >= 0)
ok(result.system >= 0)
}

test('it should give proper thread usage', async () => {
const { stdout } = spawnSync('node', [fileURLToPath(new URL('./fixtures/load.js', import.meta.url))])

const lines = stdout
.toString()
.trim()
.split('\n')
.filter(line => line.startsWith('{') && line.endsWith('}'))
.map(l => JSON.parse(l))

deepEqual(lines[0].thread, 0)
deepEqual(lines[1].thread, 1)
deepEqual(lines[2].thread, 2)
deepEqual(lines[3].thread, 3)

for (let i = 0; i < 3; i++) {
const processDifference = lines[i].processCpuUsage.user / lines[i + 1].processCpuUsage.user
const threadDifference = lines[i].threadCpuUsage.user / lines[i + 1].threadCpuUsage.user

/*
All CPU usages should be the same. Technically they should have returned the same
value but since we measure it at different times they vary a little bit.
*/
ok(processDifference > 0.95)
ok(processDifference < 1.05)

/*
Each thread is designed to have a utilization two times the other one.
But since we cant really predict the OS scheduling, we just request it to be more than 20% and that
the trend is monotonic increasing.
*/
ok(threadDifference > 1.2)
for (const line of lines) {
validateResult(line.processCpuUsage)
validateResult(line.threadCpuUsage)
}
})

test('it works on the main thread, with or without arguments', () => {
threadCpuUsage(threadCpuUsage())
const result = threadCpuUsage()

validateResult(result)
validateResult(threadCpuUsage())
validateResult(threadCpuUsage(result))

let previous = threadCpuUsage()
for (let i = 0; i < 10; i++) {
const current = threadCpuUsage()

validateResult(current)
ok(current.user >= previous.user)
ok(current.system >= previous.system)
previous = current
}
})

test('it complains for invalid arguments', async () => {
Expand Down
Loading