-
Notifications
You must be signed in to change notification settings - Fork 0
/
EnvCheck.luau
1274 lines (1084 loc) · 45.9 KB
/
EnvCheck.luau
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local passes, fails, undefined, running = 0, 0, 0, 0
local Console = RBXConsole and RBXConsole.new and RBXConsole.new or nil
local function getGlobal(path)
local value = getfenv(0)
while value ~= nil and path ~= "" do
local name, nextValue = string.match(path, "^([^.]+)%.?(.*)$")
value = value[name]
path = nextValue
end
return value
end
local function test(name, aliases, callback)
running += 1
if Console then
Console:Info(name) -- debug which function thats going to get tested
end
task.spawn(function()
if not callback then
print(`⏺️ {name}`)
elseif not getGlobal(name) then
fails += 1
warn(`⛔ {name}`)
else
local success, message = pcall(callback)
if success then
passes += 1
print(`✅ {name}{message and ` • {message}` or ""}`)
else
fails += 1
warn(`⛔ {name} failed: {message}`)
end
end
local undefinedAliases = {}
for _, alias in next, aliases do
if getGlobal(alias) == nil then
undefinedAliases[#undefinedAliases + 1] = alias
end
end
if #undefinedAliases > 0 then
undefined += 1
warn(`⚠️ {table.concat(undefinedAliases, ", ")}`)
end
running -= 1
end)
end
-- Header and summary
print("\n")
print("UNS Environment Check")
print("✅ - Pass, ⛔ - Fail, ⏺️ - No test, ⚠️ - Missing aliases\n")
task.defer(function()
repeat task.wait() until running == 0
local total = passes + fails
local rate = math.round(passes / total * 100000) / 1000
local outOf = `{passes} out of {total}`
print("\n")
print("UNS Summary")
print(`✅ Tested with a {rate}% success rate ({outOf})`)
print(`⛔ {fails} tests failed`)
print(`⚠️ {undefined} globals are missing aliases`)
end)
-- Cache Library
test("Cache", {})
test("Cache.Invalidate", {}, function() -- Invalidates Object within the instance cache.
local container = Instance.new("Folder")
local part = Instance.new("Part", container)
Cache.Invalidate(container:FindFirstChild("Part"))
assert(part ~= container:FindFirstChild("Part"), "Reference 'part' could not be invalidated")
end)
test("Cache.IsCached", {}, function() -- Returns true if Object is cached.
local part = Instance.new("Part")
assert(Cache.IsCached(part), "Part should be cached")
Cache.Invalidate(part)
assert(not Cache.IsCached(part), "Part shouldn't be cached")
end)
test("Cache.Replace", {}, function() -- Replaces Object with NewObject within the instance cache.
local part = Instance.new("Part")
local fire = Instance.new("Fire")
Cache.Replace(part, fire)
assert(part ~= fire, "Part was not replaced with Fire")
end)
test("Cache.Clone", {}, function() -- Clones Object or Function and returns it.
local part = Instance.new("Part")
local function test()
return "success"
end
local copy = Cache.Clone(test)
local clone = Cache.Clone(part)
assert(part ~= clone, "The cloned instance shouldn't be equal to original")
assert(not ({[part] = false})[clone], "The cloned instance shouldn't be equal to original")
clone.Name = "Test"
assert(part.Name == "Test", "The cloned instance should have updated the original")
assert(test() == copy(), "The cloned function should return the same value as the original, when called")
assert(test ~= copy, "The cloned function shouldn't be equal to the original")
end)
test("Cache.Compare", {}, function() -- Compare cloned instance with cached instance
local part = Instance.new("Part")
local clone = Cache.Clone(part)
assert(part ~= clone, "Clone shouldn't be equal to original")
assert(Cache.Compare(part, clone), "Clone should be equal to original when using Cache.Compare()")
end)
-- Closures
local function shallowEqual(t1, t2)
if t1 == t2 then
return true
end
local UNIQUE_TYPES = {
["function"] = true,
["table"] = true,
["userdata"] = true,
["thread"] = true,
}
for k, v in next, t1 do
if UNIQUE_TYPES[type(v)] then
if type(t2[k]) ~= type(v) then
return false
end
elseif t2[k] ~= v then
return false
end
end
for k, v in next, t2 do
if UNIQUE_TYPES[type(v)] then
if type(t2[k]) ~= type(v) then
return false
end
elseif t1[k] ~= v then
return false
end
end
return true
end
test("checkcaller", {}, function()
assert(checkcaller(), "Main scope should return true")
end)
test("getcallingscript", {}, function()
assert(getcallingscript() == script, "Main scope should return the same script as the global")
end)
test("getscriptclosure", {"getscriptfunction"}, function()
local module = game:GetService("CoreGui").RobloxGui.Modules.Common.Constants
local constants = getrenv().require(module)
local generated = getscriptclosure(module)()
assert(constants ~= generated, "Generated module shouldn't match the original")
assert(shallowEqual(constants, generated), "Generated constant table should be shallow equal to the original")
end)
test("hookfunction", {"replaceclosure"}, function()
local function test()
return true
end
local ref = hookfunction(test, function()
return false
end)
assert(test() == false, "Function should return false")
assert(ref() == true, "Original function should return true")
assert(test ~= ref, "Original function shouldn't be same as the reference")
end)
test("isfunctionhooked", {}, function()
local function test()
return true
end
hookfunction(test, function()
return false
end)
assert(isfunctionhooked(test), "Function should be marked as hooked")
end)
test("restorefunction", {}, function()
local oldVersion = version
version = function(...)
end
task.defer(function()
getfenv().version = oldVersion
end)
assert(version ~= oldVersion, "Tampering?")
restorefunction(version)
assert(version == oldVersion, "Did not restore the function to its original state")
end)
test("hooksignal", {"replacecon"}, function()
local part, changedPropNewName = Instance.new("Part")
part.Changed:Connect(function(prop)
changedPropNewName = prop
end)
hooksignal(part.Changed, function(info, prop)
return true, "Hooked"
end)
part.Name = "NewName"
assert(changedPropNewName == "Hooked", "Signal should be hook")
end)
test("issignalhooked", {}, function()
local part, changedPropNewName = Instance.new("Part")
part.Changed:Connect(function(prop)
changedPropNewName = prop
end)
hooksignal(part.Changed, function(info, prop)
return true, "Hooked"
end)
part.Name = "NewName"
assert(changedPropNewName == "Hooked", "Signal should be hook")
assert(issignalhooked(part.Changed), "Signal should be marked as hooked")
end)
test("restoresignal", {}, function()
local part, changedPropNewName = Instance.new("Part")
part.Changed:Connect(function(prop)
changedPropNewName = prop
end)
hooksignal(part.Changed, function(info, prop)
return true, "Hooked"
end)
part.Name = "NewName"
assert(changedPropNewName == "Hooked", "Signal should be hook")
assert(issignalhooked(part.Changed), "Signal should be marked as hooked")
restoresignal(part.Changed)
part.Name = "NewName2"
assert(changedPropNewName ~= "Hooked", "Signal shouldn't be hook")
assert(not issignalhooked(part.Changed), "Signal shouldn't be marked as hooked")
end)
test("iscclosure", {"iscc"}, function()
assert(iscclosure(print) == true, "Function 'print' should be a C closure")
assert(iscclosure(function() end) == false, "Executor function shouldn't be a C closure")
end)
test("islclosure", {"islc"}, function()
assert(islclosure(print) == false, "Function 'print' shouldn't be a Lua closure")
assert(islclosure(function() end) == true, "Executor function should be a Lua closure")
end)
test("isexecutorclosure", {"checkclosure", "isourclosure"}, function()
assert(isexecutorclosure(isexecutorclosure) == true, "Did not return true for an executor global")
assert(isexecutorclosure(newcclosure(function() end)) == true, "Did not return true for an executor C closure")
assert(isexecutorclosure(function() end) == true, "Did not return true for an executor Luau closure")
assert(isexecutorclosure(print) == false, "Did not return false for a Roblox global")
end)
test("loadstring", {}, function()
local bytecode = "\003\002\005print\vHello World\001\002\000\000\001\006A\000\000\000\f\000\001\000\000\000\000@\005\001\002\000\021\000\002\001\022\000\001\000\003\003\001\004\000\000\000@\003\002\000\001\000\001\024\000\000\000\000\000\001\001\000\000\000\000\000" -- luau version of print("Hello World")
local func = loadstring(bytecode)
assert(type(func) ~= "function", "Luau bytecode shouldn't be loadable!")
assert(assert(loadstring("return ... + 1"))(1) == 2, "Failed to do simple math")
assert(type(select(2, loadstring("f"))) == "string", "Loadstring did not return anything for a compiler error")
end)
test("newcclosure", {}, function()
local cfuncName = "UNS_CClosure_Test"
local function test()
return true
end
local testC = newcclosure(test, cfuncName)
assert(test() == testC(), "New C closure should return the same value as the original")
assert(test ~= testC, "New C closure shouldn't be same as the original")
assert(iscclosure(testC), "New C closure should be a C closure")
assert(debug.getinfo(testC).name == cfuncName, "New c closure's name is not the same as defined in Argument #2")
end)
-- Console
test("RBXConsole", {}, function()
local console = RBXConsole.new("UNS Testing")
local notes = {}
local function testConsole(Index: string, Type: string, aliases: {[number]: string}, Callback, OnFailNote)
if Type == "Method" then
local HasFunction, Function = pcall(function()
return console[Index]
end)
if HasFunction and Function then
if Callback then
local success, message = pcall(Callback, Function)
if not success then
notes[#notes + 1] = OnFailNote or message
end
end
else
notes[#notes + 1] = `Missing Method '{Index}'`
end
for i,alias in next, aliases do
local HasAlias, AliasFunc = pcall(function()
return console[alias]
end)
if not HasAlias or not AliasFunc then
notes[#notes + 1] = `Missing Alias '{alias}' of Method '{Index}'`
end
end
elseif Type == "Property" then
local HasProperty = pcall(function()
return console[Index]
end)
if HasProperty then
if Callback then
local success, message = pcall(Callback)
if not success then
notes[#notes + 1] = OnFailNote or message
end
end
else
notes[#notes + 1] = `Missing Property '{Index}'`
end
for i,alias in next, aliases do
local HasAlias = pcall(function()
return console[alias]
end)
if not HasAlias then
notes[#notes + 1] = `Missing Alias '{alias}' of Property '{Index}'`
end
end
end
end
testConsole("Content", "Property", {}, function()
assert(console.Content == "", "Console is not empty at the beginning")
end)
testConsole("Title", "Property", {}, function()
assert(console.Title == "UNS Testing", "Title is not the same as in the previously set function Argument #1")
console.Title = "UNS Testing 2"
assert(console.Title == "UNS Testing 2", "Title did not update after changing it")
end)
testConsole("Print", "Method", {}, function(Print)
Print(console, "This is a print")
assert(console.Content:find("[PRINT] This is a print\n"), "Did not find print message")
end)
testConsole("Info", "Method", {}, function(Info)
Info(console, "This is a info")
assert(console.Content:find("[INFO] This is a info\n"), "Did not find info message")
end)
testConsole("Error", "Method", {}, function(Error)
Error(console, "This is an error")
assert(console.Content:find("[ERROR] This is an error\n"), "Did not find error message")
end)
testConsole("Clear", "Method", {}, function(Clear)
local oldContent = console.Content
Clear(console)
assert(console.Content ~= oldContent, "Did not clear the console")
end)
testConsole("Destroy", "Method", {}, function(Destroy)
Destroy(console)
local printed = pcall(function()
Console:Print("Hey! you shouldn't see this!")
end)
assert(not printed, "Still printed after destroying the console")
end)
testConsole("Destroyed", "Property", {}, function()
assert(console.Destroyed, "Property 'Destroyed' is not marked as true, even tho the console is destroyed")
end)
return #notes ~= 0 and table.concat(notes, ", ") or nil
end)
-- Crypt Library
test("Crypt.Base64.Encode", {}, function() -- Base64 encodes input.
assert(Crypt.Base64.Encode("test") == "dGVzdA==", "Base64 encoding failed")
end)
test("Crypt.Base64.Decode", {}, function() -- Base64 decodes input.
assert(Crypt.Base64.Decode("dGVzdA==") == "test", "Base64 decoding failed")
end)
test("Crypt.Encrypt", {}, function() -- Encrypts data with key, and includes additional_data if it is passed.
local key = Crypt.GenerateKey()
local encrypted, iv = Crypt.Encrypt("test", key, nil, "CBC")
assert(iv, "Crypt.Encrypt should return an IV")
local decrypted = Crypt.Decrypt(encrypted, key, iv, "CBC")
assert(decrypted == "test", "Failed to decrypt raw string from encrypted data")
end)
test("Crypt.Decrypt", {}, function() -- Decrypts ciphertext with key. The data (along with additional_data if it is passed) is also authenticated via a MAC before being returned.
local key, iv = Crypt.GenerateKey(), Crypt.GenerateKey()
local encrypted = Crypt.Encrypt("test", key, iv, "CBC")
local decrypted = Crypt.Decrypt(encrypted, key, iv, "CBC")
assert(decrypted == "test", "Failed to decrypt raw string from encrypted data")
end)
test("Crypt.GenerateBytes", {}, function() -- Generates a random string with size (cannot be negative or exceed 1024).
local size = math.random(10, 100)
local bytes = Crypt.GenerateBytes(size)
assert(#Crypt.Base64.Decode(bytes) == size, `The decoded result should be {size} bytes long (got {#Crypt.Base64.Decode(bytes)} decoded, {#bytes} raw)`)
end)
test("Crypt.GenerateKey", {}, function() -- Generates a key that is exactly 32 Bytes Long
assert(#Crypt.Base64.Decode(Crypt.GenerateKey()) == 32, "Crypt.GenerateKey should be 32 bytes long when decoded")
end)
test("Crypt.Hash", {}, function() -- Hashes data with the algorithm. Optionally, you can pass key to create a 'keyed' hash, for which the hash will never be the same for different keys.
local notes = {}
local algorithms = {
["sha1"] = "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3",
["sha224"] = "90a3ed9e32b2aaf4c61c410eb925426119e1a9dc53d4286ade99a809",
["sha256"] = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
["sha384"] = "768412320f7b0aa5812fce428dc4706b3cae50e02a64caa16a782249bfe8efc4b7ef1ccb126255d196047dfedf17a0a9",
["sha512"] = "ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff",
["sha3-224"] = "3797bf0afbbfca4a7bbba7602a2b552746876517a7f9b7ce2db0ae7b",
["sha3-256"] = "36f028580bb02cc8272a9a020f4200e346e276ae664e45ee80745574e2f5ab80",
["sha3-384"] = "e516dabb23b6e30026863543282780a3ae0dccf05551cf0295178d7ff0f1b41eecb9db3ff219007c4e097260d58621bd",
["sha3-512"] = "9ece086e9bac491fac5c1d1046ca11d737b92a2b2ebd93f005d7b710110c0a678288166e7fbe796883a4f2e9b3ca9f484f521d0ce464345cc1aec96779149c14",
["md5"] = "098f6bcd4621d373cade4e832627b4f6",
["halfmd5"] = "098f6bcd4621d373",
["doublemd5"] = "fb469d7ef430b0baf0cab6c436e70375",
["ripemd160"] = "5e52fee47e6b070565f74372468cdc699de89107",
["ripemd256"] = "fe0289110d07daeee9d9500e14c57787d9083f6ba10e6bcb256f86bb4fe7b981",
["ripemd320"] = "3b0a2e841e589cf583634a5dd265d2b5d497c4cc44b241e34e0f62d03e98c1b9dc72970b9bc20eb5",
["keccak-224"] = "3be30a9ff64f34a5861116c5198987ad780165f8366e67aff4760b5e",
["keccak-256"] = "9c22ff5f21f0b81b113e63f7db6da94fedef11b2119b4088b89664fb9a3cb658",
["keccak-384"] = "53d0ba137307d4c2f9b6674c83edbd58b70c0f4340133ed0adc6fba1d2478a6a03b7788229e775d2de8ae8c0759d0527",
["keccak-512"] = "1e2e9fc2002b002d75198b7503210c05a1baac4560916a3c6d93bcce3a50d7f00fd395bf1647b9abb8d1afcc9c76c289b0c9383ba386a956da4b38934417789e",
["shake128"] = "d3b0aa9cd8b7255622cebc631e867d4093d6f6010191a53973c45fec9b07c774",
["shake256"] = "b54ff7255705a71ee2925e4a3e30e41aed489a579d5595e0df13e32e1e4dd202a7c7f68b31d6418d9845eb4d757adda6ab189e1bb340db818e5b3bc725d992fa",
["blake2b"] = "a71079d42853dea26e453004338670a53814b78137ffbed07603a41d76a483aa9bc33b582f77d30a65e6f29a896c0411f38312e1d66e0bf16386c86a89bea572"
}
for algorithm, hashed_value in next, algorithms do
local hash = Crypt.Hash("test", algorithm)
if hash ~= hashed_value then
notes[#notes + 1] = `Crypt.Hash on algorithm '{algorithm}' returned the wrong hash`
end
end
return #notes ~= 0 and table.concat(notes, ", ") or nil
end)
-- debug Library
test("debug.setmetatable", {"setrawmetatable"}, function() -- sets a userdata's or table's metatable, ignoring the __metatable metamethod
local object = setmetatable({}, { __index = function() return false end, __metatable = "Locked!" })
local objectReturned = debug.setmetatable(object, { __index = function() return true end })
assert(object, "Did not return the original object")
assert(object.test == true, "Failed to change the metatable")
if objectReturned then
return objectReturned == object and "Returned the original object" or "Did not return the original object"
end
return
end)
test("debug.getmetatable", {"getrawmetatable"}, function() -- gets a userdata's or table's metatable, ignoring the __metatable metamethod
local metatable = { __metatable = "Locked!" }
local object = setmetatable({}, metatable)
assert(debug.getmetatable(object) == metatable, "Did not return the metatable")
end)
test("debug.getconstant", {"getconstant"}, function() -- Returns the constant at index idx in function fi or level fi.
local function test()
print("Hello, world!")
end
assert(debug.getconstant(test, 1) == "print", "First constant must be print")
assert(debug.getconstant(test, 2) == nil, "Second constant must be nil")
assert(debug.getconstant(test, 3) == "Hello, world!", "Third constant must be 'Hello, world!'")
end)
test("debug.getconstants", {"getconstants"}, function() -- Retrieve the constants in function fi or at level fi.
local function test()
local num = 5000 .. 50000
print("Hello, world!", num, warn)
end
local constants = debug.getconstants(test)
assert(constants[1] == 50000, "First constant must be 50000")
assert(constants[2] == "print", "Second constant must be print")
assert(constants[3] == nil, "Third constant must be nil")
assert(constants[4] == "Hello, world!", "Fourth constant must be 'Hello, world!'")
assert(constants[5] == "warn", "Fifth constant must be warn")
end)
test("debug.setconstant", {"setconstant"}, function() -- Set constant idx to tuple value at level or function fi.
local function test()
return "fail"
end
debug.setconstant(test, 1, "success")
assert(test() == "success", "debug.setconstant did not set the first constant")
end)
test("debug.getinfo", {"getinfo"}, function() -- Returns a table with information about the function or stack level f. The what argument can be used to select specific pieces of information that will go in the returned table.
local types = {
source = "string",
short_src = "string",
func = "function",
what = "string",
currentline = "number",
name = "string",
nups = "number",
numparams = "number",
is_vararg = "number",
}
local function test(...)
print(...)
end
local info = debug.getinfo(test)
for k, v in next, types do
assert(info[k] ~= nil, `Did not return a table with a '{k}' field`)
assert(type(info[k]) == v, `Did not return a table with {k} as a {v} (got {type(info[k])})`)
end
end)
test("debug.getproto", {"getproto"}, function() -- Gets the inner function of f at index. Note: If activated is true, it instead will return a table of functions. These are the closures of that proto that exist within the GC.
local function test()
local function _proto()
return true
end
end
local proto = debug.getproto(test, 1, true)[1]
local realproto = debug.getproto(test, 1)
assert(proto, "Failed to get the inner function")
assert(proto() == true, "The inner function did not return anything")
if not realproto() then
return "Proto return values are disabled on this executor"
end
return
end)
test("debug.getprotos", {"getprotos"}, function() -- Returns a table containing the inner prototypes of function f. Use debug.getproto with activated set to true to get a list of closures.
local function test()
local function _1()
return true
end
local function _2()
return true
end
local function _3()
return true
end
end
for i in next, debug.getprotos(test) do
local proto = debug.getproto(test, i, true)[1]
local realproto = debug.getproto(test, i)
assert(proto(), `Failed to get inner function {i}`)
if not realproto() then
return "Proto return values are disabled on this executor"
end
end
return
end)
test("debug.getstack", {"getstack"}, function() -- Gets the method stack at level index. If index is not provided, a table is returned.
local _ = "a" .. "b"
assert(debug.getstack(1, 1) == "ab", "The first item in the stack should be 'ab'")
assert(debug.getstack(1)[1] == "ab", "The first item in the stack table should be 'ab'")
end)
test("debug.setstack", {"setstack"}, function()
local function test()
return "fail", debug.setstack(1, 1, "success")
end
assert(test() == "success", "debug.setstack did not set the first stack item")
end)
test("debug.getupvalues", {"getupvalues"}, function() -- Retrieve the upvalues in function fi or at level fi.
local upvalue = function() end
local function test()
print(upvalue)
end
local upvalues = debug.getupvalues(test)
assert(upvalues[1] == upvalue, "Unexpected value returned from debug.getupvalues")
end)
test("debug.getupvalue", {"getupvalue"}, function() -- Returns the upvalue with index idx in function or level fi.
local upvalue = function() end
local function test()
print(upvalue)
end
assert(debug.getupvalue(test, 1) == upvalue, "Unexpected value returned from debug.getupvalue")
end)
test("debug.setupvalue", {"setupvalue"}, function() -- Sets an upvalue at index idx in function or level fi.
local function upvalue()
return "fail"
end
local function test()
return upvalue()
end
debug.setupvalue(test, 1, function()
return "success"
end)
assert(test() == "success", "debug.setupvalue did not set the first upvalue")
end)
test("debug.getregistery", {"getregistery"}, function() -- Returns a read-only copy of the Lua registry.
local reg = debug.getregistery()
assert(type(reg) == "table", "Did not return a table")
assert(#reg > 0, "Did not return a table with any values")
end)
-- Table Library
test("table.freeze", {"freeze"}, function()
local origTable = {{}}
local frozenTable = table.freeze(origTable)
assert(origTable == frozenTable, "Frozen table should be equal to the original")
local changedTable = pcall(function()
origTable[1] = {}
end)
assert(not changedTable, "Table was not frozen")
local changedTableRecursive = pcall(function()
origTable[1][1] = {}
end)
assert(not changedTableRecursive, "Did not freeze the table recursively")
end)
test("table.isfrozen", {"isfrozen"}, function()
local Table = table.freeze{}
assert(table.isfrozen(Table), "Frozen table is not marked as frozen")
assert(not table.isfrozen{}, "Not frozen tables should not be marked as frozen")
end)
test("table.unfreeze", {"unfreeze"}, function()
local frozenTable = table.freeze{}
local unfrozenTable = table.unfreeze(frozenTable)
assert(unfrozenTable == frozenTable, "Unfrozen table should be equal to the frozen")
end)
-- FileSystem Library
if FileSystem and FileSystem.Dir and FileSystem.Dir.Exists and FileSystem.Dir.Delete and FileSystem.Dir.Create then
if FileSystem.Dir.Exists(".tests") then
FileSystem.Dir.Delete(".tests")
end
FileSystem.Dir.Create(".tests")
end
test("FileSystem", {})
test("FileSystem.File.Read", {}, function()
FileSystem.File.Write(".tests/readfile.txt", "success")
assert(FileSystem.File.Read(".tests/readfile.txt") == "success", "Did not return the contents of the file")
end)
test("FileSystem.List", {}, function()
FileSystem.Dir.Create(".tests/listfiles")
FileSystem.File.Write(".tests/listfiles/test_1.txt", "success")
FileSystem.File.Write(".tests/listfiles/test_2.txt", "success")
local files = FileSystem.List(".tests/listfiles")
assert(#files == 2, "Did not return the correct number of files")
assert(FileSystem.File.Is(files[1]), "Did not return a file path")
assert(FileSystem.File.Read(files[1]) == "success", "Did not return the correct files")
FileSystem.Dir.Create(".tests/listfiles_2")
FileSystem.Dir.Create(".tests/listfiles_2/test_1")
FileSystem.Dir.Create(".tests/listfiles_2/test_2")
local folders = FileSystem.List(".tests/listfiles_2")
assert(#folders == 2, "Did not return the correct number of folders")
assert(FileSystem.Dir.Is(folders[1]), "Did not return a folder path")
end)
test("FileSystem.File.Write", {}, function()
FileSystem.File.Write(".tests/FileSystem.File.Write.txt", "success")
assert(FileSystem.File.Read(".tests/FileSystem.File.Write.txt") == "success", "Did not write the file")
local requiresFileExt = pcall(function()
FileSystem.File.Write(".tests/FileSystem.File.Write", "success")
assert(FileSystem.File.Is(".tests/FileSystem.File.Write.txt"))
end)
if not requiresFileExt then
return "This executor requires a file extension in FileSystem.File.Write"
end
return
end)
test("FileSystem.Dir.Create", {}, function()
FileSystem.Dir.Create(".tests/FileSystem.Dir.Create")
assert(FileSystem.Dir.Is(".tests/FileSystem.Dir.Create"), "Did not create the folder")
end)
test("appendfile", {}, function()
FileSystem.File.Write(".tests/appendfile.txt", "su")
FileSystem.File.Append(".tests/appendfile.txt", "cce")
FileSystem.File.Append(".tests/appendfile.txt", "ss")
assert(FileSystem.File.Read(".tests/appendfile.txt") == "success", "Did not append the file")
end)
test("FileSystem.File.Is", {}, function()
FileSystem.File.Write(".tests/FileSystem.File.Is.txt", "success")
assert(FileSystem.File.Is(".tests/FileSystem.File.Is.txt") == true, "Did not return true for a file")
assert(FileSystem.File.Is(".tests") == false, "Did not return false for a folder")
assert(FileSystem.File.Is(".tests/doesnotexist.exe") == false, `Did not return false for a nonexistent path (got {FileSystem.File.Is(".tests/doesnotexist.exe")})`)
end)
test("FileSystem.Dir.Is", {}, function()
assert(FileSystem.Dir.Is(".tests") == true, "Did not return false for a folder")
assert(FileSystem.Dir.Is(".tests/doesnotexist.exe") == false, `Did not return false for a nonexistent path (got {FileSystem.Dir.Is(".tests/doesnotexist.exe")})`)
end)
test("FileSystem.Dir.Delete", {}, function()
FileSystem.Dir.Create(".tests/FileSystem.Dir.Delete")
FileSystem.Dir.Delete(".tests/FileSystem.Dir.Delete")
assert(FileSystem.Dir.Is(".tests/FileSystem.Dir.Delete") == false, `Failed to delete folder (FileSystem.Dir.Is = {FileSystem.Dir.Is(".tests/FileSystem.Dir.Delete")})`)
end)
test("FileSystem.File.Delete", {}, function()
FileSystem.File.Write(".tests/FileSystem.File.Delete.txt", "Hello, world!")
FileSystem.File.Delete(".tests/FileSystem.File.Delete.txt")
assert(FileSystem.File.Is(".tests/FileSystem.File.Delete.txt") == false, `Failed to delete folder (FileSystem.File.Is = {FileSystem.File.Is(".tests/FileSystem.Dir.Delete")})`)
end)
test("FileSystem.File.Load", {}, function()
FileSystem.File.Write(".tests/FileSystem.File.Load.txt", "return ... + 1")
assert(assert(FileSystem.File.Load(".tests/FileSystem.File.Load.txt"))(1) == 2, "Failed to load a file with arguments")
FileSystem.File.Write(".tests/FileSystem.File.Load.txt", "f")
local callback, err = FileSystem.File.Load(".tests/FileSystem.File.Load.txt")
assert(err and not callback, "Did not return an error message for a compiler error")
end)
test("FileSystem.GetAsset", {}, function()
FileSystem.File.Write(".tests/FileSystem.GetAsset.txt", "success")
local contentId = FileSystem.GetAsset(".tests/FileSystem.GetAsset.txt")
local cache1, cache2 = FileSystem.GetAsset(".tests/FileSystem.GetAsset.txt", true), FileSystem.GetAsset(".tests/FileSystem.GetAsset.txt", true)
assert(type(contentId) == "string", "Did not return a string")
assert(#contentId > 0, "Returned an empty string")
assert(string.match(contentId, "rbxasset://") == "rbxasset://", "Did not return an rbxasset url")
assert(cache1 == cache2, "Did not return the same Asset ID when caching is enabled")
end)
-- Input
--[[
declare class MouseClick
Down: RBXScriptSignal<number, number> -- read only, fires when the mouse was pressed down
Up: RBXScriptSignal<number, number> -- read only, fires when the mouse was released
Clicked: RBXScriptSignal<number, number> -- fired when the mouse button was clicked, including the simulated clicks, read only
function __call(self, duration: number?): nil -- press mouse button down for x duration and then release it, it fires the events in this order Down (INSTANT) Up (AFTER X SECONDS) Clicked (AFTER X SECONDS, BUT AFTER UP)
function Press(self): nil -- press mouse down, fires the Down Signal
function Release(self): nil -- release mouse up, fires the Up Signal
end
declare class MouseScroll
Scrolled: RBXScriptSignal<> -- gets fired every time a mouse middle scroll gets simulated, or the user scrolls the middle mouse
function __call(self, pixels: number): nil -- scroll mouse by x pixels, fires the Scrolled signal
end
declare Mouse: { -- THIS IS A GLOBAL VARIABLE; IT IS JUST LIKE THE 'table' VARIABLE WITH DIFFERENT FUNCTIONS IN IT AND IT IS DIFFERENT FROM THE CLASS CALLED 'Mouse'!
LeftButton: MouseClick,
RightButton: MouseClick,
Scroll: MouseScroll,
MoveAbsolute: (x: number, y: number) -> nil,
MoveRelative: (x: number, y: number) -> nil,
Position: {
Value: Vector2, -- read only when property CanSimulate is false
Changed: RBXScriptSignal<Vector2> -- read only
},
CanSimulate: boolean -- read only, if false then simulating anything like a mouseclick, mousescroll, etc. will not work
}
declare class KeyboardKey
Pressed: RBXScriptSignal<EnumKeyCode> -- read only
Released: RBXScriptSignal<EnumKeyCode> -- read only
LastPressed: EnumKeyCode? -- read only
function Press(self, KeyCode: EnumKeyCode | number): boolean -- simulate a key being pressed down and held down
function Release(self, KeyCode: EnumKeyCode | number): boolean -- simulate a key being released and not held down
function IsDown(self, KeyCode: EnumKeyCode | number): boolean
function __call(self, KeyCode: EnumKeyCode | number, duration: number?): boolean -- simulate a key press for x duration and then release it, it presses the key for x duration, then releases it after x duration
end
declare Keyboard: {
Keys: { [string]: number }, -- a table with all virtual key codes https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
Key: KeyboardKey,
CanSimulate: boolean -- read only, if false then simulating anything like a keypress, keyrelease, keyclick, isdown will not work and will always return false
}
]]
-- Instances
test("fireclickdetector", {}, function()
local detector, order = Instance.new("ClickDetector"), {}
detector.MouseHoverEnter:Connect(function()
order[#order + 1] = detector.MouseHoverEnter
end)
detector.MouseClick:Connect(function()
order[#order + 1] = detector.MouseClick
end)
detector.RightMouseClick:Connect(function()
order[#order + 1] = detector.RightMouseClick
end)
detector.MouseHoverLeave:Connect(function()
order[#order + 1] = detector.MouseHoverLeave
end)
fireclickdetector(detector)
assert(#order == 4 and order[1] == detector.MouseHoverEnter and order[4] == detector.MouseHoverLeave)
end)
test("fireproximityprompt", {}, function()
local prompt = Instance.new("ProximityPrompt")
fireproximityprompt(prompt)
end)
test("firetouchinterest", {}, function()
local detector = Instance.new("ClickDetector")
firetouchinterest(detector, game:GetService("Players").LocalPlayer.Character.HumanoidRootPart, true)
end)
test("firesignal", {}, function()
local btn, MovedWheelForward = Instance.new("TextButton"), false
btn.MouseWheelForward:Once(function(x, y)
MovedWheelForward = x == -51.2151 and y == 515.1251
end)
firesignal(btn.MouseWheelForward, -51.2151, 515.1251)
assert(MovedWheelForward, "Did not correctly fire the MouseWheelForward Signal of TextButton")
end)
test("getcallbackvalue", {}, function()
local bindable = Instance.new("BindableFunction")
local function test()
end
bindable.OnInvoke = test
assert(getcallbackvalue(bindable, "OnInvoke") == test, "Did not return the correct value")
end)
test("getconnections", {}, function()
local types = {
Enabled = "boolean",
ForeignState = "boolean",
LuaConnection = "boolean",
Function = "function",
Thread = "thread",
Fired = {"table", "userdata", "RBXScriptSignal"},
Fire = "function",
Defer = "function",
Disconnect = "function",
Disable = "function",
Enable = "function"
}
local function ConnectFunc()
end
game:GetService("Players").LocalPlayer.Chatted:Connect(ConnectFunc)
local connection = getconnections(game:GetService("Players").LocalPlayer.Chatted)[1]
for k, v in next, types do
local hasProp, result = pcall(function()
return connection[k] ~= nil
end)
assert(hasProp and result, `Did not return a {type(connection)} with a '{k}' field`)
if type(v) == "table" then
else
assert(type(connection[k]) == v, `Did not return a table with {type(connection)} as a {v} (got {type(connection[k])})`)
if k == "Function" then
assert(connection.Function == ConnectFunc, "Did not return the correct function for 'Function'")
end
end
end
end)
test("gethiddenproperty", {}, function()
local fire = Instance.new("Fire")
local property, isHidden = gethiddenproperty(fire, "size_xml")
assert(property == 5, "Did not return the correct value")
assert(isHidden == true, "Did not return whether the property was hidden")
end)
test("sethiddenproperty", {}, function()
local fire = Instance.new("Fire")
local hidden = sethiddenproperty(fire, "size_xml", 10)
assert(hidden, "Did not return true for the hidden property")
assert(gethiddenproperty(fire, "size_xml") == 10, "Did not set the hidden property")
end)
test("getproperties", {"getprops"}, function()
local part = Instance.new("Part")
local props = getproperties(part)
assert(props.Position ~= part.Position, "Did not return the correct value")
end)
test("gethui", {}, function()
assert(typeof(gethui()) == "Instance" and gethui():FindFirstAncestor("CoreGui") == game:GetService("CoreGui"), "Did not return an Instance or Instance is not in CoreGui")
end)
test("getinstances", {}, function()
assert(getinstances()[1]:IsA("Instance"), "The first value is not an Instance")
end)
test("getnilinstances", {}, function()
assert(getnilinstances()[1]:IsA("Instance"), "The first value is not an Instance")
assert(getnilinstances()[1].Parent == nil, "The first value is not parented to nil")
end)
test("getcacheinstances", {}, function()
assert(getcacheinstances()[1]:IsA("Instance"), "The first value is not an Instance")
end)
test("isscriptable", {}, function()
local fire = Instance.new("Fire")
assert(isscriptable(fire, "size_xml") == false, "Did not return false for a non-scriptable property (size_xml)")
assert(isscriptable(fire, "Size"), "Did not return true for a scriptable property (Size)")
end)
test("setscriptable", {}, function()
local fire = Instance.new("Fire")
local wasScriptable = setscriptable(fire, "size_xml", true)
assert(wasScriptable == false, "Did not return false for a non-scriptable property (size_xml)")
assert(isscriptable(fire, "size_xml") == true, "Did not set the scriptable property")
end)
-- Metatable
test("hookmetamethod", {}, function()
local object = setmetatable({}, { __index = newcclosure(function() return false end), __metatable = "Locked!" })
local ref = hookmetamethod(object, "__index", function() return true end)
assert(object.test == true, "Failed to hook a metamethod and change the return value")
assert(ref() == false, "Did not return the original function")
end)
test("getnamecallmethod", {}, function()
local method
local ref
ref = hookmetamethod(game, "__namecall", function(...)
if not method then
method = getnamecallmethod()
end
return ref(...)
end)
game:GetService("Lighting")
assert(method == "GetService", "Did not get the correct method (GetService)")
end)
test("setnamecallmethod", {}, function()
local overwrote
local ref
ref = hookmetamethod(game, "__namecall", function(...)
if not overwrote then
overwrote = true
setnamecallmethod("NotGetService")
end
return ref(...)
end)
local OverwroteCallmethod = pcall(function()
game:GetService("Lighting")
end)
assert(OverwroteCallmethod, "Did not overwrite the Namecall Method 'GetService' to 'NotGetService'")
end)
-- Miscellaneous
test("identifyexecutor", {"getexecutorname"}, function()
local name, version = identifyexecutor()
assert(type(name) == "string", "Did not return a string for the name")
return type(version) == "string" and "Returns version as a string" or "Does not return version"
end)
test("lz4compress", {"lz4c"}, function()
local raw = "Hello, world!"
local compressed = lz4compress(raw)
assert(type(compressed) == "string", "Compression did not return a string")
assert(lz4decompress(compressed, #raw) == raw, "Decompression did not return the original string")
end)
test("lz4decompress", {"lz4d"}, function()