]> git.lizzy.rs Git - minetest.git/blob - src/test.cpp
Implement WieldMeshSceneNode which improves wield mesh rendering
[minetest.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 struct TestSettings: public TestBase
422 {
423         void Run()
424         {
425                 Settings s;
426                 // Test reading of settings
427                 std::istringstream is(
428                         "leet = 1337\n"
429                         "leetleet = 13371337\n"
430                         "leetleet_neg = -13371337\n"
431                         "floaty_thing = 1.1\n"
432                         "stringy_thing = asd /( Â¤%&(/\" BLÖÄRP\n"
433                         "coord = (1, 2, 4.5)");
434                 s.parseConfigLines(is);
435                 UASSERT(s.getS32("leet") == 1337);
436                 UASSERT(s.getS16("leetleet") == 32767);
437                 UASSERT(s.getS16("leetleet_neg") == -32768);
438                 // Not sure if 1.1 is an exact value as a float, but doesn't matter
439                 UASSERT(fabs(s.getFloat("floaty_thing") - 1.1) < 0.001);
440                 UASSERT(s.get("stringy_thing") == "asd /( Â¤%&(/\" BLÖÄRP");
441                 UASSERT(fabs(s.getV3F("coord").X - 1.0) < 0.001);
442                 UASSERT(fabs(s.getV3F("coord").Y - 2.0) < 0.001);
443                 UASSERT(fabs(s.getV3F("coord").Z - 4.5) < 0.001);
444                 // Test the setting of settings too
445                 s.setFloat("floaty_thing_2", 1.2);
446                 s.setV3F("coord2", v3f(1, 2, 3.3));
447                 UASSERT(s.get("floaty_thing_2").substr(0,3) == "1.2");
448                 UASSERT(fabs(s.getFloat("floaty_thing_2") - 1.2) < 0.001);
449                 UASSERT(fabs(s.getV3F("coord2").X - 1.0) < 0.001);
450                 UASSERT(fabs(s.getV3F("coord2").Y - 2.0) < 0.001);
451                 UASSERT(fabs(s.getV3F("coord2").Z - 3.3) < 0.001);
452         }
453 };
454
455 struct TestSerialization: public TestBase
456 {
457         // To be used like this:
458         //   mkstr("Some\0string\0with\0embedded\0nuls")
459         // since std::string("...") doesn't work as expected in that case.
460         template<size_t N> std::string mkstr(const char (&s)[N])
461         {
462                 return std::string(s, N - 1);
463         }
464
465         void Run()
466         {
467                 // Tests some serialization primitives
468
469                 UASSERT(serializeString("") == mkstr("\0\0"));
470                 UASSERT(serializeWideString(L"") == mkstr("\0\0"));
471                 UASSERT(serializeLongString("") == mkstr("\0\0\0\0"));
472                 UASSERT(serializeJsonString("") == "\"\"");
473                 
474                 std::string teststring = "Hello world!";
475                 UASSERT(serializeString(teststring) ==
476                         mkstr("\0\14Hello world!"));
477                 UASSERT(serializeWideString(narrow_to_wide(teststring)) ==
478                         mkstr("\0\14\0H\0e\0l\0l\0o\0 \0w\0o\0r\0l\0d\0!"));
479                 UASSERT(serializeLongString(teststring) ==
480                         mkstr("\0\0\0\14Hello world!"));
481                 UASSERT(serializeJsonString(teststring) ==
482                         "\"Hello world!\"");
483
484                 std::string teststring2;
485                 std::wstring teststring2_w;
486                 std::string teststring2_w_encoded;
487                 {
488                         std::ostringstream tmp_os;
489                         std::wostringstream tmp_os_w;
490                         std::ostringstream tmp_os_w_encoded;
491                         for(int i = 0; i < 256; i++)
492                         {
493                                 tmp_os<<(char)i;
494                                 tmp_os_w<<(wchar_t)i;
495                                 tmp_os_w_encoded<<(char)0<<(char)i;
496                         }
497                         teststring2 = tmp_os.str();
498                         teststring2_w = tmp_os_w.str();
499                         teststring2_w_encoded = tmp_os_w_encoded.str();
500                 }
501                 UASSERT(serializeString(teststring2) ==
502                         mkstr("\1\0") + teststring2);
503                 UASSERT(serializeWideString(teststring2_w) ==
504                         mkstr("\1\0") + teststring2_w_encoded);
505                 UASSERT(serializeLongString(teststring2) ==
506                         mkstr("\0\0\1\0") + teststring2);
507                 // MSVC fails when directly using "\\\\"
508                 std::string backslash = "\\";
509                 UASSERT(serializeJsonString(teststring2) ==
510                         mkstr("\"") +
511                         "\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007" +
512                         "\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f" +
513                         "\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017" +
514                         "\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f" +
515                         " !\\\"" + teststring2.substr(0x23, 0x2f-0x23) +
516                         "\\/" + teststring2.substr(0x30, 0x5c-0x30) +
517                         backslash + backslash + teststring2.substr(0x5d, 0x7f-0x5d) + "\\u007f" +
518                         "\\u0080\\u0081\\u0082\\u0083\\u0084\\u0085\\u0086\\u0087" +
519                         "\\u0088\\u0089\\u008a\\u008b\\u008c\\u008d\\u008e\\u008f" +
520                         "\\u0090\\u0091\\u0092\\u0093\\u0094\\u0095\\u0096\\u0097" +
521                         "\\u0098\\u0099\\u009a\\u009b\\u009c\\u009d\\u009e\\u009f" +
522                         "\\u00a0\\u00a1\\u00a2\\u00a3\\u00a4\\u00a5\\u00a6\\u00a7" +
523                         "\\u00a8\\u00a9\\u00aa\\u00ab\\u00ac\\u00ad\\u00ae\\u00af" +
524                         "\\u00b0\\u00b1\\u00b2\\u00b3\\u00b4\\u00b5\\u00b6\\u00b7" +
525                         "\\u00b8\\u00b9\\u00ba\\u00bb\\u00bc\\u00bd\\u00be\\u00bf" +
526                         "\\u00c0\\u00c1\\u00c2\\u00c3\\u00c4\\u00c5\\u00c6\\u00c7" +
527                         "\\u00c8\\u00c9\\u00ca\\u00cb\\u00cc\\u00cd\\u00ce\\u00cf" +
528                         "\\u00d0\\u00d1\\u00d2\\u00d3\\u00d4\\u00d5\\u00d6\\u00d7" +
529                         "\\u00d8\\u00d9\\u00da\\u00db\\u00dc\\u00dd\\u00de\\u00df" +
530                         "\\u00e0\\u00e1\\u00e2\\u00e3\\u00e4\\u00e5\\u00e6\\u00e7" +
531                         "\\u00e8\\u00e9\\u00ea\\u00eb\\u00ec\\u00ed\\u00ee\\u00ef" +
532                         "\\u00f0\\u00f1\\u00f2\\u00f3\\u00f4\\u00f5\\u00f6\\u00f7" +
533                         "\\u00f8\\u00f9\\u00fa\\u00fb\\u00fc\\u00fd\\u00fe\\u00ff" +
534                         "\"");
535
536                 {
537                         std::istringstream is(serializeString(teststring2), std::ios::binary);
538                         UASSERT(deSerializeString(is) == teststring2);
539                         UASSERT(!is.eof());
540                         is.get();
541                         UASSERT(is.eof());
542                 }
543                 {
544                         std::istringstream is(serializeWideString(teststring2_w), std::ios::binary);
545                         UASSERT(deSerializeWideString(is) == teststring2_w);
546                         UASSERT(!is.eof());
547                         is.get();
548                         UASSERT(is.eof());
549                 }
550                 {
551                         std::istringstream is(serializeLongString(teststring2), std::ios::binary);
552                         UASSERT(deSerializeLongString(is) == teststring2);
553                         UASSERT(!is.eof());
554                         is.get();
555                         UASSERT(is.eof());
556                 }
557                 {
558                         std::istringstream is(serializeJsonString(teststring2), std::ios::binary);
559                         //dstream<<serializeJsonString(deSerializeJsonString(is));
560                         UASSERT(deSerializeJsonString(is) == teststring2);
561                         UASSERT(!is.eof());
562                         is.get();
563                         UASSERT(is.eof());
564                 }
565         }
566 };
567
568 struct TestNodedefSerialization: public TestBase
569 {
570         void Run()
571         {
572                 ContentFeatures f;
573                 f.name = "default:stone";
574                 for(int i = 0; i < 6; i++)
575                         f.tiledef[i].name = "default_stone.png";
576                 f.is_ground_content = true;
577                 std::ostringstream os(std::ios::binary);
578                 f.serialize(os, LATEST_PROTOCOL_VERSION);
579                 verbosestream<<"Test ContentFeatures size: "<<os.str().size()<<std::endl;
580                 std::istringstream is(os.str(), std::ios::binary);
581                 ContentFeatures f2;
582                 f2.deSerialize(is);
583                 UASSERT(f.walkable == f2.walkable);
584                 UASSERT(f.node_box.type == f2.node_box.type);
585         }
586 };
587
588 struct TestCompress: public TestBase
589 {
590         void Run()
591         {
592                 { // ver 0
593
594                 SharedBuffer<u8> fromdata(4);
595                 fromdata[0]=1;
596                 fromdata[1]=5;
597                 fromdata[2]=5;
598                 fromdata[3]=1;
599                 
600                 std::ostringstream os(std::ios_base::binary);
601                 compress(fromdata, os, 0);
602
603                 std::string str_out = os.str();
604                 
605                 infostream<<"str_out.size()="<<str_out.size()<<std::endl;
606                 infostream<<"TestCompress: 1,5,5,1 -> ";
607                 for(u32 i=0; i<str_out.size(); i++)
608                 {
609                         infostream<<(u32)str_out[i]<<",";
610                 }
611                 infostream<<std::endl;
612
613                 UASSERT(str_out.size() == 10);
614
615                 UASSERT(str_out[0] == 0);
616                 UASSERT(str_out[1] == 0);
617                 UASSERT(str_out[2] == 0);
618                 UASSERT(str_out[3] == 4);
619                 UASSERT(str_out[4] == 0);
620                 UASSERT(str_out[5] == 1);
621                 UASSERT(str_out[6] == 1);
622                 UASSERT(str_out[7] == 5);
623                 UASSERT(str_out[8] == 0);
624                 UASSERT(str_out[9] == 1);
625
626                 std::istringstream is(str_out, std::ios_base::binary);
627                 std::ostringstream os2(std::ios_base::binary);
628
629                 decompress(is, os2, 0);
630                 std::string str_out2 = os2.str();
631
632                 infostream<<"decompress: ";
633                 for(u32 i=0; i<str_out2.size(); i++)
634                 {
635                         infostream<<(u32)str_out2[i]<<",";
636                 }
637                 infostream<<std::endl;
638
639                 UASSERT(str_out2.size() == fromdata.getSize());
640
641                 for(u32 i=0; i<str_out2.size(); i++)
642                 {
643                         UASSERT(str_out2[i] == fromdata[i]);
644                 }
645
646                 }
647
648                 { // ver HIGHEST
649
650                 SharedBuffer<u8> fromdata(4);
651                 fromdata[0]=1;
652                 fromdata[1]=5;
653                 fromdata[2]=5;
654                 fromdata[3]=1;
655                 
656                 std::ostringstream os(std::ios_base::binary);
657                 compress(fromdata, os, SER_FMT_VER_HIGHEST_READ);
658
659                 std::string str_out = os.str();
660                 
661                 infostream<<"str_out.size()="<<str_out.size()<<std::endl;
662                 infostream<<"TestCompress: 1,5,5,1 -> ";
663                 for(u32 i=0; i<str_out.size(); i++)
664                 {
665                         infostream<<(u32)str_out[i]<<",";
666                 }
667                 infostream<<std::endl;
668
669                 std::istringstream is(str_out, std::ios_base::binary);
670                 std::ostringstream os2(std::ios_base::binary);
671
672                 decompress(is, os2, SER_FMT_VER_HIGHEST_READ);
673                 std::string str_out2 = os2.str();
674
675                 infostream<<"decompress: ";
676                 for(u32 i=0; i<str_out2.size(); i++)
677                 {
678                         infostream<<(u32)str_out2[i]<<",";
679                 }
680                 infostream<<std::endl;
681
682                 UASSERT(str_out2.size() == fromdata.getSize());
683
684                 for(u32 i=0; i<str_out2.size(); i++)
685                 {
686                         UASSERT(str_out2[i] == fromdata[i]);
687                 }
688
689                 }
690
691                 // Test zlib wrapper with large amounts of data (larger than its
692                 // internal buffers)
693                 {
694                         infostream<<"Test: Testing zlib wrappers with a large amount "
695                                         <<"of pseudorandom data"<<std::endl;
696                         u32 size = 50000;
697                         infostream<<"Test: Input size of large compressZlib is "
698                                         <<size<<std::endl;
699                         std::string data_in;
700                         data_in.resize(size);
701                         PseudoRandom pseudorandom(9420);
702                         for(u32 i=0; i<size; i++)
703                                 data_in[i] = pseudorandom.range(0,255);
704                         std::ostringstream os_compressed(std::ios::binary);
705                         compressZlib(data_in, os_compressed);
706                         infostream<<"Test: Output size of large compressZlib is "
707                                         <<os_compressed.str().size()<<std::endl;
708                         std::istringstream is_compressed(os_compressed.str(), std::ios::binary);
709                         std::ostringstream os_decompressed(std::ios::binary);
710                         decompressZlib(is_compressed, os_decompressed);
711                         infostream<<"Test: Output size of large decompressZlib is "
712                                         <<os_decompressed.str().size()<<std::endl;
713                         std::string str_decompressed = os_decompressed.str();
714                         UTEST(str_decompressed.size() == data_in.size(), "Output size not"
715                                         " equal (output: %u, input: %u)",
716                                         (unsigned int)str_decompressed.size(), (unsigned int)data_in.size());
717                         for(u32 i=0; i<size && i<str_decompressed.size(); i++){
718                                 UTEST(str_decompressed[i] == data_in[i],
719                                                 "index out[%i]=%i differs from in[%i]=%i",
720                                                 i, str_decompressed[i], i, data_in[i]);
721                         }
722                 }
723         }
724 };
725
726 struct TestMapNode: public TestBase
727 {
728         void Run(INodeDefManager *nodedef)
729         {
730                 MapNode n;
731
732                 // Default values
733                 UASSERT(n.getContent() == CONTENT_AIR);
734                 UASSERT(n.getLight(LIGHTBANK_DAY, nodedef) == 0);
735                 UASSERT(n.getLight(LIGHTBANK_NIGHT, nodedef) == 0);
736                 
737                 // Transparency
738                 n.setContent(CONTENT_AIR);
739                 UASSERT(nodedef->get(n).light_propagates == true);
740                 n.setContent(LEGN(nodedef, "CONTENT_STONE"));
741                 UASSERT(nodedef->get(n).light_propagates == false);
742         }
743 };
744
745 struct TestVoxelManipulator: public TestBase
746 {
747         void Run(INodeDefManager *nodedef)
748         {
749                 /*
750                         VoxelArea
751                 */
752
753                 VoxelArea a(v3s16(-1,-1,-1), v3s16(1,1,1));
754                 UASSERT(a.index(0,0,0) == 1*3*3 + 1*3 + 1);
755                 UASSERT(a.index(-1,-1,-1) == 0);
756                 
757                 VoxelArea c(v3s16(-2,-2,-2), v3s16(2,2,2));
758                 // An area that is 1 bigger in x+ and z-
759                 VoxelArea d(v3s16(-2,-2,-3), v3s16(3,2,2));
760                 
761                 std::list<VoxelArea> aa;
762                 d.diff(c, aa);
763                 
764                 // Correct results
765                 std::vector<VoxelArea> results;
766                 results.push_back(VoxelArea(v3s16(-2,-2,-3),v3s16(3,2,-3)));
767                 results.push_back(VoxelArea(v3s16(3,-2,-2),v3s16(3,2,2)));
768
769                 UASSERT(aa.size() == results.size());
770                 
771                 infostream<<"Result of diff:"<<std::endl;
772                 for(std::list<VoxelArea>::const_iterator
773                                 i = aa.begin(); i != aa.end(); ++i)
774                 {
775                         i->print(infostream);
776                         infostream<<std::endl;
777                         
778                         std::vector<VoxelArea>::iterator j = std::find(results.begin(), results.end(), *i);
779                         UASSERT(j != results.end());
780                         results.erase(j);
781                 }
782
783
784                 /*
785                         VoxelManipulator
786                 */
787                 
788                 VoxelManipulator v;
789
790                 v.print(infostream, nodedef);
791
792                 infostream<<"*** Setting (-1,0,-1)=2 ***"<<std::endl;
793                 
794                 v.setNodeNoRef(v3s16(-1,0,-1), MapNode(CONTENT_GRASS));
795
796                 v.print(infostream, nodedef);
797
798                 UASSERT(v.getNode(v3s16(-1,0,-1)).getContent() == CONTENT_GRASS);
799
800                 infostream<<"*** Reading from inexistent (0,0,-1) ***"<<std::endl;
801
802                 EXCEPTION_CHECK(InvalidPositionException, v.getNode(v3s16(0,0,-1)));
803
804                 v.print(infostream, nodedef);
805
806                 infostream<<"*** Adding area ***"<<std::endl;
807
808                 v.addArea(a);
809                 
810                 v.print(infostream, nodedef);
811
812                 UASSERT(v.getNode(v3s16(-1,0,-1)).getContent() == CONTENT_GRASS);
813                 EXCEPTION_CHECK(InvalidPositionException, v.getNode(v3s16(0,1,1)));
814         }
815 };
816
817 struct TestVoxelAlgorithms: public TestBase
818 {
819         void Run(INodeDefManager *ndef)
820         {
821                 /*
822                         voxalgo::propagateSunlight
823                 */
824                 {
825                         VoxelManipulator v;
826                         for(u16 z=0; z<3; z++)
827                         for(u16 y=0; y<3; y++)
828                         for(u16 x=0; x<3; x++)
829                         {
830                                 v3s16 p(x,y,z);
831                                 v.setNodeNoRef(p, MapNode(CONTENT_AIR));
832                         }
833                         VoxelArea a(v3s16(0,0,0), v3s16(2,2,2));
834                         {
835                                 std::set<v3s16> light_sources;
836                                 voxalgo::setLight(v, a, 0, ndef);
837                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
838                                                 v, a, true, light_sources, ndef);
839                                 //v.print(dstream, ndef, VOXELPRINT_LIGHT_DAY);
840                                 UASSERT(res.bottom_sunlight_valid == true);
841                                 UASSERT(v.getNode(v3s16(1,1,1)).getLight(LIGHTBANK_DAY, ndef)
842                                                 == LIGHT_SUN);
843                         }
844                         v.setNodeNoRef(v3s16(0,0,0), MapNode(CONTENT_STONE));
845                         {
846                                 std::set<v3s16> light_sources;
847                                 voxalgo::setLight(v, a, 0, ndef);
848                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
849                                                 v, a, true, light_sources, ndef);
850                                 UASSERT(res.bottom_sunlight_valid == true);
851                                 UASSERT(v.getNode(v3s16(1,1,1)).getLight(LIGHTBANK_DAY, ndef)
852                                                 == LIGHT_SUN);
853                         }
854                         {
855                                 std::set<v3s16> light_sources;
856                                 voxalgo::setLight(v, a, 0, ndef);
857                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
858                                                 v, a, false, light_sources, ndef);
859                                 UASSERT(res.bottom_sunlight_valid == true);
860                                 UASSERT(v.getNode(v3s16(2,0,2)).getLight(LIGHTBANK_DAY, ndef)
861                                                 == 0);
862                         }
863                         v.setNodeNoRef(v3s16(1,3,2), MapNode(CONTENT_STONE));
864                         {
865                                 std::set<v3s16> light_sources;
866                                 voxalgo::setLight(v, a, 0, ndef);
867                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
868                                                 v, a, true, light_sources, ndef);
869                                 UASSERT(res.bottom_sunlight_valid == true);
870                                 UASSERT(v.getNode(v3s16(1,1,2)).getLight(LIGHTBANK_DAY, ndef)
871                                                 == 0);
872                         }
873                         {
874                                 std::set<v3s16> light_sources;
875                                 voxalgo::setLight(v, a, 0, ndef);
876                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
877                                                 v, a, false, light_sources, ndef);
878                                 UASSERT(res.bottom_sunlight_valid == true);
879                                 UASSERT(v.getNode(v3s16(1,0,2)).getLight(LIGHTBANK_DAY, ndef)
880                                                 == 0);
881                         }
882                         {
883                                 MapNode n(CONTENT_AIR);
884                                 n.setLight(LIGHTBANK_DAY, 10, ndef);
885                                 v.setNodeNoRef(v3s16(1,-1,2), n);
886                         }
887                         {
888                                 std::set<v3s16> light_sources;
889                                 voxalgo::setLight(v, a, 0, ndef);
890                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
891                                                 v, a, true, light_sources, ndef);
892                                 UASSERT(res.bottom_sunlight_valid == true);
893                         }
894                         {
895                                 std::set<v3s16> light_sources;
896                                 voxalgo::setLight(v, a, 0, ndef);
897                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
898                                                 v, a, false, light_sources, ndef);
899                                 UASSERT(res.bottom_sunlight_valid == true);
900                         }
901                         {
902                                 MapNode n(CONTENT_AIR);
903                                 n.setLight(LIGHTBANK_DAY, LIGHT_SUN, ndef);
904                                 v.setNodeNoRef(v3s16(1,-1,2), n);
905                         }
906                         {
907                                 std::set<v3s16> light_sources;
908                                 voxalgo::setLight(v, a, 0, ndef);
909                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
910                                                 v, a, true, light_sources, ndef);
911                                 UASSERT(res.bottom_sunlight_valid == false);
912                         }
913                         {
914                                 std::set<v3s16> light_sources;
915                                 voxalgo::setLight(v, a, 0, ndef);
916                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
917                                                 v, a, false, light_sources, ndef);
918                                 UASSERT(res.bottom_sunlight_valid == false);
919                         }
920                         v.setNodeNoRef(v3s16(1,3,2), MapNode(CONTENT_IGNORE));
921                         {
922                                 std::set<v3s16> light_sources;
923                                 voxalgo::setLight(v, a, 0, ndef);
924                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
925                                                 v, a, true, light_sources, ndef);
926                                 UASSERT(res.bottom_sunlight_valid == true);
927                         }
928                 }
929                 /*
930                         voxalgo::clearLightAndCollectSources
931                 */
932                 {
933                         VoxelManipulator v;
934                         for(u16 z=0; z<3; z++)
935                         for(u16 y=0; y<3; y++)
936                         for(u16 x=0; x<3; x++)
937                         {
938                                 v3s16 p(x,y,z);
939                                 v.setNode(p, MapNode(CONTENT_AIR));
940                         }
941                         VoxelArea a(v3s16(0,0,0), v3s16(2,2,2));
942                         v.setNodeNoRef(v3s16(0,0,0), MapNode(CONTENT_STONE));
943                         v.setNodeNoRef(v3s16(1,1,1), MapNode(CONTENT_TORCH));
944                         {
945                                 MapNode n(CONTENT_AIR);
946                                 n.setLight(LIGHTBANK_DAY, 1, ndef);
947                                 v.setNode(v3s16(1,1,2), n);
948                         }
949                         {
950                                 std::set<v3s16> light_sources;
951                                 std::map<v3s16, u8> unlight_from;
952                                 voxalgo::clearLightAndCollectSources(v, a, LIGHTBANK_DAY,
953                                                 ndef, light_sources, unlight_from);
954                                 //v.print(dstream, ndef, VOXELPRINT_LIGHT_DAY);
955                                 UASSERT(v.getNode(v3s16(0,1,1)).getLight(LIGHTBANK_DAY, ndef)
956                                                 == 0);
957                                 UASSERT(light_sources.find(v3s16(1,1,1)) != light_sources.end());
958                                 UASSERT(light_sources.size() == 1);
959                                 UASSERT(unlight_from.find(v3s16(1,1,2)) != unlight_from.end());
960                                 UASSERT(unlight_from.size() == 1);
961                         }
962                 }
963         }
964 };
965
966 struct TestInventory: public TestBase
967 {
968         void Run(IItemDefManager *idef)
969         {
970                 std::string serialized_inventory =
971                 "List 0 32\n"
972                 "Width 3\n"
973                 "Empty\n"
974                 "Empty\n"
975                 "Empty\n"
976                 "Empty\n"
977                 "Empty\n"
978                 "Empty\n"
979                 "Empty\n"
980                 "Empty\n"
981                 "Empty\n"
982                 "Item default:cobble 61\n"
983                 "Empty\n"
984                 "Empty\n"
985                 "Empty\n"
986                 "Empty\n"
987                 "Empty\n"
988                 "Empty\n"
989                 "Item default:dirt 71\n"
990                 "Empty\n"
991                 "Empty\n"
992                 "Empty\n"
993                 "Empty\n"
994                 "Empty\n"
995                 "Empty\n"
996                 "Empty\n"
997                 "Item default:dirt 99\n"
998                 "Item default:cobble 38\n"
999                 "Empty\n"
1000                 "Empty\n"
1001                 "Empty\n"
1002                 "Empty\n"
1003                 "Empty\n"
1004                 "Empty\n"
1005                 "EndInventoryList\n"
1006                 "EndInventory\n";
1007                 
1008                 std::string serialized_inventory_2 =
1009                 "List main 32\n"
1010                 "Width 5\n"
1011                 "Empty\n"
1012                 "Empty\n"
1013                 "Empty\n"
1014                 "Empty\n"
1015                 "Empty\n"
1016                 "Empty\n"
1017                 "Empty\n"
1018                 "Empty\n"
1019                 "Empty\n"
1020                 "Item default:cobble 61\n"
1021                 "Empty\n"
1022                 "Empty\n"
1023                 "Empty\n"
1024                 "Empty\n"
1025                 "Empty\n"
1026                 "Empty\n"
1027                 "Item default:dirt 71\n"
1028                 "Empty\n"
1029                 "Empty\n"
1030                 "Empty\n"
1031                 "Empty\n"
1032                 "Empty\n"
1033                 "Empty\n"
1034                 "Empty\n"
1035                 "Item default:dirt 99\n"
1036                 "Item default:cobble 38\n"
1037                 "Empty\n"
1038                 "Empty\n"
1039                 "Empty\n"
1040                 "Empty\n"
1041                 "Empty\n"
1042                 "Empty\n"
1043                 "EndInventoryList\n"
1044                 "EndInventory\n";
1045                 
1046                 Inventory inv(idef);
1047                 std::istringstream is(serialized_inventory, std::ios::binary);
1048                 inv.deSerialize(is);
1049                 UASSERT(inv.getList("0"));
1050                 UASSERT(!inv.getList("main"));
1051                 inv.getList("0")->setName("main");
1052                 UASSERT(!inv.getList("0"));
1053                 UASSERT(inv.getList("main"));
1054                 UASSERT(inv.getList("main")->getWidth() == 3);
1055                 inv.getList("main")->setWidth(5);
1056                 std::ostringstream inv_os(std::ios::binary);
1057                 inv.serialize(inv_os);
1058                 UASSERT(inv_os.str() == serialized_inventory_2);
1059         }
1060 };
1061
1062 /*
1063         NOTE: These tests became non-working then NodeContainer was removed.
1064               These should be redone, utilizing some kind of a virtual
1065                   interface for Map (IMap would be fine).
1066 */
1067 #if 0
1068 struct TestMapBlock: public TestBase
1069 {
1070         class TC : public NodeContainer
1071         {
1072         public:
1073
1074                 MapNode node;
1075                 bool position_valid;
1076                 core::list<v3s16> validity_exceptions;
1077
1078                 TC()
1079                 {
1080                         position_valid = true;
1081                 }
1082
1083                 virtual bool isValidPosition(v3s16 p)
1084                 {
1085                         //return position_valid ^ (p==position_valid_exception);
1086                         bool exception = false;
1087                         for(core::list<v3s16>::Iterator i=validity_exceptions.begin();
1088                                         i != validity_exceptions.end(); i++)
1089                         {
1090                                 if(p == *i)
1091                                 {
1092                                         exception = true;
1093                                         break;
1094                                 }
1095                         }
1096                         return exception ? !position_valid : position_valid;
1097                 }
1098
1099                 virtual MapNode getNode(v3s16 p)
1100                 {
1101                         if(isValidPosition(p) == false)
1102                                 throw InvalidPositionException();
1103                         return node;
1104                 }
1105
1106                 virtual void setNode(v3s16 p, MapNode & n)
1107                 {
1108                         if(isValidPosition(p) == false)
1109                                 throw InvalidPositionException();
1110                 };
1111
1112                 virtual u16 nodeContainerId() const
1113                 {
1114                         return 666;
1115                 }
1116         };
1117
1118         void Run()
1119         {
1120                 TC parent;
1121                 
1122                 MapBlock b(&parent, v3s16(1,1,1));
1123                 v3s16 relpos(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE);
1124
1125                 UASSERT(b.getPosRelative() == relpos);
1126
1127                 UASSERT(b.getBox().MinEdge.X == MAP_BLOCKSIZE);
1128                 UASSERT(b.getBox().MaxEdge.X == MAP_BLOCKSIZE*2-1);
1129                 UASSERT(b.getBox().MinEdge.Y == MAP_BLOCKSIZE);
1130                 UASSERT(b.getBox().MaxEdge.Y == MAP_BLOCKSIZE*2-1);
1131                 UASSERT(b.getBox().MinEdge.Z == MAP_BLOCKSIZE);
1132                 UASSERT(b.getBox().MaxEdge.Z == MAP_BLOCKSIZE*2-1);
1133                 
1134                 UASSERT(b.isValidPosition(v3s16(0,0,0)) == true);
1135                 UASSERT(b.isValidPosition(v3s16(-1,0,0)) == false);
1136                 UASSERT(b.isValidPosition(v3s16(-1,-142,-2341)) == false);
1137                 UASSERT(b.isValidPosition(v3s16(-124,142,2341)) == false);
1138                 UASSERT(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true);
1139                 UASSERT(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE,MAP_BLOCKSIZE-1)) == false);
1140
1141                 /*
1142                         TODO: this method should probably be removed
1143                         if the block size isn't going to be set variable
1144                 */
1145                 /*UASSERT(b.getSizeNodes() == v3s16(MAP_BLOCKSIZE,
1146                                 MAP_BLOCKSIZE, MAP_BLOCKSIZE));*/
1147                 
1148                 // Changed flag should be initially set
1149                 UASSERT(b.getModified() == MOD_STATE_WRITE_NEEDED);
1150                 b.resetModified();
1151                 UASSERT(b.getModified() == MOD_STATE_CLEAN);
1152
1153                 // All nodes should have been set to
1154                 // .d=CONTENT_IGNORE and .getLight() = 0
1155                 for(u16 z=0; z<MAP_BLOCKSIZE; z++)
1156                 for(u16 y=0; y<MAP_BLOCKSIZE; y++)
1157                 for(u16 x=0; x<MAP_BLOCKSIZE; x++)
1158                 {
1159                         //UASSERT(b.getNode(v3s16(x,y,z)).getContent() == CONTENT_AIR);
1160                         UASSERT(b.getNode(v3s16(x,y,z)).getContent() == CONTENT_IGNORE);
1161                         UASSERT(b.getNode(v3s16(x,y,z)).getLight(LIGHTBANK_DAY) == 0);
1162                         UASSERT(b.getNode(v3s16(x,y,z)).getLight(LIGHTBANK_NIGHT) == 0);
1163                 }
1164                 
1165                 {
1166                         MapNode n(CONTENT_AIR);
1167                         for(u16 z=0; z<MAP_BLOCKSIZE; z++)
1168                         for(u16 y=0; y<MAP_BLOCKSIZE; y++)
1169                         for(u16 x=0; x<MAP_BLOCKSIZE; x++)
1170                         {
1171                                 b.setNode(v3s16(x,y,z), n);
1172                         }
1173                 }
1174                         
1175                 /*
1176                         Parent fetch functions
1177                 */
1178                 parent.position_valid = false;
1179                 parent.node.setContent(5);
1180
1181                 MapNode n;
1182                 
1183                 // Positions in the block should still be valid
1184                 UASSERT(b.isValidPositionParent(v3s16(0,0,0)) == true);
1185                 UASSERT(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true);
1186                 n = b.getNodeParent(v3s16(0,MAP_BLOCKSIZE-1,0));
1187                 UASSERT(n.getContent() == CONTENT_AIR);
1188
1189                 // ...but outside the block they should be invalid
1190                 UASSERT(b.isValidPositionParent(v3s16(-121,2341,0)) == false);
1191                 UASSERT(b.isValidPositionParent(v3s16(-1,0,0)) == false);
1192                 UASSERT(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == false);
1193                 
1194                 {
1195                         bool exception_thrown = false;
1196                         try{
1197                                 // This should throw an exception
1198                                 MapNode n = b.getNodeParent(v3s16(0,0,-1));
1199                         }
1200                         catch(InvalidPositionException &e)
1201                         {
1202                                 exception_thrown = true;
1203                         }
1204                         UASSERT(exception_thrown);
1205                 }
1206
1207                 parent.position_valid = true;
1208                 // Now the positions outside should be valid
1209                 UASSERT(b.isValidPositionParent(v3s16(-121,2341,0)) == true);
1210                 UASSERT(b.isValidPositionParent(v3s16(-1,0,0)) == true);
1211                 UASSERT(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == true);
1212                 n = b.getNodeParent(v3s16(0,0,MAP_BLOCKSIZE));
1213                 UASSERT(n.getContent() == 5);
1214
1215                 /*
1216                         Set a node
1217                 */
1218                 v3s16 p(1,2,0);
1219                 n.setContent(4);
1220                 b.setNode(p, n);
1221                 UASSERT(b.getNode(p).getContent() == 4);
1222                 //TODO: Update to new system
1223                 /*UASSERT(b.getNodeTile(p) == 4);
1224                 UASSERT(b.getNodeTile(v3s16(-1,-1,0)) == 5);*/
1225                 
1226                 /*
1227                         propagateSunlight()
1228                 */
1229                 // Set lighting of all nodes to 0
1230                 for(u16 z=0; z<MAP_BLOCKSIZE; z++){
1231                         for(u16 y=0; y<MAP_BLOCKSIZE; y++){
1232                                 for(u16 x=0; x<MAP_BLOCKSIZE; x++){
1233                                         MapNode n = b.getNode(v3s16(x,y,z));
1234                                         n.setLight(LIGHTBANK_DAY, 0);
1235                                         n.setLight(LIGHTBANK_NIGHT, 0);
1236                                         b.setNode(v3s16(x,y,z), n);
1237                                 }
1238                         }
1239                 }
1240                 {
1241                         /*
1242                                 Check how the block handles being a lonely sky block
1243                         */
1244                         parent.position_valid = true;
1245                         b.setIsUnderground(false);
1246                         parent.node.setContent(CONTENT_AIR);
1247                         parent.node.setLight(LIGHTBANK_DAY, LIGHT_SUN);
1248                         parent.node.setLight(LIGHTBANK_NIGHT, 0);
1249                         core::map<v3s16, bool> light_sources;
1250                         // The bottom block is invalid, because we have a shadowing node
1251                         UASSERT(b.propagateSunlight(light_sources) == false);
1252                         UASSERT(b.getNode(v3s16(1,4,0)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
1253                         UASSERT(b.getNode(v3s16(1,3,0)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
1254                         UASSERT(b.getNode(v3s16(1,2,0)).getLight(LIGHTBANK_DAY) == 0);
1255                         UASSERT(b.getNode(v3s16(1,1,0)).getLight(LIGHTBANK_DAY) == 0);
1256                         UASSERT(b.getNode(v3s16(1,0,0)).getLight(LIGHTBANK_DAY) == 0);
1257                         UASSERT(b.getNode(v3s16(1,2,3)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
1258                         UASSERT(b.getFaceLight2(1000, p, v3s16(0,1,0)) == LIGHT_SUN);
1259                         UASSERT(b.getFaceLight2(1000, p, v3s16(0,-1,0)) == 0);
1260                         UASSERT(b.getFaceLight2(0, p, v3s16(0,-1,0)) == 0);
1261                         // According to MapBlock::getFaceLight,
1262                         // The face on the z+ side should have double-diminished light
1263                         //UASSERT(b.getFaceLight(p, v3s16(0,0,1)) == diminish_light(diminish_light(LIGHT_MAX)));
1264                         // The face on the z+ side should have diminished light
1265                         UASSERT(b.getFaceLight2(1000, p, v3s16(0,0,1)) == diminish_light(LIGHT_MAX));
1266                 }
1267                 /*
1268                         Check how the block handles being in between blocks with some non-sunlight
1269                         while being underground
1270                 */
1271                 {
1272                         // Make neighbours to exist and set some non-sunlight to them
1273                         parent.position_valid = true;
1274                         b.setIsUnderground(true);
1275                         parent.node.setLight(LIGHTBANK_DAY, LIGHT_MAX/2);
1276                         core::map<v3s16, bool> light_sources;
1277                         // The block below should be valid because there shouldn't be
1278                         // sunlight in there either
1279                         UASSERT(b.propagateSunlight(light_sources, true) == true);
1280                         // Should not touch nodes that are not affected (that is, all of them)
1281                         //UASSERT(b.getNode(v3s16(1,2,3)).getLight() == LIGHT_SUN);
1282                         // Should set light of non-sunlighted blocks to 0.
1283                         UASSERT(b.getNode(v3s16(1,2,3)).getLight(LIGHTBANK_DAY) == 0);
1284                 }
1285                 /*
1286                         Set up a situation where:
1287                         - There is only air in this block
1288                         - There is a valid non-sunlighted block at the bottom, and
1289                         - Invalid blocks elsewhere.
1290                         - the block is not underground.
1291
1292                         This should result in bottom block invalidity
1293                 */
1294                 {
1295                         b.setIsUnderground(false);
1296                         // Clear block
1297                         for(u16 z=0; z<MAP_BLOCKSIZE; z++){
1298                                 for(u16 y=0; y<MAP_BLOCKSIZE; y++){
1299                                         for(u16 x=0; x<MAP_BLOCKSIZE; x++){
1300                                                 MapNode n;
1301                                                 n.setContent(CONTENT_AIR);
1302                                                 n.setLight(LIGHTBANK_DAY, 0);
1303                                                 b.setNode(v3s16(x,y,z), n);
1304                                         }
1305                                 }
1306                         }
1307                         // Make neighbours invalid
1308                         parent.position_valid = false;
1309                         // Add exceptions to the top of the bottom block
1310                         for(u16 x=0; x<MAP_BLOCKSIZE; x++)
1311                         for(u16 z=0; z<MAP_BLOCKSIZE; z++)
1312                         {
1313                                 parent.validity_exceptions.push_back(v3s16(MAP_BLOCKSIZE+x, MAP_BLOCKSIZE-1, MAP_BLOCKSIZE+z));
1314                         }
1315                         // Lighting value for the valid nodes
1316                         parent.node.setLight(LIGHTBANK_DAY, LIGHT_MAX/2);
1317                         core::map<v3s16, bool> light_sources;
1318                         // Bottom block is not valid
1319                         UASSERT(b.propagateSunlight(light_sources) == false);
1320                 }
1321         }
1322 };
1323
1324 struct TestMapSector: public TestBase
1325 {
1326         class TC : public NodeContainer
1327         {
1328         public:
1329
1330                 MapNode node;
1331                 bool position_valid;
1332
1333                 TC()
1334                 {
1335                         position_valid = true;
1336                 }
1337
1338                 virtual bool isValidPosition(v3s16 p)
1339                 {
1340                         return position_valid;
1341                 }
1342
1343                 virtual MapNode getNode(v3s16 p)
1344                 {
1345                         if(position_valid == false)
1346                                 throw InvalidPositionException();
1347                         return node;
1348                 }
1349
1350                 virtual void setNode(v3s16 p, MapNode & n)
1351                 {
1352                         if(position_valid == false)
1353                                 throw InvalidPositionException();
1354                 };
1355                 
1356                 virtual u16 nodeContainerId() const
1357                 {
1358                         return 666;
1359                 }
1360         };
1361         
1362         void Run()
1363         {
1364                 TC parent;
1365                 parent.position_valid = false;
1366                 
1367                 // Create one with no heightmaps
1368                 ServerMapSector sector(&parent, v2s16(1,1));
1369                 
1370                 UASSERT(sector.getBlockNoCreateNoEx(0) == 0);
1371                 UASSERT(sector.getBlockNoCreateNoEx(1) == 0);
1372
1373                 MapBlock * bref = sector.createBlankBlock(-2);
1374                 
1375                 UASSERT(sector.getBlockNoCreateNoEx(0) == 0);
1376                 UASSERT(sector.getBlockNoCreateNoEx(-2) == bref);
1377                 
1378                 //TODO: Check for AlreadyExistsException
1379
1380                 /*bool exception_thrown = false;
1381                 try{
1382                         sector.getBlock(0);
1383                 }
1384                 catch(InvalidPositionException &e){
1385                         exception_thrown = true;
1386                 }
1387                 UASSERT(exception_thrown);*/
1388
1389         }
1390 };
1391 #endif
1392
1393 struct TestCollision: public TestBase
1394 {
1395         void Run()
1396         {
1397                 /*
1398                         axisAlignedCollision
1399                 */
1400
1401                 for(s16 bx = -3; bx <= 3; bx++)
1402                 for(s16 by = -3; by <= 3; by++)
1403                 for(s16 bz = -3; bz <= 3; bz++)
1404                 {
1405                         // X-
1406                         {
1407                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1408                                 aabb3f m(bx-2, by, bz, bx-1, by+1, bz+1);
1409                                 v3f v(1, 0, 0);
1410                                 f32 dtime = 0;
1411                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1412                                 UASSERT(fabs(dtime - 1.000) < 0.001);
1413                         }
1414                         {
1415                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1416                                 aabb3f m(bx-2, by, bz, bx-1, by+1, bz+1);
1417                                 v3f v(-1, 0, 0);
1418                                 f32 dtime = 0;
1419                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == -1);
1420                         }
1421                         {
1422                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1423                                 aabb3f m(bx-2, by+1.5, bz, bx-1, by+2.5, bz-1);
1424                                 v3f v(1, 0, 0);
1425                                 f32 dtime;
1426                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == -1);
1427                         }
1428                         {
1429                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1430                                 aabb3f m(bx-2, by-1.5, bz, bx-1.5, by+0.5, bz+1);
1431                                 v3f v(0.5, 0.1, 0);
1432                                 f32 dtime;
1433                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1434                                 UASSERT(fabs(dtime - 3.000) < 0.001);
1435                         }
1436                         {
1437                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1438                                 aabb3f m(bx-2, by-1.5, bz, bx-1.5, by+0.5, bz+1);
1439                                 v3f v(0.5, 0.1, 0);
1440                                 f32 dtime;
1441                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1442                                 UASSERT(fabs(dtime - 3.000) < 0.001);
1443                         }
1444
1445                         // X+
1446                         {
1447                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1448                                 aabb3f m(bx+2, by, bz, bx+3, by+1, bz+1);
1449                                 v3f v(-1, 0, 0);
1450                                 f32 dtime;
1451                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1452                                 UASSERT(fabs(dtime - 1.000) < 0.001);
1453                         }
1454                         {
1455                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1456                                 aabb3f m(bx+2, by, bz, bx+3, by+1, bz+1);
1457                                 v3f v(1, 0, 0);
1458                                 f32 dtime;
1459                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == -1);
1460                         }
1461                         {
1462                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1463                                 aabb3f m(bx+2, by, bz+1.5, bx+3, by+1, bz+3.5);
1464                                 v3f v(-1, 0, 0);
1465                                 f32 dtime;
1466                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == -1);
1467                         }
1468                         {
1469                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1470                                 aabb3f m(bx+2, by-1.5, bz, bx+2.5, by-0.5, bz+1);
1471                                 v3f v(-0.5, 0.2, 0);
1472                                 f32 dtime;
1473                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 1);  // Y, not X!
1474                                 UASSERT(fabs(dtime - 2.500) < 0.001);
1475                         }
1476                         {
1477                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1478                                 aabb3f m(bx+2, by-1.5, bz, bx+2.5, by-0.5, bz+1);
1479                                 v3f v(-0.5, 0.3, 0);
1480                                 f32 dtime;
1481                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1482                                 UASSERT(fabs(dtime - 2.000) < 0.001);
1483                         }
1484
1485                         // TODO: Y-, Y+, Z-, Z+
1486
1487                         // misc
1488                         {
1489                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1490                                 aabb3f m(bx+2.3, by+2.29, bz+2.29, bx+4.2, by+4.2, bz+4.2);
1491                                 v3f v(-1./3, -1./3, -1./3);
1492                                 f32 dtime;
1493                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1494                                 UASSERT(fabs(dtime - 0.9) < 0.001);
1495                         }
1496                         {
1497                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1498                                 aabb3f m(bx+2.29, by+2.3, bz+2.29, bx+4.2, by+4.2, bz+4.2);
1499                                 v3f v(-1./3, -1./3, -1./3);
1500                                 f32 dtime;
1501                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 1);
1502                                 UASSERT(fabs(dtime - 0.9) < 0.001);
1503                         }
1504                         {
1505                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1506                                 aabb3f m(bx+2.29, by+2.29, bz+2.3, bx+4.2, by+4.2, bz+4.2);
1507                                 v3f v(-1./3, -1./3, -1./3);
1508                                 f32 dtime;
1509                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 2);
1510                                 UASSERT(fabs(dtime - 0.9) < 0.001);
1511                         }
1512                         {
1513                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1514                                 aabb3f m(bx-4.2, by-4.2, bz-4.2, bx-2.3, by-2.29, bz-2.29);
1515                                 v3f v(1./7, 1./7, 1./7);
1516                                 f32 dtime;
1517                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1518                                 UASSERT(fabs(dtime - 16.1) < 0.001);
1519                         }
1520                         {
1521                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1522                                 aabb3f m(bx-4.2, by-4.2, bz-4.2, bx-2.29, by-2.3, bz-2.29);
1523                                 v3f v(1./7, 1./7, 1./7);
1524                                 f32 dtime;
1525                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 1);
1526                                 UASSERT(fabs(dtime - 16.1) < 0.001);
1527                         }
1528                         {
1529                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1530                                 aabb3f m(bx-4.2, by-4.2, bz-4.2, bx-2.29, by-2.29, bz-2.3);
1531                                 v3f v(1./7, 1./7, 1./7);
1532                                 f32 dtime;
1533                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 2);
1534                                 UASSERT(fabs(dtime - 16.1) < 0.001);
1535                         }
1536                 }
1537         }
1538 };
1539
1540 struct TestSocket: public TestBase
1541 {
1542         void Run()
1543         {
1544                 const int port = 30003;
1545                 Address address(0,0,0,0, port);
1546                 Address address6((IPv6AddressBytes*) NULL, port);
1547
1548                 // IPv6 socket test
1549                 {
1550                         UDPSocket socket6;
1551
1552                         if (!socket6.init(true, true)) {
1553                                 /* Note: Failing to create an IPv6 socket is not technically an
1554                                    error because the OS may not support IPv6 or it may
1555                                    have been disabled. IPv6 is not /required/ by
1556                                    minetest and therefore this should not cause the unit
1557                                    test to fail
1558                                 */
1559                                 dstream << "WARNING: IPv6 socket creation failed (unit test)"
1560                                         << std::endl;
1561                         } else {
1562                                 const char sendbuffer[] = "hello world!";
1563                                 IPv6AddressBytes bytes;
1564                                 bytes.bytes[15] = 1;
1565
1566                                 socket6.Bind(address6);
1567
1568                                 try {
1569                                         socket6.Send(Address(&bytes, port), sendbuffer, sizeof(sendbuffer));
1570
1571                                         sleep_ms(50);
1572
1573                                         char rcvbuffer[256] = { 0 };
1574                                         Address sender;
1575
1576                                         for(;;) {
1577                                                 if (socket6.Receive(sender, rcvbuffer, sizeof(rcvbuffer )) < 0)
1578                                                         break;
1579                                         }
1580                                         //FIXME: This fails on some systems
1581                                         UASSERT(strncmp(sendbuffer, rcvbuffer, sizeof(sendbuffer)) == 0);
1582                                         UASSERT(memcmp(sender.getAddress6().sin6_addr.s6_addr,
1583                                                         Address(&bytes, 0).getAddress6().sin6_addr.s6_addr, 16) == 0);
1584                                 }
1585                                 catch (SendFailedException e) {
1586                                         errorstream << "IPv6 support enabled but not available!"
1587                                                     << std::endl;
1588                                 }
1589                         }
1590                 }
1591
1592                 // IPv4 socket test
1593                 {
1594                         UDPSocket socket(false);
1595                         socket.Bind(address);
1596
1597                         const char sendbuffer[] = "hello world!";
1598                         socket.Send(Address(127, 0, 0 ,1, port), sendbuffer, sizeof(sendbuffer));
1599
1600                         sleep_ms(50);
1601
1602                         char rcvbuffer[256] = { 0 };
1603                         Address sender;
1604                         for(;;) {
1605                                 if (socket.Receive(sender, rcvbuffer, sizeof(rcvbuffer)) < 0)
1606                                         break;
1607                         }
1608                         //FIXME: This fails on some systems
1609                         UASSERT(strncmp(sendbuffer, rcvbuffer, sizeof(sendbuffer)) == 0);
1610                         UASSERT(sender.getAddress().sin_addr.s_addr ==
1611                                         Address(127, 0, 0, 1, 0).getAddress().sin_addr.s_addr);
1612                 }
1613         }
1614 };
1615
1616 struct TestConnection: public TestBase
1617 {
1618         void TestHelpers()
1619         {
1620                 /*
1621                         Test helper functions
1622                 */
1623
1624                 // Some constants for testing
1625                 u32 proto_id = 0x12345678;
1626                 u16 peer_id = 123;
1627                 u8 channel = 2;
1628                 SharedBuffer<u8> data1(1);
1629                 data1[0] = 100;
1630                 Address a(127,0,0,1, 10);
1631                 const u16 seqnum = 34352;
1632
1633                 con::BufferedPacket p1 = con::makePacket(a, data1,
1634                                 proto_id, peer_id, channel);
1635                 /*
1636                         We should now have a packet with this data:
1637                         Header:
1638                                 [0] u32 protocol_id
1639                                 [4] u16 sender_peer_id
1640                                 [6] u8 channel
1641                         Data:
1642                                 [7] u8 data1[0]
1643                 */
1644                 UASSERT(readU32(&p1.data[0]) == proto_id);
1645                 UASSERT(readU16(&p1.data[4]) == peer_id);
1646                 UASSERT(readU8(&p1.data[6]) == channel);
1647                 UASSERT(readU8(&p1.data[7]) == data1[0]);
1648                 
1649                 //infostream<<"initial data1[0]="<<((u32)data1[0]&0xff)<<std::endl;
1650
1651                 SharedBuffer<u8> p2 = con::makeReliablePacket(data1, seqnum);
1652
1653                 /*infostream<<"p2.getSize()="<<p2.getSize()<<", data1.getSize()="
1654                                 <<data1.getSize()<<std::endl;
1655                 infostream<<"readU8(&p2[3])="<<readU8(&p2[3])
1656                                 <<" p2[3]="<<((u32)p2[3]&0xff)<<std::endl;
1657                 infostream<<"data1[0]="<<((u32)data1[0]&0xff)<<std::endl;*/
1658
1659                 UASSERT(p2.getSize() == 3 + data1.getSize());
1660                 UASSERT(readU8(&p2[0]) == TYPE_RELIABLE);
1661                 UASSERT(readU16(&p2[1]) == seqnum);
1662                 UASSERT(readU8(&p2[3]) == data1[0]);
1663         }
1664
1665         struct Handler : public con::PeerHandler
1666         {
1667                 Handler(const char *a_name)
1668                 {
1669                         count = 0;
1670                         last_id = 0;
1671                         name = a_name;
1672                 }
1673                 void peerAdded(con::Peer *peer)
1674                 {
1675                         infostream<<"Handler("<<name<<")::peerAdded(): "
1676                                         "id="<<peer->id<<std::endl;
1677                         last_id = peer->id;
1678                         count++;
1679                 }
1680                 void deletingPeer(con::Peer *peer, bool timeout)
1681                 {
1682                         infostream<<"Handler("<<name<<")::deletingPeer(): "
1683                                         "id="<<peer->id
1684                                         <<", timeout="<<timeout<<std::endl;
1685                         last_id = peer->id;
1686                         count--;
1687                 }
1688
1689                 s32 count;
1690                 u16 last_id;
1691                 const char *name;
1692         };
1693
1694         void Run()
1695         {
1696                 DSTACK("TestConnection::Run");
1697
1698                 TestHelpers();
1699
1700                 /*
1701                         Test some real connections
1702
1703                         NOTE: This mostly tests the legacy interface.
1704                 */
1705
1706                 u32 proto_id = 0xad26846a;
1707
1708                 Handler hand_server("server");
1709                 Handler hand_client("client");
1710                 
1711                 infostream<<"** Creating server Connection"<<std::endl;
1712                 con::Connection server(proto_id, 512, 5.0, false, &hand_server);
1713                 Address address(0,0,0,0, 30001);
1714                 server.Serve(address);
1715                 
1716                 infostream<<"** Creating client Connection"<<std::endl;
1717                 con::Connection client(proto_id, 512, 5.0, false, &hand_client);
1718                 
1719                 UASSERT(hand_server.count == 0);
1720                 UASSERT(hand_client.count == 0);
1721                 
1722                 sleep_ms(50);
1723                 
1724                 Address server_address(127,0,0,1, 30001);
1725                 infostream<<"** running client.Connect()"<<std::endl;
1726                 client.Connect(server_address);
1727
1728                 sleep_ms(50);
1729                 
1730                 // Client should not have added client yet
1731                 UASSERT(hand_client.count == 0);
1732                 
1733                 try
1734                 {
1735                         u16 peer_id;
1736                         SharedBuffer<u8> data;
1737                         infostream<<"** running client.Receive()"<<std::endl;
1738                         u32 size = client.Receive(peer_id, data);
1739                         infostream<<"** Client received: peer_id="<<peer_id
1740                                         <<", size="<<size
1741                                         <<std::endl;
1742                 }
1743                 catch(con::NoIncomingDataException &e)
1744                 {
1745                 }
1746
1747                 // Client should have added server now
1748                 UASSERT(hand_client.count == 1);
1749                 UASSERT(hand_client.last_id == 1);
1750                 // Server should not have added client yet
1751                 UASSERT(hand_server.count == 0);
1752                 
1753                 sleep_ms(100);
1754
1755                 try
1756                 {
1757                         u16 peer_id;
1758                         SharedBuffer<u8> data;
1759                         infostream<<"** running server.Receive()"<<std::endl;
1760                         u32 size = server.Receive(peer_id, data);
1761                         infostream<<"** Server received: peer_id="<<peer_id
1762                                         <<", size="<<size
1763                                         <<std::endl;
1764                 }
1765                 catch(con::NoIncomingDataException &e)
1766                 {
1767                         // No actual data received, but the client has
1768                         // probably been connected
1769                 }
1770                 
1771                 // Client should be the same
1772                 UASSERT(hand_client.count == 1);
1773                 UASSERT(hand_client.last_id == 1);
1774                 // Server should have the client
1775                 UASSERT(hand_server.count == 1);
1776                 UASSERT(hand_server.last_id == 2);
1777                 
1778                 //sleep_ms(50);
1779
1780                 while(client.Connected() == false)
1781                 {
1782                         try
1783                         {
1784                                 u16 peer_id;
1785                                 SharedBuffer<u8> data;
1786                                 infostream<<"** running client.Receive()"<<std::endl;
1787                                 u32 size = client.Receive(peer_id, data);
1788                                 infostream<<"** Client received: peer_id="<<peer_id
1789                                                 <<", size="<<size
1790                                                 <<std::endl;
1791                         }
1792                         catch(con::NoIncomingDataException &e)
1793                         {
1794                         }
1795                         sleep_ms(50);
1796                 }
1797
1798                 sleep_ms(50);
1799                 
1800                 try
1801                 {
1802                         u16 peer_id;
1803                         SharedBuffer<u8> data;
1804                         infostream<<"** running server.Receive()"<<std::endl;
1805                         u32 size = server.Receive(peer_id, data);
1806                         infostream<<"** Server received: peer_id="<<peer_id
1807                                         <<", size="<<size
1808                                         <<std::endl;
1809                 }
1810                 catch(con::NoIncomingDataException &e)
1811                 {
1812                 }
1813 #if 1
1814                 /*
1815                         Simple send-receive test
1816                 */
1817                 {
1818                         /*u8 data[] = "Hello World!";
1819                         u32 datasize = sizeof(data);*/
1820                         SharedBuffer<u8> data = SharedBufferFromString("Hello World!");
1821
1822                         infostream<<"** running client.Send()"<<std::endl;
1823                         client.Send(PEER_ID_SERVER, 0, data, true);
1824
1825                         sleep_ms(50);
1826
1827                         u16 peer_id;
1828                         SharedBuffer<u8> recvdata;
1829                         infostream<<"** running server.Receive()"<<std::endl;
1830                         u32 size = server.Receive(peer_id, recvdata);
1831                         infostream<<"** Server received: peer_id="<<peer_id
1832                                         <<", size="<<size
1833                                         <<", data="<<*data
1834                                         <<std::endl;
1835                         UASSERT(memcmp(*data, *recvdata, data.getSize()) == 0);
1836                 }
1837 #endif
1838                 u16 peer_id_client = 2;
1839 #if 0
1840                 /*
1841                         Send consequent packets in different order
1842                         Not compatible with new Connection, thus commented out.
1843                 */
1844                 {
1845                         //u8 data1[] = "hello1";
1846                         //u8 data2[] = "hello2";
1847                         SharedBuffer<u8> data1 = SharedBufferFromString("hello1");
1848                         SharedBuffer<u8> data2 = SharedBufferFromString("Hello2");
1849
1850                         Address client_address =
1851                                         server.GetPeerAddress(peer_id_client);
1852                         
1853                         infostream<<"*** Sending packets in wrong order (2,1,2)"
1854                                         <<std::endl;
1855                         
1856                         u8 chn = 0;
1857                         con::Channel *ch = &server.getPeer(peer_id_client)->channels[chn];
1858                         u16 sn = ch->next_outgoing_seqnum;
1859                         ch->next_outgoing_seqnum = sn+1;
1860                         server.Send(peer_id_client, chn, data2, true);
1861                         ch->next_outgoing_seqnum = sn;
1862                         server.Send(peer_id_client, chn, data1, true);
1863                         ch->next_outgoing_seqnum = sn+1;
1864                         server.Send(peer_id_client, chn, data2, true);
1865
1866                         sleep_ms(50);
1867
1868                         infostream<<"*** Receiving the packets"<<std::endl;
1869
1870                         u16 peer_id;
1871                         SharedBuffer<u8> recvdata;
1872                         u32 size;
1873
1874                         infostream<<"** running client.Receive()"<<std::endl;
1875                         peer_id = 132;
1876                         size = client.Receive(peer_id, recvdata);
1877                         infostream<<"** Client received: peer_id="<<peer_id
1878                                         <<", size="<<size
1879                                         <<", data="<<*recvdata
1880                                         <<std::endl;
1881                         UASSERT(size == data1.getSize());
1882                         UASSERT(memcmp(*data1, *recvdata, data1.getSize()) == 0);
1883                         UASSERT(peer_id == PEER_ID_SERVER);
1884                         
1885                         infostream<<"** running client.Receive()"<<std::endl;
1886                         peer_id = 132;
1887                         size = client.Receive(peer_id, recvdata);
1888                         infostream<<"** Client received: peer_id="<<peer_id
1889                                         <<", size="<<size
1890                                         <<", data="<<*recvdata
1891                                         <<std::endl;
1892                         UASSERT(size == data2.getSize());
1893                         UASSERT(memcmp(*data2, *recvdata, data2.getSize()) == 0);
1894                         UASSERT(peer_id == PEER_ID_SERVER);
1895                         
1896                         bool got_exception = false;
1897                         try
1898                         {
1899                                 infostream<<"** running client.Receive()"<<std::endl;
1900                                 peer_id = 132;
1901                                 size = client.Receive(peer_id, recvdata);
1902                                 infostream<<"** Client received: peer_id="<<peer_id
1903                                                 <<", size="<<size
1904                                                 <<", data="<<*recvdata
1905                                                 <<std::endl;
1906                         }
1907                         catch(con::NoIncomingDataException &e)
1908                         {
1909                                 infostream<<"** No incoming data for client"<<std::endl;
1910                                 got_exception = true;
1911                         }
1912                         UASSERT(got_exception);
1913                 }
1914 #endif
1915 #if 0
1916                 /*
1917                         Send large amounts of packets (infinite test)
1918                         Commented out because of infinity.
1919                 */
1920                 {
1921                         infostream<<"Sending large amounts of packets (infinite test)"<<std::endl;
1922                         int sendcount = 0;
1923                         for(;;){
1924                                 int datasize = myrand_range(0,5)==0?myrand_range(100,10000):myrand_range(0,100);
1925                                 infostream<<"datasize="<<datasize<<std::endl;
1926                                 SharedBuffer<u8> data1(datasize);
1927                                 for(u16 i=0; i<datasize; i++)
1928                                         data1[i] = i/4;
1929                                 
1930                                 int sendtimes = myrand_range(1,10);
1931                                 for(int i=0; i<sendtimes; i++){
1932                                         server.Send(peer_id_client, 0, data1, true);
1933                                         sendcount++;
1934                                 }
1935                                 infostream<<"sendcount="<<sendcount<<std::endl;
1936                                 
1937                                 //int receivetimes = myrand_range(1,20);
1938                                 int receivetimes = 20;
1939                                 for(int i=0; i<receivetimes; i++){
1940                                         SharedBuffer<u8> recvdata;
1941                                         u16 peer_id = 132;
1942                                         u16 size = 0;
1943                                         bool received = false;
1944                                         try{
1945                                                 size = client.Receive(peer_id, recvdata);
1946                                                 received = true;
1947                                         }catch(con::NoIncomingDataException &e){
1948                                         }
1949                                 }
1950                         }
1951                 }
1952 #endif
1953                 /*
1954                         Send a large packet
1955                 */
1956                 {
1957                         const int datasize = 30000;
1958                         SharedBuffer<u8> data1(datasize);
1959                         for(u16 i=0; i<datasize; i++){
1960                                 data1[i] = i/4;
1961                         }
1962
1963                         infostream<<"Sending data (size="<<datasize<<"):";
1964                         for(int i=0; i<datasize && i<20; i++){
1965                                 if(i%2==0) infostream<<" ";
1966                                 char buf[10];
1967                                 snprintf(buf, 10, "%.2X", ((int)((const char*)*data1)[i])&0xff);
1968                                 infostream<<buf;
1969                         }
1970                         if(datasize>20)
1971                                 infostream<<"...";
1972                         infostream<<std::endl;
1973                         
1974                         server.Send(peer_id_client, 0, data1, true);
1975
1976                         //sleep_ms(3000);
1977                         
1978                         SharedBuffer<u8> recvdata;
1979                         infostream<<"** running client.Receive()"<<std::endl;
1980                         u16 peer_id = 132;
1981                         u16 size = 0;
1982                         bool received = false;
1983                         u32 timems0 = porting::getTimeMs();
1984                         for(;;){
1985                                 if(porting::getTimeMs() - timems0 > 5000 || received)
1986                                         break;
1987                                 try{
1988                                         size = client.Receive(peer_id, recvdata);
1989                                         received = true;
1990                                 }catch(con::NoIncomingDataException &e){
1991                                 }
1992                                 sleep_ms(10);
1993                         }
1994                         UASSERT(received);
1995                         infostream<<"** Client received: peer_id="<<peer_id
1996                                         <<", size="<<size
1997                                         <<std::endl;
1998
1999                         infostream<<"Received data (size="<<size<<"): ";
2000                         for(int i=0; i<size && i<20; i++){
2001                                 if(i%2==0) infostream<<" ";
2002                                 char buf[10];
2003                                 snprintf(buf, 10, "%.2X", ((int)(recvdata[i]))&0xff);
2004                                 infostream<<buf;
2005                         }
2006                         if(size>20)
2007                                 infostream<<"...";
2008                         infostream<<std::endl;
2009
2010                         UASSERT(memcmp(*data1, *recvdata, data1.getSize()) == 0);
2011                         UASSERT(peer_id == PEER_ID_SERVER);
2012                 }
2013                 
2014                 // Check peer handlers
2015                 UASSERT(hand_client.count == 1);
2016                 UASSERT(hand_client.last_id == 1);
2017                 UASSERT(hand_server.count == 1);
2018                 UASSERT(hand_server.last_id == 2);
2019                 
2020                 //assert(0);
2021         }
2022 };
2023
2024 #define TEST(X) do {\
2025         X x;\
2026         infostream<<"Running " #X <<std::endl;\
2027         x.Run();\
2028         tests_run++;\
2029         tests_failed += x.test_failed ? 1 : 0;\
2030 } while (0)
2031
2032 #define TESTPARAMS(X, ...) do {\
2033         X x;\
2034         infostream<<"Running " #X <<std::endl;\
2035         x.Run(__VA_ARGS__);\
2036         tests_run++;\
2037         tests_failed += x.test_failed ? 1 : 0;\
2038 } while (0)
2039
2040 void run_tests()
2041 {
2042         DSTACK(__FUNCTION_NAME);
2043
2044         int tests_run = 0;
2045         int tests_failed = 0;
2046         
2047         // Create item and node definitions
2048         IWritableItemDefManager *idef = createItemDefManager();
2049         IWritableNodeDefManager *ndef = createNodeDefManager();
2050         define_some_nodes(idef, ndef);
2051
2052         infostream<<"run_tests() started"<<std::endl;
2053         TEST(TestUtilities);
2054         TEST(TestPath);
2055         TEST(TestSettings);
2056         TEST(TestCompress);
2057         TEST(TestSerialization);
2058         TEST(TestNodedefSerialization);
2059         TESTPARAMS(TestMapNode, ndef);
2060         TESTPARAMS(TestVoxelManipulator, ndef);
2061         TESTPARAMS(TestVoxelAlgorithms, ndef);
2062         TESTPARAMS(TestInventory, idef);
2063         //TEST(TestMapBlock);
2064         //TEST(TestMapSector);
2065         TEST(TestCollision);
2066         if(INTERNET_SIMULATOR == false){
2067                 TEST(TestSocket);
2068                 dout_con<<"=== BEGIN RUNNING UNIT TESTS FOR CONNECTION ==="<<std::endl;
2069                 TEST(TestConnection);
2070                 dout_con<<"=== END RUNNING UNIT TESTS FOR CONNECTION ==="<<std::endl;
2071         }
2072
2073         delete idef;
2074         delete ndef;
2075
2076         if(tests_failed == 0){
2077                 infostream<<"run_tests(): "<<tests_failed<<" / "<<tests_run<<" tests failed."<<std::endl;
2078                 infostream<<"run_tests() passed."<<std::endl;
2079                 return;
2080         } else {
2081                 errorstream<<"run_tests(): "<<tests_failed<<" / "<<tests_run<<" tests failed."<<std::endl;
2082                 errorstream<<"run_tests() aborting."<<std::endl;
2083                 abort();
2084         }
2085 }
2086