File: testlua.cpp

package info (click to toggle)
openmw 0.50.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 37,076 kB
  • sloc: cpp: 380,958; xml: 2,192; sh: 1,449; python: 911; makefile: 26; javascript: 5
file content (265 lines) | stat: -rw-r--r-- 10,111 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
#include <gmock/gmock.h>
#include <gtest/gtest.h>

#include <components/lua/luastate.hpp>
#include <components/testing/expecterror.hpp>
#include <components/testing/util.hpp>

namespace
{
    using namespace testing;

    constexpr VFS::Path::NormalizedView counterPath("aaa/counter.lua");

    TestingOpenMW::VFSTestFile counterFile(R"X(
x = 42
return {
    get = function() return x end,
    inc = function(v) x = x + v end
}
)X");

    constexpr VFS::Path::NormalizedView invalidPath("invalid.lua");

    TestingOpenMW::VFSTestFile invalidScriptFile("Invalid script");

    constexpr VFS::Path::NormalizedView testsPath("bbb/tests.lua");

    TestingOpenMW::VFSTestFile testsFile(R"X(
return {
    -- should work
    sin = function(x) return math.sin(x) end,
    requireMathSin = function(x) return require('math').sin(x) end,
    useCounter = function()
        local counter = require('aaa.counter')
        counter.inc(1)
        return counter.get()
    end,
    callRawset = function()
        t = {a = 1, b = 2}
        rawset(t, 'b', 3)
        return t.b
    end,
    print = print,

    -- should throw an error
    incorrectRequire = function() require('counter') end,
    modifySystemLib = function() math.sin = 5 end,
    modifySystemLib2 = function() math.__index.sin = 5 end,
    rawsetSystemLib = function() rawset(math, 'sin', 5) end,
    callLoadstring = function() loadstring('print(1)') end,
    setSqr = function() require('sqrlib').sqr = math.sin end,
    setOmwName = function() require('openmw').name = 'abc' end,

    -- should work if API is registered
    sqr = function(x) return require('sqrlib').sqr(x) end,
    apiName = function() return require('test.api').name end
}
)X");

    constexpr VFS::Path::NormalizedView metaIndexErrorPath("metaindexerror.lua");

    TestingOpenMW::VFSTestFile metaIndexErrorFile(
        "return setmetatable({}, { __index = function(t, key) error('meta index error') end })");

    std::string genBigScript()
    {
        std::stringstream buf;
        buf << "return function()\n";
        buf << "  x = {}\n";
        for (int i = 0; i < 1000; ++i)
            buf << "  x[" << i * 2 << "] = " << i << "\n";
        buf << "  return x\n";
        buf << "end\n";
        return buf.str();
    }

    constexpr VFS::Path::NormalizedView bigPath("big.lua");

    TestingOpenMW::VFSTestFile bigScriptFile(genBigScript());

    constexpr VFS::Path::NormalizedView requireBigPath("requirebig.lua");

    TestingOpenMW::VFSTestFile requireBigScriptFile("local x = require('big') ; return {x}");

    struct LuaStateTest : Test
    {
        std::unique_ptr<VFS::Manager> mVFS = TestingOpenMW::createTestVFS({
            { counterPath, &counterFile },
            { testsPath, &testsFile },
            { invalidPath, &invalidScriptFile },
            { bigPath, &bigScriptFile },
            { requireBigPath, &requireBigScriptFile },
            { metaIndexErrorPath, &metaIndexErrorFile },
        });

        LuaUtil::ScriptsConfiguration mCfg;
        LuaUtil::LuaState mLua{ mVFS.get(), &mCfg };
    };

