 semver = require 'semver'
 tv4 = require '../schema/index.js'
 
-check = (done, f) ->
-  try
-    f()
-  catch e
-    done e
-
 validateSchema = (payload, schema) ->
   res = tv4.validateMultiple payload, schema
-  chai.expect(res.errors).to.eql []
-  chai.expect(res.valid).to.equal true
+  chai.expect(res.errors, "#{schema} should produce no errors").to.eql []
+  chai.expect(res.valid, "#{schema} should validate").to.equal true
   return res.valid
 
 exports.testRuntime = (runtimeType, startServer, stopServer, host='localhost', port=8080, collection='core', version='0.5') ->

        command: command
        payload: payload

    receive = (expects, done, ignore=null) ->
      listener = (message) ->
        check done, ->
          chai.expect(message.utf8Data).to.be.a 'string'
          msg = JSON.parse message.utf8Data

          if not ignore or not ignore(msg)
            expected = expects.shift()
            chai.expect(msg.protocol, 'protocol').to.equal expected.protocol
            chai.expect(msg.command, 'command').to.equal expected.command
            if expected.payload
              for key, value of expected.payload
                type = null
                if value is String
                  type = 'string'
                else if value is Number
                  type = 'number'
                else if value is Array
                  type = 'array'
                if type
                  chai.expect(msg.payload, "payload.#{key}").to.exist
                  chai.expect(msg.payload[key], "payload.#{key}").to.be.a type
                  delete expected.payload[key]
                  delete msg.payload[key]

            chai.expect(msg).to.eql expected
          if expects.length
            connection.once 'message', listener
          else
            done()
      connection.once 'message', listener

    describe 'Runtime Protocol', ->

               tgt: { node: 'World', port: 'in' }
          ]

          listener = (message) ->
            data = JSON.parse message.utf8Data
            validateSchema data, "/#{data.protocol}/output/#{data.command}"
            return unless data.command is expects[0].command
            expected = expects.shift()
            if data.command is 'started'
              delete data.payload.time
              delete expected.payload.time
            chai.expect(data.payload).to.eql expected.payload
            return if expects.length
            # Received all packets
            connection.removeListener 'message', listener
            done()
            return
          connection.on 'message', listener

          send 'network', 'start',
            graph: 'bar'

