phptest 0.0.1

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.
@@ -0,0 +1,26 @@
1
+ name: CI
2
+
3
+ on: [push, pull_request]
4
+
5
+ jobs:
6
+ build:
7
+ runs-on: ubuntu-latest
8
+
9
+ strategy:
10
+ matrix:
11
+ node-version: [12.x, 14.x, 16.x]
12
+
13
+ steps:
14
+ # Check out the repository under $GITHUB_WORKSPACE, so this job can access it
15
+ - uses: actions/checkout@v2
16
+
17
+ - name: Use Node.js ${{ matrix.node-version }}
18
+ uses: actions/setup-node@v1
19
+ with:
20
+ node-version: ${{ matrix.node-version }}
21
+
22
+ - name: Install NPM dependencies
23
+ run: npm ci
24
+
25
+ - name: Run tests
26
+ run: npm test
package/.jshintignore ADDED
@@ -0,0 +1 @@
1
+ /node_modules
package/.jshintrc ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "bitwise": true,
3
+ "curly": true,
4
+ "eqeqeq": true,
5
+ "evil": true,
6
+ "expr": true,
7
+ "forin": true,
8
+ "globals": {
9
+ "afterEach": false,
10
+ "beforeEach": false,
11
+ "describe": false,
12
+ "it": false
13
+ },
14
+ "immed": true,
15
+ "indent": 4,
16
+ "latedef": true,
17
+ "maxlen": false,
18
+ "maxparams": false,
19
+ "newcap": true,
20
+ "noarg": true,
21
+ "node": true,
22
+ "noempty": true,
23
+ "nonew": true,
24
+ "plusplus": false,
25
+ "quotmark": "single",
26
+ "trailing": true,
27
+ "undef": true,
28
+ "unused": true,
29
+ "strict": true,
30
+ "esversion": 8
31
+ }
@@ -0,0 +1,21 @@
1
+ Copyright 2022 Dan Phillimore (asmblah)
2
+ https://github.com/uniter/phptest/
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining
5
+ a copy of this software and associated documentation files (the
6
+ "Software"), to deal in the Software without restriction, including
7
+ without limitation the rights to use, copy, modify, merge, publish,
8
+ distribute, sublicense, and/or sell copies of the Software, and to
9
+ permit persons to whom the Software is furnished to do so, subject to
10
+ the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be
13
+ included in all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,11 @@
1
+ # PHPTest
2
+
3
+ [![Build Status](https://github.com/uniter/phptest/workflows/CI/badge.svg)](https://github.com/uniter/phptest/actions?query=workflow%3ACI)
4
+
5
+ Test helper library for PHP core runtime components.
6
+
7
+ Contains shared test helper logic between [Uniter][] components such as [PHPCore][] and [PHPRuntime][].
8
+
9
+ [Uniter]: https://github.com/asmblah/uniter
10
+ [PHPCore]: https://github.com/uniter/phpcore
11
+ [PHPRuntime]: https://github.com/uniter/phpruntime
package/index.js ADDED
@@ -0,0 +1,16 @@
1
+ /*
2
+ * PHPTest - Test helper library for PHP core runtime components
3
+ * Copyright (c) Dan Phillimore (asmblah)
4
+ * https://github.com/uniter/phptest/
5
+ *
6
+ * Released under the MIT license
7
+ * https://github.com/uniter/phptest/raw/master/MIT-LICENSE.txt
8
+ */
9
+
10
+ 'use strict';
11
+
12
+ var createIntegrationTools = require('./src/createIntegrationTools');
13
+
14
+ module.exports = {
15
+ createIntegrationTools: createIntegrationTools
16
+ };
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "version": "0.0.1",
3
+ "name": "phptest",
4
+ "description": "Test helper library for PHP core runtime components",
5
+ "keywords": [
6
+ "php",
7
+ "test",
8
+ "uniter"
9
+ ],
10
+ "homepage": "https://github.com/uniter/phptest",
11
+ "author": "Dan Phillimore <dan@ovms.co> (https://github.com/asmblah)",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "https://github.com/uniter/phptest"
15
+ },
16
+ "bugs": {
17
+ "email": "dan@ovms.co",
18
+ "url": "https://github.com/uniter/phptest/issues"
19
+ },
20
+ "main": "index",
21
+ "scripts": {
22
+ "jshint": "jshint .",
23
+ "test": "npm run jshint"
24
+ },
25
+ "dependencies": {
26
+ "es6-weak-map": "^2.0.3",
27
+ "is-promise": "^4.0.0",
28
+ "jshint": "^2.13.4",
29
+ "lie": "^3.3.0",
30
+ "microdash": "^1.4.2",
31
+ "regexp.escape": "^1.1.0",
32
+ "source-map": "^0.7.3"
33
+ },
34
+ "peerDependencies": {
35
+ "core-js-pure": "^3.21.1",
36
+ "mocha": "^9.2.2",
37
+ "phpcore": "^7.1.0",
38
+ "phptoast": "^9.0.1",
39
+ "phptojs": "^9.0.0"
40
+ },
41
+ "engines": {
42
+ "node": ">=12"
43
+ },
44
+ "license": "MIT"
45
+ }
@@ -0,0 +1,298 @@
1
+ /*
2
+ * PHPTest - Test helper library for PHP core runtime components
3
+ * Copyright (c) Dan Phillimore (asmblah)
4
+ * https://github.com/uniter/phptest/
5
+ *
6
+ * Released under the MIT license
7
+ * https://github.com/uniter/phptest/raw/master/MIT-LICENSE.txt
8
+ */
9
+
10
+ 'use strict';
11
+
12
+ var _ = require('microdash'),
13
+ escapeRegex = require('regexp.escape'),
14
+ path = require('path'),
15
+ mochaPath = path.dirname(require.resolve('mocha/package.json')),
16
+ phpCorePath = path.resolve(__dirname, '../..'),
17
+ phpToAST = require('phptoast'),
18
+ phpToJS = require('phptojs'),
19
+ util = require('util'),
20
+ OpcodeExecutor = require('phpcore/src/Core/Opcode/Handler/OpcodeExecutor'),
21
+ Reference = require('../../src/Reference/Reference'),
22
+ SourceMapConsumer = require('source-map').SourceMapConsumer,
23
+ Value = require('../../src/Value').sync(),
24
+ Variable = require('../../src/Variable').sync(),
25
+ WeakMap = require('es6-weak-map'),
26
+ runtimeFactory = require('../../src/shared/runtimeFactory');
27
+
28
+ /**
29
+ * Creates an integration test helper tools object.
30
+ *
31
+ * @param {Function} initRuntime
32
+ * @returns {Object}
33
+ */
34
+ module.exports = function (initRuntime) {
35
+ // A map that allows looking up the source map data for a module later on
36
+ var moduleDataMap = new WeakMap(),
37
+ /**
38
+ * Creates a Runtime with the given mode.
39
+ *
40
+ * @param {string} mode
41
+ * @returns {Runtime}
42
+ */
43
+ createRuntime = function (mode) {
44
+ return initRuntime(runtimeFactory.create(mode));
45
+ },
46
+
47
+ createAsyncRuntime = function () {
48
+ // Create an isolated runtime we can install builtins into without affecting the main singleton one.
49
+ return createRuntime('async');
50
+ },
51
+ createPsyncRuntime = function () {
52
+ // Create an isolated runtime we can install builtins into without affecting the main singleton one.
53
+ return createRuntime('psync');
54
+ },
55
+ createSyncRuntime = function () {
56
+ // Create an isolated runtime we can install builtins into without affecting the main singleton one.
57
+ return createRuntime('sync');
58
+ },
59
+
60
+ transpile = function (path, php, phpCore, options) {
61
+ var transpiledResult,
62
+ module,
63
+ phpParser,
64
+ phpToJSBaseOptions;
65
+
66
+ options = options || {};
67
+ path = path || null;
68
+
69
+ phpParser = phpToAST.create(null, _.extend({
70
+ // Capture offsets of all nodes for line tracking
71
+ captureAllBounds: true
72
+ }, options.phpToAST));
73
+
74
+ if (path) {
75
+ phpParser.getState().setPath(path);
76
+ }
77
+
78
+ phpToJSBaseOptions = {
79
+ // Record line numbers for statements/expressions
80
+ lineNumbers: true,
81
+
82
+ path: path,
83
+
84
+ prefix: 'return '
85
+ };
86
+
87
+ if (options.sourceMap) {
88
+ // Generate a source map if specified in test options
89
+ _.extend(phpToJSBaseOptions, {
90
+ sourceMap: {
91
+ sourceContent: php,
92
+ returnMap: true
93
+ }
94
+ });
95
+ }
96
+
97
+ transpiledResult = phpToJS.transpile(
98
+ phpParser.parse(php),
99
+ _.extend(phpToJSBaseOptions, options.phpToJS),
100
+ options.transpiler
101
+ );
102
+
103
+ module = new Function('require', options.sourceMap ? transpiledResult.code : transpiledResult)(function () {
104
+ return phpCore;
105
+ });
106
+
107
+ if (path !== null) {
108
+ module = module.using({
109
+ path: path
110
+ });
111
+ }
112
+
113
+ if (options.sourceMap) {
114
+ // Allow source map data to be looked up later (see .normaliseStack(...))
115
+ moduleDataMap.set(module, {sourceMapGenerator: transpiledResult.map, path: path});
116
+ }
117
+
118
+ return module;
119
+ },
120
+
121
+ // Create isolated runtimes to be shared by all tests that don't create their own,
122
+ // to avoid modifying the singleton module exports.
123
+ asyncRuntime = createAsyncRuntime(),
124
+ psyncRuntime = createPsyncRuntime(),
125
+ syncRuntime = createSyncRuntime(),
126
+
127
+ // Errors from a Function constructor-created function may be offset by the function signature
128
+ // (currently 2), so we need to calculate this in order to adjust for source mapping below
129
+ // (Note that the unused "require" arg is given so that the signature matches the Function(...) eval above)
130
+ errorStackLineOffset = new Function(
131
+ 'require',
132
+ 'return new Error().stack;'
133
+ )()
134
+ .match(/<anonymous>:(\d+):\d+/)[1] - 1;
135
+
136
+ if (!initRuntime) {
137
+ initRuntime = function (runtime) {
138
+ return runtime;
139
+ };
140
+ }
141
+
142
+ // Force all opcodes to be async for all async mode tests, to help ensure async handling is in place.
143
+ asyncRuntime.install({
144
+ serviceGroups: [
145
+ function (internals) {
146
+ var get = internals.getServiceFetcher();
147
+
148
+ // As we'll be overriding the "opcode_executor" service.
149
+ internals.allowServiceOverride();
150
+
151
+ return {
152
+ 'opcode_executor': function () {
153
+ var referenceFactory = get('reference_factory'),
154
+ valueFactory = get('value_factory');
155
+
156
+ function AsyncOpcodeExecutor() {
157
+ }
158
+
159
+ util.inherits(AsyncOpcodeExecutor, OpcodeExecutor);
160
+
161
+ AsyncOpcodeExecutor.prototype.execute = function (opcode) {
162
+ var result = opcode.handle();
163
+
164
+ if (!opcode.isTraced()) {
165
+ // Don't attempt to make any untraced opcodes pause,
166
+ // as resuming from inside them is not possible.
167
+ return result;
168
+ }
169
+
170
+ if (result instanceof Value) {
171
+ return valueFactory.createAsyncPresent(result);
172
+ }
173
+
174
+ if (result instanceof Reference || result instanceof Variable) {
175
+ return referenceFactory.createAccessor(function () {
176
+ // Defer returning the value of the reference.
177
+ return valueFactory.createAsyncPresent(result.getValue());
178
+ }, function (value) {
179
+ // Defer assignment in a microtask to test for async handling.
180
+ return valueFactory.createAsyncMicrotaskFuture(function (resolve, reject) {
181
+ result.setValue(value).next(resolve, reject);
182
+ });
183
+ }, function (reference) {
184
+ return result.setReference(reference);
185
+ });
186
+ }
187
+
188
+ return result;
189
+ };
190
+
191
+ return new AsyncOpcodeExecutor();
192
+ }
193
+ };
194
+ }
195
+ ]
196
+ });
197
+
198
+ return {
199
+ asyncRuntime: asyncRuntime,
200
+ psyncRuntime: psyncRuntime,
201
+ syncRuntime: syncRuntime,
202
+
203
+ createAsyncEnvironment: function (options, addons) {
204
+ return asyncRuntime.createEnvironment(options, addons);
205
+ },
206
+
207
+ createAsyncRuntime: createAsyncRuntime,
208
+
209
+ createPsyncEnvironment: function (options, addons) {
210
+ return psyncRuntime.createEnvironment(options, addons);
211
+ },
212
+
213
+ createPsyncRuntime: createPsyncRuntime,
214
+
215
+ createSyncEnvironment: function (options, addons) {
216
+ return syncRuntime.createEnvironment(options, addons);
217
+ },
218
+
219
+ createSyncRuntime: createSyncRuntime,
220
+
221
+ /**
222
+ * Attempts to make this integration test slightly less brittle when future changes occur,
223
+ * by scrubbing out things that are out of our control and likely to change (such as line/column numbers
224
+ * of stack frames within Mocha) and performs source mapping of the stack frame file/line/column
225
+ *
226
+ * @param {string} stack
227
+ * @param {Function} module
228
+ * @return {Promise<string>}
229
+ */
230
+ normaliseStack: function (stack, module) {
231
+ var moduleData;
232
+
233
+ if (!moduleDataMap.has(module)) {
234
+ throw new Error(
235
+ 'Test harness error: module data map does not contain data for this module - ' +
236
+ 'did you forget to set options.sourceMap?'
237
+ );
238
+ }
239
+
240
+ moduleData = moduleDataMap.get(module);
241
+
242
+ return new SourceMapConsumer(moduleData.sourceMapGenerator/*, sourceMapUrl */)
243
+ .then(function (sourceMapConsumer) {
244
+ stack = stack.replace(
245
+ // Find stack frames for the transpiled PHP code - source maps would not be handled natively
246
+ // even if we embedded them in the generated JS, so we need to perform manual mapping
247
+ /\(eval at transpile \(.*\/test\/integration\/tools.js:\d+:\d+\), <anonymous>:(\d+):(\d+)\)/g,
248
+ function (all, line, column) {
249
+ var mappedPosition = sourceMapConsumer.originalPositionFor({
250
+ // Note: These number casts are required, the source-map library
251
+ // will otherwise fail to resolve any mappings
252
+ line: line - errorStackLineOffset,
253
+ column: column * 1
254
+ });
255
+
256
+ if (mappedPosition.line === null && mappedPosition.column === null) {
257
+ // Unless something has gone wrong, we should be able to map all generated JS frames back to PHP
258
+ throw new Error('Stack line in evaluated PHP code could not be mapped back to PHP source');
259
+ }
260
+
261
+ return '(' + mappedPosition.source + ':' + mappedPosition.line + ':' + mappedPosition.column + ')';
262
+ }
263
+ );
264
+
265
+ // Normalise Mocha frames
266
+ stack = stack.replace(new RegExp('^(.*)' + escapeRegex(mochaPath) + '(.*:)\\d+:\\d+', 'gm'), '$1/path/to/mocha$2??:??');
267
+ // Group Mocha frames (to allow for differences between versions)
268
+ stack = stack.replace(/(?:(?:.*\/path\/to\/mocha.*)([\r\n]*))+/mg, ' at [Mocha internals]$1');
269
+
270
+ // Normalise Node.js internal frames
271
+ stack = stack.replace(/^(?:([^/(]+?\()([^/]+?)\.js|(.*?)(?:node:)?internal\/(.*?)(?:\.js)?):\d+:\d+/gm, '$1$3/path/to/internal/$2$4:??:??');
272
+ // Group Node.js internal frames (to allow for differences between versions)
273
+ stack = stack.replace(/(?:(?:.*\/path\/to\/internal.*)([\r\n]*))+/mg, ' at [Node.js internals]$1');
274
+
275
+ // Normalise PHPCore frames
276
+ stack = stack.replace(new RegExp(escapeRegex(phpCorePath), 'g'), '/path/to/phpcore');
277
+
278
+ return stack;
279
+ });
280
+ },
281
+
282
+ asyncTranspile: function (path, php, options) {
283
+ return transpile(path, php, asyncRuntime, options);
284
+ },
285
+
286
+ psyncTranspile: function (path, php, options) {
287
+ return transpile(path, php, psyncRuntime, options);
288
+ },
289
+
290
+ syncTranspile: function (path, php, options) {
291
+ return transpile(path, php, syncRuntime, options);
292
+ },
293
+
294
+ transpile: function (runtime, path, php, options) {
295
+ return transpile(path, php, runtime, options);
296
+ }
297
+ };
298
+ };