| 13 | // Execute a list of commands and assertions |
| 14 | var recorded_events = ['state', 'error', 'window_update', 'headers', 'promise']; |
| 15 | function execute_sequence(stream, sequence, done) { |
| 16 | if (!done) { |
| 17 | done = sequence; |
| 18 | sequence = stream; |
| 19 | stream = createStream(); |
| 20 | } |
| 21 | |
| 22 | var outgoing_frames = []; |
| 23 | |
| 24 | var emit = stream.emit, events = []; |
| 25 | stream.emit = function(name) { |
| 26 | if (recorded_events.indexOf(name) !== -1) { |
| 27 | events.push({ name: name, data: Array.prototype.slice.call(arguments, 1) }); |
| 28 | } |
| 29 | return emit.apply(this, arguments); |
| 30 | }; |
| 31 | |
| 32 | var commands = [], checks = []; |
| 33 | sequence.forEach(function(step) { |
| 34 | if ('method' in step || 'incoming' in step || 'outgoing' in step || 'wait' in step || 'set_state' in step) { |
| 35 | commands.push(step); |
| 36 | } |
| 37 | |
| 38 | if ('outgoing' in step || 'event' in step || 'active' in step) { |
| 39 | checks.push(step); |
| 40 | } |
| 41 | }); |
| 42 | |
| 43 | var activeCount = 0; |
| 44 | function count_change(change) { |
| 45 | activeCount += change; |
| 46 | } |
| 47 | |
| 48 | function execute(callback) { |
| 49 | var command = commands.shift(); |
| 50 | if (command) { |
| 51 | if ('method' in command) { |
| 52 | var value = stream[command.method.name].apply(stream, command.method.arguments); |
| 53 | if (command.method.ret) { |
| 54 | command.method.ret(value); |
| 55 | } |
| 56 | execute(callback); |
| 57 | } else if ('incoming' in command) { |
| 58 | command.incoming.count_change = count_change; |
| 59 | stream.upstream.write(command.incoming); |
| 60 | execute(callback); |
| 61 | } else if ('outgoing' in command) { |
| 62 | outgoing_frames.push(stream.upstream.read()); |
| 63 | execute(callback); |
| 64 | } else if ('set_state' in command) { |
| 65 | stream.state = command.set_state; |
| 66 | execute(callback); |
| 67 | } else if ('wait' in command) { |
| 68 | setTimeout(execute.bind(null, callback), command.wait); |
| 69 | } else { |
| 70 | throw new Error('Invalid command', command); |
| 71 | } |
| 72 | } else { |