]> git.lizzy.rs Git - dragonfireclient.git/blob - src/test.cpp
Use setting groups for NoiseParams
[dragonfireclient.git] / src / test.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "test.h"
21 #include "irrlichttypes_extrabloated.h"
22 #include "debug.h"
23 #include "map.h"
24 #include "player.h"
25 #include "main.h"
26 #include "socket.h"
27 #include "connection.h"
28 #include "serialization.h"
29 #include "voxel.h"
30 #include "collision.h"
31 #include <sstream>
32 #include "porting.h"
33 #include "content_mapnode.h"
34 #include "nodedef.h"
35 #include "mapsector.h"
36 #include "settings.h"
37 #include "log.h"
38 #include "util/string.h"
39 #include "filesys.h"
40 #include "voxelalgorithms.h"
41 #include "inventory.h"
42 #include "util/numeric.h"
43 #include "util/serialize.h"
44 #include "noise.h" // PseudoRandom used for random data for compression
45 #include "clientserver.h" // LATEST_PROTOCOL_VERSION
46 #include <algorithm>
47
48 /*
49         Asserts that the exception occurs
50 */
51 #define EXCEPTION_CHECK(EType, code)\
52 {\
53         bool exception_thrown = false;\
54         try{ code; }\
55         catch(EType &e) { exception_thrown = true; }\
56         UASSERT(exception_thrown);\
57 }
58
59 #define UTEST(x, fmt, ...)\
60 {\
61         if(!(x)){\
62                 LOGLINEF(LMT_ERROR, "Test (%s) failed: " fmt, #x, ##__VA_ARGS__);\
63                 test_failed = true;\
64         }\
65 }
66
67 #define UASSERT(x) UTEST(x, "UASSERT")
68
69 /*
70         A few item and node definitions for those tests that need them
71 */
72
73 static content_t CONTENT_STONE;
74 static content_t CONTENT_GRASS;
75 static content_t CONTENT_TORCH;
76
77 void define_some_nodes(IWritableItemDefManager *idef, IWritableNodeDefManager *ndef)
78 {
79         ItemDefinition itemdef;
80         ContentFeatures f;
81
82         /*
83                 Stone
84         */
85         itemdef = ItemDefinition();
86         itemdef.type = ITEM_NODE;
87         itemdef.name = "default:stone";
88         itemdef.description = "Stone";
89         itemdef.groups["cracky"] = 3;
90         itemdef.inventory_image = "[inventorycube"
91                 "{default_stone.png"
92                 "{default_stone.png"
93                 "{default_stone.png";
94         f = ContentFeatures();
95         f.name = itemdef.name;
96         for(int i = 0; i < 6; i++)
97                 f.tiledef[i].name = "default_stone.png";
98         f.is_ground_content = true;
99         idef->registerItem(itemdef);
100         CONTENT_STONE = ndef->set(f.name, f);
101
102         /*
103                 Grass
104         */
105         itemdef = ItemDefinition();
106         itemdef.type = ITEM_NODE;
107         itemdef.name = "default:dirt_with_grass";
108         itemdef.description = "Dirt with grass";
109         itemdef.groups["crumbly"] = 3;
110         itemdef.inventory_image = "[inventorycube"
111                 "{default_grass.png"
112                 "{default_dirt.png&default_grass_side.png"
113                 "{default_dirt.png&default_grass_side.png";
114         f = ContentFeatures();
115         f.name = itemdef.name;
116         f.tiledef[0].name = "default_grass.png";
117         f.tiledef[1].name = "default_dirt.png";
118         for(int i = 2; i < 6; i++)
119                 f.tiledef[i].name = "default_dirt.png^default_grass_side.png";
120         f.is_ground_content = true;
121         idef->registerItem(itemdef);
122         CONTENT_GRASS = ndef->set(f.name, f);
123
124         /*
125                 Torch (minimal definition for lighting tests)
126         */
127         itemdef = ItemDefinition();
128         itemdef.type = ITEM_NODE;
129         itemdef.name = "default:torch";
130         f = ContentFeatures();
131         f.name = itemdef.name;
132         f.param_type = CPT_LIGHT;
133         f.light_propagates = true;
134         f.sunlight_propagates = true;
135         f.light_source = LIGHT_MAX-1;
136         idef->registerItem(itemdef);
137         CONTENT_TORCH = ndef->set(f.name, f);
138 }
139
140 struct TestBase
141 {
142         bool test_failed;
143         TestBase():
144                 test_failed(false)
145         {}
146 };
147
148 struct TestUtilities: public TestBase
149 {
150         void Run()
151         {
152                 /*infostream<<"wrapDegrees(100.0) = "<<wrapDegrees(100.0)<<std::endl;
153                 infostream<<"wrapDegrees(720.5) = "<<wrapDegrees(720.5)<<std::endl;
154                 infostream<<"wrapDegrees(-0.5) = "<<wrapDegrees(-0.5)<<std::endl;*/
155                 UASSERT(fabs(wrapDegrees(100.0) - 100.0) < 0.001);
156                 UASSERT(fabs(wrapDegrees(720.5) - 0.5) < 0.001);
157                 UASSERT(fabs(wrapDegrees(-0.5) - (-0.5)) < 0.001);
158                 UASSERT(fabs(wrapDegrees(-365.5) - (-5.5)) < 0.001);
159                 UASSERT(lowercase("Foo bAR") == "foo bar");
160                 UASSERT(trim("\n \t\r  Foo bAR  \r\n\t\t  ") == "Foo bAR");
161                 UASSERT(trim("\n \t\r    \r\n\t\t  ") == "");
162                 UASSERT(is_yes("YeS") == true);
163                 UASSERT(is_yes("") == false);
164                 UASSERT(is_yes("FAlse") == false);
165                 UASSERT(is_yes("-1") == true);
166                 UASSERT(is_yes("0") == false);
167                 UASSERT(is_yes("1") == true);
168                 UASSERT(is_yes("2") == true);
169                 const char *ends[] = {"abc", "c", "bc", "", NULL};
170                 UASSERT(removeStringEnd("abc", ends) == "");
171                 UASSERT(removeStringEnd("bc", ends) == "b");
172                 UASSERT(removeStringEnd("12c", ends) == "12");
173                 UASSERT(removeStringEnd("foo", ends) == "");
174                 UASSERT(urlencode("\"Aardvarks lurk, OK?\"")
175                                 == "%22Aardvarks%20lurk%2C%20OK%3F%22");
176                 UASSERT(urldecode("%22Aardvarks%20lurk%2C%20OK%3F%22")
177                                 == "\"Aardvarks lurk, OK?\"");
178                 UASSERT(padStringRight("hello", 8) == "hello   ");
179                 UASSERT(str_equal(narrow_to_wide("abc"), narrow_to_wide("abc")));
180                 UASSERT(str_equal(narrow_to_wide("ABC"), narrow_to_wide("abc"), true));
181                 UASSERT(trim("  a") == "a");
182                 UASSERT(trim("   a  ") == "a");
183                 UASSERT(trim("a   ") == "a");
184                 UASSERT(trim("") == "");
185                 UASSERT(mystoi("123", 0, 1000) == 123);
186                 UASSERT(mystoi("123", 0, 10) == 10);
187                 std::string test_str;
188                 test_str = "Hello there";
189                 str_replace(test_str, "there", "world");
190                 UASSERT(test_str == "Hello world");
191                 test_str = "ThisAisAaAtest";
192                 str_replace_char(test_str, 'A', ' ');
193                 UASSERT(test_str == "This is a test");
194                 UASSERT(string_allowed("hello", "abcdefghijklmno") == true);
195                 UASSERT(string_allowed("123", "abcdefghijklmno") == false);
196                 UASSERT(string_allowed_blacklist("hello", "123") == true);
197                 UASSERT(string_allowed_blacklist("hello123", "123") == false);
198                 UASSERT(wrap_rows("12345678",4) == "1234\n5678");
199                 UASSERT(is_number("123") == true);
200                 UASSERT(is_number("") == false);
201                 UASSERT(is_number("123a") == false);
202                 UASSERT(is_power_of_two(0) == false);
203                 UASSERT(is_power_of_two(1) == true);
204                 UASSERT(is_power_of_two(2) == true);
205                 UASSERT(is_power_of_two(3) == false);
206                 for (int exponent = 2; exponent <= 31; ++exponent) {
207                         UASSERT(is_power_of_two((1 << exponent) - 1) == false);
208                         UASSERT(is_power_of_two((1 << exponent)) == true);
209                         UASSERT(is_power_of_two((1 << exponent) + 1) == false);
210                 }
211                 UASSERT(is_power_of_two((u32)-1) == false);
212         }
213 };
214
215 struct TestPath: public TestBase
216 {
217         // adjusts a POSIX path to system-specific conventions
218         // -> changes '/' to DIR_DELIM
219         // -> absolute paths start with "C:\\" on windows
220         std::string p(std::string path)
221         {
222                 for(size_t i = 0; i < path.size(); ++i){
223                         if(path[i] == '/'){
224                                 path.replace(i, 1, DIR_DELIM);
225                                 i += std::string(DIR_DELIM).size() - 1; // generally a no-op
226                         }
227                 }
228
229                 #ifdef _WIN32
230                 if(path[0] == '\\')
231                         path = "C:" + path;
232                 #endif
233
234                 return path;
235         }
236
237         void Run()
238         {
239                 std::string path, result, removed;
240
241                 /*
242                         Test fs::IsDirDelimiter
243                 */
244                 UASSERT(fs::IsDirDelimiter('/') == true);
245                 UASSERT(fs::IsDirDelimiter('A') == false);
246                 UASSERT(fs::IsDirDelimiter(0) == false);
247                 #ifdef _WIN32
248                 UASSERT(fs::IsDirDelimiter('\\') == true);
249                 #else
250                 UASSERT(fs::IsDirDelimiter('\\') == false);
251                 #endif
252
253                 /*
254                         Test fs::PathStartsWith
255                 */
256                 {
257                         const int numpaths = 12;
258                         std::string paths[numpaths] = {
259                                 "",
260                                 p("/"),
261                                 p("/home/user/minetest"),
262                                 p("/home/user/minetest/bin"),
263                                 p("/home/user/.minetest"),
264                                 p("/tmp/dir/file"),
265                                 p("/tmp/file/"),
266                                 p("/tmP/file"),
267                                 p("/tmp"),
268                                 p("/tmp/dir"),
269                                 p("/home/user2/minetest/worlds"),
270                                 p("/home/user2/minetest/world"),
271                         };
272                         /*
273                                 expected fs::PathStartsWith results
274                                 0 = returns false
275                                 1 = returns true
276                                 2 = returns false on windows, false elsewhere
277                                 3 = returns true on windows, true elsewhere
278                                 4 = returns true if and only if
279                                     FILESYS_CASE_INSENSITIVE is true
280                         */
281                         int expected_results[numpaths][numpaths] = {
282                                 {1,2,0,0,0,0,0,0,0,0,0,0},
283                                 {1,1,0,0,0,0,0,0,0,0,0,0},
284                                 {1,1,1,0,0,0,0,0,0,0,0,0},
285                                 {1,1,1,1,0,0,0,0,0,0,0,0},
286                                 {1,1,0,0,1,0,0,0,0,0,0,0},
287                                 {1,1,0,0,0,1,0,0,1,1,0,0},
288                                 {1,1,0,0,0,0,1,4,1,0,0,0},
289                                 {1,1,0,0,0,0,4,1,4,0,0,0},
290                                 {1,1,0,0,0,0,0,0,1,0,0,0},
291                                 {1,1,0,0,0,0,0,0,1,1,0,0},
292                                 {1,1,0,0,0,0,0,0,0,0,1,0},
293                                 {1,1,0,0,0,0,0,0,0,0,0,1},
294                         };
295
296                         for (int i = 0; i < numpaths; i++)
297                         for (int j = 0; j < numpaths; j++){
298                                 /*verbosestream<<"testing fs::PathStartsWith(\""
299                                         <<paths[i]<<"\", \""
300                                         <<paths[j]<<"\")"<<std::endl;*/
301                                 bool starts = fs::PathStartsWith(paths[i], paths[j]);
302                                 int expected = expected_results[i][j];
303                                 if(expected == 0){
304                                         UASSERT(starts == false);
305                                 }
306                                 else if(expected == 1){
307                                         UASSERT(starts == true);
308                                 }
309                                 #ifdef _WIN32
310                                 else if(expected == 2){
311                                         UASSERT(starts == false);
312                                 }
313                                 else if(expected == 3){
314                                         UASSERT(starts == true);
315                                 }
316                                 #else
317                                 else if(expected == 2){
318                                         UASSERT(starts == true);
319                                 }
320                                 else if(expected == 3){
321                                         UASSERT(starts == false);
322                                 }
323                                 #endif
324                                 else if(expected == 4){
325                                         UASSERT(starts == (bool)FILESYS_CASE_INSENSITIVE);
326                                 }
327                         }
328                 }
329
330                 /*
331                         Test fs::RemoveLastPathComponent
332                 */
333                 UASSERT(fs::RemoveLastPathComponent("") == "");
334                 path = p("/home/user/minetest/bin/..//worlds/world1");
335                 result = fs::RemoveLastPathComponent(path, &removed, 0);
336                 UASSERT(result == path);
337                 UASSERT(removed == "");
338                 result = fs::RemoveLastPathComponent(path, &removed, 1);
339                 UASSERT(result == p("/home/user/minetest/bin/..//worlds"));
340                 UASSERT(removed == p("world1"));
341                 result = fs::RemoveLastPathComponent(path, &removed, 2);
342                 UASSERT(result == p("/home/user/minetest/bin/.."));
343                 UASSERT(removed == p("worlds/world1"));
344                 result = fs::RemoveLastPathComponent(path, &removed, 3);
345                 UASSERT(result == p("/home/user/minetest/bin"));
346                 UASSERT(removed == p("../worlds/world1"));
347                 result = fs::RemoveLastPathComponent(path, &removed, 4);
348                 UASSERT(result == p("/home/user/minetest"));
349                 UASSERT(removed == p("bin/../worlds/world1"));
350                 result = fs::RemoveLastPathComponent(path, &removed, 5);
351                 UASSERT(result == p("/home/user"));
352                 UASSERT(removed == p("minetest/bin/../worlds/world1"));
353                 result = fs::RemoveLastPathComponent(path, &removed, 6);
354                 UASSERT(result == p("/home"));
355                 UASSERT(removed == p("user/minetest/bin/../worlds/world1"));
356                 result = fs::RemoveLastPathComponent(path, &removed, 7);
357                 #ifdef _WIN32
358                 UASSERT(result == "C:");
359                 #else
360                 UASSERT(result == "");
361                 #endif
362                 UASSERT(removed == p("home/user/minetest/bin/../worlds/world1"));
363
364                 /*
365                         Now repeat the test with a trailing delimiter
366                 */
367                 path = p("/home/user/minetest/bin/..//worlds/world1/");
368                 result = fs::RemoveLastPathComponent(path, &removed, 0);
369                 UASSERT(result == path);
370                 UASSERT(removed == "");
371                 result = fs::RemoveLastPathComponent(path, &removed, 1);
372                 UASSERT(result == p("/home/user/minetest/bin/..//worlds"));
373                 UASSERT(removed == p("world1"));
374                 result = fs::RemoveLastPathComponent(path, &removed, 2);
375                 UASSERT(result == p("/home/user/minetest/bin/.."));
376                 UASSERT(removed == p("worlds/world1"));
377                 result = fs::RemoveLastPathComponent(path, &removed, 3);
378                 UASSERT(result == p("/home/user/minetest/bin"));
379                 UASSERT(removed == p("../worlds/world1"));
380                 result = fs::RemoveLastPathComponent(path, &removed, 4);
381                 UASSERT(result == p("/home/user/minetest"));
382                 UASSERT(removed == p("bin/../worlds/world1"));
383                 result = fs::RemoveLastPathComponent(path, &removed, 5);
384                 UASSERT(result == p("/home/user"));
385                 UASSERT(removed == p("minetest/bin/../worlds/world1"));
386                 result = fs::RemoveLastPathComponent(path, &removed, 6);
387                 UASSERT(result == p("/home"));
388                 UASSERT(removed == p("user/minetest/bin/../worlds/world1"));
389                 result = fs::RemoveLastPathComponent(path, &removed, 7);
390                 #ifdef _WIN32
391                 UASSERT(result == "C:");
392                 #else
393                 UASSERT(result == "");
394                 #endif
395                 UASSERT(removed == p("home/user/minetest/bin/../worlds/world1"));
396
397                 /*
398                         Test fs::RemoveRelativePathComponent
399                 */
400                 path = p("/home/user/minetest/bin");
401                 result = fs::RemoveRelativePathComponents(path);
402                 UASSERT(result == path);
403                 path = p("/home/user/minetest/bin/../worlds/world1");
404                 result = fs::RemoveRelativePathComponents(path);
405                 UASSERT(result == p("/home/user/minetest/worlds/world1"));
406                 path = p("/home/user/minetest/bin/../worlds/world1/");
407                 result = fs::RemoveRelativePathComponents(path);
408                 UASSERT(result == p("/home/user/minetest/worlds/world1"));
409                 path = p(".");
410                 result = fs::RemoveRelativePathComponents(path);
411                 UASSERT(result == "");
412                 path = p("./subdir/../..");
413                 result = fs::RemoveRelativePathComponents(path);
414                 UASSERT(result == "");
415                 path = p("/a/b/c/.././../d/../e/f/g/../h/i/j/../../../..");
416                 result = fs::RemoveRelativePathComponents(path);
417                 UASSERT(result == p("/a/e"));
418         }
419 };
420
421 #define TEST_CONFIG_TEXT_BEFORE               \
422         "leet = 1337\n"                           \
423         "leetleet = 13371337\n"                   \
424         "leetleet_neg = -13371337\n"              \
425         "floaty_thing = 1.1\n"                    \
426         "stringy_thing = asd /( Â¤%&(/\" BLÖÄRP\n" \
427         "coord = (1, 2, 4.5)\n"                   \
428         "      # this is just a comment\n"        \
429         "this is an invalid line\n"               \
430         "asdf = {\n"                              \
431         "       a = 5\n"                              \
432         "       b = 2.5\n"                            \
433         "       c = \"\"\"\n"                         \
434         "testy\n"                                 \
435         "   testa   \n"                           \
436         "\"\"\"\n"                                \
437         "\n"                                      \
438         "}\n"                                     \
439         "blarg = \"\"\" \n"                       \
440         "some multiline text\n"                   \
441         "     with leading whitespace!\n"         \
442         "\"\"\"\n"                                \
443         "zoop = true"
444
445 #define TEST_CONFIG_TEXT_AFTER                \
446         "leet = 1337\n"                           \
447         "leetleet = 13371337\n"                   \
448         "leetleet_neg = -13371337\n"              \
449         "floaty_thing = 1.1\n"                    \
450         "stringy_thing = asd /( Â¤%&(/\" BLÖÄRP\n" \
451         "coord = (1, 2, 4.5)\n"                   \
452         "      # this is just a comment\n"        \
453         "this is an invalid line\n"               \
454         "asdf = {\n"                              \
455         "       a = 5\n"                              \
456         "       b = 2.5\n"                            \
457         "       c = \"\"\"\n"                         \
458         "testy\n"                                 \
459         "   testa   \n"                           \
460         "\"\"\"\n"                                \
461         "\n"                                      \
462         "}\n"                                     \
463         "blarg = \"\"\"\n"                        \
464         "some multiline text\n"                   \
465         "     with leading whitespace!\n"         \
466         "\"\"\"\n"                                \
467         "zoop = true\n"                           \
468         "coord2 = (1,2,3.3)\n"                    \
469         "floaty_thing_2 = 1.2\n"                  \
470         "groupy_thing = \n"                       \
471         "groupy_thing = {\n"                      \
472         "       animals = \n"                         \
473         "       animals = {\n"                        \
474         "               cat = meow\n"                     \
475         "               dog = woof\n"                     \
476         "       }\n"                                  \
477         "       num_apples = 4\n"                     \
478         "       num_oranges = 53\n"                   \
479         "}\n"
480
481
482 struct TestSettings: public TestBase
483 {
484         void Run()
485         {
486                 Settings s;
487
488                 // Test reading of settings
489                 std::istringstream is(TEST_CONFIG_TEXT_BEFORE);
490                 s.parseConfigLines(is);
491
492                 UASSERT(s.getS32("leet") == 1337);
493                 UASSERT(s.getS16("leetleet") == 32767);
494                 UASSERT(s.getS16("leetleet_neg") == -32768);
495
496                 // Not sure if 1.1 is an exact value as a float, but doesn't matter
497                 UASSERT(fabs(s.getFloat("floaty_thing") - 1.1) < 0.001);
498                 UASSERT(s.get("stringy_thing") == "asd /( Â¤%&(/\" BLÖÄRP");
499                 UASSERT(fabs(s.getV3F("coord").X - 1.0) < 0.001);
500                 UASSERT(fabs(s.getV3F("coord").Y - 2.0) < 0.001);
501                 UASSERT(fabs(s.getV3F("coord").Z - 4.5) < 0.001);
502
503                 // Test the setting of settings too
504                 s.setFloat("floaty_thing_2", 1.2);
505                 s.setV3F("coord2", v3f(1, 2, 3.3));
506                 UASSERT(s.get("floaty_thing_2").substr(0,3) == "1.2");
507                 UASSERT(fabs(s.getFloat("floaty_thing_2") - 1.2) < 0.001);
508                 UASSERT(fabs(s.getV3F("coord2").X - 1.0) < 0.001);
509                 UASSERT(fabs(s.getV3F("coord2").Y - 2.0) < 0.001);
510                 UASSERT(fabs(s.getV3F("coord2").Z - 3.3) < 0.001);
511
512                 // Test settings groups
513                 Settings *group = s.getGroup("asdf");
514                 UASSERT(group != NULL);
515                 UASSERT(s.getGroupNoEx("zoop", group) == false);
516                 UASSERT(group->getS16("a") == 5);
517                 UASSERT(fabs(group->getFloat("b") - 2.5) < 0.001);
518
519                 Settings *group3 = new Settings;
520                 group3->set("cat", "meow");
521                 group3->set("dog", "woof");
522
523                 Settings *group2 = new Settings;
524                 group2->setS16("num_apples", 4);
525                 group2->setS16("num_oranges", 53);
526                 group2->setGroup("animals", group3);
527                 s.setGroup("groupy_thing", group2);
528
529                 // Test multiline settings
530                 UASSERT(group->get("c") == "testy\n   testa   ");
531                 UASSERT(s.get("blarg") ==
532                         "some multiline text\n"
533                         "     with leading whitespace!");
534
535                 // Test writing
536                 std::ostringstream os(std::ios_base::binary);
537                 is.clear();
538                 is.seekg(0);
539
540                 UASSERT(s.updateConfigObject(is, os, "", 0) == true);
541                 //printf(">>>> expected config:\n%s\n", TEST_CONFIG_TEXT_AFTER);
542                 //printf(">>>> actual config:\n%s\n", os.str().c_str());
543                 UASSERT(os.str() == TEST_CONFIG_TEXT_AFTER);
544         }
545 };
546
547 struct TestSerialization: public TestBase
548 {
549         // To be used like this:
550         //   mkstr("Some\0string\0with\0embedded\0nuls")
551         // since std::string("...") doesn't work as expected in that case.
552         template<size_t N> std::string mkstr(const char (&s)[N])
553         {
554                 return std::string(s, N - 1);
555         }
556
557         void Run()
558         {
559                 // Tests some serialization primitives
560
561                 UASSERT(serializeString("") == mkstr("\0\0"));
562                 UASSERT(serializeWideString(L"") == mkstr("\0\0"));
563                 UASSERT(serializeLongString("") == mkstr("\0\0\0\0"));
564                 UASSERT(serializeJsonString("") == "\"\"");
565
566                 std::string teststring = "Hello world!";
567                 UASSERT(serializeString(teststring) ==
568                         mkstr("\0\14Hello world!"));
569                 UASSERT(serializeWideString(narrow_to_wide(teststring)) ==
570                         mkstr("\0\14\0H\0e\0l\0l\0o\0 \0w\0o\0r\0l\0d\0!"));
571                 UASSERT(serializeLongString(teststring) ==
572                         mkstr("\0\0\0\14Hello world!"));
573                 UASSERT(serializeJsonString(teststring) ==
574                         "\"Hello world!\"");
575
576                 std::string teststring2;
577                 std::wstring teststring2_w;
578                 std::string teststring2_w_encoded;
579                 {
580                         std::ostringstream tmp_os;
581                         std::wostringstream tmp_os_w;
582                         std::ostringstream tmp_os_w_encoded;
583                         for(int i = 0; i < 256; i++)
584                         {
585                                 tmp_os<<(char)i;
586                                 tmp_os_w<<(wchar_t)i;
587                                 tmp_os_w_encoded<<(char)0<<(char)i;
588                         }
589                         teststring2 = tmp_os.str();
590                         teststring2_w = tmp_os_w.str();
591                         teststring2_w_encoded = tmp_os_w_encoded.str();
592                 }
593                 UASSERT(serializeString(teststring2) ==
594                         mkstr("\1\0") + teststring2);
595                 UASSERT(serializeWideString(teststring2_w) ==
596                         mkstr("\1\0") + teststring2_w_encoded);
597                 UASSERT(serializeLongString(teststring2) ==
598                         mkstr("\0\0\1\0") + teststring2);
599                 // MSVC fails when directly using "\\\\"
600                 std::string backslash = "\\";
601                 UASSERT(serializeJsonString(teststring2) ==
602                         mkstr("\"") +
603                         "\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007" +
604                         "\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f" +
605                         "\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017" +
606                         "\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f" +
607                         " !\\\"" + teststring2.substr(0x23, 0x2f-0x23) +
608                         "\\/" + teststring2.substr(0x30, 0x5c-0x30) +
609                         backslash + backslash + teststring2.substr(0x5d, 0x7f-0x5d) + "\\u007f" +
610                         "\\u0080\\u0081\\u0082\\u0083\\u0084\\u0085\\u0086\\u0087" +
611                         "\\u0088\\u0089\\u008a\\u008b\\u008c\\u008d\\u008e\\u008f" +
612                         "\\u0090\\u0091\\u0092\\u0093\\u0094\\u0095\\u0096\\u0097" +
613                         "\\u0098\\u0099\\u009a\\u009b\\u009c\\u009d\\u009e\\u009f" +
614                         "\\u00a0\\u00a1\\u00a2\\u00a3\\u00a4\\u00a5\\u00a6\\u00a7" +
615                         "\\u00a8\\u00a9\\u00aa\\u00ab\\u00ac\\u00ad\\u00ae\\u00af" +
616                         "\\u00b0\\u00b1\\u00b2\\u00b3\\u00b4\\u00b5\\u00b6\\u00b7" +
617                         "\\u00b8\\u00b9\\u00ba\\u00bb\\u00bc\\u00bd\\u00be\\u00bf" +
618                         "\\u00c0\\u00c1\\u00c2\\u00c3\\u00c4\\u00c5\\u00c6\\u00c7" +
619                         "\\u00c8\\u00c9\\u00ca\\u00cb\\u00cc\\u00cd\\u00ce\\u00cf" +
620                         "\\u00d0\\u00d1\\u00d2\\u00d3\\u00d4\\u00d5\\u00d6\\u00d7" +
621                         "\\u00d8\\u00d9\\u00da\\u00db\\u00dc\\u00dd\\u00de\\u00df" +
622                         "\\u00e0\\u00e1\\u00e2\\u00e3\\u00e4\\u00e5\\u00e6\\u00e7" +
623                         "\\u00e8\\u00e9\\u00ea\\u00eb\\u00ec\\u00ed\\u00ee\\u00ef" +
624                         "\\u00f0\\u00f1\\u00f2\\u00f3\\u00f4\\u00f5\\u00f6\\u00f7" +
625                         "\\u00f8\\u00f9\\u00fa\\u00fb\\u00fc\\u00fd\\u00fe\\u00ff" +
626                         "\"");
627
628                 {
629                         std::istringstream is(serializeString(teststring2), std::ios::binary);
630                         UASSERT(deSerializeString(is) == teststring2);
631                         UASSERT(!is.eof());
632                         is.get();
633                         UASSERT(is.eof());
634                 }
635                 {
636                         std::istringstream is(serializeWideString(teststring2_w), std::ios::binary);
637                         UASSERT(deSerializeWideString(is) == teststring2_w);
638                         UASSERT(!is.eof());
639                         is.get();
640                         UASSERT(is.eof());
641                 }
642                 {
643                         std::istringstream is(serializeLongString(teststring2), std::ios::binary);
644                         UASSERT(deSerializeLongString(is) == teststring2);
645                         UASSERT(!is.eof());
646                         is.get();
647                         UASSERT(is.eof());
648                 }
649                 {
650                         std::istringstream is(serializeJsonString(teststring2), std::ios::binary);
651                         //dstream<<serializeJsonString(deSerializeJsonString(is));
652                         UASSERT(deSerializeJsonString(is) == teststring2);
653                         UASSERT(!is.eof());
654                         is.get();
655                         UASSERT(is.eof());
656                 }
657         }
658 };
659
660 struct TestNodedefSerialization: public TestBase
661 {
662         void Run()
663         {
664                 ContentFeatures f;
665                 f.name = "default:stone";
666                 for(int i = 0; i < 6; i++)
667                         f.tiledef[i].name = "default_stone.png";
668                 f.is_ground_content = true;
669                 std::ostringstream os(std::ios::binary);
670                 f.serialize(os, LATEST_PROTOCOL_VERSION);
671                 verbosestream<<"Test ContentFeatures size: "<<os.str().size()<<std::endl;
672                 std::istringstream is(os.str(), std::ios::binary);
673                 ContentFeatures f2;
674                 f2.deSerialize(is);
675                 UASSERT(f.walkable == f2.walkable);
676                 UASSERT(f.node_box.type == f2.node_box.type);
677         }
678 };
679
680 struct TestCompress: public TestBase
681 {
682         void Run()
683         {
684                 { // ver 0
685
686                 SharedBuffer<u8> fromdata(4);
687                 fromdata[0]=1;
688                 fromdata[1]=5;
689                 fromdata[2]=5;
690                 fromdata[3]=1;
691
692                 std::ostringstream os(std::ios_base::binary);
693                 compress(fromdata, os, 0);
694
695                 std::string str_out = os.str();
696
697                 infostream<<"str_out.size()="<<str_out.size()<<std::endl;
698                 infostream<<"TestCompress: 1,5,5,1 -> ";
699                 for(u32 i=0; i<str_out.size(); i++)
700                 {
701                         infostream<<(u32)str_out[i]<<",";
702                 }
703                 infostream<<std::endl;
704
705                 UASSERT(str_out.size() == 10);
706
707                 UASSERT(str_out[0] == 0);
708                 UASSERT(str_out[1] == 0);
709                 UASSERT(str_out[2] == 0);
710                 UASSERT(str_out[3] == 4);
711                 UASSERT(str_out[4] == 0);
712                 UASSERT(str_out[5] == 1);
713                 UASSERT(str_out[6] == 1);
714                 UASSERT(str_out[7] == 5);
715                 UASSERT(str_out[8] == 0);
716                 UASSERT(str_out[9] == 1);
717
718                 std::istringstream is(str_out, std::ios_base::binary);
719                 std::ostringstream os2(std::ios_base::binary);
720
721                 decompress(is, os2, 0);
722                 std::string str_out2 = os2.str();
723
724                 infostream<<"decompress: ";
725                 for(u32 i=0; i<str_out2.size(); i++)
726                 {
727                         infostream<<(u32)str_out2[i]<<",";
728                 }
729                 infostream<<std::endl;
730
731                 UASSERT(str_out2.size() == fromdata.getSize());
732
733                 for(u32 i=0; i<str_out2.size(); i++)
734                 {
735                         UASSERT(str_out2[i] == fromdata[i]);
736                 }
737
738                 }
739
740                 { // ver HIGHEST
741
742                 SharedBuffer<u8> fromdata(4);
743                 fromdata[0]=1;
744                 fromdata[1]=5;
745                 fromdata[2]=5;
746                 fromdata[3]=1;
747
748                 std::ostringstream os(std::ios_base::binary);
749                 compress(fromdata, os, SER_FMT_VER_HIGHEST_READ);
750
751                 std::string str_out = os.str();
752
753                 infostream<<"str_out.size()="<<str_out.size()<<std::endl;
754                 infostream<<"TestCompress: 1,5,5,1 -> ";
755                 for(u32 i=0; i<str_out.size(); i++)
756                 {
757                         infostream<<(u32)str_out[i]<<",";
758                 }
759                 infostream<<std::endl;
760
761                 std::istringstream is(str_out, std::ios_base::binary);
762                 std::ostringstream os2(std::ios_base::binary);
763
764                 decompress(is, os2, SER_FMT_VER_HIGHEST_READ);
765                 std::string str_out2 = os2.str();
766
767                 infostream<<"decompress: ";
768                 for(u32 i=0; i<str_out2.size(); i++)
769                 {
770                         infostream<<(u32)str_out2[i]<<",";
771                 }
772                 infostream<<std::endl;
773
774                 UASSERT(str_out2.size() == fromdata.getSize());
775
776                 for(u32 i=0; i<str_out2.size(); i++)
777                 {
778                         UASSERT(str_out2[i] == fromdata[i]);
779                 }
780
781                 }
782
783                 // Test zlib wrapper with large amounts of data (larger than its
784                 // internal buffers)
785                 {
786                         infostream<<"Test: Testing zlib wrappers with a large amount "
787                                         <<"of pseudorandom data"<<std::endl;
788                         u32 size = 50000;
789                         infostream<<"Test: Input size of large compressZlib is "
790                                         <<size<<std::endl;
791                         std::string data_in;
792                         data_in.resize(size);
793                         PseudoRandom pseudorandom(9420);
794                         for(u32 i=0; i<size; i++)
795                                 data_in[i] = pseudorandom.range(0,255);
796                         std::ostringstream os_compressed(std::ios::binary);
797                         compressZlib(data_in, os_compressed);
798                         infostream<<"Test: Output size of large compressZlib is "
799                                         <<os_compressed.str().size()<<std::endl;
800                         std::istringstream is_compressed(os_compressed.str(), std::ios::binary);
801                         std::ostringstream os_decompressed(std::ios::binary);
802                         decompressZlib(is_compressed, os_decompressed);
803                         infostream<<"Test: Output size of large decompressZlib is "
804                                         <<os_decompressed.str().size()<<std::endl;
805                         std::string str_decompressed = os_decompressed.str();
806                         UTEST(str_decompressed.size() == data_in.size(), "Output size not"
807                                         " equal (output: %u, input: %u)",
808                                         (unsigned int)str_decompressed.size(), (unsigned int)data_in.size());
809                         for(u32 i=0; i<size && i<str_decompressed.size(); i++){
810                                 UTEST(str_decompressed[i] == data_in[i],
811                                                 "index out[%i]=%i differs from in[%i]=%i",
812                                                 i, str_decompressed[i], i, data_in[i]);
813                         }
814                 }
815         }
816 };
817
818 struct TestMapNode: public TestBase
819 {
820         void Run(INodeDefManager *nodedef)
821         {
822                 MapNode n;
823
824                 // Default values
825                 UASSERT(n.getContent() == CONTENT_AIR);
826                 UASSERT(n.getLight(LIGHTBANK_DAY, nodedef) == 0);
827                 UASSERT(n.getLight(LIGHTBANK_NIGHT, nodedef) == 0);
828
829                 // Transparency
830                 n.setContent(CONTENT_AIR);
831                 UASSERT(nodedef->get(n).light_propagates == true);
832                 n.setContent(LEGN(nodedef, "CONTENT_STONE"));
833                 UASSERT(nodedef->get(n).light_propagates == false);
834         }
835 };
836
837 struct TestVoxelManipulator: public TestBase
838 {
839         void Run(INodeDefManager *nodedef)
840         {
841                 /*
842                         VoxelArea
843                 */
844
845                 VoxelArea a(v3s16(-1,-1,-1), v3s16(1,1,1));
846                 UASSERT(a.index(0,0,0) == 1*3*3 + 1*3 + 1);
847                 UASSERT(a.index(-1,-1,-1) == 0);
848
849                 VoxelArea c(v3s16(-2,-2,-2), v3s16(2,2,2));
850                 // An area that is 1 bigger in x+ and z-
851                 VoxelArea d(v3s16(-2,-2,-3), v3s16(3,2,2));
852
853                 std::list<VoxelArea> aa;
854                 d.diff(c, aa);
855
856                 // Correct results
857                 std::vector<VoxelArea> results;
858                 results.push_back(VoxelArea(v3s16(-2,-2,-3),v3s16(3,2,-3)));
859                 results.push_back(VoxelArea(v3s16(3,-2,-2),v3s16(3,2,2)));
860
861                 UASSERT(aa.size() == results.size());
862
863                 infostream<<"Result of diff:"<<std::endl;
864                 for(std::list<VoxelArea>::const_iterator
865                                 i = aa.begin(); i != aa.end(); ++i)
866                 {
867                         i->print(infostream);
868                         infostream<<std::endl;
869
870                         std::vector<VoxelArea>::iterator j = std::find(results.begin(), results.end(), *i);
871                         UASSERT(j != results.end());
872                         results.erase(j);
873                 }
874
875
876                 /*
877                         VoxelManipulator
878                 */
879
880                 VoxelManipulator v;
881
882                 v.print(infostream, nodedef);
883
884                 infostream<<"*** Setting (-1,0,-1)=2 ***"<<std::endl;
885
886                 v.setNodeNoRef(v3s16(-1,0,-1), MapNode(CONTENT_GRASS));
887
888                 v.print(infostream, nodedef);
889
890                 UASSERT(v.getNode(v3s16(-1,0,-1)).getContent() == CONTENT_GRASS);
891
892                 infostream<<"*** Reading from inexistent (0,0,-1) ***"<<std::endl;
893
894                 EXCEPTION_CHECK(InvalidPositionException, v.getNode(v3s16(0,0,-1)));
895
896                 v.print(infostream, nodedef);
897
898                 infostream<<"*** Adding area ***"<<std::endl;
899
900                 v.addArea(a);
901
902                 v.print(infostream, nodedef);
903
904                 UASSERT(v.getNode(v3s16(-1,0,-1)).getContent() == CONTENT_GRASS);
905                 EXCEPTION_CHECK(InvalidPositionException, v.getNode(v3s16(0,1,1)));
906         }
907 };
908
909 struct TestVoxelAlgorithms: public TestBase
910 {
911         void Run(INodeDefManager *ndef)
912         {
913                 /*
914                         voxalgo::propagateSunlight
915                 */
916                 {
917                         VoxelManipulator v;
918                         for(u16 z=0; z<3; z++)
919                         for(u16 y=0; y<3; y++)
920                         for(u16 x=0; x<3; x++)
921                         {
922                                 v3s16 p(x,y,z);
923                                 v.setNodeNoRef(p, MapNode(CONTENT_AIR));
924                         }
925                         VoxelArea a(v3s16(0,0,0), v3s16(2,2,2));
926                         {
927                                 std::set<v3s16> light_sources;
928                                 voxalgo::setLight(v, a, 0, ndef);
929                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
930                                                 v, a, true, light_sources, ndef);
931                                 //v.print(dstream, ndef, VOXELPRINT_LIGHT_DAY);
932                                 UASSERT(res.bottom_sunlight_valid == true);
933                                 UASSERT(v.getNode(v3s16(1,1,1)).getLight(LIGHTBANK_DAY, ndef)
934                                                 == LIGHT_SUN);
935                         }
936                         v.setNodeNoRef(v3s16(0,0,0), MapNode(CONTENT_STONE));
937                         {
938                                 std::set<v3s16> light_sources;
939                                 voxalgo::setLight(v, a, 0, ndef);
940                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
941                                                 v, a, true, light_sources, ndef);
942                                 UASSERT(res.bottom_sunlight_valid == true);
943                                 UASSERT(v.getNode(v3s16(1,1,1)).getLight(LIGHTBANK_DAY, ndef)
944                                                 == LIGHT_SUN);
945                         }
946                         {
947                                 std::set<v3s16> light_sources;
948                                 voxalgo::setLight(v, a, 0, ndef);
949                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
950                                                 v, a, false, light_sources, ndef);
951                                 UASSERT(res.bottom_sunlight_valid == true);
952                                 UASSERT(v.getNode(v3s16(2,0,2)).getLight(LIGHTBANK_DAY, ndef)
953                                                 == 0);
954                         }
955                         v.setNodeNoRef(v3s16(1,3,2), MapNode(CONTENT_STONE));
956                         {
957                                 std::set<v3s16> light_sources;
958                                 voxalgo::setLight(v, a, 0, ndef);
959                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
960                                                 v, a, true, light_sources, ndef);
961                                 UASSERT(res.bottom_sunlight_valid == true);
962                                 UASSERT(v.getNode(v3s16(1,1,2)).getLight(LIGHTBANK_DAY, ndef)
963                                                 == 0);
964                         }
965                         {
966                                 std::set<v3s16> light_sources;
967                                 voxalgo::setLight(v, a, 0, ndef);
968                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
969                                                 v, a, false, light_sources, ndef);
970                                 UASSERT(res.bottom_sunlight_valid == true);
971                                 UASSERT(v.getNode(v3s16(1,0,2)).getLight(LIGHTBANK_DAY, ndef)
972                                                 == 0);
973                         }
974                         {
975                                 MapNode n(CONTENT_AIR);
976                                 n.setLight(LIGHTBANK_DAY, 10, ndef);
977                                 v.setNodeNoRef(v3s16(1,-1,2), n);
978                         }
979                         {
980                                 std::set<v3s16> light_sources;
981                                 voxalgo::setLight(v, a, 0, ndef);
982                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
983                                                 v, a, true, light_sources, ndef);
984                                 UASSERT(res.bottom_sunlight_valid == true);
985                         }
986                         {
987                                 std::set<v3s16> light_sources;
988                                 voxalgo::setLight(v, a, 0, ndef);
989                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
990                                                 v, a, false, light_sources, ndef);
991                                 UASSERT(res.bottom_sunlight_valid == true);
992                         }
993                         {
994                                 MapNode n(CONTENT_AIR);
995                                 n.setLight(LIGHTBANK_DAY, LIGHT_SUN, ndef);
996                                 v.setNodeNoRef(v3s16(1,-1,2), n);
997                         }
998                         {
999                                 std::set<v3s16> light_sources;
1000                                 voxalgo::setLight(v, a, 0, ndef);
1001                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
1002                                                 v, a, true, light_sources, ndef);
1003                                 UASSERT(res.bottom_sunlight_valid == false);
1004                         }
1005                         {
1006                                 std::set<v3s16> light_sources;
1007                                 voxalgo::setLight(v, a, 0, ndef);
1008                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
1009                                                 v, a, false, light_sources, ndef);
1010                                 UASSERT(res.bottom_sunlight_valid == false);
1011                         }
1012                         v.setNodeNoRef(v3s16(1,3,2), MapNode(CONTENT_IGNORE));
1013                         {
1014                                 std::set<v3s16> light_sources;
1015                                 voxalgo::setLight(v, a, 0, ndef);
1016                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
1017                                                 v, a, true, light_sources, ndef);
1018                                 UASSERT(res.bottom_sunlight_valid == true);
1019                         }
1020                 }
1021                 /*
1022                         voxalgo::clearLightAndCollectSources
1023                 */
1024                 {
1025                         VoxelManipulator v;
1026                         for(u16 z=0; z<3; z++)
1027                         for(u16 y=0; y<3; y++)
1028                         for(u16 x=0; x<3; x++)
1029                         {
1030                                 v3s16 p(x,y,z);
1031                                 v.setNode(p, MapNode(CONTENT_AIR));
1032                         }
1033                         VoxelArea a(v3s16(0,0,0), v3s16(2,2,2));
1034                         v.setNodeNoRef(v3s16(0,0,0), MapNode(CONTENT_STONE));
1035                         v.setNodeNoRef(v3s16(1,1,1), MapNode(CONTENT_TORCH));
1036                         {
1037                                 MapNode n(CONTENT_AIR);
1038                                 n.setLight(LIGHTBANK_DAY, 1, ndef);
1039                                 v.setNode(v3s16(1,1,2), n);
1040                         }
1041                         {
1042                                 std::set<v3s16> light_sources;
1043                                 std::map<v3s16, u8> unlight_from;
1044                                 voxalgo::clearLightAndCollectSources(v, a, LIGHTBANK_DAY,
1045                                                 ndef, light_sources, unlight_from);
1046                                 //v.print(dstream, ndef, VOXELPRINT_LIGHT_DAY);
1047                                 UASSERT(v.getNode(v3s16(0,1,1)).getLight(LIGHTBANK_DAY, ndef)
1048                                                 == 0);
1049                                 UASSERT(light_sources.find(v3s16(1,1,1)) != light_sources.end());
1050                                 UASSERT(light_sources.size() == 1);
1051                                 UASSERT(unlight_from.find(v3s16(1,1,2)) != unlight_from.end());
1052                                 UASSERT(unlight_from.size() == 1);
1053                         }
1054                 }
1055         }
1056 };
1057
1058 struct TestInventory: public TestBase
1059 {
1060         void Run(IItemDefManager *idef)
1061         {
1062                 std::string serialized_inventory =
1063                 "List 0 32\n"
1064                 "Width 3\n"
1065                 "Empty\n"
1066                 "Empty\n"
1067                 "Empty\n"
1068                 "Empty\n"
1069                 "Empty\n"
1070                 "Empty\n"
1071                 "Empty\n"
1072                 "Empty\n"
1073                 "Empty\n"
1074                 "Item default:cobble 61\n"
1075                 "Empty\n"
1076                 "Empty\n"
1077                 "Empty\n"
1078                 "Empty\n"
1079                 "Empty\n"
1080                 "Empty\n"
1081                 "Item default:dirt 71\n"
1082                 "Empty\n"
1083                 "Empty\n"
1084                 "Empty\n"
1085                 "Empty\n"
1086                 "Empty\n"
1087                 "Empty\n"
1088                 "Empty\n"
1089                 "Item default:dirt 99\n"
1090                 "Item default:cobble 38\n"
1091                 "Empty\n"
1092                 "Empty\n"
1093                 "Empty\n"
1094                 "Empty\n"
1095                 "Empty\n"
1096                 "Empty\n"
1097                 "EndInventoryList\n"
1098                 "EndInventory\n";
1099
1100                 std::string serialized_inventory_2 =
1101                 "List main 32\n"
1102                 "Width 5\n"
1103                 "Empty\n"
1104                 "Empty\n"
1105                 "Empty\n"
1106                 "Empty\n"
1107                 "Empty\n"
1108                 "Empty\n"
1109                 "Empty\n"
1110                 "Empty\n"
1111                 "Empty\n"
1112                 "Item default:cobble 61\n"
1113                 "Empty\n"
1114                 "Empty\n"
1115                 "Empty\n"
1116                 "Empty\n"
1117                 "Empty\n"
1118                 "Empty\n"
1119                 "Item default:dirt 71\n"
1120                 "Empty\n"
1121                 "Empty\n"
1122                 "Empty\n"
1123                 "Empty\n"
1124                 "Empty\n"
1125                 "Empty\n"
1126                 "Empty\n"
1127                 "Item default:dirt 99\n"
1128                 "Item default:cobble 38\n"
1129                 "Empty\n"
1130                 "Empty\n"
1131                 "Empty\n"
1132                 "Empty\n"
1133                 "Empty\n"
1134                 "Empty\n"
1135                 "EndInventoryList\n"
1136                 "EndInventory\n";
1137
1138                 Inventory inv(idef);
1139                 std::istringstream is(serialized_inventory, std::ios::binary);
1140                 inv.deSerialize(is);
1141                 UASSERT(inv.getList("0"));
1142                 UASSERT(!inv.getList("main"));
1143                 inv.getList("0")->setName("main");
1144                 UASSERT(!inv.getList("0"));
1145                 UASSERT(inv.getList("main"));
1146                 UASSERT(inv.getList("main")->getWidth() == 3);
1147                 inv.getList("main")->setWidth(5);
1148                 std::ostringstream inv_os(std::ios::binary);
1149                 inv.serialize(inv_os);
1150                 UASSERT(inv_os.str() == serialized_inventory_2);
1151         }
1152 };
1153
1154 /*
1155         NOTE: These tests became non-working then NodeContainer was removed.
1156               These should be redone, utilizing some kind of a virtual
1157                   interface for Map (IMap would be fine).
1158 */
1159 #if 0
1160 struct TestMapBlock: public TestBase
1161 {
1162         class TC : public NodeContainer
1163         {
1164         public:
1165
1166                 MapNode node;
1167                 bool position_valid;
1168                 core::list<v3s16> validity_exceptions;
1169
1170                 TC()
1171                 {
1172                         position_valid = true;
1173                 }
1174
1175                 virtual bool isValidPosition(v3s16 p)
1176                 {
1177                         //return position_valid ^ (p==position_valid_exception);
1178                         bool exception = false;
1179                         for(core::list<v3s16>::Iterator i=validity_exceptions.begin();
1180                                         i != validity_exceptions.end(); i++)
1181                         {
1182                                 if(p == *i)
1183                                 {
1184                                         exception = true;
1185                                         break;
1186                                 }
1187                         }
1188                         return exception ? !position_valid : position_valid;
1189                 }
1190
1191                 virtual MapNode getNode(v3s16 p)
1192                 {
1193                         if(isValidPosition(p) == false)
1194                                 throw InvalidPositionException();
1195                         return node;
1196                 }
1197
1198                 virtual void setNode(v3s16 p, MapNode & n)
1199                 {
1200                         if(isValidPosition(p) == false)
1201                                 throw InvalidPositionException();
1202                 };
1203
1204                 virtual u16 nodeContainerId() const
1205                 {
1206                         return 666;
1207                 }
1208         };
1209
1210         void Run()
1211         {
1212                 TC parent;
1213
1214                 MapBlock b(&parent, v3s16(1,1,1));
1215                 v3s16 relpos(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE);
1216
1217                 UASSERT(b.getPosRelative() == relpos);
1218
1219                 UASSERT(b.getBox().MinEdge.X == MAP_BLOCKSIZE);
1220                 UASSERT(b.getBox().MaxEdge.X == MAP_BLOCKSIZE*2-1);
1221                 UASSERT(b.getBox().MinEdge.Y == MAP_BLOCKSIZE);
1222                 UASSERT(b.getBox().MaxEdge.Y == MAP_BLOCKSIZE*2-1);
1223                 UASSERT(b.getBox().MinEdge.Z == MAP_BLOCKSIZE);
1224                 UASSERT(b.getBox().MaxEdge.Z == MAP_BLOCKSIZE*2-1);
1225
1226                 UASSERT(b.isValidPosition(v3s16(0,0,0)) == true);
1227                 UASSERT(b.isValidPosition(v3s16(-1,0,0)) == false);
1228                 UASSERT(b.isValidPosition(v3s16(-1,-142,-2341)) == false);
1229                 UASSERT(b.isValidPosition(v3s16(-124,142,2341)) == false);
1230                 UASSERT(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true);
1231                 UASSERT(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE,MAP_BLOCKSIZE-1)) == false);
1232
1233                 /*
1234                         TODO: this method should probably be removed
1235                         if the block size isn't going to be set variable
1236                 */
1237                 /*UASSERT(b.getSizeNodes() == v3s16(MAP_BLOCKSIZE,
1238                                 MAP_BLOCKSIZE, MAP_BLOCKSIZE));*/
1239
1240                 // Changed flag should be initially set
1241                 UASSERT(b.getModified() == MOD_STATE_WRITE_NEEDED);
1242                 b.resetModified();
1243                 UASSERT(b.getModified() == MOD_STATE_CLEAN);
1244
1245                 // All nodes should have been set to
1246                 // .d=CONTENT_IGNORE and .getLight() = 0
1247                 for(u16 z=0; z<MAP_BLOCKSIZE; z++)
1248                 for(u16 y=0; y<MAP_BLOCKSIZE; y++)
1249                 for(u16 x=0; x<MAP_BLOCKSIZE; x++)
1250                 {
1251                         //UASSERT(b.getNode(v3s16(x,y,z)).getContent() == CONTENT_AIR);
1252                         UASSERT(b.getNode(v3s16(x,y,z)).getContent() == CONTENT_IGNORE);
1253                         UASSERT(b.getNode(v3s16(x,y,z)).getLight(LIGHTBANK_DAY) == 0);
1254                         UASSERT(b.getNode(v3s16(x,y,z)).getLight(LIGHTBANK_NIGHT) == 0);
1255                 }
1256
1257                 {
1258                         MapNode n(CONTENT_AIR);
1259                         for(u16 z=0; z<MAP_BLOCKSIZE; z++)
1260                         for(u16 y=0; y<MAP_BLOCKSIZE; y++)
1261                         for(u16 x=0; x<MAP_BLOCKSIZE; x++)
1262                         {
1263                                 b.setNode(v3s16(x,y,z), n);
1264                         }
1265                 }
1266
1267                 /*
1268                         Parent fetch functions
1269                 */
1270                 parent.position_valid = false;
1271                 parent.node.setContent(5);
1272
1273                 MapNode n;
1274
1275                 // Positions in the block should still be valid
1276                 UASSERT(b.isValidPositionParent(v3s16(0,0,0)) == true);
1277                 UASSERT(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true);
1278                 n = b.getNodeParent(v3s16(0,MAP_BLOCKSIZE-1,0));
1279                 UASSERT(n.getContent() == CONTENT_AIR);
1280
1281                 // ...but outside the block they should be invalid
1282                 UASSERT(b.isValidPositionParent(v3s16(-121,2341,0)) == false);
1283                 UASSERT(b.isValidPositionParent(v3s16(-1,0,0)) == false);
1284                 UASSERT(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == false);
1285
1286                 {
1287                         bool exception_thrown = false;
1288                         try{
1289                                 // This should throw an exception
1290                                 MapNode n = b.getNodeParent(v3s16(0,0,-1));
1291                         }
1292                         catch(InvalidPositionException &e)
1293                         {
1294                                 exception_thrown = true;
1295                         }
1296                         UASSERT(exception_thrown);
1297                 }
1298
1299                 parent.position_valid = true;
1300                 // Now the positions outside should be valid
1301                 UASSERT(b.isValidPositionParent(v3s16(-121,2341,0)) == true);
1302                 UASSERT(b.isValidPositionParent(v3s16(-1,0,0)) == true);
1303                 UASSERT(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == true);
1304                 n = b.getNodeParent(v3s16(0,0,MAP_BLOCKSIZE));
1305                 UASSERT(n.getContent() == 5);
1306
1307                 /*
1308                         Set a node
1309                 */
1310                 v3s16 p(1,2,0);
1311                 n.setContent(4);
1312                 b.setNode(p, n);
1313                 UASSERT(b.getNode(p).getContent() == 4);
1314                 //TODO: Update to new system
1315                 /*UASSERT(b.getNodeTile(p) == 4);
1316                 UASSERT(b.getNodeTile(v3s16(-1,-1,0)) == 5);*/
1317
1318                 /*
1319                         propagateSunlight()
1320                 */
1321                 // Set lighting of all nodes to 0
1322                 for(u16 z=0; z<MAP_BLOCKSIZE; z++){
1323                         for(u16 y=0; y<MAP_BLOCKSIZE; y++){
1324                                 for(u16 x=0; x<MAP_BLOCKSIZE; x++){
1325                                         MapNode n = b.getNode(v3s16(x,y,z));
1326                                         n.setLight(LIGHTBANK_DAY, 0);
1327                                         n.setLight(LIGHTBANK_NIGHT, 0);
1328                                         b.setNode(v3s16(x,y,z), n);
1329                                 }
1330                         }
1331                 }
1332                 {
1333                         /*
1334                                 Check how the block handles being a lonely sky block
1335                         */
1336                         parent.position_valid = true;
1337                         b.setIsUnderground(false);
1338                         parent.node.setContent(CONTENT_AIR);
1339                         parent.node.setLight(LIGHTBANK_DAY, LIGHT_SUN);
1340                         parent.node.setLight(LIGHTBANK_NIGHT, 0);
1341                         core::map<v3s16, bool> light_sources;
1342                         // The bottom block is invalid, because we have a shadowing node
1343                         UASSERT(b.propagateSunlight(light_sources) == false);
1344                         UASSERT(b.getNode(v3s16(1,4,0)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
1345                         UASSERT(b.getNode(v3s16(1,3,0)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
1346                         UASSERT(b.getNode(v3s16(1,2,0)).getLight(LIGHTBANK_DAY) == 0);
1347                         UASSERT(b.getNode(v3s16(1,1,0)).getLight(LIGHTBANK_DAY) == 0);
1348                         UASSERT(b.getNode(v3s16(1,0,0)).getLight(LIGHTBANK_DAY) == 0);
1349                         UASSERT(b.getNode(v3s16(1,2,3)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
1350                         UASSERT(b.getFaceLight2(1000, p, v3s16(0,1,0)) == LIGHT_SUN);
1351                         UASSERT(b.getFaceLight2(1000, p, v3s16(0,-1,0)) == 0);
1352                         UASSERT(b.getFaceLight2(0, p, v3s16(0,-1,0)) == 0);
1353                         // According to MapBlock::getFaceLight,
1354                         // The face on the z+ side should have double-diminished light
1355                         //UASSERT(b.getFaceLight(p, v3s16(0,0,1)) == diminish_light(diminish_light(LIGHT_MAX)));
1356                         // The face on the z+ side should have diminished light
1357                         UASSERT(b.getFaceLight2(1000, p, v3s16(0,0,1)) == diminish_light(LIGHT_MAX));
1358                 }
1359                 /*
1360                         Check how the block handles being in between blocks with some non-sunlight
1361                         while being underground
1362                 */
1363                 {
1364                         // Make neighbours to exist and set some non-sunlight to them
1365                         parent.position_valid = true;
1366                         b.setIsUnderground(true);
1367                         parent.node.setLight(LIGHTBANK_DAY, LIGHT_MAX/2);
1368                         core::map<v3s16, bool> light_sources;
1369                         // The block below should be valid because there shouldn't be
1370                         // sunlight in there either
1371                         UASSERT(b.propagateSunlight(light_sources, true) == true);
1372                         // Should not touch nodes that are not affected (that is, all of them)
1373                         //UASSERT(b.getNode(v3s16(1,2,3)).getLight() == LIGHT_SUN);
1374                         // Should set light of non-sunlighted blocks to 0.
1375                         UASSERT(b.getNode(v3s16(1,2,3)).getLight(LIGHTBANK_DAY) == 0);
1376                 }
1377                 /*
1378                         Set up a situation where:
1379                         - There is only air in this block
1380                         - There is a valid non-sunlighted block at the bottom, and
1381                         - Invalid blocks elsewhere.
1382                         - the block is not underground.
1383
1384                         This should result in bottom block invalidity
1385                 */
1386                 {
1387                         b.setIsUnderground(false);
1388                         // Clear block
1389                         for(u16 z=0; z<MAP_BLOCKSIZE; z++){
1390                                 for(u16 y=0; y<MAP_BLOCKSIZE; y++){
1391                                         for(u16 x=0; x<MAP_BLOCKSIZE; x++){
1392                                                 MapNode n;
1393                                                 n.setContent(CONTENT_AIR);
1394                                                 n.setLight(LIGHTBANK_DAY, 0);
1395                                                 b.setNode(v3s16(x,y,z), n);
1396                                         }
1397                                 }
1398                         }
1399                         // Make neighbours invalid
1400                         parent.position_valid = false;
1401                         // Add exceptions to the top of the bottom block
1402                         for(u16 x=0; x<MAP_BLOCKSIZE; x++)
1403                         for(u16 z=0; z<MAP_BLOCKSIZE; z++)
1404                         {
1405                                 parent.validity_exceptions.push_back(v3s16(MAP_BLOCKSIZE+x, MAP_BLOCKSIZE-1, MAP_BLOCKSIZE+z));
1406                         }
1407                         // Lighting value for the valid nodes
1408                         parent.node.setLight(LIGHTBANK_DAY, LIGHT_MAX/2);
1409                         core::map<v3s16, bool> light_sources;
1410                         // Bottom block is not valid
1411                         UASSERT(b.propagateSunlight(light_sources) == false);
1412                 }
1413         }
1414 };
1415
1416 struct TestMapSector: public TestBase
1417 {
1418         class TC : public NodeContainer
1419         {
1420         public:
1421
1422                 MapNode node;
1423                 bool position_valid;
1424
1425                 TC()
1426                 {
1427                         position_valid = true;
1428                 }
1429
1430                 virtual bool isValidPosition(v3s16 p)
1431                 {
1432                         return position_valid;
1433                 }
1434
1435                 virtual MapNode getNode(v3s16 p)
1436                 {
1437                         if(position_valid == false)
1438                                 throw InvalidPositionException();
1439                         return node;
1440                 }
1441
1442                 virtual void setNode(v3s16 p, MapNode & n)
1443                 {
1444                         if(position_valid == false)
1445                                 throw InvalidPositionException();
1446                 };
1447
1448                 virtual u16 nodeContainerId() const
1449                 {
1450                         return 666;
1451                 }
1452         };
1453
1454         void Run()
1455         {
1456                 TC parent;
1457                 parent.position_valid = false;
1458
1459                 // Create one with no heightmaps
1460                 ServerMapSector sector(&parent, v2s16(1,1));
1461
1462                 UASSERT(sector.getBlockNoCreateNoEx(0) == 0);
1463                 UASSERT(sector.getBlockNoCreateNoEx(1) == 0);
1464
1465                 MapBlock * bref = sector.createBlankBlock(-2);
1466
1467                 UASSERT(sector.getBlockNoCreateNoEx(0) == 0);
1468                 UASSERT(sector.getBlockNoCreateNoEx(-2) == bref);
1469
1470                 //TODO: Check for AlreadyExistsException
1471
1472                 /*bool exception_thrown = false;
1473                 try{
1474                         sector.getBlock(0);
1475                 }
1476                 catch(InvalidPositionException &e){
1477                         exception_thrown = true;
1478                 }
1479                 UASSERT(exception_thrown);*/
1480
1481         }
1482 };
1483 #endif
1484
1485 struct TestCollision: public TestBase
1486 {
1487         void Run()
1488         {
1489                 /*
1490                         axisAlignedCollision
1491                 */
1492
1493                 for(s16 bx = -3; bx <= 3; bx++)
1494                 for(s16 by = -3; by <= 3; by++)
1495                 for(s16 bz = -3; bz <= 3; bz++)
1496                 {
1497                         // X-
1498                         {
1499                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1500                                 aabb3f m(bx-2, by, bz, bx-1, by+1, bz+1);
1501                                 v3f v(1, 0, 0);
1502                                 f32 dtime = 0;
1503                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1504                                 UASSERT(fabs(dtime - 1.000) < 0.001);
1505                         }
1506                         {
1507                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1508                                 aabb3f m(bx-2, by, bz, bx-1, by+1, bz+1);
1509                                 v3f v(-1, 0, 0);
1510                                 f32 dtime = 0;
1511                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == -1);
1512                         }
1513                         {
1514                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1515                                 aabb3f m(bx-2, by+1.5, bz, bx-1, by+2.5, bz-1);
1516                                 v3f v(1, 0, 0);
1517                                 f32 dtime;
1518                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == -1);
1519                         }
1520                         {
1521                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1522                                 aabb3f m(bx-2, by-1.5, bz, bx-1.5, by+0.5, bz+1);
1523                                 v3f v(0.5, 0.1, 0);
1524                                 f32 dtime;
1525                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1526                                 UASSERT(fabs(dtime - 3.000) < 0.001);
1527                         }
1528                         {
1529                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1530                                 aabb3f m(bx-2, by-1.5, bz, bx-1.5, by+0.5, bz+1);
1531                                 v3f v(0.5, 0.1, 0);
1532                                 f32 dtime;
1533                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1534                                 UASSERT(fabs(dtime - 3.000) < 0.001);
1535                         }
1536
1537                         // X+
1538                         {
1539                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1540                                 aabb3f m(bx+2, by, bz, bx+3, by+1, bz+1);
1541                                 v3f v(-1, 0, 0);
1542                                 f32 dtime;
1543                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1544                                 UASSERT(fabs(dtime - 1.000) < 0.001);
1545                         }
1546                         {
1547                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1548                                 aabb3f m(bx+2, by, bz, bx+3, by+1, bz+1);
1549                                 v3f v(1, 0, 0);
1550                                 f32 dtime;
1551                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == -1);
1552                         }
1553                         {
1554                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1555                                 aabb3f m(bx+2, by, bz+1.5, bx+3, by+1, bz+3.5);
1556                                 v3f v(-1, 0, 0);
1557                                 f32 dtime;
1558                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == -1);
1559                         }
1560                         {
1561                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1562                                 aabb3f m(bx+2, by-1.5, bz, bx+2.5, by-0.5, bz+1);
1563                                 v3f v(-0.5, 0.2, 0);
1564                                 f32 dtime;
1565                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 1);  // Y, not X!
1566                                 UASSERT(fabs(dtime - 2.500) < 0.001);
1567                         }
1568                         {
1569                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1570                                 aabb3f m(bx+2, by-1.5, bz, bx+2.5, by-0.5, bz+1);
1571                                 v3f v(-0.5, 0.3, 0);
1572                                 f32 dtime;
1573                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1574                                 UASSERT(fabs(dtime - 2.000) < 0.001);
1575                         }
1576
1577                         // TODO: Y-, Y+, Z-, Z+
1578
1579                         // misc
1580                         {
1581                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1582                                 aabb3f m(bx+2.3, by+2.29, bz+2.29, bx+4.2, by+4.2, bz+4.2);
1583                                 v3f v(-1./3, -1./3, -1./3);
1584                                 f32 dtime;
1585                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1586                                 UASSERT(fabs(dtime - 0.9) < 0.001);
1587                         }
1588                         {
1589                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1590                                 aabb3f m(bx+2.29, by+2.3, bz+2.29, bx+4.2, by+4.2, bz+4.2);
1591                                 v3f v(-1./3, -1./3, -1./3);
1592                                 f32 dtime;
1593                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 1);
1594                                 UASSERT(fabs(dtime - 0.9) < 0.001);
1595                         }
1596                         {
1597                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1598                                 aabb3f m(bx+2.29, by+2.29, bz+2.3, bx+4.2, by+4.2, bz+4.2);
1599                                 v3f v(-1./3, -1./3, -1./3);
1600                                 f32 dtime;
1601                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 2);
1602                                 UASSERT(fabs(dtime - 0.9) < 0.001);
1603                         }
1604                         {
1605                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1606                                 aabb3f m(bx-4.2, by-4.2, bz-4.2, bx-2.3, by-2.29, bz-2.29);
1607                                 v3f v(1./7, 1./7, 1./7);
1608                                 f32 dtime;
1609                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1610                                 UASSERT(fabs(dtime - 16.1) < 0.001);
1611                         }
1612                         {
1613                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1614                                 aabb3f m(bx-4.2, by-4.2, bz-4.2, bx-2.29, by-2.3, bz-2.29);
1615                                 v3f v(1./7, 1./7, 1./7);
1616                                 f32 dtime;
1617                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 1);
1618                                 UASSERT(fabs(dtime - 16.1) < 0.001);
1619                         }
1620                         {
1621                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1622                                 aabb3f m(bx-4.2, by-4.2, bz-4.2, bx-2.29, by-2.29, bz-2.3);
1623                                 v3f v(1./7, 1./7, 1./7);
1624                                 f32 dtime;
1625                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 2);
1626                                 UASSERT(fabs(dtime - 16.1) < 0.001);
1627                         }
1628                 }
1629         }
1630 };
1631
1632 struct TestSocket: public TestBase
1633 {
1634         void Run()
1635         {
1636                 const int port = 30003;
1637                 Address address(0,0,0,0, port);
1638                 Address address6((IPv6AddressBytes*) NULL, port);
1639
1640                 // IPv6 socket test
1641                 {
1642                         UDPSocket socket6;
1643
1644                         if (!socket6.init(true, true)) {
1645                                 /* Note: Failing to create an IPv6 socket is not technically an
1646                                    error because the OS may not support IPv6 or it may
1647                                    have been disabled. IPv6 is not /required/ by
1648                                    minetest and therefore this should not cause the unit
1649                                    test to fail
1650                                 */
1651                                 dstream << "WARNING: IPv6 socket creation failed (unit test)"
1652                                         << std::endl;
1653                         } else {
1654                                 const char sendbuffer[] = "hello world!";
1655                                 IPv6AddressBytes bytes;
1656                                 bytes.bytes[15] = 1;
1657
1658                                 socket6.Bind(address6);
1659
1660                                 try {
1661                                         socket6.Send(Address(&bytes, port), sendbuffer, sizeof(sendbuffer));
1662
1663                                         sleep_ms(50);
1664
1665                                         char rcvbuffer[256] = { 0 };
1666                                         Address sender;
1667
1668                                         for(;;) {
1669                                                 if (socket6.Receive(sender, rcvbuffer, sizeof(rcvbuffer )) < 0)
1670                                                         break;
1671                                         }
1672                                         //FIXME: This fails on some systems
1673                                         UASSERT(strncmp(sendbuffer, rcvbuffer, sizeof(sendbuffer)) == 0);
1674                                         UASSERT(memcmp(sender.getAddress6().sin6_addr.s6_addr,
1675                                                         Address(&bytes, 0).getAddress6().sin6_addr.s6_addr, 16) == 0);
1676                                 }
1677                                 catch (SendFailedException e) {
1678                                         errorstream << "IPv6 support enabled but not available!"
1679                                                     << std::endl;
1680                                 }
1681                         }
1682                 }
1683
1684                 // IPv4 socket test
1685                 {
1686                         UDPSocket socket(false);
1687                         socket.Bind(address);
1688
1689                         const char sendbuffer[] = "hello world!";
1690                         socket.Send(Address(127, 0, 0 ,1, port), sendbuffer, sizeof(sendbuffer));
1691
1692                         sleep_ms(50);
1693
1694                         char rcvbuffer[256] = { 0 };
1695                         Address sender;
1696                         for(;;) {
1697                                 if (socket.Receive(sender, rcvbuffer, sizeof(rcvbuffer)) < 0)
1698                                         break;
1699                         }
1700                         //FIXME: This fails on some systems
1701                         UASSERT(strncmp(sendbuffer, rcvbuffer, sizeof(sendbuffer)) == 0);
1702                         UASSERT(sender.getAddress().sin_addr.s_addr ==
1703                                         Address(127, 0, 0, 1, 0).getAddress().sin_addr.s_addr);
1704                 }
1705         }
1706 };
1707
1708 struct TestConnection: public TestBase
1709 {
1710         void TestHelpers()
1711         {
1712                 /*
1713                         Test helper functions
1714                 */
1715
1716                 // Some constants for testing
1717                 u32 proto_id = 0x12345678;
1718                 u16 peer_id = 123;
1719                 u8 channel = 2;
1720                 SharedBuffer<u8> data1(1);
1721                 data1[0] = 100;
1722                 Address a(127,0,0,1, 10);
1723                 const u16 seqnum = 34352;
1724
1725                 con::BufferedPacket p1 = con::makePacket(a, data1,
1726                                 proto_id, peer_id, channel);
1727                 /*
1728                         We should now have a packet with this data:
1729                         Header:
1730                                 [0] u32 protocol_id
1731                                 [4] u16 sender_peer_id
1732                                 [6] u8 channel
1733                         Data:
1734                                 [7] u8 data1[0]
1735                 */
1736                 UASSERT(readU32(&p1.data[0]) == proto_id);
1737                 UASSERT(readU16(&p1.data[4]) == peer_id);
1738                 UASSERT(readU8(&p1.data[6]) == channel);
1739                 UASSERT(readU8(&p1.data[7]) == data1[0]);
1740
1741                 //infostream<<"initial data1[0]="<<((u32)data1[0]&0xff)<<std::endl;
1742
1743                 SharedBuffer<u8> p2 = con::makeReliablePacket(data1, seqnum);
1744
1745                 /*infostream<<"p2.getSize()="<<p2.getSize()<<", data1.getSize()="
1746                                 <<data1.getSize()<<std::endl;
1747                 infostream<<"readU8(&p2[3])="<<readU8(&p2[3])
1748                                 <<" p2[3]="<<((u32)p2[3]&0xff)<<std::endl;
1749                 infostream<<"data1[0]="<<((u32)data1[0]&0xff)<<std::endl;*/
1750
1751                 UASSERT(p2.getSize() == 3 + data1.getSize());
1752                 UASSERT(readU8(&p2[0]) == TYPE_RELIABLE);
1753                 UASSERT(readU16(&p2[1]) == seqnum);
1754                 UASSERT(readU8(&p2[3]) == data1[0]);
1755         }
1756
1757         struct Handler : public con::PeerHandler
1758         {
1759                 Handler(const char *a_name)
1760                 {
1761                         count = 0;
1762                         last_id = 0;
1763                         name = a_name;
1764                 }
1765                 void peerAdded(con::Peer *peer)
1766                 {
1767                         infostream<<"Handler("<<name<<")::peerAdded(): "
1768                                         "id="<<peer->id<<std::endl;
1769                         last_id = peer->id;
1770                         count++;
1771                 }
1772                 void deletingPeer(con::Peer *peer, bool timeout)
1773                 {
1774                         infostream<<"Handler("<<name<<")::deletingPeer(): "
1775                                         "id="<<peer->id
1776                                         <<", timeout="<<timeout<<std::endl;
1777                         last_id = peer->id;
1778                         count--;
1779                 }
1780
1781                 s32 count;
1782                 u16 last_id;
1783                 const char *name;
1784         };
1785
1786         void Run()
1787         {
1788                 DSTACK("TestConnection::Run");
1789
1790                 TestHelpers();
1791
1792                 /*
1793                         Test some real connections
1794
1795                         NOTE: This mostly tests the legacy interface.
1796                 */
1797
1798                 u32 proto_id = 0xad26846a;
1799
1800                 Handler hand_server("server");
1801                 Handler hand_client("client");
1802
1803                 infostream<<"** Creating server Connection"<<std::endl;
1804                 con::Connection server(proto_id, 512, 5.0, false, &hand_server);
1805                 Address address(0,0,0,0, 30001);
1806                 server.Serve(address);
1807
1808                 infostream<<"** Creating client Connection"<<std::endl;
1809                 con::Connection client(proto_id, 512, 5.0, false, &hand_client);
1810
1811                 UASSERT(hand_server.count == 0);
1812                 UASSERT(hand_client.count == 0);
1813
1814                 sleep_ms(50);
1815
1816                 Address server_address(127,0,0,1, 30001);
1817                 infostream<<"** running client.Connect()"<<std::endl;
1818                 client.Connect(server_address);
1819
1820                 sleep_ms(50);
1821
1822                 // Client should not have added client yet
1823                 UASSERT(hand_client.count == 0);
1824
1825                 try
1826                 {
1827                         u16 peer_id;
1828                         SharedBuffer<u8> data;
1829                         infostream<<"** running client.Receive()"<<std::endl;
1830                         u32 size = client.Receive(peer_id, data);
1831                         infostream<<"** Client received: peer_id="<<peer_id
1832                                         <<", size="<<size
1833                                         <<std::endl;
1834                 }
1835                 catch(con::NoIncomingDataException &e)
1836                 {
1837                 }
1838
1839                 // Client should have added server now
1840                 UASSERT(hand_client.count == 1);
1841                 UASSERT(hand_client.last_id == 1);
1842                 // Server should not have added client yet
1843                 UASSERT(hand_server.count == 0);
1844
1845                 sleep_ms(100);
1846
1847                 try
1848                 {
1849                         u16 peer_id;
1850                         SharedBuffer<u8> data;
1851                         infostream<<"** running server.Receive()"<<std::endl;
1852                         u32 size = server.Receive(peer_id, data);
1853                         infostream<<"** Server received: peer_id="<<peer_id
1854                                         <<", size="<<size
1855                                         <<std::endl;
1856                 }
1857                 catch(con::NoIncomingDataException &e)
1858                 {
1859                         // No actual data received, but the client has
1860                         // probably been connected
1861                 }
1862
1863                 // Client should be the same
1864                 UASSERT(hand_client.count == 1);
1865                 UASSERT(hand_client.last_id == 1);
1866                 // Server should have the client
1867                 UASSERT(hand_server.count == 1);
1868                 UASSERT(hand_server.last_id == 2);
1869
1870                 //sleep_ms(50);
1871
1872                 while(client.Connected() == false)
1873                 {
1874                         try
1875                         {
1876                                 u16 peer_id;
1877                                 SharedBuffer<u8> data;
1878                                 infostream<<"** running client.Receive()"<<std::endl;
1879                                 u32 size = client.Receive(peer_id, data);
1880                                 infostream<<"** Client received: peer_id="<<peer_id
1881                                                 <<", size="<<size
1882                                                 <<std::endl;
1883                         }
1884                         catch(con::NoIncomingDataException &e)
1885                         {
1886                         }
1887                         sleep_ms(50);
1888                 }
1889
1890                 sleep_ms(50);
1891
1892                 try
1893                 {
1894                         u16 peer_id;
1895                         SharedBuffer<u8> data;
1896                         infostream<<"** running server.Receive()"<<std::endl;
1897                         u32 size = server.Receive(peer_id, data);
1898                         infostream<<"** Server received: peer_id="<<peer_id
1899                                         <<", size="<<size
1900                                         <<std::endl;
1901                 }
1902                 catch(con::NoIncomingDataException &e)
1903                 {
1904                 }
1905 #if 1
1906                 /*
1907                         Simple send-receive test
1908                 */
1909                 {
1910                         /*u8 data[] = "Hello World!";
1911                         u32 datasize = sizeof(data);*/
1912                         SharedBuffer<u8> data = SharedBufferFromString("Hello World!");
1913
1914                         infostream<<"** running client.Send()"<<std::endl;
1915                         client.Send(PEER_ID_SERVER, 0, data, true);
1916
1917                         sleep_ms(50);
1918
1919                         u16 peer_id;
1920                         SharedBuffer<u8> recvdata;
1921                         infostream<<"** running server.Receive()"<<std::endl;
1922                         u32 size = server.Receive(peer_id, recvdata);
1923                         infostream<<"** Server received: peer_id="<<peer_id
1924                                         <<", size="<<size
1925                                         <<", data="<<*data
1926                                         <<std::endl;
1927                         UASSERT(memcmp(*data, *recvdata, data.getSize()) == 0);
1928                 }
1929 #endif
1930                 u16 peer_id_client = 2;
1931 #if 0
1932                 /*
1933                         Send consequent packets in different order
1934                         Not compatible with new Connection, thus commented out.
1935                 */
1936                 {
1937                         //u8 data1[] = "hello1";
1938                         //u8 data2[] = "hello2";
1939                         SharedBuffer<u8> data1 = SharedBufferFromString("hello1");
1940                         SharedBuffer<u8> data2 = SharedBufferFromString("Hello2");
1941
1942                         Address client_address =
1943                                         server.GetPeerAddress(peer_id_client);
1944
1945                         infostream<<"*** Sending packets in wrong order (2,1,2)"
1946                                         <<std::endl;
1947
1948                         u8 chn = 0;
1949                         con::Channel *ch = &server.getPeer(peer_id_client)->channels[chn];
1950                         u16 sn = ch->next_outgoing_seqnum;
1951                         ch->next_outgoing_seqnum = sn+1;
1952                         server.Send(peer_id_client, chn, data2, true);
1953                         ch->next_outgoing_seqnum = sn;
1954                         server.Send(peer_id_client, chn, data1, true);
1955                         ch->next_outgoing_seqnum = sn+1;
1956                         server.Send(peer_id_client, chn, data2, true);
1957
1958                         sleep_ms(50);
1959
1960                         infostream<<"*** Receiving the packets"<<std::endl;
1961
1962                         u16 peer_id;
1963                         SharedBuffer<u8> recvdata;
1964                         u32 size;
1965
1966                         infostream<<"** running client.Receive()"<<std::endl;
1967                         peer_id = 132;
1968                         size = client.Receive(peer_id, recvdata);
1969                         infostream<<"** Client received: peer_id="<<peer_id
1970                                         <<", size="<<size
1971                                         <<", data="<<*recvdata
1972                                         <<std::endl;
1973                         UASSERT(size == data1.getSize());
1974                         UASSERT(memcmp(*data1, *recvdata, data1.getSize()) == 0);
1975                         UASSERT(peer_id == PEER_ID_SERVER);
1976
1977                         infostream<<"** running client.Receive()"<<std::endl;
1978                         peer_id = 132;
1979                         size = client.Receive(peer_id, recvdata);
1980                         infostream<<"** Client received: peer_id="<<peer_id
1981                                         <<", size="<<size
1982                                         <<", data="<<*recvdata
1983                                         <<std::endl;
1984                         UASSERT(size == data2.getSize());
1985                         UASSERT(memcmp(*data2, *recvdata, data2.getSize()) == 0);
1986                         UASSERT(peer_id == PEER_ID_SERVER);
1987
1988                         bool got_exception = false;
1989                         try
1990                         {
1991                                 infostream<<"** running client.Receive()"<<std::endl;
1992                                 peer_id = 132;
1993                                 size = client.Receive(peer_id, recvdata);
1994                                 infostream<<"** Client received: peer_id="<<peer_id
1995                                                 <<", size="<<size
1996                                                 <<", data="<<*recvdata
1997                                                 <<std::endl;
1998                         }
1999                         catch(con::NoIncomingDataException &e)
2000                         {
2001                                 infostream<<"** No incoming data for client"<<std::endl;
2002                                 got_exception = true;
2003                         }
2004                         UASSERT(got_exception);
2005                 }
2006 #endif
2007 #if 0
2008                 /*
2009                         Send large amounts of packets (infinite test)
2010                         Commented out because of infinity.
2011                 */
2012                 {
2013                         infostream<<"Sending large amounts of packets (infinite test)"<<std::endl;
2014                         int sendcount = 0;
2015                         for(;;){
2016                                 int datasize = myrand_range(0,5)==0?myrand_range(100,10000):myrand_range(0,100);
2017                                 infostream<<"datasize="<<datasize<<std::endl;
2018                                 SharedBuffer<u8> data1(datasize);
2019                                 for(u16 i=0; i<datasize; i++)
2020                                         data1[i] = i/4;
2021
2022                                 int sendtimes = myrand_range(1,10);
2023                                 for(int i=0; i<sendtimes; i++){
2024                                         server.Send(peer_id_client, 0, data1, true);
2025                                         sendcount++;
2026                                 }
2027                                 infostream<<"sendcount="<<sendcount<<std::endl;
2028
2029                                 //int receivetimes = myrand_range(1,20);
2030                                 int receivetimes = 20;
2031                                 for(int i=0; i<receivetimes; i++){
2032                                         SharedBuffer<u8> recvdata;
2033                                         u16 peer_id = 132;
2034                                         u16 size = 0;
2035                                         bool received = false;
2036                                         try{
2037                                                 size = client.Receive(peer_id, recvdata);
2038                                                 received = true;
2039                                         }catch(con::NoIncomingDataException &e){
2040                                         }
2041                                 }
2042                         }
2043                 }
2044 #endif
2045                 /*
2046                         Send a large packet
2047                 */
2048                 {
2049                         const int datasize = 30000;
2050                         SharedBuffer<u8> data1(datasize);
2051                         for(u16 i=0; i<datasize; i++){
2052                                 data1[i] = i/4;
2053                         }
2054
2055                         infostream<<"Sending data (size="<<datasize<<"):";
2056                         for(int i=0; i<datasize && i<20; i++){
2057                                 if(i%2==0) infostream<<" ";
2058                                 char buf[10];
2059                                 snprintf(buf, 10, "%.2X", ((int)((const char*)*data1)[i])&0xff);
2060                                 infostream<<buf;
2061                         }
2062                         if(datasize>20)
2063                                 infostream<<"...";
2064                         infostream<<std::endl;
2065
2066                         server.Send(peer_id_client, 0, data1, true);
2067
2068                         //sleep_ms(3000);
2069
2070                         SharedBuffer<u8> recvdata;
2071                         infostream<<"** running client.Receive()"<<std::endl;
2072                         u16 peer_id = 132;
2073                         u16 size = 0;
2074                         bool received = false;
2075                         u32 timems0 = porting::getTimeMs();
2076                         for(;;){
2077                                 if(porting::getTimeMs() - timems0 > 5000 || received)
2078                                         break;
2079                                 try{
2080                                         size = client.Receive(peer_id, recvdata);
2081                                         received = true;
2082                                 }catch(con::NoIncomingDataException &e){
2083                                 }
2084                                 sleep_ms(10);
2085                         }
2086                         UASSERT(received);
2087                         infostream<<"** Client received: peer_id="<<peer_id
2088                                         <<", size="<<size
2089                                         <<std::endl;
2090
2091                         infostream<<"Received data (size="<<size<<"): ";
2092                         for(int i=0; i<size && i<20; i++){
2093                                 if(i%2==0) infostream<<" ";
2094                                 char buf[10];
2095                                 snprintf(buf, 10, "%.2X", ((int)(recvdata[i]))&0xff);
2096                                 infostream<<buf;
2097                         }
2098                         if(size>20)
2099                                 infostream<<"...";
2100                         infostream<<std::endl;
2101
2102                         UASSERT(memcmp(*data1, *recvdata, data1.getSize()) == 0);
2103                         UASSERT(peer_id == PEER_ID_SERVER);
2104                 }
2105
2106                 // Check peer handlers
2107                 UASSERT(hand_client.count == 1);
2108                 UASSERT(hand_client.last_id == 1);
2109                 UASSERT(hand_server.count == 1);
2110                 UASSERT(hand_server.last_id == 2);
2111
2112                 //assert(0);
2113         }
2114 };
2115
2116 #define TEST(X) do {\
2117         X x;\
2118         infostream<<"Running " #X <<std::endl;\
2119         x.Run();\
2120         tests_run++;\
2121         tests_failed += x.test_failed ? 1 : 0;\
2122 } while (0)
2123
2124 #define TESTPARAMS(X, ...) do {\
2125         X x;\
2126         infostream<<"Running " #X <<std::endl;\
2127         x.Run(__VA_ARGS__);\
2128         tests_run++;\
2129         tests_failed += x.test_failed ? 1 : 0;\
2130 } while (0)
2131
2132 void run_tests()
2133 {
2134         DSTACK(__FUNCTION_NAME);
2135
2136         int tests_run = 0;
2137         int tests_failed = 0;
2138
2139         // Create item and node definitions
2140         IWritableItemDefManager *idef = createItemDefManager();
2141         IWritableNodeDefManager *ndef = createNodeDefManager();
2142         define_some_nodes(idef, ndef);
2143
2144         infostream<<"run_tests() started"<<std::endl;
2145         TEST(TestUtilities);
2146         TEST(TestPath);
2147         TEST(TestSettings);
2148         TEST(TestCompress);
2149         TEST(TestSerialization);
2150         TEST(TestNodedefSerialization);
2151         TESTPARAMS(TestMapNode, ndef);
2152         TESTPARAMS(TestVoxelManipulator, ndef);
2153         TESTPARAMS(TestVoxelAlgorithms, ndef);
2154         TESTPARAMS(TestInventory, idef);
2155         //TEST(TestMapBlock);
2156         //TEST(TestMapSector);
2157         TEST(TestCollision);
2158         if(INTERNET_SIMULATOR == false){
2159                 TEST(TestSocket);
2160                 dout_con<<"=== BEGIN RUNNING UNIT TESTS FOR CONNECTION ==="<<std::endl;
2161                 TEST(TestConnection);
2162                 dout_con<<"=== END RUNNING UNIT TESTS FOR CONNECTION ==="<<std::endl;
2163         }
2164
2165         delete idef;
2166         delete ndef;
2167
2168         if(tests_failed == 0){
2169                 infostream<<"run_tests(): "<<tests_failed<<" / "<<tests_run<<" tests failed."<<std::endl;
2170                 infostream<<"run_tests() passed."<<std::endl;
2171                 return;
2172         } else {
2173                 errorstream<<"run_tests(): "<<tests_failed<<" / "<<tests_run<<" tests failed."<<std::endl;
2174                 errorstream<<"run_tests() aborting."<<std::endl;
2175                 abort();
2176         }
2177 }
2178