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