summaryrefslogtreecommitdiffstats
path: root/test/wp.js
blob: ab2d2a77ef762b89bc48a0c0a2bad6621e73973f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
 * Talking to the WordPress under test.
 *
 * Everything goes through WP-CLI in the `cli` container of `compose.yml`, so
 * the tests configure the store exactly the way a store owner would.
 *
 * @module
 */

import { spawnSync } from "node:child_process";
import { dirname } from "node:path";
import { fileURLToPath } from "node:url";

const HERE = dirname(fileURLToPath(import.meta.url));

/** Where the site answers, from the host. */
export const SITE = "http://127.0.0.1:8090";

/** Hostname the fake API is reached by, from both the browser and PHP. */
export const FAKE_HOST = "fakecep";

/** Port the fake API listens on. */
export const FAKE_PORT = 8899;

/** Base URL of the fake API, as both sides must spell it. */
export const FAKE_URL = `http://${FAKE_HOST}:${FAKE_PORT}`;

/**
 * Run a WP-CLI command in the container.
 *
 * @param {string[]} args Arguments after `wp`.
 * @returns {string} Trimmed stdout.
 */
export function wp(args) {
  const result = spawnSync("docker", ["compose", "exec", "-T", "cli", "wp", ...args], {
    cwd: HERE,
    encoding: "utf8",
  });

  if (result.status !== 0) {
    throw new Error(`wp ${args.join(" ")} failed:\n${result.stdout}\n${result.stderr}`);
  }

  return String(result.stdout).trim();
}

/**
 * Run PHP inside WordPress.
 *
 * @param {string} code PHP to evaluate.
 * @returns {string} Trimmed stdout.
 */
export function wpEval(code) {
  return wp(["eval", code]);
}

/**
 * Set one option.
 *
 * @param {string} name Option name.
 * @param {string} value Option value.
 */
export function setOption(name, value) {
  wp(["option", "update", name, value]);
}

/**
 * Read the WordPress debug log and clear it.
 *
 * @returns {string} Whatever had been logged.
 */
export function drainDebugLog() {
  const result = spawnSync(
    "docker",
    [
      "compose",
      "exec",
      "-T",
      "cli",
      "sh",
      "-c",
      "cat /var/www/html/wp-content/debug.log 2>/dev/null; : > /var/www/html/wp-content/debug.log 2>/dev/null || true",
    ],
    { cwd: HERE, encoding: "utf8" },
  );

  return String(result.stdout || "").trim();
}