]> git.saurik.com Git - wxWidgets.git/blob - tests/filename/filenametest.cpp
Fix wxMenu::GetTitle() before the menu is appended to the menu bar.
[wxWidgets.git] / tests / filename / filenametest.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: tests/filename/filename.cpp
3 // Purpose: wxFileName unit test
4 // Author: Vadim Zeitlin
5 // Created: 2004-07-25
6 // Copyright: (c) 2004 Vadim Zeitlin
7 ///////////////////////////////////////////////////////////////////////////////
8
9 // ----------------------------------------------------------------------------
10 // headers
11 // ----------------------------------------------------------------------------
12
13 #include "testprec.h"
14
15 #ifdef __BORLANDC__
16 #pragma hdrstop
17 #endif
18
19 #ifndef WX_PRECOMP
20 #include "wx/utils.h"
21 #endif // WX_PRECOMP
22
23 #include "wx/filename.h"
24 #include "wx/filefn.h"
25 #include "wx/stdpaths.h"
26 #include "wx/scopeguard.h"
27
28 #ifdef __WINDOWS__
29 #include "wx/msw/registry.h"
30 #endif // __WINDOWS__
31
32 #ifdef __UNIX__
33 #include <unistd.h>
34 #endif // __UNIX__
35
36 #include "testfile.h"
37 #include "testdate.h"
38
39 // ----------------------------------------------------------------------------
40 // test data
41 // ----------------------------------------------------------------------------
42
43 static struct TestFileNameInfo
44 {
45 const char *fullname;
46 const char *volume;
47 const char *path;
48 const char *name;
49 const char *ext;
50 bool isAbsolute;
51 wxPathFormat format;
52 } filenames[] =
53 {
54 // the empty string
55 { "", "", "", "", "", false, wxPATH_UNIX },
56 { "", "", "", "", "", false, wxPATH_DOS },
57 { "", "", "", "", "", false, wxPATH_VMS },
58
59 // Unix file names
60 { "/usr/bin/ls", "", "/usr/bin", "ls", "", true, wxPATH_UNIX },
61 { "/usr/bin/", "", "/usr/bin", "", "", true, wxPATH_UNIX },
62 { "~/.zshrc", "", "~", ".zshrc", "", true, wxPATH_UNIX },
63 { "../../foo", "", "../..", "foo", "", false, wxPATH_UNIX },
64 { "foo.bar", "", "", "foo", "bar", false, wxPATH_UNIX },
65 { "~/foo.bar", "", "~", "foo", "bar", true, wxPATH_UNIX },
66 { "~user/foo.bar", "", "~user", "foo", "bar", true, wxPATH_UNIX },
67 { "~user/", "", "~user", "", "", true, wxPATH_UNIX },
68 { "/foo", "", "/", "foo", "", true, wxPATH_UNIX },
69 { "Mahogany-0.60/foo.bar", "", "Mahogany-0.60", "foo", "bar", false, wxPATH_UNIX },
70 { "/tmp/wxwin.tar.bz", "", "/tmp", "wxwin.tar", "bz", true, wxPATH_UNIX },
71
72 // Windows file names
73 { "foo.bar", "", "", "foo", "bar", false, wxPATH_DOS },
74 { "\\foo.bar", "", "\\", "foo", "bar", false, wxPATH_DOS },
75 { "c:foo.bar", "c", "", "foo", "bar", false, wxPATH_DOS },
76 { "c:\\foo.bar", "c", "\\", "foo", "bar", true, wxPATH_DOS },
77 { "c:\\Windows\\command.com", "c", "\\Windows", "command", "com", true, wxPATH_DOS },
78 { "\\\\?\\Volume{8089d7d7-d0ac-11db-9dd0-806d6172696f}\\",
79 "Volume{8089d7d7-d0ac-11db-9dd0-806d6172696f}", "\\", "", "", true, wxPATH_DOS },
80 { "\\\\?\\Volume{8089d7d7-d0ac-11db-9dd0-806d6172696f}\\Program Files\\setup.exe",
81 "Volume{8089d7d7-d0ac-11db-9dd0-806d6172696f}", "\\Program Files", "setup", "exe", true, wxPATH_DOS },
82
83 #if 0
84 // NB: when using the wxFileName::GetLongPath() function on these two
85 // strings, the program will hang for several seconds blocking inside
86 // Win32 GetLongPathName() function
87 { "\\\\server\\foo.bar", "server", "\\", "foo", "bar", true, wxPATH_DOS },
88 { "\\\\server\\dir\\foo.bar", "server", "\\dir", "foo", "bar", true, wxPATH_DOS },
89 #endif
90
91 // consecutive [back]slashes should be treated as single occurrences of
92 // them and not interpreted as share names if there is a volume name
93 { "c:\\aaa\\bbb\\ccc", "c", "\\aaa\\bbb", "ccc", "", true, wxPATH_DOS },
94 { "c:\\\\aaa\\bbb\\ccc", "c", "\\\\aaa\\bbb", "ccc", "", true, wxPATH_DOS },
95
96 // wxFileName support for Mac file names is broken currently
97 #if 0
98 // Mac file names
99 { "Volume:Dir:File", "Volume", "Dir", "File", "", true, wxPATH_MAC },
100 { "Volume:Dir:Subdir:File", "Volume", "Dir:Subdir", "File", "", true, wxPATH_MAC },
101 { "Volume:", "Volume", "", "", "", true, wxPATH_MAC },
102 { ":Dir:File", "", "Dir", "File", "", false, wxPATH_MAC },
103 { ":File.Ext", "", "", "File", ".Ext", false, wxPATH_MAC },
104 { "File.Ext", "", "", "File", ".Ext", false, wxPATH_MAC },
105 #endif // 0
106
107 #if 0
108 // VMS file names
109 // NB: on Windows they have the same effect of the \\server\\ strings
110 // (see the note above)
111 { "device:[dir1.dir2.dir3]file.txt", "device", "dir1.dir2.dir3", "file", "txt", true, wxPATH_VMS },
112 #endif
113 { "file.txt", "", "", "file", "txt", false, wxPATH_VMS },
114 };
115
116 // ----------------------------------------------------------------------------
117 // test class
118 // ----------------------------------------------------------------------------
119
120 class FileNameTestCase : public CppUnit::TestCase
121 {
122 public:
123 FileNameTestCase() { }
124
125 private:
126 CPPUNIT_TEST_SUITE( FileNameTestCase );
127 CPPUNIT_TEST( TestConstruction );
128 CPPUNIT_TEST( TestComparison );
129 CPPUNIT_TEST( TestSplit );
130 CPPUNIT_TEST( TestSetPath );
131 CPPUNIT_TEST( TestStrip );
132 CPPUNIT_TEST( TestNormalize );
133 CPPUNIT_TEST( TestReplace );
134 CPPUNIT_TEST( TestGetHumanReadable );
135 #ifdef __WINDOWS__
136 CPPUNIT_TEST( TestShortLongPath );
137 #endif // __WINDOWS__
138 CPPUNIT_TEST( TestUNC );
139 CPPUNIT_TEST( TestVolumeUniqueName );
140 CPPUNIT_TEST( TestCreateTempFileName );
141 CPPUNIT_TEST( TestGetTimes );
142 CPPUNIT_TEST( TestSetTimes );
143 CPPUNIT_TEST( TestExists );
144 CPPUNIT_TEST( TestIsSame );
145 #if defined(__UNIX__)
146 CPPUNIT_TEST( TestSymlinks );
147 #endif // __UNIX__
148 CPPUNIT_TEST_SUITE_END();
149
150 void TestConstruction();
151 void TestComparison();
152 void TestSplit();
153 void TestSetPath();
154 void TestStrip();
155 void TestNormalize();
156 void TestReplace();
157 void TestGetHumanReadable();
158 #ifdef __WINDOWS__
159 void TestShortLongPath();
160 #endif // __WINDOWS__
161 void TestUNC();
162 void TestVolumeUniqueName();
163 void TestCreateTempFileName();
164 void TestGetTimes();
165 void TestSetTimes();
166 void TestExists();
167 void TestIsSame();
168 #if defined(__UNIX__)
169 void TestSymlinks();
170 #endif // __UNIX__
171
172 DECLARE_NO_COPY_CLASS(FileNameTestCase)
173 };
174
175 // register in the unnamed registry so that these tests are run by default
176 CPPUNIT_TEST_SUITE_REGISTRATION( FileNameTestCase );
177
178 // also include in its own registry so that these tests can be run alone
179 CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( FileNameTestCase, "FileNameTestCase" );
180
181 void FileNameTestCase::TestConstruction()
182 {
183 for ( size_t n = 0; n < WXSIZEOF(filenames); n++ )
184 {
185 const TestFileNameInfo& fni = filenames[n];
186
187 wxFileName fn(fni.fullname, fni.format);
188
189 // the original full name could contain consecutive [back]slashes,
190 // squeeze them except for the double backslash in the beginning in
191 // Windows filenames where it has special meaning
192 wxString fullnameOrig;
193 if ( fni.format == wxPATH_DOS )
194 {
195 // copy the backslashes at beginning unchanged
196 const char *p = fni.fullname;
197 while ( *p == '\\' )
198 fullnameOrig += *p++;
199
200 // replace consecutive slashes with single ones in the rest
201 for ( char chPrev = '\0'; *p; p++ )
202 {
203 if ( *p == '\\' && chPrev == '\\' )
204 continue;
205
206 chPrev = *p;
207 fullnameOrig += chPrev;
208 }
209 }
210 else // !wxPATH_DOS
211 {
212 fullnameOrig = fni.fullname;
213 }
214
215 fullnameOrig.Replace("//", "/");
216
217
218 wxString fullname = fn.GetFullPath(fni.format);
219 CPPUNIT_ASSERT_EQUAL( fullnameOrig, fullname );
220
221 // notice that we use a dummy working directory to ensure that paths
222 // with "../.." in them could be normalized, otherwise this would fail
223 // if the test is run from root directory or its direct subdirectory
224 CPPUNIT_ASSERT_MESSAGE
225 (
226 (const char *)wxString::Format("Normalize(%s) failed", fni.fullname).mb_str(),
227 fn.Normalize(wxPATH_NORM_ALL, "/foo/bar/baz", fni.format)
228 );
229
230 if ( *fni.volume && *fni.path )
231 {
232 // check that specifying the volume separately or as part of the
233 // path doesn't make any difference
234 wxString pathWithVolume = fni.volume;
235 pathWithVolume += wxFileName::GetVolumeSeparator(fni.format);
236 pathWithVolume += fni.path;
237
238 CPPUNIT_ASSERT_EQUAL( wxFileName(pathWithVolume,
239 fni.name,
240 fni.ext,
241 fni.format), fn );
242 }
243 }
244
245 wxFileName fn;
246
247 // empty strings
248 fn.AssignDir(wxEmptyString);
249 CPPUNIT_ASSERT( !fn.IsOk() );
250
251 fn.Assign(wxEmptyString);
252 CPPUNIT_ASSERT( !fn.IsOk() );
253
254 fn.Assign(wxEmptyString, wxEmptyString);
255 CPPUNIT_ASSERT( !fn.IsOk() );
256
257 fn.Assign(wxEmptyString, wxEmptyString, wxEmptyString);
258 CPPUNIT_ASSERT( !fn.IsOk() );
259
260 fn.Assign(wxEmptyString, wxEmptyString, wxEmptyString, wxEmptyString);
261 CPPUNIT_ASSERT( !fn.IsOk() );
262 }
263
264 void FileNameTestCase::TestComparison()
265 {
266 wxFileName fn1(wxT("/tmp/file1"));
267 wxFileName fn2(wxT("/tmp/dir2/../file2"));
268 fn1.Normalize();
269 fn2.Normalize();
270 CPPUNIT_ASSERT_EQUAL(fn1.GetPath(), fn2.GetPath());
271 }
272
273 void FileNameTestCase::TestSplit()
274 {
275 for ( size_t n = 0; n < WXSIZEOF(filenames); n++ )
276 {
277 const TestFileNameInfo& fni = filenames[n];
278 wxString volume, path, name, ext;
279 wxFileName::SplitPath(fni.fullname,
280 &volume, &path, &name, &ext, fni.format);
281
282 CPPUNIT_ASSERT_EQUAL( wxString(fni.volume), volume );
283 CPPUNIT_ASSERT_EQUAL( wxString(fni.path), path );
284 CPPUNIT_ASSERT_EQUAL( wxString(fni.name), name );
285 CPPUNIT_ASSERT_EQUAL( wxString(fni.ext), ext );
286 }
287
288 // special case of empty extension
289 wxFileName fn("foo.");
290 CPPUNIT_ASSERT_EQUAL( wxString("foo."), fn.GetFullPath() );
291 }
292
293 void FileNameTestCase::TestSetPath()
294 {
295 wxFileName fn("d:\\test\\foo.bar", wxPATH_DOS);
296 fn.SetPath("c:\\temp", wxPATH_DOS);
297 CPPUNIT_ASSERT( fn.SameAs(wxFileName("c:\\temp\\foo.bar", wxPATH_DOS)) );
298
299 fn = wxFileName("/usr/bin/ls", wxPATH_UNIX);
300 fn.SetPath("/usr/local/bin", wxPATH_UNIX);
301 CPPUNIT_ASSERT( fn.SameAs(wxFileName("/usr/local/bin/ls", wxPATH_UNIX)) );
302 }
303
304 void FileNameTestCase::TestNormalize()
305 {
306 // prepare some data to be used later
307 wxString sep = wxFileName::GetPathSeparator();
308 wxString cwd = wxGetCwd();
309 wxString home = wxGetUserHome();
310
311 cwd.Replace(sep, wxT("/"));
312 if (cwd.Last() != wxT('/'))
313 cwd += wxT('/');
314 home.Replace(sep, wxT("/"));
315 if (home.Last() != wxT('/'))
316 home += wxT('/');
317
318 // since we will always be testing paths using the wxPATH_UNIX
319 // format, we need to remove the volume, if present
320 if (home.Contains(wxT(':')))
321 home = home.AfterFirst(wxT(':'));
322 if (cwd.Contains(wxT(':')))
323 cwd = cwd.AfterFirst(wxT(':'));
324
325 static const struct FileNameTest
326 {
327 const char *original;
328 int flags;
329 const char *expected;
330 wxPathFormat fmt;
331 } tests[] =
332 {
333 // test wxPATH_NORM_ENV_VARS
334 #ifdef __WINDOWS__
335 { "%ABCDEF%/g/h/i", wxPATH_NORM_ENV_VARS, "abcdef/g/h/i", wxPATH_UNIX },
336 #else
337 { "$(ABCDEF)/g/h/i", wxPATH_NORM_ENV_VARS, "abcdef/g/h/i", wxPATH_UNIX },
338 #endif
339
340 // test wxPATH_NORM_DOTS
341 { "a/.././b/c/../../", wxPATH_NORM_DOTS, "", wxPATH_UNIX },
342 { "", wxPATH_NORM_DOTS, "", wxPATH_UNIX },
343 { "./foo", wxPATH_NORM_DOTS, "foo", wxPATH_UNIX },
344 { "b/../bar", wxPATH_NORM_DOTS, "bar", wxPATH_UNIX },
345 { "c/../../quux", wxPATH_NORM_DOTS, "../quux", wxPATH_UNIX },
346 { "/c/../../quux", wxPATH_NORM_DOTS, "/quux", wxPATH_UNIX },
347
348 // test wxPATH_NORM_TILDE: notice that ~ is only interpreted specially
349 // when it is the first character in the file name
350 { "/a/b/~", wxPATH_NORM_TILDE, "/a/b/~", wxPATH_UNIX },
351 { "/~/a/b", wxPATH_NORM_TILDE, "/~/a/b", wxPATH_UNIX },
352 { "~/a/b", wxPATH_NORM_TILDE, "HOME/a/b", wxPATH_UNIX },
353
354 // test wxPATH_NORM_CASE
355 { "Foo", wxPATH_NORM_CASE, "Foo", wxPATH_UNIX },
356 { "Foo", wxPATH_NORM_CASE, "foo", wxPATH_DOS },
357 { "C:\\Program Files\\wx", wxPATH_NORM_CASE,
358 "c:\\program files\\wx", wxPATH_DOS },
359 { "C:/Program Files/wx", wxPATH_NORM_ALL | wxPATH_NORM_CASE,
360 "c:\\program files\\wx", wxPATH_DOS },
361 { "C:\\Users\\zeitlin", wxPATH_NORM_ALL | wxPATH_NORM_CASE,
362 "c:\\users\\zeitlin", wxPATH_DOS },
363
364 // test wxPATH_NORM_ABSOLUTE
365 { "a/b/", wxPATH_NORM_ABSOLUTE, "CWD/a/b/", wxPATH_UNIX },
366 { "a/b/c.ext", wxPATH_NORM_ABSOLUTE, "CWD/a/b/c.ext", wxPATH_UNIX },
367 { "/a", wxPATH_NORM_ABSOLUTE, "/a", wxPATH_UNIX },
368
369 // test giving no flags at all to Normalize()
370 { "a/b/", 0, "a/b/", wxPATH_UNIX },
371 { "a/b/c.ext", 0, "a/b/c.ext", wxPATH_UNIX },
372 { "/a", 0, "/a", wxPATH_UNIX },
373
374 // test handling dots without wxPATH_NORM_DOTS and wxPATH_NORM_ABSOLUTE
375 // for both existing and non-existent files (this is important under
376 // MSW where GetLongPathName() works only for the former)
377 { "./foo", wxPATH_NORM_LONG, "./foo", wxPATH_UNIX },
378 { "../foo", wxPATH_NORM_LONG, "../foo", wxPATH_UNIX },
379 { ".\\test.bkl", wxPATH_NORM_LONG, ".\\test.bkl", wxPATH_DOS },
380 { ".\\foo", wxPATH_NORM_LONG, ".\\foo", wxPATH_DOS },
381 { "..\\Makefile.in", wxPATH_NORM_LONG, "..\\Makefile.in", wxPATH_DOS },
382 { "..\\foo", wxPATH_NORM_LONG, "..\\foo", wxPATH_DOS },
383 };
384
385 // set the env var ABCDEF
386 wxSetEnv("ABCDEF", "abcdef");
387
388 for ( size_t i = 0; i < WXSIZEOF(tests); i++ )
389 {
390 const FileNameTest& fnt = tests[i];
391 wxFileName fn(fnt.original, fnt.fmt);
392
393 // be sure this normalization does not fail
394 WX_ASSERT_MESSAGE
395 (
396 ("#%d: Normalize(%s) failed", (int)i, fnt.original),
397 fn.Normalize(fnt.flags, cwd, fnt.fmt)
398 );
399
400 // compare result with expected string
401 wxString expected(tests[i].expected);
402 expected.Replace("HOME/", home);
403 expected.Replace("CWD/", cwd);
404 WX_ASSERT_EQUAL_MESSAGE
405 (
406 ("array element #%d", (int)i),
407 expected, fn.GetFullPath(fnt.fmt)
408 );
409 }
410
411 // MSW-only test for wxPATH_NORM_LONG: notice that we only run it if short
412 // names generation is not disabled for this system as otherwise the file
413 // MKINST~1 doesn't exist at all and normalizing it fails (it's possible
414 // that we're on a FAT partition in which case the test would still succeed
415 // and also that the registry key was changed recently and didn't take
416 // effect yet but these are marginal cases which we consciously choose to
417 // ignore for now)
418 #ifdef __WINDOWS__
419 long shortNamesDisabled;
420 if ( wxRegKey
421 (
422 wxRegKey::HKLM,
423 "SYSTEM\\CurrentControlSet\\Control\\FileSystem"
424 ).QueryValue("NtfsDisable8dot3NameCreation", &shortNamesDisabled) &&
425 !shortNamesDisabled )
426 {
427 wxFileName fn("..\\MKINST~1");
428 CPPUNIT_ASSERT( fn.Normalize(wxPATH_NORM_LONG, cwd) );
429 CPPUNIT_ASSERT_EQUAL( "..\\mkinstalldirs", fn.GetFullPath() );
430 }
431 //else: when in doubt, don't run the test
432 #endif // __WINDOWS__
433 }
434
435 void FileNameTestCase::TestReplace()
436 {
437 static const struct FileNameTest
438 {
439 const char *original;
440 const char *env_contents;
441 const char *replace_fmtstring;
442 const char *expected;
443 wxPathFormat fmt;
444 } tests[] =
445 {
446 { "/usr/a/strange path/lib/someFile.ext", "/usr/a/strange path", "$%s", "$TEST_VAR/lib/someFile.ext", wxPATH_UNIX },
447 { "/usr/a/path/lib/someFile.ext", "/usr/a/path", "$%s", "$TEST_VAR/lib/someFile.ext", wxPATH_UNIX },
448 { "/usr/a/path/lib/someFile", "/usr/a/path/", "$%s", "$TEST_VARlib/someFile", wxPATH_UNIX },
449 { "/usr/a/path/lib/", "/usr/a/path/", "$(%s)", "$(TEST_VAR)lib/", wxPATH_UNIX },
450 { "/usr/a/path/lib/", "/usr/a/path/", "${{%s}}", "${{TEST_VAR}}lib/", wxPATH_UNIX },
451 { "/usr/a/path/lib/", "/usr/a/path/", "%s", "TEST_VARlib/", wxPATH_UNIX },
452 { "/usr/a/path/lib/", "/usr/a/path/", "%s//", "TEST_VAR/lib/", wxPATH_UNIX },
453 // note: empty directory components are automatically removed by wxFileName thus
454 // using // in the replace format string has no effect
455
456 { "/usr/../a/path/lib/", "/usr/a/path/", "%s", "/usr/../a/path/lib/", wxPATH_UNIX },
457 { "/usr/a/path/usr/usr", "/usr", "%s", "TEST_VAR/a/pathTEST_VAR/usr", wxPATH_UNIX },
458 { "/usr/a/path/usr/usr", "/usr", "$%s", "$TEST_VAR/a/path$TEST_VAR/usr", wxPATH_UNIX },
459 { "/a/b/c/d", "a/", "%s", "/TEST_VARb/c/d", wxPATH_UNIX },
460
461 { "C:\\A\\Strange Path\\lib\\someFile", "C:\\A\\Strange Path", "%%%s%%", "%TEST_VAR%\\lib\\someFile", wxPATH_WIN },
462 { "C:\\A\\Path\\lib\\someFile", "C:\\A\\Path", "%%%s%%", "%TEST_VAR%\\lib\\someFile", wxPATH_WIN },
463 { "C:\\A\\Path\\lib\\someFile", "C:\\A\\Path", "$(%s)", "$(TEST_VAR)\\lib\\someFile", wxPATH_WIN }
464 };
465
466 for ( size_t i = 0; i < WXSIZEOF(tests); i++ )
467 {
468 const FileNameTest& fnt = tests[i];
469 wxFileName fn(fnt.original, fnt.fmt);
470
471 // set the environment variable
472 wxSetEnv("TEST_VAR", fnt.env_contents);
473
474 // be sure this ReplaceEnvVariable does not fail
475 WX_ASSERT_MESSAGE
476 (
477 ("#%d: ReplaceEnvVariable(%s) failed", (int)i, fnt.replace_fmtstring),
478 fn.ReplaceEnvVariable("TEST_VAR", fnt.replace_fmtstring, fnt.fmt)
479 );
480
481 // compare result with expected string
482 wxString expected(fnt.expected);
483 WX_ASSERT_EQUAL_MESSAGE
484 (
485 ("array element #%d", (int)i),
486 expected, fn.GetFullPath(fnt.fmt)
487 );
488 }
489
490 // now test ReplaceHomeDir
491
492 wxFileName fn = wxFileName::DirName(wxGetHomeDir());
493 fn.AppendDir("test1");
494 fn.AppendDir("test2");
495 fn.AppendDir("test3");
496 fn.SetName("some file");
497
498 WX_ASSERT_MESSAGE
499 (
500 ("ReplaceHomeDir(%s) failed", fn.GetFullPath()),
501 fn.ReplaceHomeDir()
502 );
503
504 CPPUNIT_ASSERT_EQUAL( wxString("~/test1/test2/test3/some file"),
505 fn.GetFullPath(wxPATH_UNIX) );
506 }
507
508 void FileNameTestCase::TestGetHumanReadable()
509 {
510 static const struct TestData
511 {
512 const char *result;
513 int size;
514 int prec;
515 wxSizeConvention conv;
516 } testData[] =
517 {
518 { "NA", 0, 1, wxSIZE_CONV_TRADITIONAL },
519 { "2.0 KB", 2000, 1, wxSIZE_CONV_TRADITIONAL },
520 { "1.953 KiB", 2000, 3, wxSIZE_CONV_IEC },
521 { "2.000 KB", 2000, 3, wxSIZE_CONV_SI },
522 { "297 KB", 304351, 0, wxSIZE_CONV_TRADITIONAL },
523 { "304 KB", 304351, 0, wxSIZE_CONV_SI },
524 };
525
526 CLocaleSetter loc; // we want to use "C" locale for LC_NUMERIC
527 // so that regardless of the system's locale
528 // the decimal point used by GetHumanReadableSize()
529 // is always '.'
530 for ( unsigned n = 0; n < WXSIZEOF(testData); n++ )
531 {
532 const TestData& td = testData[n];
533
534 // take care of using the decimal point for the current locale before
535 // the actual comparison
536 CPPUNIT_ASSERT_EQUAL
537 (
538 td.result,
539 wxFileName::GetHumanReadableSize(td.size, "NA", td.prec, td.conv)
540 );
541 }
542
543 // also test the default convention value
544 CPPUNIT_ASSERT_EQUAL( "1.4 MB", wxFileName::GetHumanReadableSize(1512993, "") );
545 }
546
547 void FileNameTestCase::TestStrip()
548 {
549 CPPUNIT_ASSERT_EQUAL( "", wxFileName::StripExtension("") );
550 CPPUNIT_ASSERT_EQUAL( ".", wxFileName::StripExtension(".") );
551 CPPUNIT_ASSERT_EQUAL( ".vimrc", wxFileName::StripExtension(".vimrc") );
552 CPPUNIT_ASSERT_EQUAL( "bad", wxFileName::StripExtension("bad") );
553 CPPUNIT_ASSERT_EQUAL( "good", wxFileName::StripExtension("good.wav") );
554 CPPUNIT_ASSERT_EQUAL( "good.wav", wxFileName::StripExtension("good.wav.wav") );
555 }
556
557 #ifdef __WINDOWS__
558
559 void FileNameTestCase::TestShortLongPath()
560 {
561 wxFileName fn("C:\\Program Files\\Windows NT\\Accessories\\wordpad.exe");
562
563 // incredibly enough, GetLongPath() used to return different results during
564 // the first and subsequent runs, test for this
565 CPPUNIT_ASSERT_EQUAL( fn.GetLongPath(), fn.GetLongPath() );
566 CPPUNIT_ASSERT_EQUAL( fn.GetShortPath(), fn.GetShortPath() );
567 }
568
569 #endif // __WINDOWS__
570
571 void FileNameTestCase::TestUNC()
572 {
573 wxFileName fn("//share/path/name.ext", wxPATH_DOS);
574 CPPUNIT_ASSERT_EQUAL( "share", fn.GetVolume() );
575 CPPUNIT_ASSERT_EQUAL( "\\path", fn.GetPath(wxPATH_NO_SEPARATOR, wxPATH_DOS) );
576
577 fn.Assign("\\\\share2\\path2\\name.ext", wxPATH_DOS);
578 CPPUNIT_ASSERT_EQUAL( "share2", fn.GetVolume() );
579 CPPUNIT_ASSERT_EQUAL( "\\path2", fn.GetPath(wxPATH_NO_SEPARATOR, wxPATH_DOS) );
580 }
581
582 void FileNameTestCase::TestVolumeUniqueName()
583 {
584 wxFileName fn("\\\\?\\Volume{8089d7d7-d0ac-11db-9dd0-806d6172696f}\\",
585 wxPATH_DOS);
586 CPPUNIT_ASSERT_EQUAL( "Volume{8089d7d7-d0ac-11db-9dd0-806d6172696f}",
587 fn.GetVolume() );
588 CPPUNIT_ASSERT_EQUAL( "\\", fn.GetPath(wxPATH_NO_SEPARATOR, wxPATH_DOS) );
589 CPPUNIT_ASSERT_EQUAL( "\\\\?\\Volume{8089d7d7-d0ac-11db-9dd0-806d6172696f}\\",
590 fn.GetFullPath(wxPATH_DOS) );
591
592 fn.Assign("\\\\?\\Volume{8089d7d7-d0ac-11db-9dd0-806d6172696f}\\"
593 "Program Files\\setup.exe", wxPATH_DOS);
594 CPPUNIT_ASSERT_EQUAL( "Volume{8089d7d7-d0ac-11db-9dd0-806d6172696f}",
595 fn.GetVolume() );
596 CPPUNIT_ASSERT_EQUAL( "\\Program Files",
597 fn.GetPath(wxPATH_NO_SEPARATOR, wxPATH_DOS) );
598 CPPUNIT_ASSERT_EQUAL( "\\\\?\\Volume{8089d7d7-d0ac-11db-9dd0-806d6172696f}\\"
599 "Program Files\\setup.exe",
600 fn.GetFullPath(wxPATH_DOS) );
601 }
602
603 void FileNameTestCase::TestCreateTempFileName()
604 {
605 static const struct TestData
606 {
607 const char *prefix;
608 const char *expectedFolder;
609 bool shouldSucceed;
610 } testData[] =
611 {
612 { "", "$SYSTEM_TEMP", true },
613 { "foo", "$SYSTEM_TEMP", true },
614 { "..", "$SYSTEM_TEMP", true },
615 { "../bar", "..", true },
616 #ifdef __WINDOWS__
617 { "$USER_DOCS_DIR\\", "$USER_DOCS_DIR", true },
618 { "c:\\a\\directory\\which\\does\\not\\exist", "", false },
619 #elif defined( __UNIX__ )
620 { "$USER_DOCS_DIR/", "$USER_DOCS_DIR", true },
621 { "/tmp/foo", "/tmp", true },
622 { "/tmp/a/directory/which/does/not/exist", "", false },
623 #endif // __UNIX__
624 };
625
626 for ( size_t n = 0; n < WXSIZEOF(testData); n++ )
627 {
628 wxString prefix = testData[n].prefix;
629 prefix.Replace("$USER_DOCS_DIR", wxStandardPaths::Get().GetDocumentsDir());
630
631 std::string errDesc = wxString::Format("failed on prefix '%s'", prefix).ToStdString();
632
633 wxString path = wxFileName::CreateTempFileName(prefix);
634 CPPUNIT_ASSERT_EQUAL_MESSAGE( errDesc, !testData[n].shouldSucceed, path.empty() );
635
636 if (testData[n].shouldSucceed)
637 {
638 errDesc += "; path is " + path.ToStdString();
639
640 // test the place where the temp file has been created
641 wxString expected = testData[n].expectedFolder;
642 expected.Replace("$SYSTEM_TEMP", wxStandardPaths::Get().GetTempDir());
643 expected.Replace("$USER_DOCS_DIR", wxStandardPaths::Get().GetDocumentsDir());
644 CPPUNIT_ASSERT_EQUAL_MESSAGE( errDesc, expected, wxFileName(path).GetPath() );
645
646 // the temporary file is created with full permissions for the current process
647 // so we should always be able to remove it:
648 CPPUNIT_ASSERT_MESSAGE( errDesc, wxRemoveFile(path) );
649 }
650 }
651 }
652
653 void FileNameTestCase::TestGetTimes()
654 {
655 wxFileName fn(wxFileName::CreateTempFileName("filenametest"));
656 CPPUNIT_ASSERT( fn.IsOk() );
657 wxON_BLOCK_EXIT1( wxRemoveFile, fn.GetFullPath() );
658
659 wxDateTime dtAccess, dtMod, dtCreate;
660 CPPUNIT_ASSERT( fn.GetTimes(&dtAccess, &dtMod, &dtCreate) );
661
662 // make sure all retrieved dates are equal to the current date&time
663 // with an accuracy up to 1 minute
664 CPPUNIT_ASSERT(dtCreate.IsEqualUpTo(wxDateTime::Now(), wxTimeSpan(0,1)));
665 CPPUNIT_ASSERT(dtMod.IsEqualUpTo(wxDateTime::Now(), wxTimeSpan(0,1)));
666 CPPUNIT_ASSERT(dtAccess.IsEqualUpTo(wxDateTime::Now(), wxTimeSpan(0,1)));
667 }
668
669 void FileNameTestCase::TestSetTimes()
670 {
671 wxFileName fn(wxFileName::CreateTempFileName("filenametest"));
672 CPPUNIT_ASSERT( fn.IsOk() );
673 wxON_BLOCK_EXIT1( wxRemoveFile, fn.GetFullPath() );
674
675 const wxDateTime dtAccess(1, wxDateTime::Jan, 2013);
676 const wxDateTime dtModify(1, wxDateTime::Feb, 2013);
677 const wxDateTime dtCreate(1, wxDateTime::Mar, 2013);
678
679 CPPUNIT_ASSERT( fn.SetTimes(&dtAccess, &dtModify, &dtCreate) );
680
681 wxDateTime dtAccess2,
682 dtModify2,
683 dtCreate2;
684 CPPUNIT_ASSERT( fn.GetTimes(&dtAccess2, &dtModify2, &dtCreate2) );
685 CPPUNIT_ASSERT_EQUAL( dtAccess, dtAccess2 );
686 CPPUNIT_ASSERT_EQUAL( dtModify, dtModify2 );
687
688 // Under Unix the creation time can't be set.
689 #ifdef __WINDOWS__
690 CPPUNIT_ASSERT_EQUAL( dtCreate, dtCreate2 );
691 #endif // __WINDOWS__
692 }
693
694 void FileNameTestCase::TestExists()
695 {
696 wxFileName fn(wxFileName::CreateTempFileName("filenametest"));
697 CPPUNIT_ASSERT( fn.IsOk() );
698 wxON_BLOCK_EXIT1( wxRemoveFile, fn.GetFullPath() );
699
700 CPPUNIT_ASSERT( fn.FileExists() );
701 CPPUNIT_ASSERT( !wxFileName::DirExists(fn.GetFullPath()) );
702
703 // FIXME-VC6: This compiler crashes with
704 //
705 // fatal error C1001: INTERNAL COMPILER ERROR
706 // (compiler file 'msc1.cpp', line 1794)
707 //
708 // when compiling calls to Exists() with parameter for some reason, just
709 // disable these tests there.
710 #ifndef __VISUALC6__
711 CPPUNIT_ASSERT( fn.Exists(wxFILE_EXISTS_REGULAR) );
712 CPPUNIT_ASSERT( !fn.Exists(wxFILE_EXISTS_DIR) );
713 #endif
714 CPPUNIT_ASSERT( fn.Exists() );
715
716 const wxString& tempdir = wxFileName::GetTempDir();
717
718 wxFileName fileInTempDir(tempdir, "bloordyblop");
719 CPPUNIT_ASSERT( !fileInTempDir.Exists() );
720 CPPUNIT_ASSERT( fileInTempDir.DirExists() );
721
722 wxFileName dirTemp(wxFileName::DirName(tempdir));
723 CPPUNIT_ASSERT( !dirTemp.FileExists() );
724 CPPUNIT_ASSERT( dirTemp.DirExists() );
725
726 #ifndef __VISUALC6__
727 CPPUNIT_ASSERT( dirTemp.Exists(wxFILE_EXISTS_DIR) );
728 CPPUNIT_ASSERT( !dirTemp.Exists(wxFILE_EXISTS_REGULAR) );
729 #endif
730 CPPUNIT_ASSERT( dirTemp.Exists() );
731
732 #ifdef __UNIX__
733 CPPUNIT_ASSERT( !wxFileName::FileExists("/dev/null") );
734 CPPUNIT_ASSERT( !wxFileName::DirExists("/dev/null") );
735 CPPUNIT_ASSERT( wxFileName::Exists("/dev/null") );
736 CPPUNIT_ASSERT( wxFileName::Exists("/dev/null", wxFILE_EXISTS_DEVICE) );
737 #ifdef __LINUX__
738 // These files are only guaranteed to exist under Linux.
739 // No need for wxFILE_EXISTS_NO_FOLLOW here; wxFILE_EXISTS_SYMLINK implies it
740 CPPUNIT_ASSERT( wxFileName::Exists("/dev/core", wxFILE_EXISTS_SYMLINK) );
741 CPPUNIT_ASSERT( wxFileName::Exists("/dev/log", wxFILE_EXISTS_SOCKET) );
742 #endif // __LINUX__
743 #ifndef __VMS
744 wxString fifo = dirTemp.GetPath() + "/fifo";
745 if (mkfifo(fifo.c_str(), 0600) == 0)
746 {
747 wxON_BLOCK_EXIT1(wxRemoveFile, fifo);
748
749 CPPUNIT_ASSERT( wxFileName::Exists(fifo, wxFILE_EXISTS_FIFO) );
750 }
751 #endif
752 #endif // __UNIX__
753 }
754
755 void FileNameTestCase::TestIsSame()
756 {
757 wxFileName fn1( wxFileName::CreateTempFileName( "filenametest1" ) );
758 CPPUNIT_ASSERT( fn1.IsOk() );
759 wxON_BLOCK_EXIT1( wxRemoveFile, fn1.GetFullPath() );
760
761 wxFileName fn2( wxFileName::CreateTempFileName( "filenametest2" ) );
762 CPPUNIT_ASSERT( fn2.IsOk() );
763 wxON_BLOCK_EXIT1( wxRemoveFile, fn2.GetFullPath() );
764
765 CPPUNIT_ASSERT( fn1.SameAs( fn1 ) );
766 CPPUNIT_ASSERT( !fn1.SameAs( fn2 ) );
767
768 #if defined(__UNIX__)
769 // We need to create a temporary directory and a temporary link.
770 // Unfortunately we can't use wxFileName::CreateTempFileName() for neither
771 // as it creates plain files, so use tempnam() explicitly instead.
772 char* tn = tempnam(NULL, "wxfn1");
773 const wxString tempdir1 = wxString::From8BitData(tn);
774 free(tn);
775
776 CPPUNIT_ASSERT( wxFileName::Mkdir(tempdir1) );
777 // Unfortunately the casts are needed to select the overload we need here.
778 wxON_BLOCK_EXIT2( static_cast<bool (*)(const wxString&, int)>(wxFileName::Rmdir),
779 tempdir1, static_cast<int>(wxPATH_RMDIR_RECURSIVE) );
780
781 tn = tempnam(NULL, "wxfn2");
782 const wxString tempdir2 = wxString::From8BitData(tn);
783 free(tn);
784 CPPUNIT_ASSERT_EQUAL( 0, symlink(tempdir1.c_str(), tempdir2.c_str()) );
785 wxON_BLOCK_EXIT1( wxRemoveFile, tempdir2 );
786
787
788 wxFileName fn3(tempdir1, "foo");
789 wxFileName fn4(tempdir2, "foo");
790
791 // These files have different paths, hence are different.
792 CPPUNIT_ASSERT( !fn3.SameAs(fn4) );
793
794 // Create and close a file to trigger creating it.
795 wxFile(fn3.GetFullPath(), wxFile::write);
796
797 // Now that both files do exist we should be able to detect that they are
798 // actually the same file.
799 CPPUNIT_ASSERT( fn3.SameAs(fn4) );
800 #endif // __UNIX__
801 }
802
803 #if defined(__UNIX__)
804
805 // Tests for functions that are changed by ShouldFollowLink()
806 void FileNameTestCase::TestSymlinks()
807 {
808 const wxString tmpdir(wxStandardPaths::Get().GetTempDir());
809
810 wxFileName tmpfn(wxFileName::DirName(tmpdir));
811
812 wxDateTime dtAccessTmp, dtModTmp, dtCreateTmp;
813 CPPUNIT_ASSERT(tmpfn.GetTimes(&dtAccessTmp, &dtModTmp, &dtCreateTmp));
814
815 // Create a temporary directory
816 #ifdef __VMS
817 wxString name = tmpdir + ".filenametestXXXXXX]";
818 mkdir( name.char_str() , 0222 );
819 wxString tempdir = name;
820 #else
821 wxString name = tmpdir + "/filenametestXXXXXX";
822 wxString tempdir = wxString::From8BitData(mkdtemp(name.char_str()));
823 tempdir << wxFileName::GetPathSeparator();
824 #endif
825 wxFileName tempdirfn(wxFileName::DirName(tempdir));
826 CPPUNIT_ASSERT(tempdirfn.DirExists());
827
828 // Create a regular file in that dir, to act as a symlink target
829 wxFileName targetfn(wxFileName::CreateTempFileName(tempdir));
830 CPPUNIT_ASSERT(targetfn.FileExists());
831
832 // Create a symlink to that file
833 wxFileName linktofile(tempdir, "linktofile");
834 CPPUNIT_ASSERT_EQUAL(0, symlink(targetfn.GetFullPath().c_str(),
835 linktofile.GetFullPath().c_str()));
836
837 // ... and another to the temporary directory
838 const wxString linktodirName(tempdir + "/linktodir");
839 wxFileName linktodir(wxFileName::DirName(linktodirName));
840 CPPUNIT_ASSERT_EQUAL(0, symlink(tmpfn.GetFullPath().c_str(),
841 linktodirName.c_str()));
842
843 // And symlinks to both of those symlinks
844 wxFileName linktofilelnk(tempdir, "linktofilelnk");
845 CPPUNIT_ASSERT_EQUAL(0, symlink(linktofile.GetFullPath().c_str(),
846 linktofilelnk.GetFullPath().c_str()));
847 wxFileName linktodirlnk(tempdir, "linktodirlnk");
848 CPPUNIT_ASSERT_EQUAL(0, symlink(linktodir.GetFullPath().c_str(),
849 linktodirlnk.GetFullPath().c_str()));
850
851 // Run the tests twice: once in the default symlink following mode and the
852 // second time without following symlinks.
853 bool deref = true;
854 for ( int n = 0; n < 2; ++n, deref = !deref )
855 {
856 const std::string msg(deref ? " failed for the link target"
857 : " failed for the path itself");
858
859 if ( !deref )
860 {
861 linktofile.DontFollowLink();
862 linktodir.DontFollowLink();
863 linktofilelnk.DontFollowLink();
864 linktodirlnk.DontFollowLink();
865 }
866
867 // Test SameAs()
868 CPPUNIT_ASSERT_EQUAL_MESSAGE
869 (
870 "Comparison with file" + msg,
871 deref, linktofile.SameAs(targetfn)
872 );
873
874 CPPUNIT_ASSERT_EQUAL_MESSAGE
875 (
876 "Comparison with directory" + msg,
877 deref, linktodir.SameAs(tmpfn)
878 );
879
880 // A link-to-a-link should dereference through to the final target
881 CPPUNIT_ASSERT_EQUAL_MESSAGE
882 (
883 "Comparison with link to a file" + msg,
884 deref,
885 linktofilelnk.SameAs(targetfn)
886 );
887 CPPUNIT_ASSERT_EQUAL_MESSAGE
888 (
889 "Comparison with link to a directory" + msg,
890 deref,
891 linktodirlnk.SameAs(tmpfn)
892 );
893
894 // Test GetTimes()
895 wxDateTime dtAccess, dtMod, dtCreate;
896 CPPUNIT_ASSERT_MESSAGE
897 (
898 "Getting times of a directory" + msg,
899 linktodir.GetTimes(&dtAccess, &dtMod, &dtCreate)
900 );
901
902 // IsEqualTo() should be true only when dereferencing. Don't test each
903 // individually: accessing to create the link will have updated some
904 bool equal = dtCreate.IsEqualTo(dtCreateTmp) &&
905 dtMod.IsEqualTo(dtModTmp) &&
906 dtAccess.IsEqualTo(dtAccessTmp);
907 CPPUNIT_ASSERT_EQUAL_MESSAGE
908 (
909 "Comparing directory times" + msg,
910 deref,
911 equal
912 );
913
914 // Test (File|Dir)Exists()
915 CPPUNIT_ASSERT_EQUAL_MESSAGE
916 (
917 "Testing file existence" + msg,
918 deref,
919 linktofile.FileExists()
920 );
921 CPPUNIT_ASSERT_EQUAL_MESSAGE
922 (
923 "Testing directory existence" + msg,
924 deref,
925 linktodir.DirExists()
926 );
927
928 // Test wxFileName::Exists
929 // The wxFILE_EXISTS_NO_FOLLOW flag should override DontFollowLink()
930 CPPUNIT_ASSERT_EQUAL_MESSAGE
931 (
932 "Testing file existence" + msg,
933 false,
934 linktofile.Exists(wxFILE_EXISTS_REGULAR | wxFILE_EXISTS_NO_FOLLOW)
935 );
936 CPPUNIT_ASSERT_EQUAL_MESSAGE
937 (
938 "Testing directory existence" + msg,
939 false,
940 linktodir.Exists(wxFILE_EXISTS_DIR | wxFILE_EXISTS_NO_FOLLOW)
941 );
942 // and the static versions
943 CPPUNIT_ASSERT_EQUAL_MESSAGE
944 (
945 "Testing file existence" + msg,
946 false,
947 wxFileName::Exists(linktofile.GetFullPath(), wxFILE_EXISTS_REGULAR | wxFILE_EXISTS_NO_FOLLOW)
948 );
949 CPPUNIT_ASSERT_EQUAL_MESSAGE
950 (
951 "Testing file existence" + msg,
952 true,
953 wxFileName::Exists(linktofile.GetFullPath(), wxFILE_EXISTS_REGULAR)
954 );
955 CPPUNIT_ASSERT_EQUAL_MESSAGE
956 (
957 "Testing directory existence" + msg,
958 false,
959 wxFileName::Exists(linktodir.GetFullPath(), wxFILE_EXISTS_DIR | wxFILE_EXISTS_NO_FOLLOW)
960 );
961 CPPUNIT_ASSERT_EQUAL_MESSAGE
962 (
963 "Testing directory existence" + msg,
964 true,
965 wxFileName::Exists(linktodir.GetFullPath(), wxFILE_EXISTS_DIR)
966 );
967 }
968
969 // Finally test Exists() after removing the file.
970 CPPUNIT_ASSERT(wxRemoveFile(targetfn.GetFullPath()));
971 // This should succeed, as the symlink still exists and
972 // the default wxFILE_EXISTS_ANY implies wxFILE_EXISTS_NO_FOLLOW
973 CPPUNIT_ASSERT(wxFileName(tempdir, "linktofile").Exists());
974 // So should this one, as wxFILE_EXISTS_SYMLINK does too
975 CPPUNIT_ASSERT(wxFileName(tempdir, "linktofile").
976 Exists(wxFILE_EXISTS_SYMLINK));
977 // but not this one, as the now broken symlink is followed
978 CPPUNIT_ASSERT(!wxFileName(tempdir, "linktofile").
979 Exists(wxFILE_EXISTS_REGULAR));
980 CPPUNIT_ASSERT(linktofile.Exists());
981
982 // This is also a convenient place to test Rmdir() as we have things to
983 // remove.
984
985 // First, check that removing a symlink to a directory fails.
986 CPPUNIT_ASSERT( !wxFileName::Rmdir(linktodirName) );
987
988 // And recursively removing it only removes the symlink itself, not the
989 // directory.
990 CPPUNIT_ASSERT( wxFileName::Rmdir(linktodirName, wxPATH_RMDIR_RECURSIVE) );
991 CPPUNIT_ASSERT( tmpfn.Exists() );
992
993 // Finally removing the directory itself does remove everything.
994 CPPUNIT_ASSERT(tempdirfn.Rmdir(wxPATH_RMDIR_RECURSIVE));
995 CPPUNIT_ASSERT( !tempdirfn.Exists() );
996 }
997
998 #endif // __UNIX__