2022.2.25
到目前为止,我们已经熟悉了智能合约的开发、编译、部署、测试,而在实 际工作中,把这些过程串起来才能算作是真正意义上的工作流。比如修改了合约 代码需要重新运行测试,但是重新运行测试之前需要重新编译,而部署的过程也 是类似的,每次部署的都要是最新的合约代码。通过 npm script 机制,我们可以把智能合约的工作流串起来,让能自动化的尽可能自动化,在 package.json 中作如下修改:
"scripts": {
"compile": "node scripts/compile.js",
"pretest": "npm run compile",
"test": "mocha tests/",
"predeploy": "npm run compile",
"deploy": "node scripts/deploy.js"
},
上面的改动中,我们为项目增加了 3 条命令:compile、test、deploy,其中 pretest、predeploy 是利用了 npm script 的生命周期机制,把我们的 compile、test、deploy 串起来。
接下来我们可以使用 npm run test
运行测试,结果如下:
kimshan@MacBook-Pro contract_workflow % npm run test
> contract_workflow@1.0.0 pretest /Users/kimshan/workplace/blockchain/contract_workflow
> npm run compile
> contract_workflow@1.0.0 compile /Users/kimshan/workplace/blockchain/contract_workflow
> node scripts/compile.js
save compiled contract Car to /Users/kimshan/workplace/blockchain/contract_workflow/compiled/Car.json
> contract_workflow@1.0.0 test /Users/kimshan/workplace/blockchain/contract_workflow
> mocha tests/
contract
合约部署账户: 0xe0104E0DD74463FF989b4eba3273689A88a28f0e
合约部署成功: 0x4D71163996B0F9baD8298Bcc4bCe7DbEa57489a6
✔ deployed contract
合约部署账户: 0xe0104E0DD74463FF989b4eba3273689A88a28f0e
合约部署成功: 0xD87B515BEB7081A5f6A9307a7cCfDF6f5aa8AD2D
✔ should has initial brand
合约部署账户: 0xe0104E0DD74463FF989b4eba3273689A88a28f0e
合约部署成功: 0x113C02D05E3952c657343c1546B9d42D17C17F22
✔ can change the brand (76ms)
#sum.js
#sum()
✔ sum() should return 0
✔ sum(1) should return 1
✔ sum(1, 2) should return 3
✔ sum(1, 2, 3) should return 6
7 passing (389ms)
kimshan@MacBook-Pro contract_workflow % npm run deploy
> contract_workflow@1.0.0 predeploy /Users/kimshan/workplace/blockchain/contract_workflow
> npm run compile
> contract_workflow@1.0.0 compile /Users/kimshan/workplace/blockchain/contract_workflow
> node scripts/compile.js
save compiled contract Car to /Users/kimshan/workplace/blockchain/contract_workflow/compiled/Car.json
> contract_workflow@1.0.0 deploy /Users/kimshan/workplace/blockchain/contract_workflow
> node scripts/deploy.js
部署合约账户: 0x31b706f614958cee40344C5c534FA2f8445477d7
合约部署耗时: 191.231ms
合约部署成功: 0xA77F303Ec324E1B2Bd8904406716Ce1Be70B1627