2017-09-22 94 views
3

我想從單個文件Lua腳本中測試函數,比如script.lua。該腳本看起來像如下:如何測試單個文件Lua腳本中的函數?

-- some fields from gvsp dissector which shall be post processed in custom dissector 
gvsp_field0_f = Field.new("gvsp.<field0-name>") 
gvsp_field1_f = Field.new("gvsp.<field1-name>") 

-- custom protocol declaration 
custom_protocol = Proto("custom","Custom Postdissector") 

-- custom protocol field declarations 
field0_f = ProtoField.string("custom.<field0-name>","Custom Field 0") 
field1_f = ProtoField.string("custom.<field1-name>","Custom Field 1") 

-- register custom protocol as postdissector 
register_postdissector(custom_protocol) 

function custom_protocol.dissector(buffer,pinfo,tree) 
    -- local field values of "pre" dissector which are analyzed 
    local gvsp_field0_value = gvsp_field0_f() 
    local gvsp_field1_value = gvsp_field1_f() 

    -- functions which shell be unit tested 
    function0(...) 
    function1(...) 
end 

function0(...) 
    -- implementation 
end 

function1(...) 
    -- implementation 
end 

比方說,我不想從腳本文件中的函數分成單獨的模塊文件(這可能會使事情變得更容易)。如何定義script.lua文件中的script.lua或單獨的test_script.lua文件中定義的測試功能(最好是luaunit,因爲容易集成,但其他工具也可以)?

+0

這取決於_how_你定義的東西lot_。你使用'local'(這會讓事情變得更難)還是你使用「local''ENV'ironments」(更容易)?你的代碼結構如何?請添加一個如何定義函數的小代碼示例(不一定是實際的代碼,只是與您定義的東西相匹配的虛函數)。目前,沒有足夠的信息來給出有意義的信息答案。 – nobody

+0

該腳本非常類似於https://wiki.wireshark.org/Lua/Dissectors#postdissectors中的解析程序,在文件末尾定義了用於協議'dissector'函數的'local'函數。但我不堅持這種結構。 – thinwybk

回答

0

要啓用獨立的腳本和單元測試執行,至少需要3個文件(在本例中爲4,因爲單個測試框架luaunit由單個文件組成)集成到項目目錄中。對於這個例子,所有文件都駐留在同一個目錄中。腳本script.lua可能沒有定義任何函數,但必須從模塊module.lua中導入所需的所有函數。

-- script imports module functions 
module = require('module') 

-- ... and uses it to print the result of the addition function 
result = module.addtwo(1,1) 
print(result) 

module.lua實現accoring到Lua module skeleton它的功能將自動通過其他腳本文件或模塊註冊的進口。

-- capture the name searched for by require 
local NAME=... 

-- table for our functions 
local M = { } 

-- A typical local function that is also published in the 
-- module table. 
local function addtwo(a,b) return a+b end 
M.addtwo = addtwo 

-- Shorthand form is less typing and doesn't use a local variable 
function M.subtwo(x) return x-2 end 

return M 

test_module.lua包含用於模塊的功能和進口luaunit.lua(單元測試框架),用於其執行單元測試。 test_module.lua包含以下內容。

luaunit = require('luaunit') 
script = require('module') 

function testAddPositive() 
    luaunit.assertEquals(module.addtwo(1,1),2) 
end 

os.exit(luaunit.LuaUnit.run()) 

如果運行通過執行lua test_module.lua測試是從腳本功能分開進行測試。

. 
Ran 1 tests in 0.000 seconds, 1 success, 0 failures 
OK 

該腳本照常與輸出2執行與lua script.lua

2

簡單的回答:你不能!

幾年前,我已經向Lua團隊詢問了這個問題,因爲沒有明顯的方式讓腳本知道它是否是運行或包含的主腳本(例如,'require')。

在可預見的將來,似乎沒有興趣添加這樣的功能!

+0

好的。那麼在單獨的'test_script.lua'中執行測試呢? – thinwybk

+0

我不確定我是否理解。那個怎麼樣?只需「要求」文件即可從測試文件中進行測試,並根據需要調用其公共功能。 – tonypdmtr

+0

在下面的例子中,除了單元測試之外,還會執行腳本主要功能。我不希望腳本主要功能在單元測試執行期間執行。 – thinwybk

相關問題