1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: tests/exec/exec.cpp
3 // Purpose: test wxExecute()
4 // Author: Francesco Montorsi
5 // (based on console sample TestExecute() function)
8 // Copyright: (c) 2009 Francesco Montorsi
9 ///////////////////////////////////////////////////////////////////////////////
11 // ----------------------------------------------------------------------------
13 // ----------------------------------------------------------------------------
22 #include "wx/process.h"
23 #include "wx/sstream.h"
26 #define COMMAND "echo hi"
27 #define ASYNC_COMMAND "xclock"
28 #define SHELL_COMMAND "echo hi from shell"
29 #define REDIRECT_COMMAND "cat -n Makefile"
30 #elif defined(__WXMSW__)
31 #define COMMAND "cmd.exe /c \"echo hi\""
32 #define ASYNC_COMMAND "notepad"
33 #define SHELL_COMMAND "echo hi"
34 #define REDIRECT_COMMAND COMMAND
36 #error "no command to exec"
39 // ----------------------------------------------------------------------------
41 // ----------------------------------------------------------------------------
43 class ExecTestCase
: public CppUnit
::TestCase
49 CPPUNIT_TEST_SUITE( ExecTestCase
);
50 CPPUNIT_TEST( TestShell
);
51 CPPUNIT_TEST( TestExecute
);
52 CPPUNIT_TEST( TestProcess
);
53 CPPUNIT_TEST_SUITE_END();
59 DECLARE_NO_COPY_CLASS(ExecTestCase
)
62 // register in the unnamed registry so that these tests are run by default
63 CPPUNIT_TEST_SUITE_REGISTRATION( ExecTestCase
);
65 // also include in it's own registry so that these tests can be run alone
66 CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( ExecTestCase
, "ExecTestCase" );
69 void ExecTestCase
::TestShell()
71 CPPUNIT_ASSERT( wxShell(SHELL_COMMAND
) );
74 void ExecTestCase
::TestExecute()
77 CPPUNIT_ASSERT( wxExecute(COMMAND
, wxEXEC_SYNC
) == 0 );
80 long pid
= wxExecute(ASYNC_COMMAND
, wxEXEC_ASYNC
);
81 CPPUNIT_ASSERT( pid
!= 0 );
82 CPPUNIT_ASSERT( wxKill(pid
) == 0 );
84 // test running COMMAND again, but this time with redirection:
86 CPPUNIT_ASSERT( wxExecute(COMMAND
, stdout
, wxEXEC_SYNC
) == 0 );
87 CPPUNIT_ASSERT( stdout
[0] == "hi" );
90 void ExecTestCase
::TestProcess()
92 // test wxExecute with wxProcess
93 wxProcess
*proc
= new wxProcess
;
94 long pid
= wxExecute(ASYNC_COMMAND
, wxEXEC_ASYNC
, proc
);
95 CPPUNIT_ASSERT( proc
->GetPid() == pid
&& pid
!= 0 );
97 // we're not going to process the wxEVT_END_PROCESS event,
98 // so the proc instance will auto-delete itself after we kill
99 // the asynch process:
100 CPPUNIT_ASSERT( wxKill(pid
) == 0 );
103 // test wxExecute with wxProcess and REDIRECTION
104 wxProcess
*proc2
= new wxProcess
;
106 CPPUNIT_ASSERT( wxExecute(COMMAND
, wxEXEC_SYNC
, proc2
) == 0 );
108 wxStringOutputStream stdout
;
109 CPPUNIT_ASSERT( proc2
->GetInputStream() );
110 CPPUNIT_ASSERT( proc2
->GetInputStream()->Read(stdout
).GetLastError() == wxSTREAM_EOF
);
112 wxString
str(stdout
.GetString());
113 CPPUNIT_ASSERT_EQUAL( "hi", str
.Trim() );