@testmonitor/testmonitor-cli 0.0.1 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.editorconfig ADDED
@@ -0,0 +1,15 @@
1
+ root = true
2
+
3
+ [*]
4
+ charset = utf-8
5
+ end_of_line = lf
6
+ indent_size = 4
7
+ indent_style = space
8
+ insert_final_newline = true
9
+ trim_trailing_whitespace = true
10
+
11
+ [*.md]
12
+ trim_trailing_whitespace = false
13
+
14
+ [*.{yml,yaml}]
15
+ indent_size = 2
@@ -0,0 +1,10 @@
1
+ # Build artifacts
2
+ build
3
+ coverage
4
+ dist
5
+
6
+ # Markdown files
7
+ **/*.md
8
+
9
+ # Lock files
10
+ package-lock.json
package/CHANGELOG.md ADDED
@@ -0,0 +1,9 @@
1
+ # Change Log
2
+ All notable changes to this project will be documented in this file.
3
+
4
+ The format is based on [Keep a Changelog](http://keepachangelog.com/)
5
+ and this project adheres to [Semantic Versioning](http://semver.org/).
6
+
7
+ ## [1.0.0] - 2025-08-15
8
+ ### Added
9
+ - Initial version.
package/README.md CHANGED
@@ -1,95 +1,128 @@
1
1
  # TestMonitor CLI
2
2
 
3
- TestMonitor CLI (`testmonitor-cli`) is a command-line tool to submit JUnit XML test results to a JSON API.
3
+ The TestMonitor CLI (`testmonitor-cli`) lets you interact with the TestMonitor platform directly from your terminal or CI pipelines. You can use it to submit automated test results through a simple, scriptable interface.
4
+
5
+ ## Table of Contents
6
+
7
+ - [Installation](#installation)
8
+ - [Getting Started](#getting-started)
9
+ - [Command Reference](#command-reference)
10
+ - [Documentation](#documention)
11
+ - [License](#license)
4
12
 
5
13
  ## Installation
6
14
 
7
- Simply install the package by using NPM or Yarn:
15
+ Install the CLI globally using NPM:
16
+
17
+ ```sh
18
+ npm install -g @testmonitor/testmonitor-cli
19
+ ```
20
+
21
+ To upgrade to the latest version later on, run:
8
22
 
9
23
  ```sh
10
- npm install -g testmonitor-cli
24
+ npm update -g @testmonitor/testmonitor-cli
11
25
  ```
12
26
 
13
- or
27
+ After installation, you can verify the installed version with:
14
28
 
15
29
  ```sh
16
- yarn global add testmonitor-cli
30
+ testmonitor-cli --version
17
31
  ```
18
32
 
19
- This installs the TestMonitor CLI tool globally on your system.
33
+ ## Getting Started
20
34
 
21
- ## Authentication
35
+ To begin using the CLI, follow these steps:
22
36
 
23
- TestMonitor CLI requires authentication via an API token. Set the token as an environment variable:
37
+ ### Authenticate
24
38
 
39
+ Set your API token using the TESTMONITOR_TOKEN environment variable.
40
+
41
+ **macOS/Linux:**
25
42
  ```sh
26
43
  export TESTMONITOR_TOKEN=<your_api_token>
27
44
  ```
28
45
 
29
- On Windows (PowerShell):
30
-
46
+ **Windows (PowerShell):**
31
47
  ```sh
32
48
  $env:TESTMONITOR_TOKEN="<your_api_token>"
33
49
  ```
34
50
 
35
- ## Usage
51
+ > You can find or regenerate your API token in your TestMonitor user profile settings under API Tokens.
52
+
53
+ ### Check your connection
36
54
 
37
- Once you've setup your TestMonitor token, you can start submitting JUnit reports:
55
+ Verify that your domain and token are set up correctly:
38
56
 
39
57
  ```sh
40
- testmonitor-cli submit -d <TESTMONITOR_DOMAIN> -i <INTEGRATION_ID> -f <FILE_PATH>
58
+ testmonitor-cli check auth -d domain.testmonitor.com
41
59
  ```
42
60
 
43
- For example:
61
+ If the connection is successful, you’ll see:
44
62
 
45
63
  ```sh
46
- testmonitor-cli submit -d domain.testmonitor.com -i 12345-abcdef-67890-ghijkl -f results.xml
64
+ Connection successful.
47
65
  ```
48
66
 
49
- ## Commands
67
+ If the check fails, try the following:
50
68
 
51
- ### `submit`
69
+ - **Invalid token**: Regenerate it from your user profile in TestMonitor and update the TESTMONITOR_TOKEN variable.
70
+ - **Wrong domain**: Double-check that the --domain flag matches the full domain assigned to your TestMonitor workspace (e.g., mycompany.testmonitor.com).
71
+ - **Deleted or inactive account**: Log into TestMonitor to ensure your user account is still active.
52
72
 
53
- Submit a JUnit XML test report.
73
+ If problems persist, contact support@testmonitor.com.
54
74
 
55
- **Options:**
56
- ```sh
57
- -d, --domain <domain> TestMonitor domain (required)
58
- -i, --integration-id <id> Integration ID (required)
59
- -f, --file <path> Path to JUnit XML file (required)
60
- ```
75
+ ## Command Reference
61
76
 
62
- ## Development
77
+ This section lists all available commands grouped by functionality.
63
78
 
64
- Clone the repository and install dependencies:
79
+ ### Check
65
80
 
66
- ```sh
67
- git clone https://github.com/testmonitor/testmonitor-cli.git
68
- cd testmonitor-cli
69
- npm install
70
- ```
81
+ Tools for verifying your CLI setup and connection to the TestMonitor API.
82
+
83
+ #### Auth
84
+
85
+ Verify API token and domain connectivity.
71
86
 
72
- Run locally:
73
87
  ```sh
74
- node index.js submit -d api.testmonitor.com -i 12345-abcdef-67890-ghijkl -f test-results.xml
88
+ testmonitor-cli check auth [options]
75
89
  ```
76
90
 
77
- Run tests:
91
+ | Option | Description |
92
+ |--------------------------|----------------------------------|
93
+ | -d, --domain <domain> | TestMonitor domain (required) |
94
+
95
+ ### JUnit
96
+
97
+ Commands for managing JUnit-style test reports.
98
+
99
+ #### Submit
100
+
101
+ Submit a JUnit XML report and create a new test run in your TestMonitor project.
102
+
78
103
  ```sh
79
- npm test
104
+ testmonitor-cli junit submit [options]
80
105
  ```
81
106
 
82
- ## Versioning
83
-
84
- We use [SemVer](http://semver.org/) for versioning. For the versions available, see the [tags](https://github.com/testmonitor/testmonitor/tags)
85
- and the [releases](https://github.com/testmonitor/testmonitor/releases) on this repository.
107
+ | Option | Description |
108
+ |-----------------------------------|--------------------------------------------------|
109
+ | -d, --domain <domain> | TestMonitor domain (required) |
110
+ | -i, --integration-id <id> | JUnit integration ID (required) |
111
+ | -f, --file <path> | Path to JUnit XML file (required) |
112
+ | -n, --name <name> | Custom test run name |
113
+ | -m, --milestone-id <id> | Target milestone ID |
114
+ | -o, --milestone-name <name> | Milestone name to find or create |
115
+ | -e, --test-environment-id <id> | Target test environment ID |
116
+ | -t, --type <type> | Test type (e.g. cypress, playwright, phpunit) |
117
+ | -p, --preserve-names | Preserve original test case names |
118
+ | -s, --skip-root-suite | Skip root test suite nesting |
119
+ | -v, --verbose | Output debug information |
86
120
 
87
- ## Authors
121
+ ## Documentation
88
122
 
89
- * **Thijs Kok** - *Lead developer* - [ThijsKok](https://github.com/thijskok)
90
- * **Stephan Grootveld** - *Developer* - [Stefanius](https://github.com/stefanius)
91
- * **Frank Keulen** - *Developer* - [FrankIsGek](https://github.com/frankisgek)
123
+ Please refer to our [knowledge base](https://help.testmonitor.com/) for more information.
92
124
 
93
125
  ## License
94
126
 
95
- TestMonitor is a commercial product, provided as a SaaS application to the customers of TestManagement BV.
127
+ Copyright (c) TestMonitor | we are Cerios B.V.
128
+ All rights reserved.
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ var N=Object.defineProperty;var D=(n,e)=>()=>(n&&(e=n(n=0)),e);var S=(n,e)=>{for(var t in e)N(n,t,{get:e[t],enumerable:!0})};var b={};S(b,{default:()=>L});var L,T=D(()=>{L={name:"@testmonitor/testmonitor-cli",type:"module",version:"0.0.2",description:"The TestMonitor CLI lets you interact with the TestMonitor platform directly from your terminal or CI pipelines.",keywords:["testmonitor","cli"],homepage:"https://www.testmonitor.com/",bugs:{url:"https://github.com/testmonitor/testmonitor-cli/issues"},repository:{type:"git",url:"git+https://github.com/testmonitor/testmonitor-cli.git"},author:"TestMonitor | we are Cerios B.V.",main:"src/index.js",bin:{"testmonitor-cli":"dist/index.js"},scripts:{start:"node src/index.js",build:"node esbuild.config.js",lint:"eslint .","lint:fix":"eslint . --fix",test:"NODE_OPTIONS='--experimental-vm-modules' jest","test:watch":"NODE_OPTIONS='--experimental-vm-modules' jest --watch","test:coverage":"NODE_OPTIONS='--experimental-vm-modules' jest --coverage"},dependencies:{axios:"^1.7.9",chalk:"^5.4.1",commander:"^14.0.0",dotenv:"^17.2.0",ora:"^8.2.0","strip-ansi":"^7.1.0",table:"^6.9.0"},devDependencies:{chai:"^5.2.0",esbuild:"^0.25.6",eslint:"^9.31.0","eslint-config-prettier":"^10.1.5","eslint-formatter-junit":"^8.40.0","eslint-plugin-import":"^2.32.0","eslint-plugin-jest":"^28.14.0","eslint-plugin-jsdoc":"^51.4.1",jest:"^29.7.0","jest-junit":"^16.0.0",prettier:"^3.6.2"},engines:{node:">=16.0.0"}}});import"dotenv/config";import{Command as W}from"commander";async function y(){return"0.0.2"}import{Command as B}from"commander";import{Command as X}from"commander";import C from"os";import R from"fs";import P from"axios";import O from"form-data";var V=await y(),q=`NodeJS/${process.nodeVersion}`,J=`${C.platform()} ${C.release()}`,A=`TestMonitorCLI/${V} (${q}; ${J}; +https://www.testmonitor.com/)`,u=class{constructor({domain:e,apiKey:t,httpClient:o}){this.baseURL=`https://${e}/api/v1`,this.apiKey=t,this.httpClient=o||P.create({baseURL:this.baseURL,headers:{Authorization:`Bearer ${this.apiKey}`,"User-Agent":A}})}async get(e,t={}){return this._request("get",e,null,t)}async post(e,t={},o={}){return this._request("post",e,t,o)}async put(e,t={},o={}){return this._request("put",e,t,o)}async delete(e,t={}){return this._request("delete",e,null,t)}async _request(e,t,o,i){let s={...o instanceof O?o.getHeaders():{"Content-Type":"application/json"},...i.headers||{}};try{return(await this.httpClient.request({method:e,url:t,data:o,headers:s,...i})).data}catch(a){let f=a.response?.data?.message||a.message;throw new Error(f)}}async checkConnection(){return this.get("/my-account")}async submitJUnitReport({integrationId:e,filePath:t,name:o,type:i,milestoneId:r,milestoneName:s,preserveNames:a,skipRootSuite:f,testEnvironmentId:w}){let c=new O;c.append("integration_id",e),c.append("report",R.createReadStream(t));let v={name:o,type:i,milestone:s,milestone_id:r,preserve_names:a?1:null,skip_root_suite:f?1:null,test_environment_id:w};for(let[m,l]of Object.entries(v))l!=null&&c.append(m,l);return this.post("/reporters/junit/submit",c)}};import d from"chalk";import K from"ora";import{table as F}from"table";var h=class{#e="TestMonitor";info(e){console.log(`${this.#e}: ${e}`)}success(e){console.log(`${this.#e}: ${d.green(e)}`)}warn(e){console.warn(`${this.#e}: ${d.yellow(e)}`)}error(e,t){let o=`${this.#e}: ${d.red(e)}`;console.error(o),process.env.DEBUG&&t instanceof Error&&console.error(d.gray(t.stack||t.message))}debug(e){process.env.DEBUG&&console.log(`${this.#e}: ${e}`)}line(e=""){console.log(e)}async spin(e,t,o={}){let i=K({text:`${this.#e}: ${e}`,color:"green"}).start();try{let r=await t();return i.succeed(`${this.#e}: ${d.green(o.successMessage||e)}`),r}catch(r){throw i.fail(`${this.#e}: ${d.red(o.errorMessage||e)}`),r}}table(e,t){let o=F(e,{singleLine:!0,...t});console.log(o)}};async function G(n,{client:e}={}){let{domain:t}=n,o=new h,i=process.env.TESTMONITOR_TOKEN;i||(o.error("TESTMONITOR_TOKEN environment variable is not set."),process.exit(1));let r=e||new u({domain:t,apiKey:i});try{let{data:s}=await o.spin("Connecting...",()=>r.checkConnection(),{successMessage:"Connection successful.",errorMessage:"Failed to connect."});o.line(),o.table([["User ID",s.id],["Name",s.name],["Email",s.email]])}catch(s){let a=s.response?.data?.message||s.message;o.line(),o.error(a,s),process.exit(1)}}var _=new X("auth").description("Verify connectivity with your TestMonitor instance.").requiredOption("-d, --domain <domain>","Your TestMonitor domain name (e.g., mydomain.testmonitor.com)").action(async n=>{await G(n)});var x=new B("check").name("check").description("Commands for verifying the connection state.").helpOption("-h, --help","Display help for command.");x.addCommand(_);var M=x;import{Command as Q}from"commander";import"dotenv/config";import Y from"fs";import{Command as z}from"commander";async function H(n,{client:e}={}){let{domain:t,integrationId:o,file:i,name:r,milestoneId:s,milestoneName:a,preserveNames:f,skipRootSuite:w,testEnvironmentId:c,type:v}=n,m=new h,l=process.env.TESTMONITOR_TOKEN;l||(m.error("TESTMONITOR_TOKEN environment variable is not set."),process.exit(1)),Y.existsSync(i)||(m.error(`File not found at path ${i}`),process.exit(1));let j=e||new u({domain:t,apiKey:l});try{let{data:p}=await m.spin("Submitting...",()=>j.submitJUnitReport({integrationId:o,filePath:i,name:r,type:v,milestoneId:s,milestoneName:a,preserveNames:f,skipRootSuite:w,testEnvironmentId:c}),{successMessage:"Report submitted.",errorMessage:"Failed to submit."});m.line(),m.table([["JUnit file",p.name],["Test run code",p.test_run.code],["Test run URL",p.test_run.links.show]])}catch(p){let k=p.response?.data?.message||p.message;m.line(),m.error(k,p),process.exit(1)}}var $=new z("submit").name("submit").description("Submit a JUnit XML file to your TestMonitor instance.").helpOption("-h, --help","Display help for command.").requiredOption("-d, --domain <domain>","Your TestMonitor domain name (e.g., mydomain.testmonitor.com)").requiredOption("-i, --integration-id <id>","The JUnit integration ID").requiredOption("-f, --file <path>","Path to your JUnit XML file").option("-m, --milestone-id <id>","Milestone ID for the new test run (required if not set in configuration))").option("-o, --milestone-name <name>","Find or create a milestone by name for the test run.").option("-n, --name <name>","Custom name for the test run (auto-generated if omitted).").option("-p, --preserve-names","Preserve test case names exactly as in the XML file.").option("-s, --skip-root-suite","Skip the root suite and start from nested suites.").option("-e, --test-environment-id <id>","Test environment ID for the new test run.").option("-t, --type <type>","The automation test type (cypress, playwright, phpunit, selenium).").option("-v, --verbose","Enable verbose debug output.").action(n=>H(n));var I=new Q("junit").name("junit").description("Commands for JUnit XML report submission.").helpOption("-h, --help","Display help for command.");I.addCommand($);var E=I;var g=new W;g.name("testmonitor-cli").version(await y(),"-v, --version","Display the current CLI version.").description("CLI tool for interacting with the TestMonitor API.").helpCommand(!1).helpOption("-h, --help","Display help for command.");g.on("option:verbose",function(){process.env.VERBOSE=this.opts().verbose});g.addCommand(M);g.addCommand(E);g.parse(process.argv);
package/package.json CHANGED
@@ -1,43 +1,57 @@
1
1
  {
2
- "name": "@testmonitor/testmonitor-cli",
3
- "version": "0.0.1",
4
- "description": "TestMonitor CLI tool",
5
- "keywords": [
6
- "testmonitor",
7
- "cli"
8
- ],
9
- "homepage": "https://www.testmonitor.com/",
10
- "bugs": {
11
- "url": "https://github.com/testmonitor/testmonitor-cli/issues"
12
- },
13
- "repository": {
14
- "type": "git",
15
- "url": "git+https://github.com/testmonitor/testmonitor-cli.git"
16
- },
17
- "author": "TestMonitor | we are Cerios B.V.",
18
- "main": "index.js",
19
- "bin": {
20
- "testmonitor-cli": "index.js"
21
- },
22
- "scripts": {
23
- "start": "node index.js",
24
- "lint": "eslint .",
25
- "test": "mocha"
26
- },
27
- "dependencies": {
28
- "axios": "^1.7.9",
29
- "chalk": "^5.4.1",
30
- "commander": "^13.1.0",
31
- "dotenv": "^16.4.7",
32
- "table": "^6.9.0"
33
- },
34
- "devDependencies": {
35
- "chai": "^5.2.0",
36
- "eslint": "^9.21.0",
37
- "mocha": "^11.1.0",
38
- "sinon": "^19.0.2"
39
- },
40
- "engines": {
41
- "node": ">=16.0.0"
42
- }
2
+ "name": "@testmonitor/testmonitor-cli",
3
+ "type": "module",
4
+ "version": "0.0.4",
5
+ "description": "The TestMonitor CLI lets you interact with the TestMonitor platform directly from your terminal or CI pipelines.",
6
+ "keywords": [
7
+ "testmonitor",
8
+ "cli"
9
+ ],
10
+ "homepage": "https://www.testmonitor.com/",
11
+ "bugs": {
12
+ "url": "https://github.com/testmonitor/testmonitor-cli/issues"
13
+ },
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/testmonitor/testmonitor-cli.git"
17
+ },
18
+ "author": "TestMonitor | we are Cerios B.V.",
19
+ "main": "src/index.js",
20
+ "bin": {
21
+ "testmonitor-cli": "dist/index.js"
22
+ },
23
+ "scripts": {
24
+ "start": "node src/index.js",
25
+ "build": "node esbuild.config.js",
26
+ "lint": "eslint .",
27
+ "lint:fix": "eslint . --fix",
28
+ "test": "NODE_OPTIONS='--experimental-vm-modules' jest",
29
+ "test:watch": "NODE_OPTIONS='--experimental-vm-modules' jest --watch",
30
+ "test:coverage": "NODE_OPTIONS='--experimental-vm-modules' jest --coverage"
31
+ },
32
+ "dependencies": {
33
+ "axios": "^1.7.9",
34
+ "chalk": "^5.4.1",
35
+ "commander": "^14.0.0",
36
+ "dotenv": "^17.2.0",
37
+ "ora": "^8.2.0",
38
+ "strip-ansi": "^7.1.0",
39
+ "table": "^6.9.0"
40
+ },
41
+ "devDependencies": {
42
+ "chai": "^5.2.0",
43
+ "esbuild": "^0.25.6",
44
+ "eslint": "^9.31.0",
45
+ "eslint-config-prettier": "^10.1.5",
46
+ "eslint-formatter-junit": "^8.40.0",
47
+ "eslint-plugin-import": "^2.32.0",
48
+ "eslint-plugin-jest": "^28.14.0",
49
+ "eslint-plugin-jsdoc": "^51.4.1",
50
+ "jest": "^29.7.0",
51
+ "jest-junit": "^16.0.0",
52
+ "prettier": "^3.6.2"
53
+ },
54
+ "engines": {
55
+ "node": ">=18.0.0"
56
+ }
43
57
  }
@@ -0,0 +1,45 @@
1
+ import { Command } from 'commander';
2
+
3
+ import { APIClient } from '../../lib/api-client.js';
4
+ import { Logger } from '../../lib/logger.js';
5
+
6
+ export async function handleCheckConnection(options, { client } = {}) {
7
+ const { domain } = options;
8
+
9
+ const log = new Logger();
10
+ const apiKey = process.env.TESTMONITOR_TOKEN;
11
+
12
+ if (!apiKey) {
13
+ log.error('TESTMONITOR_TOKEN environment variable is not set.');
14
+ process.exit(1);
15
+ }
16
+
17
+ const apiClient = client || new APIClient({ domain, apiKey });
18
+
19
+ try {
20
+ const { data } = await log.spin('Connecting...', () => apiClient.checkConnection(), {
21
+ successMessage: 'Connection successful.',
22
+ errorMessage: 'Failed to connect.',
23
+ });
24
+
25
+ log.line();
26
+ log.table([
27
+ ['User ID', data.id],
28
+ ['Name', data.name],
29
+ ['Email', data.email],
30
+ ]);
31
+ } catch (error) {
32
+ const message = error.response?.data?.message || error.message;
33
+
34
+ log.line();
35
+ log.error(message, error);
36
+ process.exit(1);
37
+ }
38
+ }
39
+
40
+ export const checkAuthCommand = new Command('auth')
41
+ .description('Verify connectivity with your TestMonitor instance.')
42
+ .requiredOption('-d, --domain <domain>', 'Your TestMonitor domain name (e.g., mydomain.testmonitor.com)')
43
+ .action(async (options) => {
44
+ await handleCheckConnection(options);
45
+ });
@@ -0,0 +1,12 @@
1
+ import { Command } from 'commander';
2
+
3
+ import { checkAuthCommand } from './check-auth-command.js';
4
+
5
+ const checkGroup = new Command('check')
6
+ .name('check')
7
+ .description('Commands for verifying the connection state.')
8
+ .helpOption('-h, --help', 'Display help for command.');
9
+
10
+ checkGroup.addCommand(checkAuthCommand);
11
+
12
+ export default checkGroup;
@@ -0,0 +1,12 @@
1
+ import { Command } from 'commander';
2
+
3
+ import { submitJUnitXMLCommand } from './submit-junit-xml-command.js';
4
+
5
+ const junitGroup = new Command('junit')
6
+ .name('junit')
7
+ .description('Commands for JUnit XML report submission.')
8
+ .helpOption('-h, --help', 'Display help for command.');
9
+
10
+ junitGroup.addCommand(submitJUnitXMLCommand);
11
+
12
+ export default junitGroup;
@@ -0,0 +1,90 @@
1
+ import 'dotenv/config';
2
+ import fs from 'fs';
3
+
4
+ import { Command } from 'commander';
5
+
6
+ import { APIClient } from '../../lib/api-client.js';
7
+ import { Logger } from '../../lib/logger.js';
8
+
9
+ export async function handleSubmitJUnitXML(options, { client } = {}) {
10
+ const {
11
+ domain,
12
+ integrationId,
13
+ file,
14
+ name,
15
+ milestoneId,
16
+ milestoneName,
17
+ preserveNames,
18
+ skipRootSuite,
19
+ testEnvironmentId,
20
+ type,
21
+ } = options;
22
+
23
+ const log = new Logger();
24
+ const apiKey = process.env.TESTMONITOR_TOKEN;
25
+
26
+ if (!apiKey) {
27
+ log.error('TESTMONITOR_TOKEN environment variable is not set.');
28
+ process.exit(1);
29
+ }
30
+
31
+ if (!fs.existsSync(file)) {
32
+ log.error(`File not found at path ${file}`);
33
+ process.exit(1);
34
+ }
35
+
36
+ const apiClient = client || new APIClient({ domain, apiKey });
37
+
38
+ try {
39
+ const { data } = await log.spin(
40
+ 'Submitting...',
41
+ () =>
42
+ apiClient.submitJUnitReport({
43
+ integrationId,
44
+ filePath: file,
45
+ name,
46
+ type,
47
+ milestoneId,
48
+ milestoneName,
49
+ preserveNames,
50
+ skipRootSuite,
51
+ testEnvironmentId,
52
+ }),
53
+ {
54
+ successMessage: 'Report submitted.',
55
+ errorMessage: 'Failed to submit.',
56
+ }
57
+ );
58
+
59
+ log.line();
60
+ log.table([
61
+ ['JUnit file', data.name],
62
+ ['Test run code', data.test_run.code],
63
+ ['Test run URL', data.test_run.links.show],
64
+ ]);
65
+ } catch (error) {
66
+ const message = error.response?.data?.message || error.message;
67
+
68
+ log.line();
69
+ log.error(message, error);
70
+ process.exit(1);
71
+ }
72
+ }
73
+
74
+ // Command to submit a JUnit XML file
75
+ export const submitJUnitXMLCommand = new Command('submit')
76
+ .name('submit')
77
+ .description('Submit a JUnit XML file to your TestMonitor instance.')
78
+ .helpOption('-h, --help', 'Display help for command.')
79
+ .requiredOption('-d, --domain <domain>', 'Your TestMonitor domain name (e.g., mydomain.testmonitor.com)')
80
+ .requiredOption('-i, --integration-id <id>', 'The JUnit integration ID')
81
+ .requiredOption('-f, --file <path>', 'Path to your JUnit XML file')
82
+ .option('-m, --milestone-id <id>', 'Milestone ID for the new test run (required if not set in configuration))')
83
+ .option('-o, --milestone-name <name>', 'Find or create a milestone by name for the test run.')
84
+ .option('-n, --name <name>', 'Custom name for the test run (auto-generated if omitted).')
85
+ .option('-p, --preserve-names', 'Preserve test case names exactly as in the XML file.')
86
+ .option('-s, --skip-root-suite', 'Skip the root suite and start from nested suites.')
87
+ .option('-e, --test-environment-id <id>', 'Test environment ID for the new test run.')
88
+ .option('-t, --type <type>', 'The automation test type (cypress, playwright, phpunit, selenium).')
89
+ .option('-v, --verbose', 'Enable verbose debug output.')
90
+ .action((options) => handleSubmitJUnitXML(options));
package/src/index.js ADDED
@@ -0,0 +1,25 @@
1
+ import 'dotenv/config';
2
+
3
+ import { Command } from 'commander';
4
+
5
+ import { appVersion } from './lib/app-version.js';
6
+ import checkGroup from './commands/check/index.js';
7
+ import junitGroup from './commands/junit/index.js';
8
+
9
+ const program = new Command();
10
+
11
+ program
12
+ .name('testmonitor-cli')
13
+ .version(await appVersion(), '-v, --version', 'Display the current CLI version.')
14
+ .description('CLI tool for interacting with the TestMonitor API.')
15
+ .helpCommand(false)
16
+ .helpOption('-h, --help', 'Display help for command.');
17
+
18
+ program.on('option:verbose', function () {
19
+ process.env.VERBOSE = this.opts().verbose;
20
+ });
21
+
22
+ program.addCommand(checkGroup);
23
+ program.addCommand(junitGroup);
24
+
25
+ program.parse(process.argv);
@@ -0,0 +1,113 @@
1
+ import os from 'os';
2
+ import fs from 'fs';
3
+
4
+ import axios from 'axios';
5
+ import FormData from 'form-data';
6
+
7
+ import { appVersion } from './app-version.js';
8
+
9
+ const cliVersion = await appVersion();
10
+ const nodeVersion = `NodeJS/${process.nodeVersion}`;
11
+ const osVersion = `${os.platform()} ${os.release()}`;
12
+ const userAgent = `TestMonitorCLI/${cliVersion} (${nodeVersion}; ${osVersion}; +https://www.testmonitor.com/)`;
13
+
14
+ export class APIClient {
15
+ constructor({ domain, apiKey, httpClient }) {
16
+ this.baseURL = `https://${domain}/api/v1`;
17
+ this.apiKey = apiKey;
18
+
19
+ this.httpClient =
20
+ httpClient ||
21
+ axios.create({
22
+ baseURL: this.baseURL,
23
+ headers: {
24
+ Authorization: `Bearer ${this.apiKey}`,
25
+ 'User-Agent': userAgent,
26
+ },
27
+ });
28
+ }
29
+
30
+ async get(path, config = {}) {
31
+ return this._request('get', path, null, config);
32
+ }
33
+
34
+ async post(path, data = {}, config = {}) {
35
+ return this._request('post', path, data, config);
36
+ }
37
+
38
+ async put(path, data = {}, config = {}) {
39
+ return this._request('put', path, data, config);
40
+ }
41
+
42
+ async delete(path, config = {}) {
43
+ return this._request('delete', path, null, config);
44
+ }
45
+
46
+ async _request(method, path, data, config) {
47
+ const isFormData = data instanceof FormData;
48
+ const headers = {
49
+ ...(isFormData ? data.getHeaders() : { 'Content-Type': 'application/json' }),
50
+ ...(config.headers || {}),
51
+ };
52
+
53
+ try {
54
+ const response = await this.httpClient.request({
55
+ method,
56
+ url: path,
57
+ data,
58
+ headers,
59
+ ...config,
60
+ });
61
+
62
+ return response.data;
63
+ } catch (err) {
64
+ const message = err.response?.data?.message || err.message;
65
+ throw new Error(message);
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Check connection to the API by fetching account info
71
+ */
72
+ async checkConnection() {
73
+ return this.get('/my-account');
74
+ }
75
+
76
+ /**
77
+ * Submit a JUnit report using plain data and file path
78
+ */
79
+ async submitJUnitReport({
80
+ integrationId,
81
+ filePath,
82
+ name,
83
+ type,
84
+ milestoneId,
85
+ milestoneName,
86
+ preserveNames,
87
+ skipRootSuite,
88
+ testEnvironmentId,
89
+ }) {
90
+ const form = new FormData();
91
+
92
+ form.append('integration_id', integrationId);
93
+ form.append('report', fs.createReadStream(filePath));
94
+
95
+ const optional = {
96
+ name,
97
+ type,
98
+ milestone: milestoneName,
99
+ milestone_id: milestoneId,
100
+ preserve_names: preserveNames ? 1 : null,
101
+ skip_root_suite: skipRootSuite ? 1 : null,
102
+ test_environment_id: testEnvironmentId,
103
+ };
104
+
105
+ for (const [key, value] of Object.entries(optional)) {
106
+ if (value !== undefined && value !== null) {
107
+ form.append(key, value);
108
+ }
109
+ }
110
+
111
+ return this.post('/reporters/junit/submit', form);
112
+ }
113
+ }
@@ -0,0 +1,8 @@
1
+ export async function appVersion() {
2
+ if (typeof __APP_VERSION__ !== 'undefined') {
3
+ return __APP_VERSION__;
4
+ }
5
+
6
+ const pkg = await import('../../package.json', { with: { type: 'json' } });
7
+ return pkg.default.version;
8
+ }
@@ -0,0 +1,59 @@
1
+ import chalk from 'chalk';
2
+ import ora from 'ora';
3
+ import { table } from 'table';
4
+
5
+ export class Logger {
6
+ #prefix = 'TestMonitor';
7
+
8
+ info(message) {
9
+ console.log(`${this.#prefix}: ${message}`);
10
+ }
11
+
12
+ success(message) {
13
+ console.log(`${this.#prefix}: ${chalk.green(message)}`);
14
+ }
15
+
16
+ warn(message) {
17
+ console.warn(`${this.#prefix}: ${chalk.yellow(message)}`);
18
+ }
19
+
20
+ error(message, err) {
21
+ const output = `${this.#prefix}: ${chalk.red(message)}`;
22
+ console.error(output);
23
+
24
+ if (process.env.DEBUG && err instanceof Error) {
25
+ console.error(chalk.gray(err.stack || err.message));
26
+ }
27
+ }
28
+
29
+ debug(message) {
30
+ if (process.env.DEBUG) {
31
+ console.log(`${this.#prefix}: ${message}`);
32
+ }
33
+ }
34
+
35
+ line(message = '') {
36
+ console.log(message);
37
+ }
38
+
39
+ async spin(message, callback, options = {}) {
40
+ const spinner = ora({
41
+ text: `${this.#prefix}: ${message}`,
42
+ color: 'green',
43
+ }).start();
44
+
45
+ try {
46
+ const result = await callback();
47
+ spinner.succeed(`${this.#prefix}: ${chalk.green(options.successMessage || message)}`);
48
+ return result;
49
+ } catch (error) {
50
+ spinner.fail(`${this.#prefix}: ${chalk.red(options.errorMessage || message)}`);
51
+ throw error;
52
+ }
53
+ }
54
+
55
+ table(rows, config) {
56
+ const output = table(rows, { ...{ singleLine: true }, ...config });
57
+ console.log(output);
58
+ }
59
+ }
@@ -1,83 +0,0 @@
1
- import fs from 'fs';
2
- import axios from 'axios';
3
- import FormData from 'form-data';
4
- import chalk from 'chalk';
5
- import { table, getBorderCharacters } from 'table';
6
-
7
- export class SubmitReport {
8
- constructor({ domain, apiKey, integrationId, file, name, type, milestoneId, milestoneName, preserveNames, skipRootSuite, testEnvironmentId }) {
9
- this.domain = domain;
10
- this.apiKey = apiKey;
11
- this.integrationId = integrationId;
12
- this.file = file;
13
- this.name = name;
14
- this.type = type;
15
- this.milestoneId = milestoneId;
16
- this.milestoneName = milestoneName;
17
- this.preserveNames = preserveNames;
18
- this.skipRootSuite = skipRootSuite;
19
- this.testEnvironmentId = testEnvironmentId;
20
- }
21
-
22
- async run() {
23
- const formData = new FormData();
24
-
25
- // Required
26
- formData.append('integration_id', this.integrationId);
27
- formData.append('report', fs.createReadStream(this.file));
28
-
29
- // Optional
30
- const optional = {
31
- name: this.name,
32
- type: this.type,
33
- milestone: this.milestoneName,
34
- milestone_id: this.milestoneId,
35
- preserve_names: this.preserveNames ? 1: null,
36
- skip_root_suite: this.skipRootSuite ? 1 : null,
37
- test_environment_id: this.testEnvironmentId,
38
- };
39
-
40
- for (const [key, value] of Object.entries(optional)) {
41
- if (value !== undefined && value !== null) {
42
- formData.append(key, value);
43
- }
44
- }
45
-
46
- try {
47
- const response = await axios.post(
48
- `https://${this.domain}/api/v1/reporters/junit/submit`,
49
- formData,
50
- {
51
- headers: {
52
- ...formData.getHeaders(),
53
- Authorization: `Bearer ${this.apiKey}`,
54
- },
55
- }
56
- );
57
-
58
- const { data } = response.data;
59
-
60
- const config = {
61
- border: getBorderCharacters('ramac'),
62
- singleLine: true,
63
- };
64
-
65
- const rows = [
66
- [chalk.bold('File'), data.name],
67
- [chalk.bold('Date'), data.created_at],
68
- [chalk.bold('ID'), data.test_run.id],
69
- [chalk.bold('Code'), data.test_run.code],
70
- [chalk.bold('Name'), data.test_run.name],
71
- [chalk.bold('URL'), data.test_run.links.show],
72
- ];
73
-
74
- console.log(table(rows, config));
75
-
76
- console.log('Report submitted ' + chalk.green('successfully') + '.');
77
- } catch (error) {
78
- const message = error.response?.data?.message || error.message;
79
- console.error(chalk.red('Error') + ': ' + message);
80
- process.exit(1);
81
- }
82
- }
83
- }
@@ -1,64 +0,0 @@
1
- import { Command } from 'commander';
2
- import { SubmitReport } from '../actions/SubmitReport.js';
3
- import fs from 'fs';
4
- import chalk from 'chalk';
5
- import 'dotenv/config';
6
-
7
- const submitCommand = new Command('submit')
8
- .description('Submit a JUnit XML file to your TestMonitor instance.')
9
- .helpOption('-h, --help', 'Display help for command')
10
- .requiredOption('-d, --domain <domain>', 'Your TestMonitor domain name (e.g., mydomain.testmonitor.com)')
11
- .requiredOption('-i, --integration-id <id>', 'The JUnit integration ID')
12
- .requiredOption('-f, --file <path>', 'Path to your JUnit XML file')
13
- .option('-m, --milestone-id <id>', 'The milestone ID for the new test run (required if not configured in your JUnit configuration)')
14
- .option('-o, --milestone-name <name>', 'Finds or creates a milestone matching the name for the new test run')
15
- .option('-n, --name <name>', 'The name for the new test run (will be auto-generated if not provided)')
16
- .option('-p, --preserve-names', 'Preserve test case names exactly as they appear in the XML file.')
17
- .option('-s, --skip-root-suite', 'Skip the root test suite and start from its nested suites.')
18
- .option('-e, --test-environment-id <id>', 'The test environment ID for the new test run')
19
- .option('-t, --type <type>', 'The automation test type (cypress, playwright, phpunit, selenium)')
20
- .option('-v, --verbose', 'Output additional debug information')
21
- .action(async (options) => {
22
- const {
23
- domain,
24
- integrationId,
25
- file,
26
- name,
27
- milestoneId,
28
- milestoneName,
29
- preserveNames,
30
- skipRootSuite,
31
- testEnvironmentId,
32
- type,
33
- verbose
34
- } = options;
35
-
36
- const apiKey = process.env.TESTMONITOR_TOKEN;
37
-
38
- if (!apiKey) {
39
- console.error(chalk.red('Error') + ': TESTMONITOR_TOKEN environment variable is not set.');
40
- process.exit(1);
41
- }
42
-
43
- if (!fs.existsSync(file)) {
44
- console.error(chalk.red('Error') + `: File not found at path ${file}`);
45
- process.exit(1);
46
- }
47
-
48
- const action = new SubmitReport({
49
- domain,
50
- apiKey,
51
- integrationId,
52
- file,
53
- name,
54
- type,
55
- milestoneId,
56
- milestoneName,
57
- preserveNames,
58
- skipRootSuite,
59
- testEnvironmentId
60
- });
61
- await action.run();
62
- });
63
-
64
- export default submitCommand;
package/index.js DELETED
@@ -1,20 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import { Command } from 'commander';
4
- import submitCommand from './commands/submit.js';
5
- import 'dotenv/config';
6
-
7
- const program = new Command();
8
-
9
- program
10
- .name('testmonitor-cli')
11
- .version('0.0.1')
12
- .description('CLI tool for interacting with the TestMonitor API.');
13
-
14
- program.addCommand(submitCommand);
15
-
16
- program.on('option:verbose', function () {
17
- process.env.VERBOSE = this.opts().verbose;
18
- });
19
-
20
- program.parse(process.argv);