    TEST_F(LuaStateTest, Sandbox)
    {
        const VFS::Path::Normalized path(counterPath);
        sol::table script1 = mLua.runInNewSandbox(path);

        EXPECT_EQ(LuaUtil::call(script1["get"]).get<int>(), 42);
        LuaUtil::call(script1["inc"], 3);
        EXPECT_EQ(LuaUtil::call(script1["get"]).get<int>(), 45);

        sol::table script2 = mLua.runInNewSandbox(path);
        EXPECT_EQ(LuaUtil::call(script2["get"]).get<int>(), 42);
        LuaUtil::call(script2["inc"], 1);
        EXPECT_EQ(LuaUtil::call(script2["get"]).get<int>(), 43);

        EXPECT_EQ(LuaUtil::call(script1["get"]).get<int>(), 45);
    }

    TEST_F(LuaStateTest, ToString)
    {
        EXPECT_EQ(LuaUtil::toString(sol::make_object(mLua.unsafeState(), 3.14)), "3.14");
        EXPECT_EQ(LuaUtil::toString(sol::make_object(mLua.unsafeState(), true)), "true");
        EXPECT_EQ(LuaUtil::toString(sol::nil), "nil");
        EXPECT_EQ(LuaUtil::toString(sol::make_object(mLua.unsafeState(), "something")), "\"something\"");
    }

    TEST_F(LuaStateTest, Cast)
    {
        EXPECT_EQ(LuaUtil::cast<int>(sol::make_object(mLua.unsafeState(), 3.14)), 3);
        EXPECT_ERROR(LuaUtil::cast<int>(sol::make_object(mLua.unsafeState(), "3.14")),
            "Value \"\"3.14\"\" can not be casted to int");
        EXPECT_ERROR(LuaUtil::cast<std::string_view>(sol::make_object(mLua.unsafeState(), sol::nil)),
            "Value \"nil\" can not be casted to string");
        EXPECT_ERROR(LuaUtil::cast<std::string>(sol::make_object(mLua.unsafeState(), sol::nil)),
            "Value \"nil\" can not be casted to string");
        EXPECT_ERROR(LuaUtil::cast<sol::table>(sol::make_object(mLua.unsafeState(), sol::nil)),
            "Value \"nil\" can not be casted to sol::table");
        EXPECT_ERROR(LuaUtil::cast<sol::function>(sol::make_object(mLua.unsafeState(), "3.14")),
            "Value \"\"3.14\"\" can not be casted to sol::function");
        EXPECT_ERROR(LuaUtil::cast<sol::protected_function>(sol::make_object(mLua.unsafeState(), "3.14")),
            "Value \"\"3.14\"\" can not be casted to sol::function");
    }

    TEST_F(LuaStateTest, ErrorHandling)
    {
        const VFS::Path::Normalized path("invalid.lua");
        EXPECT_ERROR(mLua.runInNewSandbox(path), "[string \"invalid.lua\"]:1:");
    }

    TEST_F(LuaStateTest, CustomRequire)
    {
        const VFS::Path::Normalized path("bbb/tests.lua");
        sol::table script = mLua.runInNewSandbox(path);

        EXPECT_FLOAT_EQ(
            LuaUtil::call(script["sin"], 1).get<float>(), -LuaUtil::call(script["requireMathSin"], -1).get<float>());

        EXPECT_EQ(LuaUtil::call(script["useCounter"]).get<int>(), 43);
        EXPECT_EQ(LuaUtil::call(script["useCounter"]).get<int>(), 44);
        {
            sol::table script2 = mLua.runInNewSandbox(path);
            EXPECT_EQ(LuaUtil::call(script2["useCounter"]).get<int>(), 43);
        }
        EXPECT_EQ(LuaUtil::call(script["useCounter"]).get<int>(), 45);

        EXPECT_ERROR(LuaUtil::call(script["incorrectRequire"]), "module not found: counter");
    }

    TEST_F(LuaStateTest, ReadOnly)
    {
        const VFS::Path::Normalized path("bbb/tests.lua");
        sol::table script = mLua.runInNewSandbox(path);

        // rawset itself is allowed
        EXPECT_EQ(LuaUtil::call(script["callRawset"]).get<int>(), 3);

        // but read-only object can not be modified even with rawset
        EXPECT_ERROR(
            LuaUtil::call(script["rawsetSystemLib"]), "bad argument #1 to 'rawset' (table expected, got userdata)");
        EXPECT_ERROR(LuaUtil::call(script["modifySystemLib"]), "a userdata value");
        EXPECT_ERROR(LuaUtil::call(script["modifySystemLib2"]), "a nil value");

        EXPECT_EQ(LuaUtil::getMutableFromReadOnly(LuaUtil::makeReadOnly(script)), script);
    }

