forked from meteor/meteor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
selftest.js
1917 lines (1658 loc) · 59.6 KB
/
selftest.js
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var _ = require('underscore');
var files = require('./files.js');
var utils = require('./utils.js');
var parseStack = require('./parse-stack.js');
var release = require('./release.js');
var catalog = require('./catalog.js');
var archinfo = require('./archinfo.js');
var Future = require('fibers/future');
var isopackets = require("./isopackets.js");
var config = require('./config.js');
var buildmessage = require('./buildmessage.js');
var util = require('util');
var child_process = require('child_process');
var webdriver = require('browserstack-webdriver');
var phantomjs = require('phantomjs');
var catalogRemote = require('./catalog-remote.js');
var Console = require('./console.js').Console;
var tropohouseModule = require('./tropohouse.js');
var packageMapModule = require('./package-map.js');
var isopackCacheModule = require('./isopack-cache.js');
// Exception representing a test failure
var TestFailure = function (reason, details) {
var self = this;
self.reason = reason;
self.details = details || {};
self.stack = (new Error).stack;
};
// Use this to decorate functions that throw TestFailure. Decorate the
// first function that should not be included in the call stack shown
// to the user.
var markStack = function (f) {
return parseStack.markTop(f);
};
// Call from a test to throw a TestFailure exception and bail out of the test
var fail = markStack(function (reason) {
throw new TestFailure(reason);
});
// Call from a test to assert that 'actual' is equal to 'expected',
// with 'actual' being the value that the test got and 'expected'
// being the expected value
var expectEqual = markStack(function (actual, expected) {
var Package = isopackets.load('ejson');
if (! Package.ejson.EJSON.equals(actual, expected)) {
throw new TestFailure("not-equal", {
expected: expected,
actual: actual
});
}
});
// Call from a test to assert that 'actual' is truthy.
var expectTrue = markStack(function (actual) {
if (! actual) {
throw new TestFailure('not-true');
}
});
// Call from a test to assert that 'actual' is falsey.
var expectFalse = markStack(function (actual) {
if (actual) {
throw new TestFailure('not-false');
}
});
var expectThrows = markStack(function (f) {
var threw = false;
try {
f();
} catch (e) {
threw = true;
}
if (! threw)
throw new TestFailure("expected-exception");
});
// Execute a command synchronously, discarding stderr.
var execFileSync = function (binary, args, opts) {
return Future.wrap(function(cb) {
var cb2 = function(err, stdout, stderr) { cb(err, stdout); };
child_process.execFile(binary, args, opts, cb2);
})().wait();
};
var doOrThrow = function (f) {
var ret;
var messages = buildmessage.capture(function () {
ret = f();
});
if (messages.hasMessages()) {
throw Error(messages.formatMessages());
}
return ret;
};
// Our current strategy for running tests that need warehouses is to build all
// packages from the checkout into this temporary tropohouse directory, and for
// each test that need a fake warehouse, copy the built packages into the
// test-specific warehouse directory. This isn't particularly fast, but it'll
// do for now. We build the packages during the first test that needs them.
var builtPackageTropohouseDir = null;
var tropohouseLocalCatalog = null;
var tropohouseIsopackCache = null;
// Let's build a minimal set of packages that's enough to get self-test
// working. (And that doesn't need us to download any Atmosphere packages.)
var ROOT_PACKAGES_TO_BUILD_IN_SANDBOX = [
// We need the tool in order to run from the fake warehouse at all.
"meteor-tool",
// We need the packages in the skeleton app in order to test 'meteor create'.
"meteor-platform", "autopublish", "insecure"
];
var setUpBuiltPackageTropohouse = function () {
if (builtPackageTropohouseDir)
return;
builtPackageTropohouseDir = files.mkdtemp('built-package-tropohouse');
if (config.getPackagesDirectoryName() !== 'packages')
throw Error("running self-test with METEOR_PACKAGE_SERVER_URL set?");
var tropohouse = new tropohouseModule.Tropohouse(builtPackageTropohouseDir);
tropohouseLocalCatalog = newSelfTestCatalog();
var versions = {};
_.each(
tropohouseLocalCatalog.getAllNonTestPackageNames(),
function (packageName) {
versions[packageName] =
tropohouseLocalCatalog.getLatestVersion(packageName).version;
});
var packageMap = new packageMapModule.PackageMap(versions, {
localCatalog: tropohouseLocalCatalog
});
// Make an isopack cache that doesn't automatically save isopacks to disk and
// has no access to versioned packages.
tropohouseIsopackCache = new isopackCacheModule.IsopackCache({
packageMap: packageMap,
includeCordovaUnibuild: true
});
doOrThrow(function () {
buildmessage.enterJob("building self-test packages", function () {
// Build the packages into the in-memory IsopackCache.
tropohouseIsopackCache.buildLocalPackages(
ROOT_PACKAGES_TO_BUILD_IN_SANDBOX);
});
});
// Save all the isopacks into builtPackageTropohouseDir/packages. (Note that
// we are always putting them into the default 'packages' (assuming
// $METEOR_PACKAGE_SERVER_URL is not set in the self-test process itself) even
// though some tests will want them to be under
// 'packages-for-server/test-packages'; we'll fix this in _makeWarehouse.
tropohouseIsopackCache.eachBuiltIsopack(function (name, isopack) {
tropohouse._saveIsopack(isopack, name);
});
};
var newSelfTestCatalog = function () {
if (! files.inCheckout())
throw Error("Only can build packages from a checkout");
var catalogLocal = require('./catalog-local.js');
var selfTestCatalog = new catalogLocal.LocalCatalog;
var messages = buildmessage.capture(
{ title: "scanning local core packages" },
function () {
// When building a fake warehouse from a checkout, we use local packages,
// but *ONLY THOSE FROM THE CHECKOUT*: not app packages or $PACKAGE_DIRS
// packages. One side effect of this: we really really expect them to all
// build, and we're fine with dying if they don't (there's no worries
// about needing to springboard).
selfTestCatalog.initialize({
localPackageSearchDirs: [files.pathJoin(
files.getCurrentToolsDir(), 'packages')]
});
});
if (messages.hasMessages()) {
Console.arrowError("Errors while scanning core packages:");
Console.printMessages(messages);
throw new Error("scan failed?");
}
return selfTestCatalog;
};
///////////////////////////////////////////////////////////////////////////////
// Matcher
///////////////////////////////////////////////////////////////////////////////
// Handles the job of waiting until text is seen that matches a
// regular expression.
var Matcher = function (run) {
var self = this;
self.buf = "";
self.ended = false;
self.matchPattern = null;
self.matchFuture = null;
self.matchStrict = null;
self.run = run; // used only to set a field on exceptions
};
_.extend(Matcher.prototype, {
write: function (data) {
var self = this;
self.buf += data;
self._tryMatch();
},
match: function (pattern, timeout, strict) {
var self = this;
if (self.matchFuture)
throw new Error("already have a match pending?");
self.matchPattern = pattern;
self.matchStrict = strict;
var f = self.matchFuture = new Future;
self._tryMatch(); // could clear self.matchFuture
var timer = null;
if (timeout) {
timer = setTimeout(function () {
self.matchPattern = null;
self.matchStrict = null;
self.matchFuture = null;
f['throw'](new TestFailure('match-timeout', { run: self.run }));
}, timeout * 1000);
}
try {
return f.wait();
} finally {
if (timer)
clearTimeout(timer);
}
},
end: function () {
var self = this;
self.ended = true;
self._tryMatch();
},
matchEmpty: function () {
var self = this;
if (self.buf.length > 0) {
Console.info("Extra junk is :", self.buf);
throw new TestFailure('junk-at-end', { run: self.run });
}
},
_tryMatch: function () {
var self = this;
var f = self.matchFuture;
if (! f)
return;
var ret = null;
if (self.matchPattern instanceof RegExp) {
var m = self.buf.match(self.matchPattern);
if (m) {
if (self.matchStrict && m.index !== 0) {
self.matchFuture = null;
self.matchStrict = null;
self.matchPattern = null;
Console.info("Extra junk is: ", self.buf.substr(0, m.index));
f['throw'](new TestFailure(
'junk-before', { run: self.run, pattern: self.matchPattern }));
return;
}
ret = m;
self.buf = self.buf.slice(m.index + m[0].length);
}
} else {
var i = self.buf.indexOf(self.matchPattern);
if (i !== -1) {
if (self.matchStrict && i !== 0) {
self.matchFuture = null;
self.matchStrict = null;
self.matchPattern = null;
Console.info("Extra junk is: ", self.buf.substr(0, i));
f['throw'](new TestFailure('junk-before',
{ run: self.run, pattern: self.matchPattern }));
return;
}
ret = self.matchPattern;
self.buf = self.buf.slice(i + self.matchPattern.length);
}
}
if (ret !== null) {
self.matchFuture = null;
self.matchStrict = null;
self.matchPattern = null;
f['return'](ret);
return;
}
if (self.ended) {
var failure = new TestFailure('no-match', { run: self.run,
pattern: self.matchPattern });
self.matchFuture = null;
self.matchStrict = null;
self.matchPattern = null;
f['throw'](failure);
return;
}
}
});
///////////////////////////////////////////////////////////////////////////////
// OutputLog
///////////////////////////////////////////////////////////////////////////////
// Maintains a line-by-line merged log of multiple output channels
// (eg, stdout and stderr).
var OutputLog = function (run) {
var self = this;
// each entry is an object with keys 'channel', 'text', and if it is
// the last entry and there was no newline terminator, 'bare'
self.lines = [];
// map from a channel name to an object representing a partially
// read line of text on that channel. That object has keys 'text'
// (text read), 'offset' (cursor position, equal to text.length
// unless a '\r' has been read).
self.buffers = {};
// a Run, exclusively for inclusion in exceptions
self.run = run;
};
_.extend(OutputLog.prototype, {
write: function (channel, text) {
var self = this;
if (! _.has(self.buffers, 'channel'))
self.buffers[channel] = { text: '', offset: 0};
var b = self.buffers[channel];
while (text.length) {
var m = text.match(/^[^\n\r]+/);
if (m) {
// A run of non-control characters.
b.text = b.text.substr(0, b.offset) +
m[0] + b.text.substr(b.offset + m[0].length);
b.offset += m[0].length;
text = text.substr(m[0].length);
continue;
}
if (text[0] === '\r') {
b.offset = 0;
text = text.substr(1);
continue;
}
if (text[0] === '\n') {
self.lines.push({ channel: channel, text: b.text });
b.text = '';
b.offset = 0;
text = text.substr(1);
continue;
}
throw new Error("conditions should have been exhaustive?");
}
},
end: function () {
var self = this;
_.each(_.keys(self.buffers), function (channel) {
if (self.buffers[channel].text.length) {
self.lines.push({ channel: channel,
text: self.buffers[channel].text,
bare: true });
self.buffers[channel] = { text: '', offset: 0};
}
});
},
forbid: function (pattern, channel) {
var self = this;
_.each(self.lines, function (line) {
if (channel && channel !== line.channel)
return;
var match = (pattern instanceof RegExp) ?
(line.text.match(pattern)) : (line.text.indexOf(pattern) !== -1);
if (match)
throw new TestFailure('forbidden-string-present', { run: self.run });
});
},
get: function () {
var self = this;
return self.lines;
}
});
///////////////////////////////////////////////////////////////////////////////
// Sandbox
///////////////////////////////////////////////////////////////////////////////
// Represents an install of the tool. Creating this creates a private
// sandbox with its own state, separate from the state of the current
// meteor install or checkout, from the user's homedir, and from the
// state of any other sandbox. It also creates an empty directory
// which will be, by default, the cwd for runs created inside the
// sandbox (you can change this with the cd() method).
//
// This will throw TestFailure if it has to build packages to set up
// the sandbox and the build fails. So, only call it from inside
// tests.
//
// options:
// - warehouse: set to sandbox the warehouse too. If you don't do
// this, the tests are run in the same context (checkout or
// warehouse) as the actual copy of meteor you're running (the
// meteor in 'meteor self-test'. This may only be set when you're
// running 'meteor self-test' from a checkout. If it is set, it
// should look something like this:
// {
// version1: { tools: 'tools1', notices: (...) },
// version2: { tools: 'tools2', upgraders: ["a"],
// notices: (...), latest: true }
// }
// This would set up a simulated warehouse with two releases in it,
// one called 'version1' and having a tools version of 'tools1', and
// similarly with 'version2'/'tools2', with the latter being marked
// as the latest release, and the latter also having a single
// upgrader named "a". The releases are made by building the
// checkout into a release, and are identical except for their
// version names. If you pass 'notices' (which is optional), set it
// to the verbatim contents of the notices.json file for the
// release, as an object.
// - fakeMongo: if set, set an environment variable that causes our
// 'fake-mongod' stub process to be started instead of 'mongod'. The
// tellMongo method then becomes available on Runs for controlling
// the stub.
// - clients
// - browserstack: true if browserstack clients should be used
// - port: the port that the clients should run on
var Sandbox = function (options) {
var self = this;
// default options
options = _.extend({ clients: {} }, options);
self.root = files.mkdtemp();
self.warehouse = null;
self.home = files.pathJoin(self.root, 'home');
files.mkdir(self.home, 0755);
self.cwd = self.home;
self.env = {};
self.fakeMongo = options.fakeMongo;
// By default, tests use the package server that this meteor binary is built
// with. If a test is tagged 'test-package-server', it uses the test
// server. Tests that publish packages should have this flag; tests that
// assume that the release's packages can be found on the server should not.
// Note that this only affects subprocess meteor runs, not direct invocation
// of packageClient!
if (_.contains(runningTest.tags, 'test-package-server')) {
if (_.has(options, 'warehouse')) {
// test-package-server and warehouse are basically two different ways of
// sort of faking out the package system for tests. test-package-server
// means "use a specific production test server"; warehouse means "use
// some fake files we put on disk and never sync" (see _makeEnv where the
// offline flag is set). Combining them doesn't make sense: either you
// don't sync, in which case you don't see the stuff you published, or you
// do sync, and suddenly the mock catalog we built is overridden by
// test-package-server.
// XXX we should just run servers locally instead of either of these
// strategies
throw Error("test-package-server and warehouse cannot be combined");
}
self.set('METEOR_PACKAGE_SERVER_URL', exports.testPackageServerUrl);
}
if (_.has(options, 'warehouse')) {
if (!files.inCheckout())
throw Error("make only use a fake warehouse in a checkout");
self.warehouse = files.pathJoin(self.root, 'tropohouse');
self._makeWarehouse(options.warehouse);
}
self.clients = [new PhantomClient({
host: 'localhost',
port: options.clients.port || 3000
})];
if (options.clients && options.clients.browserstack) {
var browsers = [
{ browserName: 'firefox' },
{ browserName: 'chrome' },
{ browserName: 'internet explorer',
browserVersion: '11' },
{ browserName: 'internet explorer',
browserVersion: '8',
timeout: 60 },
{ browserName: 'safari' },
{ browserName: 'android' }
];
_.each(browsers, function (browser) {
self.clients.push(new BrowserStackClient({
host: 'localhost',
port: 3000,
browserName: browser.browserName,
browserVersion: browser.browserVersion,
timeout: browser.timeout
}));
});
}
var meteorScript = process.platform === "win32" ? "meteor.bat" : "meteor";
// Figure out the 'meteor' to run
if (self.warehouse)
self.execPath = files.pathJoin(self.warehouse, meteorScript);
else
self.execPath = files.pathJoin(files.getCurrentToolsDir(), meteorScript);
};
_.extend(Sandbox.prototype, {
// Create a new test run of the tool in this sandbox.
run: function (/* arguments */) {
var self = this;
return new Run(self.execPath, {
sandbox: self,
args: _.toArray(arguments),
cwd: self.cwd,
env: self._makeEnv(),
fakeMongo: self.fakeMongo
});
},
// Tests a set of clients with the argument function. Each call to f(run)
// instantiates a Run with a different client.
// Use:
// sandbox.testWithAllClients(function (run) {
// // pre-connection checks
// run.connectClient();
// // post-connection checks
// });
testWithAllClients: function (f) {
var self = this;
var argsArray = _.compact(_.toArray(arguments).slice(1));
console.log("running test with " + self.clients.length + " client(s).");
_.each(self.clients, function (client) {
console.log("testing with " + client.name + "...");
var run = new Run(self.execPath, {
sandbox: self,
args: argsArray,
cwd: self.cwd,
env: self._makeEnv(),
fakeMongo: self.fakeMongo,
client: client
});
run.baseTimeout = client.timeout;
f(run);
});
},
// Copy an app from a template into the current directory in the
// sandbox. 'to' is the subdirectory to put the app in, and
// 'template' is a subdirectory of tools/tests/apps to copy.
//
// Note that the arguments are the opposite order from 'cp'. That
// seems more intuitive to me -- if you disagree, my apologies.
//
// For example:
// s.createApp('myapp', 'empty');
// s.cd('myapp');
createApp: function (to, template, options) {
var self = this;
options = options || {};
files.cp_r(files.pathJoin(files.convertToStandardPath(__dirname), 'tests',
'apps', template),
files.pathJoin(self.cwd, to),
{ ignore: [/^local$/] });
// If the test isn't explicitly managing a mock warehouse, ensure that apps
// run with our release by default.
if (options.release) {
self.write(files.pathJoin(to, '.meteor/release'), options.release);
} else if (!self.warehouse && release.current.isProperRelease()) {
self.write(files.pathJoin(to, '.meteor/release'), release.current.name);
}
if (options.dontPrepareApp)
return;
// Prepare the app (ie, build or download packages). We give this a nice
// long timeout, which allows the next command to not need a bloated
// timeout. (meteor create does this anyway.)
self.cd(to, function () {
var run = self.run("--prepare-app");
// XXX Can we cache the output of running this once somewhere, so that
// multiple calls to createApp with the same template get the same cache?
// This is a little tricky because isopack-buildinfo.json uses absolute
// paths.
run.waitSecs(20);
run.expectExit(0);
});
},
// Same as createApp, but with a package.
//
// @param packageDir {String} The directory in which to create the package
// @param packageName {String} The package name to create. This string will
// replace all appearances of ~package-name~
// in any package*.js files in the template
// @param template {String} The package template to use. Found as a
// subdirectory in tests/packages/
//
// For example:
// s.createPackage('me_mypack', me:mypack', 'empty');
// s.cd('me_mypack');
createPackage: function (packageDir, packageName, template) {
var self = this;
var packagePath = files.pathJoin(self.cwd, packageDir);
var templatePackagePath = files.pathJoin(
files.convertToStandardPath(__dirname), 'tests', 'packages', template);
files.cp_r(templatePackagePath, packagePath);
_.each(files.readdir(packagePath), function (file) {
if (file.match(/^package.*\.js$/)) {
var packageJsFile = files.pathJoin(packagePath, file);
files.writeFile(
packageJsFile,
files.readFile(packageJsFile, "utf8")
.replace("~package-name~", packageName));
}
});
},
// Change the cwd to be used for subsequent runs. For example:
// s.run('create', 'myapp').expectExit(0);
// s.cd('myapp');
// s.run('add', 'somepackage') ...
// If you provide a callback, it will invoke the callback and then
// change the cwd back to the previous value. eg:
// s.cd('app1', function () {
// s.run('add', 'somepackage');
// });
// s.cd('app2', function () {
// s.run('add', 'somepackage');
// });
cd: function (relativePath, callback) {
var self = this;
var previous = self.cwd;
self.cwd = files.pathResolve(self.cwd, relativePath);
if (callback) {
callback();
self.cwd = previous;
}
},
// Set an environment variable for subsequent runs.
set: function (name, value) {
var self = this;
self.env[name] = value;
},
// Undo set().
unset: function (name) {
var self = this;
delete self.env[name];
},
// Write to a file in the sandbox, overwriting its current contents
// if any. 'filename' is a path intepreted relative to the Sandbox's
// cwd. 'contents' is a string (utf8 is assumed).
write: function (filename, contents) {
var self = this;
files.writeFile(files.pathJoin(self.cwd, filename), contents, 'utf8');
},
// Reads a file in the sandbox as a utf8 string. 'filename' is a
// path intepreted relative to the Sandbox's cwd. Returns null if
// file does not exist.
read: function (filename) {
var self = this;
var file = files.pathJoin(self.cwd, filename);
if (!files.exists(file))
return null;
else
return files.readFile(files.pathJoin(self.cwd, filename), 'utf8');
},
// Copy the contents of one file to another. In these series of tests, we often
// want to switch contents of package.js files. It is more legible to copy in
// the backup file rather than trying to write into it manually.
cp: function(from, to) {
var self = this;
var contents = self.read(from);
if (!contents) {
throw new Error("File " + from + " does not exist.");
};
self.write(to, contents);
},
// Delete a file in the sandbox. 'filename' is as in write().
unlink: function (filename) {
var self = this;
files.unlink(files.pathJoin(self.cwd, filename));
},
// Make a directory in the sandbox. 'filename' is as in write().
mkdir: function (dirname) {
var self = this;
var dirPath = files.pathJoin(self.cwd, dirname);
if (! files.exists(dirPath)) {
files.mkdir(dirPath);
}
},
// Rename something in the sandbox. 'oldName' and 'newName' are as in write().
rename: function (oldName, newName) {
var self = this;
files.rename(files.pathJoin(self.cwd, oldName),
files.pathJoin(self.cwd, newName));
},
// Return the current contents of .meteorsession in the sandbox.
readSessionFile: function () {
var self = this;
return files.readFile(files.pathJoin(self.root, '.meteorsession'), 'utf8');
},
// Overwrite .meteorsession in the sandbox with 'contents'. You
// could use this in conjunction with readSessionFile to save and
// restore authentication states.
writeSessionFile: function (contents) {
var self = this;
return files.writeFile(files.pathJoin(self.root, '.meteorsession'),
contents, 'utf8');
},
_makeEnv: function () {
var self = this;
var env = _.clone(self.env);
env.METEOR_SESSION_FILE = files.convertToOSPath(
files.pathJoin(self.root, '.meteorsession'));
if (self.warehouse) {
// Tell it where the warehouse lives.
env.METEOR_WAREHOUSE_DIR = files.convertToOSPath(self.warehouse);
// Don't ever try to refresh the stub catalog we made.
env.METEOR_OFFLINE_CATALOG = "t";
}
// By default (ie, with no mock warehouse and no --release arg) we should be
// testing the actual release this is built in, so we pretend that it is the
// latest release.
if (!self.warehouse && release.current.isProperRelease())
env.METEOR_TEST_LATEST_RELEASE = release.current.name;
return env;
},
// Writes a stub warehouse (really a tropohouse) to the directory
// self.warehouse. This warehouse only contains a meteor-tool package and some
// releases containing that tool only (and no packages).
//
// packageServerUrl indicates which package server we think we are using. Use
// the default, if we do not pass this in; you should pass it in any case that
// you will be specifying $METEOR_PACKAGE_SERVER_URL in the environment of a
// command you are running in this sandbox.
_makeWarehouse: function (releases) {
var self = this;
// Ensure we have a tropohouse to copy stuff out of.
setUpBuiltPackageTropohouse();
var serverUrl = self.env.METEOR_PACKAGE_SERVER_URL;
var packagesDirectoryName = config.getPackagesDirectoryName(serverUrl);
files.cp_r(files.pathJoin(builtPackageTropohouseDir, 'packages'),
files.pathJoin(self.warehouse, packagesDirectoryName),
{ preserveSymlinks: true });
var stubCatalog = {
syncToken: {},
formatVersion: "1.0",
collections: {
packages: [],
versions: [],
builds: [],
releaseTracks: [],
releaseVersions: []
}
};
var packageVersions = {};
var toolPackageVersion = null;
tropohouseIsopackCache.eachBuiltIsopack(function (packageName, isopack) {
var packageRec = tropohouseLocalCatalog.getPackage(packageName);
if (! packageRec)
throw Error("no package record for " + packageName);
stubCatalog.collections.packages.push(packageRec);
var versionRec = tropohouseLocalCatalog.getLatestVersion(packageName);
if (! versionRec)
throw Error("no version record for " + packageName);
stubCatalog.collections.versions.push(versionRec);
stubCatalog.collections.builds.push({
buildArchitectures: isopack.buildArchitectures(),
versionId: versionRec._id,
_id: utils.randomToken()
});
if (packageName === "meteor-tool") {
toolPackageVersion = versionRec.version;
} else {
packageVersions[packageName] = versionRec.version;
}
});
if (! toolPackageVersion)
throw Error("no meteor-tool?");
stubCatalog.collections.releaseTracks.push({
name: catalog.DEFAULT_TRACK,
_id: utils.randomToken()
});
// Now create each requested release.
_.each(releases, function (configuration, releaseName) {
// Release info
stubCatalog.collections.releaseVersions.push({
track: catalog.DEFAULT_TRACK,
_id: Math.random().toString(),
version: releaseName,
orderKey: releaseName,
description: "test release " + releaseName,
recommended: !!configuration.recommended,
tool: configuration.tool || "meteor-tool@" + toolPackageVersion,
packages: packageVersions
});
});
var dataFile = config.getPackageStorage({
root: self.warehouse,
serverUrl: serverUrl
});
self.warehouseOfficialCatalog = new catalogRemote.RemoteCatalog();
self.warehouseOfficialCatalog.initialize({
packageStorage: dataFile
});
self.warehouseOfficialCatalog.insertData(stubCatalog);
// And a cherry on top
// XXX this is hacky
files.linkToMeteorScript(
files.pathJoin(self.warehouse, packagesDirectoryName, "meteor-tool", toolPackageVersion,
'mt-' + archinfo.host(), 'meteor'),
files.pathJoin(self.warehouse, 'meteor'));
}
});
///////////////////////////////////////////////////////////////////////////////
// Client
///////////////////////////////////////////////////////////////////////////////
var Client = function (options) {
var self = this;
self.host = options.host;
self.port = options.port;
self.url = "http://" + self.host + ":" + self.port + '/' +
(Math.random() * 0x100000000 + 1).toString(36);
self.timeout = options.timeout || 40;
if (! self.connect || ! self.stop) {
console.log("Missing methods in subclass of Client.");
}
};
// PhantomClient
var PhantomClient = function (options) {
var self = this;
Client.apply(this, arguments);
self.name = "phantomjs";
self.process = null;
self._logError = true;
};
util.inherits(PhantomClient, Client);
_.extend(PhantomClient.prototype, {
connect: function () {
var self = this;
var phantomPath = phantomjs.path;
var scriptPath = files.pathJoin(files.getCurrentToolsDir(), "tools",
"phantom", "open-url.js");
self.process = child_process.execFile(phantomPath, ["--load-images=no",
files.convertToOSPath(scriptPath), self.url],
{}, function (error, stdout, stderr) {
if (self._logError && error) {
console.log("PhantomJS exited with error ", error, "\nstdout:\n", stdout, "\nstderr:\n", stderr);
}
});
},
stop: function() {
var self = this;
// Suppress the expected SIGTERM exit 'failure'
self._logError = false;
self.process && self.process.kill();
self.process = null;
}
});
// BrowserStackClient
var browserStackKey = null;
var BrowserStackClient = function (options) {
var self = this;
Client.apply(this, arguments);
self.tunnelProcess = null;
self.driver = null;
self.browserName = options.browserName;
self.browserVersion = options.browserVersion;
self.name = "BrowserStack - " + self.browserName;
if (self.browserVersion) {
self.name += " " + self.browserVersion;
}
};
util.inherits(BrowserStackClient, Client);
_.extend(BrowserStackClient.prototype, {
connect: function () {
var self = this;
// memoize the key
if (browserStackKey === null)
browserStackKey = self._getBrowserStackKey();
if (! browserStackKey)
throw new Error("BrowserStack key not found. Ensure that you " +
"have installed your S3 credentials.");
var capabilities = {
'browserName' : self.browserName,
'browserstack.user' : 'meteor',
'browserstack.local' : 'true',
'browserstack.key' : browserStackKey
};
if (self.browserVersion) {
capabilities.browserVersion = self.browserVersion;
}
self._launchBrowserStackTunnel(function (error) {
if (error)
throw error;
self.driver = new webdriver.Builder().
usingServer('http://hub.browserstack.com/wd/hub').
withCapabilities(capabilities).
build();
self.driver.get(self.url);
});
},
stop: function() {
var self = this;
self.tunnelProcess && self.tunnelProcess.kill();
self.tunnelProcess = null;
self.driver && self.driver.quit();
self.driver = null;
},
_getBrowserStackKey: function () {