• 单元测试

    单元测试

    单元测试(unit testing),是指对软件中的最小可测试单元进行检查和验证。对于单元测试中单元的含义,一般来说,要根据实际情况去判定其具体含义,如 C 语言中单元指一个函数,Java 里单元指一个类,图形化的软件中可以指一个窗口或一个菜单等。总的来说,单元就是人为规定的最小的被测功能模块。单元测试是在软件开发过程中要进行的最低级别的测试活动,软件的独立单元将在与程序的其他部分相隔离的情况下进行测试。

    单元测试的书写、验证,互联网公司几乎都是研发自己完成的,我们要保证代码出手时可交付、符合预期。如果连自己的预期都没达到,后面所有的工作,都将是额外无用功。

    Lua 中我们没有找到比较好的测试库,参考了 Golang、Python 等语言的单元测试书写方法以及调用规则,编写了lua-resty-test测试库,这里给自己的库推广一下,希望这东东也是你们的真爱。

    nginx示例配置

    1. #you do not need the following line if you are using
    2. #the ngx_openresty bundle:
    3. lua_package_path "/path/to/lua-resty-redis/lib/?.lua;;";
    4. server {
    5. location /test {
    6. content_by_lua_file test_case_lua/unit/test_example.lua;
    7. }
    8. }

    test_case_lua/unit/test_example.lua:

    1. local iresty_test = require "resty.iresty_test"
    2. local tb = iresty_test.new({unit_name="example"})
    3. function tb:init( )
    4. self:log("init complete")
    5. end
    6. function tb:test_00001( )
    7. error("invalid input")
    8. end
    9. function tb:atest_00002()
    10. self:log("never be called")
    11. end
    12. function tb:test_00003( )
    13. self:log("ok")
    14. end
    15. -- units test
    16. tb:run()
    • init 里面我们可以完成一些基础、公共变量的初始化,例如特定的 url 等
    • test_***** 函数中添加我们的单元测试代码
    • 搞定测试代码,它即是单元测试,也是成压力测试

    输出日志:

    1. TIME Name Log
    2. 0.000 [example] unit test start
    3. 0.000 [example] init complete
    4. 0.000 \_[test_00001] fail ...de/nginx/main_server/test_case_lua/unit/test_example.lua:9: invalid input
    5. 0.000 \_[test_00003] ok
    6. 0.000 \_[test_00003] PASS
    7. 0.000 [example] unit test complete