1+ /*
2+ * examples.js: Macros for testing code in examples/
3+ *
4+ * (C) 2010 Nodejitsu Inc.
5+ * MIT LICENCE
6+ *
7+ */
8+
9+ var assert = require ( 'assert' ) ,
10+ fs = require ( 'fs' ) ,
11+ path = require ( 'path' ) ,
12+ spawn = require ( 'child_process' ) . spawn ,
13+ async = require ( 'async' ) ;
14+
15+ var rootDir = path . join ( __dirname , '..' , '..' ) ,
16+ examplesDir = path . join ( rootDir , 'examples' ) ;
17+
18+ //
19+ // ### function shouldHaveDeps ()
20+ //
21+ // Ensures that all `npm` dependencies are installed in `/examples`.
22+ //
23+ exports . shouldHaveDeps = function ( ) {
24+ return {
25+ "Before testing examples" : {
26+ topic : function ( ) {
27+ async . waterfall ( [
28+ //
29+ // 1. Read files in examples dir
30+ //
31+ async . apply ( fs . readdir , examplesDir ) ,
32+ //
33+ // 2. If node_modules exists, continue. Otherwise
34+ // exec `npm` to install them
35+ //
36+ function checkNodeModules ( files , next ) {
37+ if ( files . indexOf ( 'node_modules' ) !== - 1 ) {
38+ return next ( ) ;
39+ }
40+
41+ var child = spawn ( 'npm' , [ 'install' ] , {
42+ cwd : examplesDir
43+ } ) ;
44+
45+ child . on ( 'exit' , function ( code ) {
46+ return code
47+ ? next ( new Error ( 'npm install exited with non-zero exit code' ) )
48+ : next ( ) ;
49+ } ) ;
50+ } ,
51+ //
52+ // 3. Read files in examples dir again to ensure the install
53+ // worked as expected.
54+ //
55+ async . apply ( fs . readdir , examplesDir ) ,
56+ ] , this . callback ) ;
57+ } ,
58+ "examples/node_modules should exist" : function ( err , files ) {
59+ assert . notEqual ( files . indexOf ( 'node_modules' ) , - 1 ) ;
60+ }
61+ }
62+ }
63+ } ;
64+
65+ //
66+ // ### function shouldRequire (file)
67+ // #### @file {string} File to attempt to require
68+ //
69+ // Returns a test which attempts to require `file`.
70+ //
71+ exports . shouldRequire = function ( file ) {
72+ return {
73+ "should have no errors" : function ( ) {
74+ try { assert . isObject ( require ( file ) ) }
75+ catch ( ex ) { assert . isNull ( ex ) }
76+ }
77+ } ;
78+ } ;
79+
80+ //
81+ // ### function shouldHaveNoErrors ()
82+ //
83+ // Returns a vows context that attempts to require
84+ // every relevant example file in `examples`.
85+ //
86+ exports . shouldHaveNoErrors = function ( ) {
87+ var context = { } ;
88+
89+ [ 'balancer' , 'http' , 'middleware' , 'websocket' ] . forEach ( function ( dir ) {
90+ var name = 'examples/' + dir ,
91+ files = fs . readdirSync ( path . join ( rootDir , 'examples' , dir ) ) ;
92+
93+ files . forEach ( function ( file ) {
94+ context [ name + '/' + file ] = exports . shouldRequire ( path . join (
95+ examplesDir , dir , file
96+ ) ) ;
97+ } ) ;
98+ } ) ;
99+
100+ return context ;
101+ } ;
0 commit comments