    TEST_F(LuaStateTest, Print)
    {
        const VFS::Path::Normalized path("bbb/tests.lua");
        {
            sol::table script = mLua.runInNewSandbox(path);
            testing::internal::CaptureStdout();
            LuaUtil::call(script["print"], 1, 2, 3);
            std::string output = testing::internal::GetCapturedStdout();
            EXPECT_EQ(output, "unnamed:\t1\t2\t3\n");
        }
        {
            sol::table script = mLua.runInNewSandbox(path, "prefix");
            testing::internal::CaptureStdout();
            LuaUtil::call(script["print"]); // print with no arguments
            std::string output = testing::internal::GetCapturedStdout();
            EXPECT_EQ(output, "prefix:\n");
        }
    }

    TEST_F(LuaStateTest, UnsafeFunction)
    {
        const VFS::Path::Normalized path("bbb/tests.lua");
        sol::table script = mLua.runInNewSandbox(path);
        EXPECT_ERROR(LuaUtil::call(script["callLoadstring"]), "a nil value");
    }

    TEST_F(LuaStateTest, ProvideAPI)
    {
        LuaUtil::LuaState lua(mVFS.get(), &mCfg);
        lua.protectedCall([&](LuaUtil::LuaView& view) {
            sol::table api1 = LuaUtil::makeReadOnly(view.sol().create_table_with("name", "api1"));
            sol::table api2 = LuaUtil::makeReadOnly(view.sol().create_table_with("name", "api2"));

            const VFS::Path::Normalized path("bbb/tests.lua");

            sol::table script1 = lua.runInNewSandbox(path, "", { { "test.api", api1 } });

            lua.addCommonPackage("sqrlib", view.sol().create_table_with("sqr", [](int x) { return x * x; }));

            sol::table script2 = lua.runInNewSandbox(path, "", { { "test.api", api2 } });

            EXPECT_ERROR(LuaUtil::call(script1["sqr"], 3), "module not found: sqrlib");
            EXPECT_EQ(LuaUtil::call(script2["sqr"], 3).get<int>(), 9);

            EXPECT_EQ(LuaUtil::call(script1["apiName"]).get<std::string>(), "api1");
            EXPECT_EQ(LuaUtil::call(script2["apiName"]).get<std::string>(), "api2");
        });
    }

    TEST_F(LuaStateTest, GetLuaVersion)
    {
        EXPECT_THAT(LuaUtil::getLuaVersion(), HasSubstr("Lua"));
    }

    TEST_F(LuaStateTest, RemovedScriptsGarbageCollecting)
    {
        auto getMem = [&] {
            for (int i = 0; i < 5; ++i)
                lua_gc(mLua.unsafeState(), LUA_GCCOLLECT, 0);
            return mLua.getTotalMemoryUsage();
        };
        int64_t memWithScript;
        const VFS::Path::Normalized path("requireBig.lua");
        {
            sol::object s = mLua.runInNewSandbox(path);
            memWithScript = getMem();
        }
        for (int i = 0; i < 100; ++i) // run many times to make small memory leaks visible
            mLua.runInNewSandbox(path);
        int64_t memWithoutScript = getMem();
        // At this moment all instances of the script should be garbage-collected.
        EXPECT_LT(memWithoutScript, memWithScript);
    }

    TEST_F(LuaStateTest, SafeIndexMetamethod)
    {
        const VFS::Path::Normalized path("metaIndexError.lua");
        sol::table t = mLua.runInNewSandbox(path);
        // without safe get we crash here
        EXPECT_ERROR(LuaUtil::safeGet(t, "any key"), "meta index error");
    }
}