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