Skip to content

Commit

Permalink
second batch of chapters
Browse files Browse the repository at this point in the history
  • Loading branch information
zzo committed Jan 29, 2013
1 parent 016a3f6 commit 0766b57
Show file tree
Hide file tree
Showing 39 changed files with 633 additions and 0 deletions.
27 changes: 27 additions & 0 deletions ch5/pg115
@@ -0,0 +1,27 @@
/**
* Return current stock price for given symbol
* in the callback
*
* @method getPrice
* @param symbol <String> the ticker symbol
* @param cb <Function> callback with results cb(error, value)
* @param httpObj <HTTP> Optional HTTP object for injection
* @return nothing
**/
function getPrice(symbol, cb, httpObj) {
var http = httpObj || require('http')
, options = {
host: 'download.finance.yahoo.com' // Thanks Yahoo!
, path: '/d/quotes.csv?s=' + symbol + '&f=l1'
}
;

http.get(options, function(res) {
res.on('data', function(d) {
cb(null, d);
});
}).on('error', function(e) {
cb(e.message);
});
}

15 changes: 15 additions & 0 deletions ch5/pg116
@@ -0,0 +1,15 @@
/**
* A simple stub for HTTP object
*/
var events = require('events').EventEmitter
, util = require('util')
, myhttp = function() { // Dummy up NodeJS's 'http' object
var _this = this ;
events.call(this);
this.get = function(options, cb) {
cb(_this);
return _this;
};
}
;
util.inherits(myhttp, events);
15 changes: 15 additions & 0 deletions ch5/pg117
@@ -0,0 +1,15 @@
testPrice: function() {
var symbol = 'YHOO'
, stockPrice = 50 // Wishful thinking??
, _this = this
, http = new myhttp()
;

getPrice(symbol, function(err, price) {
_this.resume(function() {
Y.Assert.areEqual(stockPrice, price, "Prices not equal!");
}, http); // Inject our 'http' object
http.fire('data', stockPrice); // Our mock data
this.wait(1000);
}
}
14 changes: 14 additions & 0 deletions ch5/pg117.1
@@ -0,0 +1,14 @@
testPriceError: function() {
var symbol = 'YHOO'
, _this = this
, http = new myhttp()
;

getPrice(symbol, function(err, price) {
_this.resume(function() {
Y.Assert.areEqual(err, 'an error', "Did not get error!"); }, http);
http.fire('error', { message: 'an error'} );
this.wait(1000);
}
}

3 changes: 3 additions & 0 deletions ch5/pg121
@@ -0,0 +1,3 @@
RewriteEngine On
RewriteCond %{QUERY_STRING} coverage=1
RewriteRule ^(.*)$ make_coverage.pl?file=%{DOCUMENT_ROOT}/$1 [L]
8 changes: 8 additions & 0 deletions ch5/pg122
@@ -0,0 +1,8 @@
#!/usr/bin/perl
use CGI;
my $q = CGI->new;
my $file = $q->param('file');
system("java -jar /path/to/yuitest_coverage.jar -o /tmp/$$.js $file");
print $q->header('application/JavaScript');
open(C, "/tmp/$$.js");
print <C>;
22 changes: 22 additions & 0 deletions ch5/pg123
@@ -0,0 +1,22 @@
var Module = require('module')
, path = require('path')
, originalLoader = Module._load
, coverageBase = '/tmp'
, COVERAGE_ME = []
;

Module._load = coverageLoader;

// Figure out what files to generate code coverage for
// & put into COVERAGE_ME
// And run those JS files thru yuitest-coverage.jar
// and dump the output into coverageBase
// Then execute tests
// All calls to 'require' will filter thru this:
function coverageLoader(request, parent, isMain) {
if (COVERAGE_ME[request]) {
request = PATH.join(coverageBase, path.basename(request));
}
return originalLoader(request, parent, isMain);
}
// At the end dump the global _yuitest_coverage variable
7 changes: 7 additions & 0 deletions ch5/pg124
@@ -0,0 +1,7 @@
var tempFile = PATH.join(coverageBase, PATH.basename(file));
, realFile = require.resolve(file)
;
exec('java -jar ' + coverageJar + " -o " + tempFile + " " + realFile
, function(err) {
FILES_FOR_COVERAGE[keep] = 1;
});
4 changes: 4 additions & 0 deletions ch5/pg125
@@ -0,0 +1,4 @@
var realFile = require.resolve(file)
, coverFile = realFile.replace('.js', '.cover');
;
exec('java -jar ' + coverageJar + " -o " + coverFile + " " + realFile, function(err) {});
9 changes: 9 additions & 0 deletions ch5/pg126
@@ -0,0 +1,9 @@
var TestRunner = Y.Test.Runner;
TestRunner.subscribe(TestRunner. TEST_SUITE_COMPLETE_EVENT, getResults);
TestRunner.run();
function getResults(data) {
var reporter = new Y.Test.Reporter(
"http://www.yourserver.com/path/to/target"
, Y.Test.Format.JUnitXML);
reporter.report(results);
}
11 changes: 11 additions & 0 deletions ch5/pg127
@@ -0,0 +1,11 @@
function getResults(data) {
// Use JUnitXML format for unit test results
var reporter = new Y.Test.Reporter(
"http://www.yourserver.com/path/to/target"
, Y.Test.Format.JUnitXML);

// Toss in coverage results
reporter.addField("coverageResults", Y.Test.Runner.getCoverage(Y.Coverage.Format.JSON));
// Ship it
reporter.report(results);
}
10 changes: 10 additions & 0 deletions ch5/pg130
@@ -0,0 +1,10 @@
my $old = '/a/b/c';
my $new = '/d/e/f';
open(F, "wrong.lcov");
open(G, ">right.lcov");
while(<F>) {
s#^$old#$new#;
print G;
}
close(G);
close(F);
23 changes: 23 additions & 0 deletions ch5/pg131
@@ -0,0 +1,23 @@
<html lang="en">
<body class="yui3-skin-sam">
<div id="log"></div>
<h3>Running dummy unit test for APP_FILE</h3>
<script src="http://yui.yahooapis.com/3.4.0/build/yui/yui.js"></script>
<script src="/path/to/coveraged/file/without/tests.js"></script>
<script>
YUI().use('test', function(Y) {
Y.Test.Runner.add(
new Y.Test.Suite('no test').add(
new Y.Test.Case({
name: 'dummy_NOTESTS'
, 'testFile': function() {
Y.Assert.areEqual(true, true);
}
})
)
);
Y.TestRunner.go();
});
</script>
</body>
</html>
39 changes: 39 additions & 0 deletions ch5/pg132
@@ -0,0 +1,39 @@
#!/usr/local/bin/perl
use Getopt::Long;
use File::Find;
use File::Basename;

my($debug, $test_dir, @src_dir, $src_base);
my $src_key = 'src'; // root of source tree

GetOptions (
"test_dir=s" => \$test_dir,
132 | Chapter 5: Code Coverage
"src_dir=s" => \@src_dir,
"src_base=s" => \$src_base,
) || die "Bad Options!\n";;

my $src_files = {};
find(\&all_src_files, @src_dir);
find(\&all_tested_files, $test_dir);

sub all_src_files {
return unless (/\.js$/);
foreach my $src_dir (@src_dir) {
$File::Find::name =~ s/^\Q$src_base\E//;
}
$src_files->{$File::Find::name}++;
}

sub all_tested_files {
return unless (/\.html?$/);
open(F, $_) || die "Can't open $_: $!\n";
while(my $line = <F>) {
if ($line =~ /["']([^"]+?\/($src_key\/[^"]+?\.js))["']/) {
my($full_file_path) = $2;
print "Test file $File::Find::name is coveraging
$full_file_path\n" if ($debug);
delete $src_files->{$full_file_path};
}.
}
}
16 changes: 16 additions & 0 deletions ch6/pg140
@@ -0,0 +1,16 @@
var webdriverjs = require("webdriverjs")
, browser = webdriverjs.remote({
host: 'localhost'
, port: 4444
, desiredCapabilities: { browserName: 'firefox' }
})
;

browser
.testMode()
.init()
.url("http://search.yahoo.com")
.setValue("#yschsp", "JavaScript")
.submitForm("#sf")
.tests.visible('#resultCount', true, 'Got result count')
.end();
17 changes: 17 additions & 0 deletions ch6/pg140.1
@@ -0,0 +1,17 @@
var webdriverjs = require("webdriverjs")
, browser = webdriverjs.remote({
host: 'localhost'
, port: 4444
, desiredCapabilities: { browserName: 'firefox' }
})
;

browser
.testMode()
.init()
.url("http://search.yahoo.com")
.setValue("#yschsp", "javascript")
.submitForm("#sf")
.tests.visible('#resultCount', true, 'Got result count')
.saveScreenshot('results.png')
.end();
24 changes: 24 additions & 0 deletions ch6/pg142
@@ -0,0 +1,24 @@
var soda = require('soda')
, browser = soda.createClient({
url: 'http://search.yahoo.com'
, host: 'localhost'
, browser: 'safari'
})
;

browser
.chain
.session()
.open('/')
.type('yschsp', 'JavaScript')
.submit('sf')
.waitForPageToLoad(5000)
.assertElementPresent('resultCount')
.end(function(err) {
browser.testComplete(function() {
if (err) {
console.log('Test failures: ' + err);
} else {
console.log('success!');
}
})
11 changes: 11 additions & 0 deletions ch6/pg144
@@ -0,0 +1,11 @@
var casper = require('casper').create();
casper.start('http://search.yahoo.com/', function() {
this.fill('form#sf', { "p": 'JavaScript' }, false);
this.click('#yschbt');
});
casper.then(function() {
this.test.assertExists('#resultCount', 'Got result count');
});
casper.run(function() {
this.exit();
});
20 changes: 20 additions & 0 deletions ch6/pg145
@@ -0,0 +1,20 @@
var casper = require('casper').create();
casper.start('http://search.yahoo.com/', function() {
this.fill('form#sf', { "p": 'JavaScript' }, false);
this.click('#yschbt');
});

casper.then(function() {
this.capture('results.png', {
top: 0,
left: 0,
width: 1024,
height: 768
});

this.test.assertExists('#resultCount', 'Got result count');
});

casper.run(function() {
this.exit();
});
19 changes: 19 additions & 0 deletions ch6/pg146
@@ -0,0 +1,19 @@
var casper = require('casper').create();
casper.start('http://search.yahoo.com/', function() {
this.fill('form#sf', { "p": 'JavaScript' }, false);
this.click('#yschbt');
});
casper.then(function() {
this.capture('results.png', {
top: 0,
left: 0,
width: 1024,
height: 768
});

this.test.assertExists('#resultCount', 'Got result count');
});

casper.run(function() {
this.test.renderResults(true, 0, 'test-results.xml');
});
12 changes: 12 additions & 0 deletions ch6/pg149
@@ -0,0 +1,12 @@
var Proxy = require('browsermob-proxy').Proxy
, fs = require('fs')
, proxy = new Proxy()
;

proxy.doHAR('http://yahoo.com', function(err, data) {
if (err) {
console.error('ERROR: ' + err);
} else {
fs.writeFileSync('yahoo.com.har', data, 'utf8');
}
});
49 changes: 49 additions & 0 deletions ch6/pg149.1
@@ -0,0 +1,49 @@
var Proxy = require('browsermob-proxy').Proxy
, webdriverjs = require("webdriverjs")
, fs = require('fs')
, proxy = new Proxy()
;

/*
* Call into the proxy with a 'name' for this session, a Selenium
* function to run the interaction we want to capture, and
* finally a callback that will contain either the HAR data or
* an error
*/
proxy.cbHAR('search.yahoo.com', doSeleniumStuff, function(err, data) {
if (err) {
console.error('Error capturing HAR: ' + err);
} else {
fs.writeFileSync('search.yahoo.com.har', data, 'utf8');
}
});

/*
* This is the Selenium function that gets passed the proxy webdriverjs
* should use and a callback to call when the interaction is done
*/
function doSeleniumStuff(proxy, cb) {
var browser = webdriverjs.remote({
host: 'localhost'
, port: 4444
, desiredCapabilities: {
browserName: 'firefox'
, seleniumProtocol: 'WebDriver'
, proxy: { httpProxy: proxy }
}
});

// Just run our regular Selenium stuff - note this can just
// be your regular test code or something special you want
// to capture with a HAR
// Just pass the browsermob-proxy callback to 'end()'
browser
.testMode()
.init()
.url("http://search.yahoo.com")
.setValue("#yschsp", "JavaScript")
.submitForm("#sf")
.tests.visible('#resultCount', true, 'Got result count')
.saveScreenshot('results.png')
.end(cb);
}

0 comments on commit 0766b57

Please sign in to comment.