Is it possible to conditionally load libraries in Lua?

I am creating a script for mpv and in it I load the library mpvas follows:

-- script.lua

local mp = require('mp')

I use the bustedunit test structure to write tests for this, and they are contained in a separate file, for example:

-- script-tests.lua

describe('my script unit tests', function()
    local script = require('script')

    it('...', function()
        assert.is_true(true)
    end)
end)

The problem occurs when I run unit tests, I get the following:

./script.lua:1: module 'mp' not found:No LuaRocks module found for mp

I understand what mpis available when my script is executed in mpv, but not when performing my unit tests. Is there a way to stop this requirewhile doing unit tests? or am I thinking about it wrong?

Decision

In the end, I created a stub mp(trying to use the global flag, as Adam suggested, but that didn't work). There he is:

-- script.lua

local plugin = {}
local mpv_loaded, mp = pcall(require, 'mp')

plugin.mp = mp

---------------------------------------------------------------------
-- Stub MPV library for unit tests
if not mpv_loaded then
    plugin.mp = {}

    function plugin.mp.osd_message(message)
        plugin.mp.message = message
    end

    function plugin.mp.log(level, message)
        -- stub
    end

    function plugin.mp.add_forced_key_binding(...)
        -- stub
    end

    function plugin.mp.remove_key_binding(...)
        -- stub
    end
end

---------------------------------------------------------------------
-- Display message on screen.
function plugin:show_message(message)
    self.mp.osd_message(message)
end

return plugin

 

-- script-tests.lua

describe('my script unit tests', function()
    local plugin = require('script')

    it('...', function()
        message = 'It is better to play than do nothing.'
        plugin:show_message(message)

        assert.is_same(plugin.mp.message, message)
    end)

end)
+4
2

, , , -, :

local mpv_loaded, mp = pcall(function() return require 'mp' end)

if not mpv_loaded then
    -- handle the bad require, in this case 'mp' holds the error message
else
    -- 'mp' contains the lib as it normally would
end
+2

​​ mp.

, unit test _UNITTEST:

-- script-tests.lua
_UNITTEST = true

describe('my script unit tests', function()
    local script = require('script')

    it('...', function()
        assert.is_true(true)
    end)
end)

script:

-- script.lua
local mp = not _UNITTEST and require('mp')

Busted documentation, . , mp, stub.

+3

Source: https://habr.com/ru/post/1678726/


All Articles