Support monitoring only some events in wxGTK wxFileSystemWatcher.
[wxWidgets.git] / tests / fswatcher / fswatchertest.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: tests/fswatcher/fswatchertest.cpp
3 // Purpose: wxFileSystemWatcher unit test
4 // Author: Bartosz Bekier
5 // Created: 2009-06-11
6 // RCS-ID: $Id$
7 // Copyright: (c) 2009 Bartosz Bekier
8 ///////////////////////////////////////////////////////////////////////////////
9
10 // ----------------------------------------------------------------------------
11 // headers
12 // ----------------------------------------------------------------------------
13
14 #include "testprec.h"
15
16 #ifdef __BORLANDC__
17 #pragma hdrstop
18 #endif
19
20 #ifndef WX_PRECOMP
21 #include "wx/timer.h"
22 #endif
23
24 #include "wx/evtloop.h"
25 #include "wx/filename.h"
26 #include "wx/filefn.h"
27 #include "wx/stdpaths.h"
28 #include "wx/fswatcher.h"
29
30 #include "testfile.h"
31
32 // ----------------------------------------------------------------------------
33 // local functions
34 // ----------------------------------------------------------------------------
35
36 // class generating file system events
37 class EventGenerator
38 {
39 public:
40 static EventGenerator& Get()
41 {
42 if (!ms_instance)
43 ms_instance = new EventGenerator(GetWatchDir());
44
45 return *ms_instance;
46 }
47
48 EventGenerator(const wxFileName& path) : m_base(path)
49 {
50 m_old = wxFileName();
51 m_file = RandomName();
52 m_new = RandomName();
53 }
54
55 // operations
56 bool CreateFile()
57 {
58 wxFile file(m_file.GetFullPath(), wxFile::write);
59 return file.IsOpened() && m_file.FileExists();
60 }
61
62 bool RenameFile()
63 {
64 CPPUNIT_ASSERT(m_file.FileExists());
65
66 wxLogDebug("Renaming %s=>%s", m_file.GetFullPath(), m_new.GetFullPath());
67
68 bool ret = wxRenameFile(m_file.GetFullPath(), m_new.GetFullPath());
69 if (ret)
70 {
71 m_old = m_file;
72 m_file = m_new;
73 m_new = RandomName();
74 }
75
76 return ret;
77 }
78
79 bool DeleteFile()
80 {
81 CPPUNIT_ASSERT(m_file.FileExists());
82
83 bool ret = wxRemoveFile(m_file.GetFullPath());
84 if (ret)
85 {
86 m_old = m_file;
87 m_file = m_new;
88 m_new = RandomName();
89 }
90
91 return ret;
92 }
93
94 bool TouchFile()
95 {
96 return m_file.Touch();
97 }
98
99 bool ReadFile()
100 {
101 wxFile f(m_file.GetFullPath());
102 CPPUNIT_ASSERT(f.IsOpened());
103
104 char buf[1];
105 ssize_t count = f.Read(buf, sizeof(buf));
106 CPPUNIT_ASSERT(count > 0);
107
108 return true;
109 }
110
111 bool ModifyFile()
112 {
113 CPPUNIT_ASSERT(m_file.FileExists());
114
115 wxFile file(m_file.GetFullPath(), wxFile::write_append);
116 CPPUNIT_ASSERT(file.IsOpened());
117
118 CPPUNIT_ASSERT(file.Write("Words of Wisdom, Lloyd. Words of wisdom\n"));
119 return file.Close();
120 }
121
122 // helpers
123 wxFileName RandomName(int length = 10)
124 {
125 return RandomName(m_base, length);
126 }
127
128 // static helpers
129 static const wxFileName& GetWatchDir()
130 {
131 static wxFileName dir;
132
133 if (dir.DirExists())
134 return dir;
135
136 wxString tmp = wxStandardPaths::Get().GetTempDir();
137 dir.AssignDir(tmp);
138
139 // XXX look for more unique name? there is no function to generate
140 // unique filename, the file always get created...
141 dir.AppendDir("fswatcher_test");
142 CPPUNIT_ASSERT(!dir.DirExists());
143 CPPUNIT_ASSERT(dir.Mkdir());
144
145 return dir;
146 }
147
148 static void RemoveWatchDir()
149 {
150 wxFileName dir = GetWatchDir();
151 CPPUNIT_ASSERT(dir.DirExists());
152
153 // just to be really sure we know what we remove
154 CPPUNIT_ASSERT_EQUAL( "fswatcher_test", dir.GetDirs().Last() );
155
156 // FIXME-VC6: using non-static Rmdir() results in ICE
157 CPPUNIT_ASSERT( wxFileName::Rmdir(dir.GetFullPath(), wxPATH_RMDIR_RECURSIVE) );
158 }
159
160 static wxFileName RandomName(const wxFileName& base, int length = 10)
161 {
162 static int ALFA_CNT = 'z' - 'a';
163
164 wxString s;
165 for (int i = 0 ; i < length; ++i)
166 {
167 char c = 'a' + (rand() % ALFA_CNT);
168 s += c;
169 }
170
171 return wxFileName(base.GetFullPath(), s);
172 }
173
174 public:
175 wxFileName m_base; // base dir for doing operations
176 wxFileName m_file; // current file name
177 wxFileName m_old; // previous file name
178 wxFileName m_new; // name after renaming
179
180 protected:
181 static EventGenerator* ms_instance;
182 };
183
184 EventGenerator* EventGenerator::ms_instance = 0;
185
186
187 // custom event handler
188 class EventHandler : public wxEvtHandler
189 {
190 public:
191 enum { WAIT_DURATION = 3 };
192
193 EventHandler(int types = wxFSW_EVENT_ALL) :
194 eg(EventGenerator::Get()), m_loop(0), m_count(0), m_watcher(0),
195 m_eventTypes(types)
196 {
197 m_loop = new wxEventLoop();
198 Connect(wxEVT_IDLE, wxIdleEventHandler(EventHandler::OnIdle));
199 Connect(wxEVT_FSWATCHER, wxFileSystemWatcherEventHandler(
200 EventHandler::OnFileSystemEvent));
201 }
202
203 virtual ~EventHandler()
204 {
205 delete m_watcher;
206 if (m_loop)
207 {
208 if (m_loop->IsRunning())
209 m_loop->Exit();
210 delete m_loop;
211 }
212 }
213
214 void Exit()
215 {
216 m_loop->Exit();
217 }
218
219 // sends idle event, so we get called in a moment
220 void SendIdle()
221 {
222 wxIdleEvent* e = new wxIdleEvent();
223 QueueEvent(e);
224 }
225
226 void Run()
227 {
228 SendIdle();
229 m_loop->Run();
230 }
231
232 void OnIdle(wxIdleEvent& /*evt*/)
233 {
234 bool more = Action();
235 m_count++;
236
237 if (more)
238 {
239 SendIdle();
240 }
241 }
242
243 // returns whether we should produce more idle events
244 virtual bool Action()
245 {
246 switch (m_count)
247 {
248 case 0:
249 CPPUNIT_ASSERT(Init());
250 break;
251 case 1:
252 GenerateEvent();
253 break;
254 case 2:
255 // actual test
256 CheckResult();
257 Exit();
258 break;
259
260 // TODO a mechanism that will break the loop in case we
261 // don't receive a file system event
262 // this below doesn't quite work, so all tests must pass :-)
263 #if 0
264 case 2:
265 m_loop.Yield();
266 m_loop.WakeUp();
267 CPPUNIT_ASSERT(KeepWaiting());
268 m_loop.Yield();
269 break;
270 case 3:
271 break;
272 case 4:
273 CPPUNIT_ASSERT(AfterWait());
274 break;
275 #endif
276 } // switch (m_count)
277
278 return m_count <= 0;
279 }
280
281 virtual bool Init()
282 {
283 // test we're good to go
284 CPPUNIT_ASSERT(wxEventLoopBase::GetActive());
285
286 // XXX only now can we construct Watcher, because we need
287 // active loop here
288 m_watcher = new wxFileSystemWatcher();
289 m_watcher->SetOwner(this);
290
291 // add dir to be watched
292 wxFileName dir = EventGenerator::GetWatchDir();
293 CPPUNIT_ASSERT(m_watcher->Add(dir, m_eventTypes));
294
295 return true;
296 }
297
298 virtual bool KeepWaiting()
299 {
300 // did we receive event already?
301 if (!tested)
302 {
303 // well, let's wait a bit more
304 wxSleep(WAIT_DURATION);
305 }
306
307 return true;
308 }
309
310 virtual bool AfterWait()
311 {
312 // fail if still no events
313 WX_ASSERT_MESSAGE
314 (
315 ("No events during %d seconds!", static_cast<int>(WAIT_DURATION)),
316 tested
317 );
318
319 return true;
320 }
321
322 virtual void OnFileSystemEvent(wxFileSystemWatcherEvent& evt)
323 {
324 wxLogDebug("--- %s ---", evt.ToString());
325 m_lastEvent = wxDynamicCast(evt.Clone(), wxFileSystemWatcherEvent);
326 m_events.Add(m_lastEvent);
327
328 // test finished
329 SendIdle();
330 tested = true;
331 }
332
333 virtual void CheckResult()
334 {
335 CPPUNIT_ASSERT_MESSAGE( "No events received", !m_events.empty() );
336
337 const wxFileSystemWatcherEvent * const e = m_events.front();
338
339 // this is our "reference event"
340 const wxFileSystemWatcherEvent expected = ExpectedEvent();
341
342 CPPUNIT_ASSERT_EQUAL( expected.GetChangeType(), e->GetChangeType() );
343
344 CPPUNIT_ASSERT_EQUAL((int)wxEVT_FSWATCHER, e->GetEventType());
345
346 // XXX this needs change
347 CPPUNIT_ASSERT_EQUAL(wxEVT_CATEGORY_UNKNOWN, e->GetEventCategory());
348
349 CPPUNIT_ASSERT_EQUAL(expected.GetPath(), e->GetPath());
350 CPPUNIT_ASSERT_EQUAL(expected.GetNewPath(), e->GetNewPath());
351
352 // Under MSW extra modification events are sometimes reported after a
353 // rename and we just can't get rid of them, so ignore them in this
354 // test if they do happen.
355 if ( e->GetChangeType() == wxFSW_EVENT_RENAME &&
356 m_events.size() == 2 )
357 {
358 const wxFileSystemWatcherEvent* const e2 = m_events.back();
359 if ( e2->GetChangeType() == wxFSW_EVENT_MODIFY &&
360 e2->GetPath() == e->GetNewPath() )
361 {
362 // This is a modify event for the new file, ignore it.
363 return;
364 }
365 }
366
367 WX_ASSERT_EQUAL_MESSAGE
368 (
369 (
370 "Extra events received, last one is of type %x, path=\"%s\" "
371 "(the original event was for \"%s\" (\"%s\")",
372 m_events.back()->GetChangeType(),
373 m_events.back()->GetPath().GetFullPath(),
374 e->GetPath().GetFullPath(),
375 e->GetNewPath().GetFullPath()
376 ),
377 1, m_events.size()
378 );
379
380 }
381
382 virtual void GenerateEvent() = 0;
383
384 virtual wxFileSystemWatcherEvent ExpectedEvent() = 0;
385
386
387 protected:
388 EventGenerator& eg;
389 wxEventLoopBase* m_loop; // loop reference
390 int m_count; // idle events count
391
392 wxFileSystemWatcher* m_watcher;
393 int m_eventTypes; // Which event-types to watch. Normally all of them
394 bool tested; // indicates, whether we have already passed the test
395
396 #include "wx/arrimpl.cpp"
397 WX_DEFINE_ARRAY_PTR(wxFileSystemWatcherEvent*, wxArrayEvent);
398 wxArrayEvent m_events;
399 wxFileSystemWatcherEvent* m_lastEvent;
400 };
401
402
403 // ----------------------------------------------------------------------------
404 // test class
405 // ----------------------------------------------------------------------------
406
407 class FileSystemWatcherTestCase : public CppUnit::TestCase
408 {
409 public:
410 FileSystemWatcherTestCase() { }
411
412 virtual void setUp();
413 virtual void tearDown();
414
415 protected:
416 wxEventLoopBase* m_loop;
417
418 private:
419 CPPUNIT_TEST_SUITE( FileSystemWatcherTestCase );
420 CPPUNIT_TEST( TestEventCreate );
421 CPPUNIT_TEST( TestEventDelete );
422 #if !defined(__VISUALC__) || wxCHECK_VISUALC_VERSION(7)
423 CPPUNIT_TEST( TestTrees );
424 #endif
425
426 // kqueue-based implementation doesn't collapse create/delete pairs in
427 // renames and doesn't detect neither modifications nor access to the
428 // files reliably currently so disable these tests
429 //
430 // FIXME: fix the code and reenable them
431 #ifndef wxHAS_KQUEUE
432 CPPUNIT_TEST( TestEventRename );
433 CPPUNIT_TEST( TestEventModify );
434
435 // MSW implementation doesn't detect file access events currently
436 #ifndef __WINDOWS__
437 CPPUNIT_TEST( TestEventAccess );
438 #endif // __WINDOWS__
439 #endif // !wxHAS_KQUEUE
440
441 #ifdef wxHAS_INOTIFY
442 CPPUNIT_TEST( TestSingleWatchtypeEvent );
443 #endif // wxHAS_INOTIFY
444
445 CPPUNIT_TEST( TestNoEventsAfterRemove );
446 CPPUNIT_TEST_SUITE_END();
447
448 void TestEventCreate();
449 void TestEventDelete();
450 void TestEventRename();
451 void TestEventModify();
452 void TestEventAccess();
453 #ifdef wxHAS_INOTIFY
454 void TestSingleWatchtypeEvent();
455 #endif // wxHAS_INOTIFY
456 #if !defined(__VISUALC__) || wxCHECK_VISUALC_VERSION(7)
457 void TestTrees(); // Visual C++ 6 can't build this
458 #endif
459 void TestNoEventsAfterRemove();
460
461 DECLARE_NO_COPY_CLASS(FileSystemWatcherTestCase)
462 };
463
464 // the test currently hangs under OS X for some reason and this prevents tests
465 // ran by buildbot from completing so disable it until someone has time to
466 // debug it
467 //
468 // FIXME: debug and fix this!
469 #ifndef __WXOSX__
470 // register in the unnamed registry so that these tests are run by default
471 CPPUNIT_TEST_SUITE_REGISTRATION( FileSystemWatcherTestCase );
472 #endif
473
474 // also include in its own registry so that these tests can be run alone
475 CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( FileSystemWatcherTestCase,
476 "FileSystemWatcherTestCase" );
477
478 void FileSystemWatcherTestCase::setUp()
479 {
480 wxLog::AddTraceMask(wxTRACE_FSWATCHER);
481 EventGenerator::Get().GetWatchDir();
482 }
483
484 void FileSystemWatcherTestCase::tearDown()
485 {
486 EventGenerator::Get().RemoveWatchDir();
487 }
488
489 // ----------------------------------------------------------------------------
490 // TestEventCreate
491 // ----------------------------------------------------------------------------
492 void FileSystemWatcherTestCase::TestEventCreate()
493 {
494 wxLogDebug("TestEventCreate()");
495
496 class EventTester : public EventHandler
497 {
498 public:
499 virtual void GenerateEvent()
500 {
501 CPPUNIT_ASSERT(eg.CreateFile());
502 }
503
504 virtual wxFileSystemWatcherEvent ExpectedEvent()
505 {
506 wxFileSystemWatcherEvent event(wxFSW_EVENT_CREATE);
507 event.SetPath(eg.m_file);
508 event.SetNewPath(eg.m_file);
509 return event;
510 }
511 };
512
513 EventTester tester;
514
515 wxLogTrace(wxTRACE_FSWATCHER, "TestEventCreate tester created()");
516
517 tester.Run();
518 }
519
520 // ----------------------------------------------------------------------------
521 // TestEventDelete
522 // ----------------------------------------------------------------------------
523 void FileSystemWatcherTestCase::TestEventDelete()
524 {
525 wxLogDebug("TestEventDelete()");
526
527 class EventTester : public EventHandler
528 {
529 public:
530 virtual void GenerateEvent()
531 {
532 CPPUNIT_ASSERT(eg.DeleteFile());
533 }
534
535 virtual wxFileSystemWatcherEvent ExpectedEvent()
536 {
537 wxFileSystemWatcherEvent event(wxFSW_EVENT_DELETE);
538 event.SetPath(eg.m_old);
539
540 // CHECK maybe new path here could be NULL or sth?
541 event.SetNewPath(eg.m_old);
542 return event;
543 }
544 };
545
546 // we need to create a file now, so we can delete it
547 EventGenerator::Get().CreateFile();
548
549 EventTester tester;
550 tester.Run();
551 }
552
553 // ----------------------------------------------------------------------------
554 // TestEventRename
555 // ----------------------------------------------------------------------------
556 void FileSystemWatcherTestCase::TestEventRename()
557 {
558 wxLogDebug("TestEventRename()");
559
560 class EventTester : public EventHandler
561 {
562 public:
563 virtual void GenerateEvent()
564 {
565 CPPUNIT_ASSERT(eg.RenameFile());
566 }
567
568 virtual wxFileSystemWatcherEvent ExpectedEvent()
569 {
570 wxFileSystemWatcherEvent event(wxFSW_EVENT_RENAME);
571 event.SetPath(eg.m_old);
572 event.SetNewPath(eg.m_file);
573 return event;
574 }
575 };
576
577 // need a file to rename later
578 EventGenerator::Get().CreateFile();
579
580 EventTester tester;
581 tester.Run();
582 }
583
584 // ----------------------------------------------------------------------------
585 // TestEventModify
586 // ----------------------------------------------------------------------------
587 void FileSystemWatcherTestCase::TestEventModify()
588 {
589 wxLogDebug("TestEventModify()");
590
591 class EventTester : public EventHandler
592 {
593 public:
594 virtual void GenerateEvent()
595 {
596 CPPUNIT_ASSERT(eg.ModifyFile());
597 }
598
599 virtual wxFileSystemWatcherEvent ExpectedEvent()
600 {
601 wxFileSystemWatcherEvent event(wxFSW_EVENT_MODIFY);
602 event.SetPath(eg.m_file);
603 event.SetNewPath(eg.m_file);
604 return event;
605 }
606 };
607
608 // we need to create a file to modify
609 EventGenerator::Get().CreateFile();
610
611 EventTester tester;
612 tester.Run();
613 }
614
615 // ----------------------------------------------------------------------------
616 // TestEventAccess
617 // ----------------------------------------------------------------------------
618 void FileSystemWatcherTestCase::TestEventAccess()
619 {
620 wxLogDebug("TestEventAccess()");
621
622 class EventTester : public EventHandler
623 {
624 public:
625 virtual void GenerateEvent()
626 {
627 CPPUNIT_ASSERT(eg.ReadFile());
628 }
629
630 virtual wxFileSystemWatcherEvent ExpectedEvent()
631 {
632 wxFileSystemWatcherEvent event(wxFSW_EVENT_ACCESS);
633 event.SetPath(eg.m_file);
634 event.SetNewPath(eg.m_file);
635 return event;
636 }
637 };
638
639 // we need to create a file to read from it and write sth to it
640 EventGenerator::Get().CreateFile();
641 EventGenerator::Get().ModifyFile();
642
643 EventTester tester;
644 tester.Run();
645 }
646
647 #ifdef wxHAS_INOTIFY
648 // ----------------------------------------------------------------------------
649 // TestSingleWatchtypeEvent: Watch only wxFSW_EVENT_ACCESS
650 // ----------------------------------------------------------------------------
651 void FileSystemWatcherTestCase::TestSingleWatchtypeEvent()
652 {
653 wxLogDebug("TestSingleWatchtypeEvent()");
654
655 class EventTester : public EventHandler
656 {
657 public:
658 // We could pass wxFSW_EVENT_CREATE or MODIFY instead, but not RENAME or
659 // DELETE as the event path fields would be wrong in CheckResult()
660 EventTester() : EventHandler(wxFSW_EVENT_ACCESS) {}
661
662 virtual void GenerateEvent()
663 {
664 // As wxFSW_EVENT_ACCESS is passed to the ctor only ReadFile() will
665 // generate an event. Without it they all will, and the test fails
666 CPPUNIT_ASSERT(eg.CreateFile());
667 CPPUNIT_ASSERT(eg.ModifyFile());
668 CPPUNIT_ASSERT(eg.ReadFile());
669 }
670
671 virtual wxFileSystemWatcherEvent ExpectedEvent()
672 {
673 wxFileSystemWatcherEvent event(wxFSW_EVENT_ACCESS);
674 event.SetPath(eg.m_file);
675 event.SetNewPath(eg.m_file);
676 return event;
677 }
678 };
679
680 EventTester tester;
681 tester.Run();
682 }
683 #endif // wxHAS_INOTIFY
684
685 // ----------------------------------------------------------------------------
686 // TestTrees
687 // ----------------------------------------------------------------------------
688
689 #if !defined(__VISUALC__) || wxCHECK_VISUALC_VERSION(7)
690 void FileSystemWatcherTestCase::TestTrees()
691 {
692 class TreeTester : public EventHandler
693 {
694 const size_t subdirs;
695 const size_t files;
696
697 public:
698 TreeTester() : subdirs(5), files(3) {}
699
700 void GrowTree(wxFileName dir
701 #ifdef __UNIX__
702 , bool withSymlinks = false
703 #endif
704 )
705 {
706 CPPUNIT_ASSERT(dir.Mkdir());
707 // Now add a subdir with an easy name to remember in WatchTree()
708 dir.AppendDir("child");
709 CPPUNIT_ASSERT(dir.Mkdir());
710 wxFileName child(dir); // Create a copy to which to symlink
711
712 // Create a branch of 5 numbered subdirs, each containing 3
713 // numbered files
714 for ( unsigned d = 0; d < subdirs; ++d )
715 {
716 dir.AppendDir(wxString::Format("subdir%u", d+1));
717 CPPUNIT_ASSERT(dir.Mkdir());
718
719 const wxString prefix = dir.GetPathWithSep();
720 const wxString ext[] = { ".txt", ".log", "" };
721 for ( unsigned f = 0; f < files; ++f )
722 {
723 // Just create the files.
724 wxFile(prefix + wxString::Format("file%u", f+1) + ext[f],
725 wxFile::write);
726 }
727 #if defined(__UNIX__)
728 if ( withSymlinks )
729 {
730 // Create a symlink to a files, and another to 'child'
731 CPPUNIT_ASSERT_EQUAL(0,
732 symlink(wxString(prefix + "file1").c_str(),
733 wxString(prefix + "file.lnk").c_str()));
734 CPPUNIT_ASSERT_EQUAL(0,
735 symlink(child.GetFullPath().c_str(),
736 wxString(prefix + "dir.lnk").c_str()));
737 }
738 #endif // __UNIX__
739 }
740 }
741
742 void RmDir(wxFileName dir)
743 {
744 CPPUNIT_ASSERT(dir.DirExists());
745
746 CPPUNIT_ASSERT(dir.Rmdir(wxPATH_RMDIR_RECURSIVE));
747 }
748
749 void WatchDir(wxFileName dir)
750 {
751 CPPUNIT_ASSERT(m_watcher);
752
753 // Store the initial count; there may already be some watches
754 const int initial = m_watcher->GetWatchedPathsCount();
755
756 m_watcher->Add(dir);
757 CPPUNIT_ASSERT_EQUAL(initial + 1,
758 m_watcher->GetWatchedPathsCount());
759 }
760
761 void RemoveSingleWatch(wxFileName dir)
762 {
763 CPPUNIT_ASSERT(m_watcher);
764
765 const int initial = m_watcher->GetWatchedPathsCount();
766
767 m_watcher->Remove(dir);
768 CPPUNIT_ASSERT_EQUAL(initial - 1,
769 m_watcher->GetWatchedPathsCount());
770 }
771
772 void WatchTree(const wxFileName& dir)
773 {
774 CPPUNIT_ASSERT(m_watcher);
775
776 size_t treeitems = 1; // the trunk
777 #ifndef __WINDOWS__
778 // When there's no file mask, wxMSW sets a single watch
779 // on the trunk which is implemented recursively.
780 // wxGTK always sets an additional watch for each subdir
781 treeitems += subdirs + 1; // +1 for 'child'
782 #endif // __WINDOWS__
783
784 // Store the initial count; there may already be some watches
785 const int initial = m_watcher->GetWatchedPathsCount();
786
787 GrowTree(dir);
788
789 m_watcher->AddTree(dir);
790 const int plustree = m_watcher->GetWatchedPathsCount();
791
792 CPPUNIT_ASSERT_EQUAL(initial + treeitems, plustree);
793
794 m_watcher->RemoveTree(dir);
795 CPPUNIT_ASSERT_EQUAL(initial, m_watcher->GetWatchedPathsCount());
796
797 // Now test the refcount mechanism by watching items more than once
798 wxFileName child(dir);
799 child.AppendDir("child");
800 m_watcher->AddTree(child);
801 // Check some watches were added; we don't care about the number
802 CPPUNIT_ASSERT(initial < m_watcher->GetWatchedPathsCount());
803 // Now watch the whole tree and check that the count is the same
804 // as it was the first time, despite also adding 'child' separately
805 // Except that in wxMSW this isn't true: each watch will be a
806 // single, recursive dir; so fudge the count
807 size_t fudge = 0;
808 #ifdef __WINDOWS__
809 fudge = 1;
810 #endif // __WINDOWS__
811 m_watcher->AddTree(dir);
812 CPPUNIT_ASSERT_EQUAL(plustree + fudge, m_watcher->GetWatchedPathsCount());
813 m_watcher->RemoveTree(child);
814 CPPUNIT_ASSERT(initial < m_watcher->GetWatchedPathsCount());
815 m_watcher->RemoveTree(dir);
816 CPPUNIT_ASSERT_EQUAL(initial, m_watcher->GetWatchedPathsCount());
817 #if defined(__UNIX__)
818 // Finally, test a tree containing internal symlinks
819 RmDir(dir);
820 GrowTree(dir, true /* test symlinks */);
821
822 // Without the DontFollowLink() call AddTree() would now assert
823 // (and without the assert, it would infinitely loop)
824 wxFileName fn = dir;
825 fn.DontFollowLink();
826 CPPUNIT_ASSERT(m_watcher->AddTree(fn));
827 CPPUNIT_ASSERT(m_watcher->RemoveTree(fn));
828
829 // Regrow the tree without symlinks, ready for the next test
830 RmDir(dir);
831 GrowTree(dir, false);
832 #endif // __UNIX__
833 }
834
835 void WatchTreeWithFilespec(const wxFileName& dir)
836 {
837 CPPUNIT_ASSERT(m_watcher);
838 CPPUNIT_ASSERT(dir.DirExists()); // Was built in WatchTree()
839
840 // Store the initial count; there may already be some watches
841 const int initial = m_watcher->GetWatchedPathsCount();
842
843 // When we use a filter, both wxMSW and wxGTK implementations set
844 // an additional watch for each subdir (+1 for the root dir itself
845 // and another +1 for "child").
846 const size_t treeitems = subdirs + 2;
847 m_watcher->AddTree(dir, wxFSW_EVENT_ALL, "*.txt");
848
849 const int plustree = m_watcher->GetWatchedPathsCount();
850 CPPUNIT_ASSERT_EQUAL(initial + treeitems, plustree);
851
852 // RemoveTree should try to remove only those files that were added
853 m_watcher->RemoveTree(dir);
854 CPPUNIT_ASSERT_EQUAL(initial, m_watcher->GetWatchedPathsCount());
855 }
856
857 void RemoveAllWatches()
858 {
859 CPPUNIT_ASSERT(m_watcher);
860
861 m_watcher->RemoveAll();
862 CPPUNIT_ASSERT_EQUAL(0, m_watcher->GetWatchedPathsCount());
863 }
864
865 virtual void GenerateEvent()
866 {
867 // We don't use this function for events. Just run the tests
868
869 wxFileName watchdir = EventGenerator::GetWatchDir();
870 CPPUNIT_ASSERT(watchdir.DirExists());
871
872 wxFileName treedir(watchdir);
873 treedir.AppendDir("treetrunk");
874 CPPUNIT_ASSERT(!treedir.DirExists());
875
876 wxFileName singledir(watchdir);
877 singledir.AppendDir("single");
878 CPPUNIT_ASSERT(!singledir.DirExists());
879 CPPUNIT_ASSERT(singledir.Mkdir());
880
881 WatchDir(singledir);
882 WatchTree(treedir);
883 // Now test adding and removing a tree using a filespec
884 // wxMSW uses the generic method to add matching files; which fails
885 // as it doesn't support adding files :/ So disable the test
886 #ifndef __WINDOWS__
887 WatchTreeWithFilespec(treedir);
888 #endif // __WINDOWS__
889
890 RemoveSingleWatch(singledir);
891 // Add it back again, ready to test RemoveAll()
892 WatchDir(singledir);
893
894 RemoveAllWatches();
895
896 // Clean up
897 RmDir(singledir);
898 RmDir(treedir);
899
900 Exit();
901 }
902
903 virtual wxFileSystemWatcherEvent ExpectedEvent()
904 {
905 CPPUNIT_FAIL("Shouldn't be called");
906
907 return wxFileSystemWatcherEvent(wxFSW_EVENT_ERROR);
908 }
909
910 virtual void CheckResult()
911 {
912 // Do nothing. We override this to prevent receiving events in
913 // ExpectedEvent()
914 }
915 };
916
917 TreeTester tester;
918 tester.Run();
919 }
920 #endif // !defined(__VISUALC__) || wxCHECK_VISUALC_VERSION(7)
921
922
923 namespace
924 {
925
926 // We can't define this class locally inside TestNoEventsAfterRemove() for some
927 // reason with g++ 4.0 under OS X 10.5, it results in the following mysterious
928 // error:
929 //
930 // /var/tmp//ccTkNCkc.s:unknown:Non-global symbol:
931 // __ZThn80_ZN25FileSystemWatcherTestCase23TestNoEventsAfterRemoveEvEN11EventTester6NotifyEv.eh
932 // can't be a weak_definition
933 //
934 // So define this class outside the function instead.
935 class NoEventsAfterRemoveEventTester : public EventHandler,
936 public wxTimer
937 {
938 public:
939 NoEventsAfterRemoveEventTester()
940 {
941 // We need to use an inactivity timer as we never get any file
942 // system events in this test, so we consider that the test is
943 // finished when this 1s timeout expires instead of, as usual,
944 // stopping after getting the file system events.
945 Start(1000, true);
946 }
947
948 virtual void GenerateEvent()
949 {
950 m_watcher->Remove(EventGenerator::GetWatchDir());
951 CPPUNIT_ASSERT(eg.CreateFile());
952 }
953
954 virtual void CheckResult()
955 {
956 CPPUNIT_ASSERT( m_events.empty() );
957 }
958
959 virtual wxFileSystemWatcherEvent ExpectedEvent()
960 {
961 CPPUNIT_FAIL( "Shouldn't be called" );
962
963 return wxFileSystemWatcherEvent(wxFSW_EVENT_ERROR);
964 }
965
966 virtual void Notify()
967 {
968 SendIdle();
969 }
970 };
971
972 } // anonymous namespace
973
974 void FileSystemWatcherTestCase::TestNoEventsAfterRemove()
975 {
976 NoEventsAfterRemoveEventTester tester;
977 tester.Run();
978 }