{"action":"opened","issue":{"url":"https://api.github.com/repos/hustxiaoc/node.js/issues/12","labels_url":"https://api.github.com/repos/hustxiaoc/node.js/issues/12/labels{/name}","comments_url":"https://api.github.com/repos/hustxiaoc/node.js/issues/12/comments","events_url":"https://api.github.com/repos/hustxiaoc/node.js/issues/12/events","html_url":"https://github.com/hustxiaoc/node.js/issues/12","id":122184561,"number":12,"title":"多进程下的测试覆盖率","user":{"login":"hustxiaoc","id":1102038,"avatar_url":"https://avatars.githubusercontent.com/u/1102038?v=3","gravatar_id":"","url":"https://api.github.com/users/hustxiaoc","html_url":"https://github.com/hustxiaoc","followers_url":"https://api.github.com/users/hustxiaoc/followers","following_url":"https://api.github.com/users/hustxiaoc/following{/other_user}","gists_url":"https://api.github.com/users/hustxiaoc/gists{/gist_id}","starred_url":"https://api.github.com/users/hustxiaoc/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/hustxiaoc/subscriptions","organizations_url":"https://api.github.com/users/hustxiaoc/orgs","repos_url":"https://api.github.com/users/hustxiaoc/repos","events_url":"https://api.github.com/users/hustxiaoc/events{/privacy}","received_events_url":"https://api.github.com/users/hustxiaoc/received_events","type":"User","site_admin":false},"labels":[],"state":"open","locked":false,"assignee":null,"milestone":null,"comments":0,"created_at":"2015-12-15T03:21:00Z","updated_at":"2015-12-15T03:21:00Z","closed_at":null,"body":"单元测试在 Node.js 项目开发中的重要性就不言而喻了，项目一旦稍微大起来了就经常出现拆东墙补西墙的情况。这边修复了一个 bug，那边又不知道什么时候产生了一个新的 bug，越到后面没有经过完整的测试都不敢随便发布。\r\n\r\n## 代码覆盖率\r\n测试的时候，我们常常关心，是否所有代码都测试到了。这个指标就叫做“代码覆盖率”（code coverage），它有四个测量维度。\r\n\r\n- 行覆盖率（line coverage）：是否每一行都执行了？\r\n- 函数覆盖率（function coverage）：是否每个函数都调用了？\r\n- 分支覆盖率（branch coverage）：是否每个 if 代码块都执行了？\r\n- 语句覆盖率（statement coverage）：是否每个语句都执行了？\r\n\r\n\r\n目前在 Node.js 开发中比较流行的测试覆盖率工具是 Istanbul。\r\n\r\n>Yet another JS code coverage tool that computes statement, line, function and branch coverage with module loader hooks to transparently add coverage when running tests. Supports all JS coverage use cases including unit tests, server side functional tests and browser tests. Built for scale.\r\n\r\nIstanbul 不但可以统计到整个项目的代码覆盖率，还会生成一份漂亮的覆盖率报告，准确的标记出哪些代码没有被覆盖到。 \r\n\r\n平常我们写的 JS 测试用例大部分都是单进程的场景，下面我们来看一个多进程项目的测试情况又是怎么样的呢？\r\n\r\n\r\n## 多进程 demo\r\n先写一个简单的 demo，使用 Mocha 做单元测试，Istanbul 生成测试覆盖率。\r\n下面是整个项目的目录结构。\r\n\r\n```bash\r\n.istanbul-cluster-demo\r\n|____.gitignore\r\n|____lib\r\n| |____master.js\r\n| |____worker.js\r\n|____package.json\r\n|____test\r\n| |____index.test.js\r\n```\r\n\r\nmaster.js\r\n\r\n```\r\n'use strict';\r\n\r\nconst path = require('path');\r\nconst childProcess = require('child_process');\r\n\r\nlet rid = 0;\r\nconst service = {};\r\nconst requestQueue = new Map();\r\n\r\nmodule.exports = function (ready) {\r\n  const worker = childProcess.fork(path.join(__dirname,'./worker'));\r\n\r\n  function send() {\r\n    rid++;\r\n    let args = [].slice.call(arguments);\r\n    const method = args.slice(0,1)[0];\r\n    const callback = args.slice(-1)[0];\r\n\r\n    const req = {\r\n      rid: rid,\r\n      method:method,\r\n      args:args.slice(1,-1)\r\n    };\r\n\r\n    requestQueue.set(rid,Object.assign({\r\n      callback: callback\r\n    }, req));\r\n\r\n    worker.send(req);\r\n  }\r\n\r\n  worker.on('message', function(message){\r\n    if (message.action === 'register') {\r\n       message.methods.forEach((method) => {\r\n        service[method] = send.bind(null, method);\r\n       });\r\n       ready(service);\r\n    } else {\r\n      const req = requestQueue.get(message.rid);\r\n      const callback = req.callback;\r\n      if (message.success) {\r\n        callback(null, message.data);\r\n      } else {\r\n        callback(new Error(message.error));\r\n      }\r\n      requestQueue.delete(message.rid);\r\n    }\r\n  });\r\n}\r\n```\r\n\r\nworker.js\r\n\r\n```\r\n'use strict';\r\n\r\nconst service = {\r\n  add() {\r\n    const args = [].slice.call(arguments);\r\n    return args.slice().reduce(function(a,b) {\r\n      return a+b;\r\n    });\r\n  },\r\n\r\n  time() {\r\n    const args = [].slice.call(arguments);\r\n    return new Promise((resolve, reject)=> {\r\n       setTimeout( ()=> {\r\n          const ret = args.slice().reduce(function(a,b) {\r\n                        return a*b;\r\n                      });\r\n          resolve(ret);\r\n       }, 1000);\r\n    });\r\n  }\r\n}\r\n\r\nif (process.send) {\r\n  process.send({\r\n    action:'register',\r\n    methods: Object.keys(service)\r\n  });\r\n}\r\n\r\nprocess.on('message', function(message) {\r\n  let ret = { success: false, rid: message.rid };\r\n  const method = message.method;\r\n  if (service[method]) {\r\n    try {\r\n      const result = service[method].apply(service, message.args);\r\n      ret.success = true;\r\n      if(typeof result.then === 'function') {\r\n        return result.then((data)=> {\r\n          ret.data = data;\r\n          process.send(ret);\r\n        }).catch((err)=>{\r\n          ret.success = false;\r\n          ret.error = err.message;\r\n          process.send(err);\r\n        })\r\n      }\r\n      ret.data = result;\r\n    } catch (err) {\r\n      ret.error = err.message;\r\n    }\r\n  }\r\n  process.send(ret);\r\n});\r\n```\r\n\r\n上面的 demo 实现了一个简单的进程间 rpc 功能，master 进程提供接口，worker 进程实现具体的逻辑，并通过进程间通信给 master 调用。 \r\n\r\nworker 进程 向 master 进程注册了 add 和 time 方法，分别提供相加和相乘的服务。\r\n\r\n## 测试用例\r\n接着使用 Mocha 写一个脚本测试下功能。\r\n\r\nindex.test.js\r\n\r\n```\r\n'use strict';\r\nconst master = require('../lib/master');\r\nconst assert = require('assert');\r\n\r\ndescribe('test/index.test.js', function() {\r\n  let service;\r\n  before(function(done) {\r\n    master(function(_service){\r\n      service = _service;\r\n      done();\r\n    });\r\n  });\r\n\r\n  it('add should work', function(done) {\r\n    service.add(1,2,3,4,5, function(err, result) {\r\n        assert(result === 1+2+3+4+5);\r\n        done();\r\n    });\r\n  });\r\n\r\n  it('time should work', function(done) {\r\n    service.time(1,2,3,4,5, function(err, result) {\r\n        assert(result === 1*2*3*4*5);\r\n        done();\r\n    });\r\n  });\r\n});\r\n\r\n```\r\n\r\n运行  `node --harmony node_modules/.bin/istanbul cover  ./node_modules/mocha/bin/_mocha --  test/**/*.test.js` 输出\r\n\r\n![测试结果](http://gtms02.alicdn.com/tps/i2/TB1fMrJKVXXXXXaXXXXXsjJFVXX-1344-530.png)\r\n\r\n所有的测试用例都已经跑通并统计出各种覆盖率， 再看看生成的覆盖率报告\r\n![覆盖率报告，子进程没有被统计到](http://gtms04.alicdn.com/tps/i4/TB1QRPfKVXXXXbvaXXXHP4SLXXX-1570-372.png)\r\n\r\n发现并没有 worker.js 的覆盖率数据，所以上面输出的覆盖率是不完整的。\r\n\r\n## 分析原因\r\n为什么测试的结果中会没有 worker.js 的覆盖率数据呢，稍微想一下其实很简单，master.js 之所以有覆盖率数据因为它通过 Istanbul 启动执行的，代码运行之前 Istanbul 会对 master.js 进行 instrument。下面是一段代码被 instrument 前后的情况。\r\n\r\nbefore instrument\r\n```\r\nfunction test() { return \"Node.js\"; }\r\n```\r\n\r\nafter instrument\r\n```\r\nvar __cov_lgAhQ3cOIwE1WdZw07U4cQ = (Function('return this'))();\r\nif (!__cov_lgAhQ3cOIwE1WdZw07U4cQ.__coverage__) { __cov_lgAhQ3cOIwE1WdZw07U4cQ.__coverage__ = {}; }\r\n__cov_lgAhQ3cOIwE1WdZw07U4cQ = __cov_lgAhQ3cOIwE1WdZw07U4cQ.__coverage__;\r\nif (!(__cov_lgAhQ3cOIwE1WdZw07U4cQ['demo.js'])) {\r\n   __cov_lgAhQ3cOIwE1WdZw07U4cQ['demo.js'] = {\"path\":\"demo.js\",\"s\":{\"1\":1,\"2\":0},\"b\":{},\"f\":{\"1\":0},\"fnMap\":{\"1\":{\"name\":\"test\",\"line\":1,\"loc\":{\"start\":{\"line\":1,\"column\":0},\"end\":{\"line\":1,\"column\":16}}}},\"statementMap\":{\"1\":{\"start\":{\"line\":1,\"column\":0},\"end\":{\"line\":1,\"column\":37}},\"2\":{\"start\":{\"line\":1,\"column\":18},\"end\":{\"line\":1,\"column\":35}}},\"branchMap\":{}};\r\n}\r\n__cov_lgAhQ3cOIwE1WdZw07U4cQ = __cov_lgAhQ3cOIwE1WdZw07U4cQ['demo.js'];\r\nfunction test(){__cov_lgAhQ3cOIwE1WdZw07U4cQ.f['1']++;__cov_lgAhQ3cOIwE1WdZw07U4cQ.s['2']++;return'Node.js';}\r\n```\r\n可以看出 instrument 后的代码每一行是否被执行都可以监测到，而 worker.js 是 master.js 通过调用 childProcess.fork， 在一个很干净的 Node.js 环境中执行， 执行的代码没有被 instrument，执行情况自然无法被 Istanbul 检测到。\r\n\r\n## 解决方案\r\n所以要获取 worker.js 的覆盖率，必须在执行 worker.js 代码之前先注入 Istanbul，那很自然的就会想到 hack 掉 childProcess.fork。\r\n\r\n```\r\nconst childProcess = require('child_process');\r\nconst fork = childProcess.fork;\r\nconst path = require('path');\r\n\r\nchildProcess.fork = function(modulePath, args, options) {\r\n  const execPath = path.resolve(__dirname,'../node_modules/.bin/istanbul');\r\n  args = ['cover', '--report', 'none', '--print', 'none', '--include-pid',modulePath+'.js'];\r\n  return fork.apply(childProcess,[execPath, args, options]);\r\n}\r\n```\r\n\r\n虽然这样处理后 master.js 和 worker.js 的覆盖率都有了，但由于它们是在不同的进程中产生的，Istanbul 不会自动将 2 个文件的覆盖率数据合并处理，所以我们可以先产生覆盖率数据，再根据覆盖率数据生成报告。由于涉及到多个进程，启动  Istanbul 时需要加上 `include-pid` 参数，这样每个进程生成的 coverage.json 文件就会带上进程 pid，否则 子进程的  coverage.json 会覆盖掉 主进程的。\r\n\r\n运行 `istanbul report --root ./coverage text-summary json lcov` 便会自动对生成的 coverage-pid.json 文件合并处理，产生最终的覆盖率数据以及覆盖率报告。\r\n\r\n最后将这 2 条命令集成到 Node.js 项目的 package.json 文件中。\r\n\r\n```\r\n\"scripts\": {\r\n    \"test\":\"npm run cov && npm run report\",\r\n    \"report\":\"node --harmony node_modules/.bin/istanbul report --root ./coverage text-summary json lcov\",\r\n    \"cov\": \"node --harmony node_modules/.bin/istanbul cover  --report none --print none --include-pid  ./node_modules/mocha/bin/_mocha -- 'test/**/*.test.js'\"\r\n  }\r\n```\r\n\r\n执行 `npm test`\r\n![主进程和子进程中的所有代码覆盖率都被统计到](http://gtms04.alicdn.com/tps/i4/TB1w8DHKVXXXXa.XXXX.KiBGVXX-1560-430.png)\r\n 可以看到主进程和子进程中的所有代码覆盖率都被统计到了。\r\n \r\n "}}