void CDeleteCommand::ExecuteL(CConsoleBase& aConsole) { // Connect to the SIF server RSoftwareInstall sif; TInt err = sif.Connect(); if (err != KErrNone) { aConsole.Printf(KTxtSifConnectionFailure); User::Leave(err); } CleanupClosePushL(sif); // Delete the component TRequestStatus status; sif.Uninstall(iComponentId, status); aConsole.Printf(KTxtDeleting); User::WaitForRequest(status); if (status.Int() != KErrNone) { User::Leave(status.Int()); } // Disconnect from the SIF server CleanupStack::PopAndDestroy(&sif); }
/** * * Write to the log. * * @param "const TDesC& aMsg" * The message string to write * * @param "TInt aLogMode" * The log mode (as bitmask of TTestFrameworkLogMode) * * @xxxx * */ void CTestFrameworkServer::WriteLog(const TDesC& aMsg, TInt aLogMode) { if(aLogMode & ELogToConsole) { if(iConsole) { CConsoleBase* theConsole = iConsole->Console(); theConsole->Printf(aMsg); theConsole->Printf(_L("\n")); // add newline } } if(aLogMode & ELogToFile) { if(iFileLogger) { iFileLogger->WriteLog(aMsg); } } if(aLogMode & ELogToPort) { RDebug::Print(aMsg); } }
void UseKernelCpuTime() { test.Start(_L("Create CCpuMeter")); CCpuMeter* m = CCpuMeter::New(); test_NotNull(m); TInt iv = 1000500; // on average 1000.5 ms TRequestStatus s; CConsoleBase* console = test.Console(); console->Read(s); FOREVER { User::AfterHighRes(1000000); m->Measure(); m->Display(iv); while (s!=KRequestPending) { User::WaitForRequest(s); TKeyCode k = console->KeyCode(); if (k == EKeyEscape) { delete m; return; } if (m->iNumCpus > 1) { // SMP only options if (k == EKeySpace) m->DisplayCoreControlInfo(); else if (k>='1' && k<=('0'+m->iNumCpus)) m->ChangeNumberOfCores(k - '0'); } console->Read(s); } } }
void CCTSYIntegrationTestSuiteStepBase::ConsolePrintL(const TDesC& aText ) { CConsoleBase* con = NULL; TRAPD(err, con = Console::NewL(_L("Interactive Print"), TSize(KConsFullScreen, KConsFullScreen))); TEST(err == KErrNone); CleanupStack::PushL(con); con->Printf(_L("%S"), &aText); CleanupStack::PopAndDestroy(); // con }
LOCAL_C void mainL() { CCommandLineArguments* cmdLine = CCommandLineArguments::NewLC(); CConsoleBase* console = Console::NewL(_L("Siftestintegrationlockfile"),TSize(KConsFullScreen,KConsFullScreen)); CleanupStack::PushL(console); TInt argTotal(cmdLine->Count()); if (argTotal < 2 || argTotal > 3) { console->Printf(_L("Incorrect arguments specified: expected 1, received %d"), argTotal - 1); User::Leave(KErrArgument); } TPtrC filename(cmdLine->Arg(1)); _LIT(KDoLockFileParam, " lockfile"); if (argTotal == 2) { RBuf params; params.CreateL(filename.Length() + KDoLockFileParam().Length()); params.CleanupClosePushL(); params.Append(cmdLine->Arg(1)); params.Append(KDoLockFileParam()); // Since this executable is used by TEF, we wish to lock the file after the launched process has exited, so we spawn this process again with a different set of parameters RProcess newInstance; User::LeaveIfError(newInstance.Create(_L("Siftestintegrationlockfile"), params)); CleanupClosePushL(newInstance); newInstance.Resume(); TRequestStatus status; newInstance.Rendezvous(status); User::WaitForRequest(status); User::LeaveIfError(status.Int()); CleanupStack::PopAndDestroy(2, ¶ms); // newInstance } else { // This is the execution for locking the file, invoked using the branch above console->Printf(_L("Locking file %S for read"), &filename); RFs fs; User::LeaveIfError(fs.Connect()); CleanupClosePushL(fs); RFile file; User::LeaveIfError(file.Open(fs, filename, EFileShareReadersOnly|EFileRead)); CleanupClosePushL(file); // Signal the invoker only here, so that the file will definitely get locked before TEF proceeds to the next step RProcess::Rendezvous(KErrNone); User::After(10*1000*1000); // Wait for 10 seconds CleanupStack::PopAndDestroy(2 , &fs); // file } CleanupStack::PopAndDestroy(2, cmdLine); // console, }
// Implementation: called when read has completed. void ConsoleUI::RunL() { TKeyCode kc = con_->KeyCode(); pj_bool_t reschedule = PJ_TRUE; switch (kc) { case 'w': snd_stop(); CActiveScheduler::Stop(); reschedule = PJ_FALSE; break; case 'a': snd_start(PJMEDIA_DIR_CAPTURE_PLAYBACK); break; case 't': snd_start(PJMEDIA_DIR_CAPTURE); break; case 'p': snd_start(PJMEDIA_DIR_PLAYBACK); break; case 'd': snd_stop(); break; default: PJ_LOG(3,(THIS_FILE, "Keycode '%c' (%d) is pressed", kc, kc)); break; } PrintMenu(); if (reschedule) Run(); }
// ----------------------------------------------------------------------------- // CHtiFramework::StartL // The method that gets the show going. // ----------------------------------------------------------------------------- TInt CHtiFramework::StartL() { HTI_LOG_FUNC_IN( "CHtiFramework::StartL" ); CConsoleBase* console = iDispatcher->GetConsole(); if ( console ) { console->Printf( _L( "HTI up and running.\n" ) ); } // start scheduler CActiveScheduler::Start(); HTI_LOG_FUNC_OUT( "CHtiFramework::StartL" ); return KErrNone; }
TInt CCTSYIntegrationTestSuiteStepBase::DoPauseL(const TDesC& aText, TTimeDuration aTimeout /* = ETimeMedium */) /** Performs a pause, usually to allow user to intervene in Manual tests @param aText - text for prompt @param aTimeout - @return KErrNone if user pressed a key */ { TInt ret = KErrNone; CConsoleBase* con = NULL; TRAPD(err, con = Console::NewL(_L("Interactive Test"), TSize(KConsFullScreen, KConsFullScreen))); INFO_PRINTF2(_L("Console status = %d"), err); TEST(err == KErrNone); CleanupStack::PushL(con); TConsoleReadRequestStatus readRequest(*con); //add to cleanup stack CleanupStack::PushL(readRequest); con->Printf(_L("%S (timeout %d secs) ..."), &aText, aTimeout / KOneSecond); con->Read(readRequest); ret = WaitForRequestWithTimeOut(readRequest, aTimeout); if (ret == KErrTimedOut) { WARN_PRINTF1(_L("[doPause] No keypress detected, timeout! Manual action may not have occurred.")); } if (readRequest.Int() == KRequestPending) { readRequest.Cancel(); } CleanupStack::PopAndDestroy(); // readRequest CleanupStack::PopAndDestroy(); // con return ret; }
void CThreadBase::SetUpTestL( const TDesC& aThreadName ) { // Set's up extra resources. CConsoleBase* console = NULL; TSize size; // Create and name an RTest iTest = new(ELeave) RTest(aThreadName); iTest->Start(_L("Starting test")); // Position our console window size = iTest->Console()->ScreenSize(); size.iWidth = size.iWidth - 4; size.iHeight = (size.iHeight / 2) - 3; console = Console::NewL(aThreadName, size); delete const_cast<RTest*>(iTest)->Console(); iTest->SetConsole(console); console->ClearScreen(); }
LOCAL_C void ActiveTestL() { CConsoleBase* console = Console::NewL(_L("ACTIVETEST"), TSize(KConsFullScreen, KConsFullScreen)); CleanupStack::PushL(console); CActiveScheduler* scheduler = new(ELeave) CActiveScheduler; CleanupStack::PushL(scheduler); CActiveScheduler::Install(scheduler); CActiveConsole* activeConsole = CActiveConsole::NewLC(*console); activeConsole->RequestCharacter(); CActiveScheduler::Start(); // NB CActiveScheduler::Start only returns when someone somewhere has // called CActiveScheduler::Stop. CleanupStack::PopAndDestroy(2); // activeConsole, scheduler console->Printf(_L("\nPress any key")); console->Getch(); // get and ignore character CleanupStack::PopAndDestroy(); // console }
void Write(const TDesC& str) { if (cons) { cons->Write(str); } if (foutput.SubSessionHandle()!=0) { TInt len=str.Length()*2; TPtrC8 p( (const TUint8*)str.Ptr(), len ); foutput.Write(p); foutput.Flush(); } }
void CTestConsole::Write(const TDesC16& aString) { iCon->Write(aString); if (iFile) { TUint8 space[200]; TPtr8 ptr(space,200); ptr.Copy(aString); iFile->Write(ptr); } }
LOCAL_C void MainL() { _LIT(KTitle,"TestExecuteLogger Test Code for serial logging"); CConsoleBase* console = Console::NewL(KTitle,TSize(KConsFullScreen,KConsFullScreen)); CleanupStack::PushL(console); CTestExecuteLogger logger; TInt logLevel =1 ; TBool separateLogFiles(EFalse); _LIT(KScriptPath,"E:\\plattest\\Selective.script"); TPtrC scriptFilePath(KScriptPath); console->Write(_L("logger.InitialiseLoggingL next2 \n")) ; logger.InitialiseLoggingL(scriptFilePath, separateLogFiles, logLevel); console->Write(_L("post logger.InitialiseLoggingL next \n")); TestWorkAPIsL(logger, console) ; console->Write(_L("attempting TerminateLoggingL \n")) ; logger.TerminateLoggingL(3, 4, 3); //suggested by todays fortune cookie... console->Write(_L("Done testing, press a key to finish \n")) ; console->Getch() ; CleanupStack::PopAndDestroy(console); }
LOCAL_C void mainL() { TInt timerDuration(KDefaultTimeout); // There's only something useful to do if the timeDuration is // a positive value. if(timerDuration > 0) { CConsoleBase* console; // write all your messages to this console=Console::NewL(KTxtExampleCode,TSize(KConsFullScreen,KConsFullScreen)); console->Printf(KFormatRunning, timerDuration); while(1) { //console->Printf(KTxtExampleCode); User::After(1000000); //After 1 sec } } }
static void MainL(void) /** Takes a User Prompt Service policy resource file and dumps it as human readable text to the console. The user may also specify the name of an output file on the command line. If so, text is also written to this file. */ { RFs fs; User::LeaveIfError(fs.Connect()); CleanupClosePushL(fs); CConsoleBase* console = Console::NewL(KAppName, TSize(KDefaultConsWidth, KDefaultConsHeight)); CleanupStack::PushL(console); CCommandLineArguments* args = CCommandLineArguments::NewLC(); if (args->Count() > 1) { CPolicyReader* reader = CPolicyReader::NewLC(fs, args->Arg(1)); CPrinter* printer(0); if (args->Count() > 2) { RFile outFile; User::LeaveIfError(outFile.Replace(fs, args->Arg(2), EFileShareExclusive | EFileWrite)); CleanupClosePushL(outFile); printer = CPrinter::NewLC(console, outFile); CleanupStack::Pop(printer); CleanupStack::PopAndDestroy(&outFile); CleanupStack::PushL(printer); } else { printer = CPrinter::NewLC(console); } __UHEAP_MARK; PrintPoliciesL(printer, reader); __UHEAP_MARKEND; if (args->Count() < 3) { // If no output file is specified then pause after finishing // because the console will vanish when it is closed. console->Printf(_L("Press any key to continue\r\n")); console->Getch(); } CleanupStack::PopAndDestroy(2, reader); // printer, reader } else { console->Printf(_L("Usage: dumppolicy.exe policy.rsc <output.txt>\r\n")); console->Printf(_L("Press any key to continue\r\n")); console->Getch(); } CleanupStack::PopAndDestroy(3, &fs); // args, console, fs }
/** @fn void StartConsoleL() Start the console and create the ini file, then call the read method to manually test the contents. */ LOCAL_C void StartConsoleL() { // set INI file drive IniFileName[0] = 'A' + static_cast<TInt>(RFs::GetSystemDrive()); // Create the console and put it on the cleanup stack CConsoleBase* console = Console::NewL(KConsoleName, TSize(KConsFullScreen, KConsFullScreen)); CleanupStack::PushL(console); // Call the main function and trap the result TRAPD(error, WriteIniFileL()); // create the ini file if(!error) { TRAPD(error2, ReadIniFileL()); // perform test error = error2; } if (error) console->Printf(KFailedMessage, error); else console->Printf(KOkMessage); CleanupStack::PopAndDestroy(console); // close console }
void CPrinter::PrintL(TRefByValue<const TDesC16> aFormat, ...) { VA_LIST list; VA_START(list, aFormat); iBuffer.Zero(); iBuffer.AppendFormatList(aFormat, list); iCon->Printf(iBuffer); if (iLogToFile) { HBufC8* utf8 = CnvUtfConverter::ConvertFromUnicodeToUtf8L(iBuffer); CleanupStack::PushL(utf8); User::LeaveIfError(iFile.Write(*utf8)); CleanupStack::PopAndDestroy(utf8); } VA_END(list); }
void TestUiTimer::RunL() { // display the current progress if(iEmailOperation!=NULL) { TImSmtpProgress temp; TPckgC<TImSmtpProgress> paramPack(temp); paramPack.Set(iEmailOperation->ProgressL()); TImSmtpProgress progress=paramPack(); iConsole->SetPos(0, 12); TBuf<80> progressBuf = Progress(progress.iSendFileProgress.iSessionState); iConsole->Printf(TRefByValue<const TDesC>_L(" Operation Progress : %S "), &progressBuf); iConsole->SetPos(0, 13); iConsole->Printf(TRefByValue<const TDesC>_L(" Progress: %d/%d %d/%d \n"), progress.MsgNo() + 1, progress.SendTotal(), progress.iSendFileProgress.iBytesSent, progress.iSendFileProgress.iBytesSent + progress.iSendFileProgress.iBytesToSend); iConsole->SetPos(0, 15); iConsole->Printf(TRefByValue<const TDesC>_L(" Error: %d \n"), progress.Error()); } IssueRequest(); };
LOCAL_C void InitConsoleL() { // create a full screen console object CConsoleBase* console; console = Console::NewL(KTxtTitle, TSize(KConsFullScreen,KConsFullScreen)); CleanupStack::PushL(console); //Gets the size of the console TSize screenSize = console->ScreenSize(); test.Printf(_L("Screen size %d %d\r\n"),screenSize.iWidth,screenSize.iHeight); // Gets the cursor's x-position TInt x = console->WhereX(); // Gets the cursor's y-position TInt y = console->WhereY(); test_Equal(x, 0); test_Equal(y, 0); test.Printf(_L("**1** Cursor positions x: %d y: %d\r\n"),x, y); // Sets the cursor's x-position for(TInt i=0; i<4; i++) { console->SetPos(screenSize.iWidth + i); x = console->WhereX(); test_Equal(x, screenSize.iWidth -3); } test.Printf(_L("**2** Cursor positions x: %d y: %d\r\n"),x, y); // Clears the console and set cursor to position 0,0 console->ClearScreen(); test_Equal(console->WhereX(), 0); test_Equal(console->WhereY(), 0); // Sets the cursor's x-position and y-position for(TInt j=0; j<4; j++) { console->SetPos(screenSize.iWidth - j, screenSize.iHeight - j); x = console->WhereX(); y = console->WhereY(); test_Equal(x, screenSize.iWidth -3); test_Equal(y, screenSize.iHeight -3); } test.Printf(_L("**3** Cursor positions x: %d y: %d\r\n"),x, y); console->SetPos(0,0); x = console->WhereX(); y = console->WhereY(); test_Equal(x, 0); test_Equal(y, 0); test.Printf(_L("**4** Cursor positions x: %d y: %d\r\n"),x, y); console->SetPos(screenSize.iWidth/2,screenSize.iHeight/2); x = console->WhereX(); y = console->WhereY(); test.Printf(_L("**5** Cursor positions x: %d y: %d\r\n"),x, y); // Sets the percentage height of the cursor console->SetCursorHeight(50); // Gets the current cursor position relative to the console window TPoint cursorPos = console->CursorPos(); test.Printf(_L("CursorPos iX: %d iY: %d\r\n"),cursorPos.iX, cursorPos.iY); // Puts the cursor at the specified position relative // to the current cursor position TPoint relPos; relPos.iX = screenSize.iWidth/4; relPos.iY = screenSize.iHeight/4; console->SetCursorPosRel(relPos); cursorPos = console->CursorPos(); test.Printf(_L("CursorPosRel iX: %d iY: %d\r\n"),cursorPos.iX, cursorPos.iY); // Puts the cursor at the absolute position in the window cursorPos.iX = screenSize.iWidth/6; cursorPos.iY = screenSize.iHeight/6; console->SetCursorPosAbs(cursorPos); cursorPos = console->CursorPos(); test.Printf(_L("CursorPosAbs iX: %d iY: %d\r\n"),cursorPos.iX, cursorPos.iY); // Sets a new console title console->SetTitle(KTxtNewTitle); // Writes the content of the specified descriptor to the console window console->Write(KTxtWrite); cursorPos.iX = cursorPos.iX + 6; console->SetCursorPosAbs(cursorPos); // Clears the console from the current cursor position to the end of the line console->ClearToEndOfLine(); // Clears the console and set cursor to position 0,0 console->ClearScreen(); TUint keyModifiers = console->KeyModifiers(); test.Printf(_L("keyModifiers %d"),keyModifiers); TKeyCode keyCode = console->KeyCode(); ReadConsole(console); SimulateKeyPress(EStdKeyEnter); keyCode = console->Getch(); // cleanup and return CleanupStack::PopAndDestroy(); // close console }
TInt GetNumberEntry ( const TInt aMaxDigits, // max numbers of digits const TInt aMin, // min value allowed const TInt aMax, // max value allowed const TInt aInputWait, // (s) how long to wait for each user key entry const TInt aDefaultVal, // default value if timed out const TDesC &aPrompt // string prompt ) /** * This method gets numeric user entry from the console. It checks that the key entered * is between 0 to 9 inclusive. This method exits by user hitting the * Enter key or timing out. * * @param aMaxNumbers integer for max numbers of digits * @param aMin integer for min value allowed * @param aMax integer for max value allowed * @param aInputWait integer for number of seconds to wait for each user key entry * @param aDefaultVal integer for default value if time-out occurs without * @param aPrompt string prompt * @return KErrNone. */ { TInt keyFolded; // actual digit entered, not TKeyCode TRequestStatus stat1,stat2; RTimer timer; TBool bCorrectEntry = EFalse; TInt userNum = -1; TInt limit; TKeyCode key; TTimeIntervalMicroSeconds32 anInterval = aInputWait * 1000000; CConsoleBase *pConsole = test.Console(); timer.CreateLocal(); while (!bCorrectEntry) { userNum = -1; limit = aMaxDigits; key = EKeyNull; INFO_PRINTF1(aPrompt); // print prompt INFO_PRINTF1(_L(" (range %d-%d) or <CR> for default of %d: "), aMin, aMax, aDefaultVal); // exits loop when Enter keyed or limit reached (by decrement to 0) while ((key != EKeyEnter) && limit) { pConsole->Read(stat1); // set read timer.After(stat2, anInterval); // set wait for this period User::WaitForRequest(stat1,stat2); // whatever comes first if(stat1 == KErrNone) // user entered key { timer.Cancel(); User::WaitForRequest(stat2); key = pConsole->KeyCode(); if((key >= '0') && (key <= '9')) { // valid digit keyFolded = (TKeyCode)(key - '0'); // convert to digit INFO_PRINTF1(_L("%d"), keyFolded); // echo limit--; // tracks number of digits // "append" to number if (-1 == userNum) // ie first char entered { userNum = keyFolded; } else // next char entered { userNum = userNum * 10 + keyFolded; // shift } } } else // timer went off, use default unless valid key entered before timer expired { pConsole->ReadCancel(); User::WaitForRequest(stat1); if (-1 == userNum) { // no value entered before timer went off userNum = aDefaultVal; } break; } } // endwhile test.Printf (_L("\n")); if ((userNum >= aMin) && (userNum <= aMax)) { bCorrectEntry = ETrue; // exit loop } else // return to loop { if (userNum == -1) { // <CR> was entered before any numbers, so use default userNum = aDefaultVal; break; } INFO_PRINTF1(_L("Try again, Entry out of limit. Must be between %d and %d inclusive.\n\n"), aMin, aMax); } } // endwhile return (userNum); }
TBool CTestBitStr::PerformTestsL(CConsoleBase& aConsole) { TBool pass = ETrue; // Test the encoding varying length bit strings by encoding 65 // different bit strings with a single bit set in each position. Position -1 // indicates the empty bit string. for (TInt8 bitNum = -1; bitNum < 64; bitNum++) { TBuf8<8> bitStr; TUint numOctets; if (bitNum >= 0) { numOctets = 1 + (bitNum / 8); } else { numOctets = 0; } bitStr.SetLength(numOctets); bitStr.FillZ(); TUint8 valToEncode = 0; if (bitNum >= 0 ) { // The most significant bit in the most significant byte is bit zero valToEncode = (TUint8) (1 << (7 - (bitNum % 8))); bitStr[bitNum / 8] = valToEncode; } // Get the encoder and decoder CASN1EncBitString* encoder = CASN1EncBitString::NewLC(bitStr, bitNum + 1); TASN1DecBitString decoder; // Prepare an encode buffer TInt totalLength = encoder->LengthDER(); HBufC8* encodeBuffer = HBufC8::NewMaxLC(totalLength); TPtr8 tEncodeBuf = encodeBuffer->Des(); // Write into the encode buffer TUint writeLength = 0; encoder->WriteDERL(tEncodeBuf, writeLength); // Read it out again and check lengths plus encoded value TInt readLength = 0; HBufC8* decodeBuffer = decoder.ExtractOctetStringL(tEncodeBuf, readLength); CleanupStack::PushL(decodeBuffer); TPtr8 tDecodeBuf = decodeBuffer->Des(); if (writeLength != STATIC_CAST(TUint, readLength)) { aConsole.Write(_L("ERROR!\n")); iASN1Action.ReportProgressL(KErrASN1EncodingError, 1, 1); pass = EFalse; } else if (bitNum >= 0 && valToEncode != tDecodeBuf[bitNum / 8]) { aConsole.Write(_L("ENCODING ERROR!\n")); iASN1Action.ReportProgressL(KErrASN1EncodingError, 1, 1); pass = EFalse; } else { iASN1Action.ReportProgressL(KErrNone, bitNum + 1, 65); } CleanupStack::PopAndDestroy(3, encoder); // decodeBuffer, encodeBuffer, encoder } return pass; }
/** * Subroutine performing pre-processing tasks for testexecute execution * Also, responsible for triggering the state machine through instance of ScriptMaster * @param aScheduler - Instance of ActiveScheduler created through MainL() * @param aSysDrive - Default system drive letter to be used for all script parsing */ LOCAL_C void ProcessMainL(CActiveScheduler* aScheduler, const TDriveName aSysDrive) { TDriveName defaultSysDrive(aSysDrive); TDriveName testSysDrive(KTEFLegacySysDrive); TInt waitForLoggingTime = 0; TBuf<KMaxTestExecuteNameLength> htmlLogPath; // Create a object of the Parser for TestExecute.ini CTestExecuteIniData* parseTestExecuteIni = NULL; TRAPD(err, parseTestExecuteIni = CTestExecuteIniData::NewL(defaultSysDrive)); if (err == KErrNone) { CleanupStack::PushL(parseTestExecuteIni); // Extract all the key values within the object parseTestExecuteIni->ExtractValuesFromIni(); } // Read and parse the command line for the flags // -d -slf -help and -v TBuf<KMaxTestExecuteCommandLength> commandLine; TDesC* selTestCfgFileData = NULL; //the pointer to the data of in the .tcs file ReadCommandLineL(commandLine); // Make lower case because we parse it for flags and search for ".script" commandLine.LowerCase(); TBool separateLogFiles(EFalse); // -slf TBool justInTime(EFalse); // -d TBool graphicalWindowServer(EFalse); // -gws TBool helpRequest(EFalse); // -help TBool versionRequest(EFalse); // -v TBool includeSelectiveCases(EFalse); // -tci TBool excludeSelectiveCases(EFalse); // -tcx TBool pipe(EFalse) ; // Set up the bools from the command line ParseCommandLine(commandLine,separateLogFiles,justInTime,graphicalWindowServer,includeSelectiveCases, excludeSelectiveCases,pipe, helpRequest,versionRequest,*parseTestExecuteIni,err); // If -d then set Just In Time debugging. Panicks break into debug on emulator (justInTime) ? (User::SetJustInTime(ETrue)) : (User::SetJustInTime(EFalse)); // Hooks for creating the Graphical Window server #ifdef GWS #endif // Create a console _LIT(KMessage,"TestExecute Script Engine"); CConsoleBase* console = Console::NewL(KMessage,TSize(KConsFullScreen,KConsFullScreen)); CleanupStack::PushL(console); console->SetCursorHeight(0); RConsoleLogger consoleLogger(*console); CScriptControl::iRunScriptFailCount=0; // A lex for getting the first command line argument, ie the script file path TLex lex(commandLine); TPtrC scriptFilePath(lex.NextToken()); TInt ret = KErrNotFound; if (scriptFilePath.CompareF(KNull) != 0) { _LIT(KTEFSwitchPrefix, "-"); if(scriptFilePath.Mid(0,1).CompareF(KTEFSwitchPrefix) == 0) { // If the first command line argument is not the script file path but a optional switches // Then set the script file path for the execution to be 'blank' scriptFilePath.Set(KNull); } else { TBuf<KBuffSize> tempScriptPath(scriptFilePath); // Check whether script name is provided along with folder path in the command line // If not, take the path from testexecute.ini & name from the command line ret=scriptFilePath.FindC(KTEFColon); if(ret==KErrNotFound) { if (parseTestExecuteIni != NULL) { TBuf<KMaxTestExecuteNameLength> tempBuffer; parseTestExecuteIni->GetKeyValueFromIni(KTEFDefaultScriptPath, tempBuffer); // If the relative script file path does not refer to the root, // we will look for DefaultScriptDir entry in testexecute.ini // If available prepend it to the relative path // else if the relative path refers to root, // then set the default system drive, i.e. c: // else leaving it as it is (considering invalid path) if (scriptFilePath.Left(1).CompareF(KTEFSlash) != 0 && tempBuffer.Length() > 0) scriptFilePath.Set(tempBuffer); else if (scriptFilePath.Left(1).CompareF(KTEFSlash) == 0) scriptFilePath.Set(defaultSysDrive); else scriptFilePath.Set(KNull); } else { // If the file path is not provided in command line as well as in testexecute.ini // then set the script file path to be 'blank' scriptFilePath.Set(KNull); } // Construct the full file path from the values extracted from command line and ini file TBuf<KBuffSize> storeScriptPathTemp(scriptFilePath); storeScriptPathTemp.Append(tempScriptPath); scriptFilePath.Set(storeScriptPathTemp); tempScriptPath.Copy(scriptFilePath); } //If scriptFilePath is not appended by .script Append .script if(scriptFilePath.Find(KTEFScriptExtension)==KErrNotFound) { tempScriptPath.Append(KTEFScriptExtension); } scriptFilePath.Set(tempScriptPath); } } TPtrC pipeName ; if(pipe) { TLex flagLex(commandLine); //first of all navigate the command line arguments to the selective test cases flag... while(!flagLex.Eos()) { TPtrC token(flagLex.NextToken()); if( (token.CompareF(KTestExecuteCommandLineFlagPipe) == 0) ) { break; } } pipeName.Set(flagLex.NextToken()) ; } TSelectiveTestingOptions* selTestingOptions =NULL; if (includeSelectiveCases && excludeSelectiveCases) { //mutually exclusive options have been encountered includeSelectiveCases =EFalse; excludeSelectiveCases =EFalse; console->Printf(KTEFInvalidCommandSetMessage); console->Printf(KTEFEnterKeyMessage); console->Getch(); } else { if(includeSelectiveCases || excludeSelectiveCases) { RArray<TRange> selectiveCaseRange; ParseCommandLineForSelectiveTestingOptions(commandLine,*parseTestExecuteIni,selectiveCaseRange, selTestCfgFileData); //you need to sort these two arrays first, and also if they are both empty ignore the entire option altogether. if( selectiveCaseRange.Count() > 0 ) { CleanupStack::PushL(selTestCfgFileData); TLinearOrder<TRange> orderingrng(TRange::CompareTRangeStartOrder) ; selectiveCaseRange.Sort(orderingrng ); ESelectiveTesting selectiveTestingType(iExclusive); if(includeSelectiveCases) { selectiveTestingType = iInclusive ; } selTestingOptions = new(ELeave) TSelectiveTestingOptions(selectiveCaseRange, selectiveTestingType); } else { //if no arguments to this option have been found, ignore it... includeSelectiveCases =EFalse; excludeSelectiveCases =EFalse; delete selTestCfgFileData; } } } if (scriptFilePath.CompareF(KNull)==0) { if (!separateLogFiles && !justInTime) { // Print the product version details through console window console->Printf(KTEFVersionMessage); console->Printf(KTEFProductVersion); if (!(versionRequest && !helpRequest)) { // Print the help & usage informations through console window along with product version console->Printf(KTEFConsoleHelpMessage1); console->Printf(KTEFConsoleHelpMessage2); console->Printf(KTEFConsoleHelpMessage3); console->Printf(KTEFConsoleHelpMessage4); console->Printf(KTEFConsoleHelpMessage5); } } else { // Display a error message on the console window for invalid set of arguments console->Printf(KTEFInvalidCommandSetMessage); } // Exit on a key press from user console->Printf(KTEFEnterKeyMessage); console->Getch(); } else { // Create a Interface class object for generating HTML & XML logs CTestExecuteLogger *tefLogger = new(ELeave) CTestExecuteLogger(); CleanupStack::PushL(tefLogger); TInt logMode; TInt logLevel; TInt remotePanicDetection; TBuf<KMaxTestExecuteNameLength> iniSysDrive; if (parseTestExecuteIni != NULL) { // Parse ini for retrieving logging options set through ini parseTestExecuteIni->GetKeyValueFromIni(KTEFLogMode, logMode); parseTestExecuteIni->GetKeyValueFromIni(KTEFLogSeverityKey, logLevel); parseTestExecuteIni->GetKeyValueFromIni(KTEFRemotePanicDetection, remotePanicDetection); parseTestExecuteIni->GetKeyValueFromIni(KTEFDefaultSysDrive, iniSysDrive); parseTestExecuteIni->GetKeyValueFromIni(KTEFWaitForLoggingTime, waitForLoggingTime); parseTestExecuteIni->GetKeyValueFromIni(KTEFHtmlKey, htmlLogPath); } else { // Set default values for logging options if parser is not functioning logMode = TLoggerOptions(ELogHTMLOnly); logLevel = RFileFlogger::TLogSeverity(ESevrAll); remotePanicDetection = 0; iniSysDrive.Copy(KTEFIniSysDrive); waitForLoggingTime = 5; htmlLogPath.Copy(KTestExecuteLogPath); htmlLogPath.Replace(0, 2, defaultSysDrive); } tefLogger->SetLoggerOptions(logMode); if(pipe) { tefLogger->SetPipeName(pipeName) ; } // Initialise the logging passing in the script file path & log level to the interface tefLogger->InitialiseLoggingL(scriptFilePath, separateLogFiles, logLevel); // Check to see if defaultsysdrive key is set in testexecute.ini // if set to SYSDRIVE, assign the default system drive obtained from the plugin // else, if a true value is set in testexecute.ini, use it as system drive for all test artifacts if (iniSysDrive.Length() == 2 && iniSysDrive.Right(1).Compare(KTEFColon) == 0) testSysDrive.Copy(iniSysDrive); else if (iniSysDrive.CompareF(KTEFIniSysDrive) == 0) testSysDrive.Copy(defaultSysDrive); // Pass the first command line argument to the script master // which is always the command script CScriptMaster* scriptMaster = new (ELeave) CScriptMaster(scriptFilePath,*tefLogger, consoleLogger, defaultSysDrive, testSysDrive, selTestingOptions); // To kick the state machine of the script master off - // Call the kick method which jumps us into the RunL() of the CScriptMaster class // CScriptMaster is the top AO in the hierarchy. scriptMaster->Kick(); // Construct and Install a test watcher object for capturing remote panics during test execution CTestWatcher* testWatcher = NULL; if (remotePanicDetection != 0) { testWatcher = CTestWatcher::NewL(); testWatcher->StartL(); } // Enter the Active Scheduler aScheduler->Start(); // Cleanup delete scriptMaster; TInt commentedCommandsCnt=CScriptControl::commentedCommandsCount; if(commentedCommandsCnt==-1) { CScriptControl::commentedCommandsCount=0; //If the path specified fails check out for path from testexecute.ini if(ret!=KErrNotFound) { //To get scriptFile name i.e get sampleFile.script TInt posOfLastSlash=scriptFilePath.LocateReverse('\\') ; scriptFilePath.Set(scriptFilePath.Mid(posOfLastSlash+1)); TBuf<KBuffSize> tempStore(scriptFilePath); if (parseTestExecuteIni != NULL) { TBuf<KMaxTestExecuteNameLength> tempBuffer; parseTestExecuteIni->GetKeyValueFromIni(KTEFDefaultScriptPath, tempBuffer); if (tempBuffer.CompareF(KNull) != 0) { scriptFilePath.Set(tempBuffer); TBuf<KBuffSize> tempStoreScriptPath(scriptFilePath); tempStoreScriptPath.Append(tempStore); scriptFilePath.Set(tempStoreScriptPath); TBuf<KMaxTestExecuteNameLength> scriptFileLocation(scriptFilePath); CScriptMaster* scriptMaster = new (ELeave) CScriptMaster(scriptFilePath,*tefLogger, consoleLogger, defaultSysDrive, testSysDrive, selTestingOptions); // To kick the state machine of the script master off - // Call the kick method which jumps us into the RunL() of the CScriptMaster class // CScriptMaster is the top AO in the hierarchy. scriptMaster->Kick(); // Enter the Active Scheduler aScheduler->Start(); commentedCommandsCnt=CScriptControl::commentedCommandsCount; if(commentedCommandsCnt==-1) { CScriptControl::commentedCommandsCount=0; } // Cleanup delete scriptMaster; } } } } delete selTestingOptions; TInt commandsCount = CScriptControl::commentedCommandsCount; TInt countOfRemotePanics = 0; // Stop and Process the test watcher object for extracting panic informations and print them to the log files if (remotePanicDetection != 0) { testWatcher->Stop(); countOfRemotePanics = testWatcher->iSharedData->iPanicDetails.Count(); if (countOfRemotePanics > 0) { tefLogger->LogExtra((TText8*)__FILE__,__LINE__,ESevrErr, _L("The panic detection thread detected %d panics:"), countOfRemotePanics); for (TInt count = 0; count < countOfRemotePanics; count++) tefLogger->LogExtra((TText8*)__FILE__,__LINE__,ESevrErr,_L("Remote Panic %d - Name of Panicked Thread: %S, Exit Reason: %d, Exit Category %S"), count+1, &(testWatcher->iSharedData->iPanicDetails)[count]->iThreadName,(testWatcher->iSharedData->iPanicDetails)[count]->iReason,&(testWatcher->iSharedData->iPanicDetails)[count]->iCategory); } delete testWatcher; } // Call the Termination routine for logging within the interface tefLogger->TerminateLoggingL(commandsCount, countOfRemotePanics, CScriptControl::iRunScriptFailCount); CleanupStack::Pop(tefLogger); delete tefLogger; } if(includeSelectiveCases || excludeSelectiveCases) { CleanupStack::PopAndDestroy(selTestCfgFileData); selTestCfgFileData = NULL; } // Close the parser instance if it is active CleanupStack::PopAndDestroy(console); if (parseTestExecuteIni != NULL) { CleanupStack::PopAndDestroy(parseTestExecuteIni); } if (scriptFilePath.CompareF(KNull)!=0) { // Wait for flogger to write to file _LIT(KHtmExtension,".htm"); TParse fileNameParse; fileNameParse.Set(scriptFilePath, NULL, NULL); TPtrC fileName = fileNameParse.Name(); htmlLogPath.Append(fileName); htmlLogPath.Append(KHtmExtension); #ifdef _DEBUG RDebug::Print(_L("Log file path--> %S"), &htmlLogPath); #endif RFs fs; fs.Connect(); TBool answer = EFalse; while(ETrue) { TInt err = fs.IsFileOpen(htmlLogPath, answer); if ((KErrNone==err&&!answer) || KErrNotFound==err || KErrPathNotFound==err) { break; } User::After(100000); } if (waitForLoggingTime > 0) { User::After(waitForLoggingTime*1000000); } } }
// Cancel asynchronous read. void ConsoleUI::DoCancel() { con_->ReadCancel(); }
void MainL() { /* Create the named - pipe */ int ret_val = mkfifo(HALF_DUPLEX, S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH); if ((ret_val == -1) && (errno != EEXIST)) { perror("Error creating the named pipe"); return ; //exit (1); } int pipe = open(HALF_DUPLEX, O_RDONLY | O_NONBLOCK); _LIT(KTitle,"TestExecute Standalone Logger Test Code"); CConsoleBase* console = Console::NewL(KTitle,TSize(KConsFullScreen,KConsFullScreen)); CleanupStack::PushL(console); _LIT(KMessage1,"Connect() To Logger and Close() immediately\r\n"); console->Printf(KMessage1); RTestExecutePIPSLogServ logger; User::LeaveIfError(logger.Connect()); logger.Close(); _LIT(KMessage2,"Immediate re-Connect() To Logger and Close() immediately\r\n"); console->Printf(KMessage2); User::LeaveIfError(logger.Connect()); logger.Close(); _LIT(KMessage3,"Immediate re-Connect() To Logger CreateLog() and Close() immediately\r\n"); console->Printf(KMessage3); User::LeaveIfError(logger.Connect()); User::LeaveIfError(logger.CreateLog(KLogFile1)); logger.Close(); // OS needs time to shutdown the server // No delay means we get server terminated from the OS User::After(1000000); _LIT(KMessage4,"Connect() To Logger CreateLog() %S Call API's\r\n"); TBuf<80> logFile(KLogFile1); console->Printf(KMessage4,&logFile); User::LeaveIfError(logger.Connect()); User::LeaveIfError(logger.CreateLog(KLogFile1)); TBuf<20> buf16(K16BitString); TBuf8<20> buf8(K8BitString); logger.Write(K16BitText); logger.Write(K8BitText); logger.WriteFormat(K16BitFormatText,16,&buf16); logger.WriteFormat(K8BitFormatText,8,&buf8); logger.LogExtra(((TText8*)__FILE__), __LINE__,ESevrInfo,K16BitFormatText,1,&buf16); _LIT(KMessage5,"ALL API's Called - Call Close(),\r\n"); console->Printf(KMessage5); //console->Getch(); logger.Close(); //try an empty pipe _LIT(KLogFileEmpty,""); _LIT(KMessageEmp,"Connect() To Logger CreateLog() %S Call API's\r\n"); TBuf<80> logFiley(KLogFileEmpty); console->Printf(KMessageEmp,&logFiley); User::LeaveIfError(logger.Connect()); User::LeaveIfError(logger.CreateLog(KLogFileEmpty)); logger.Write(K16BitText); logger.Write(K8BitText); logger.WriteFormat(K16BitFormatText,16,&buf16); logger.WriteFormat(K8BitFormatText,8,&buf8); logger.LogExtra(((TText8*)__FILE__), __LINE__,ESevrInfo,K16BitFormatText,1,&buf16); console->Printf(KMessage5); console->Getch(); logger.Close(); CleanupStack::PopAndDestroy(console); }
// Run console UI void ConsoleUI::Run() { con_->Read(iStatus); SetActive(); }
void CListCommand::ExecuteL(CConsoleBase& aConsole) { // Connect to the SCR server RSoftwareComponentRegistry scr; TInt err = scr.Connect(); if (err != KErrNone) { aConsole.Printf(_L("\nFailed to connect to the SCR server")); User::Leave(err); } CleanupClosePushL(scr); // Create an SCR view RSoftwareComponentRegistryView scrView; scrView.OpenViewL(scr, iFilter); CleanupClosePushL(scrView); // Iterate over the matching components CComponentEntry* entry = CComponentEntry::NewLC(); TBool first(ETrue); while (scrView.NextComponentL(*entry, iLocale)) { if (first) { first = EFalse; } else { aConsole.Printf(KTxtPressToContinue); aConsole.Getch(); aConsole.ClearScreen(); } aConsole.Printf(_L("\n============= Component Info =============\n")); aConsole.Printf(_L("\nComponent ID : %d"), entry->ComponentId()); aConsole.Printf(_L("\nComponent name : %S"), &entry->Name()); aConsole.Printf(_L("\nVendor name : %S"), &entry->Vendor()); aConsole.Printf(_L("\nSoftware type : %S"), &entry->SoftwareType()); aConsole.Printf(_L("\nSCOMO state : %S"), entry->ScomoState() == EActivated ? &KTxtActivated : &KTxtDeactivated ); aConsole.Printf(_L("\nComponent size : %d"), entry->ComponentSize()); aConsole.Printf(_L("\nInstalled drives : %S"), &entry->InstalledDrives()); aConsole.Printf(_L("\nVersion : %S"), &entry->Version()); aConsole.Printf(_L("\n\n=========================================\n")); } // Disconnect from the SCR server and cleanup the entry CleanupStack::PopAndDestroy(3, &scr); }
/** * * Open a log. * * @param "const TDesC& aLogName" * The log name * * @param "TInt aLogMode" * The log mode (as bitmask of TTestFrameworkLogMode) * * @xxxx * */ void CTestFrameworkServer::OpenLogL(const TDesC& aLogName, TInt aLogMode) { // NB we need to check if a console is already open - if so, we do NOT // create another one. Ditto with file / port. if(aLogMode & ELogToConsole) { if(!iConsole) { iConsole = CServerConsole::NewL(aLogName); CConsoleBase* theConsole = iConsole->Console(); theConsole->Printf(_L("%S : Server log starting\n"), &aLogName); iLogMode |= ELogToConsole; if (aLogMode & ELogConsoleFull) iLogMode |= ELogConsoleFull; } } // NB relative paths will not work with TParse (there is no file server open). // Exception is a bare filename (with no path) : this will be found in root of C: // NOTE! We have no mechanism to notify this error. The console will display // and then exit. The log file cannot be opened. // TO BE ENHANCED - if console is made active, then we can pause if(aLogMode & ELogToFile) { if(!iFileLogger) { TRAPD(err, iFileLogger = CFileLogger::NewL()); if(err != KErrNone) { // if we can't create a logger, we panic User::Panic(_L("TestFrameworkServer"), 1); } _LIT(KLogPath, "C:\\Logs\\TestResults"); _LIT(KDefault, "C:\\.htm"); TParse parseLogName; parseLogName.Set(aLogName, NULL, NULL); TFileName logFilePath; logFilePath = KLogPath; if(parseLogName.PathPresent()) logFilePath.Append(parseLogName.Path()); else logFilePath.Append(_L("\\")); // overwrite extension if supplied with .htm TParse logFileFullName; TInt returnCode = logFileFullName.Set(KDefault, &logFilePath, &aLogName); if (returnCode == KErrNone) { TInt ret = iFileLogger->Connect(); if (ret == KErrNone) { iFileLogger->CreateLog(logFilePath, logFileFullName.NameAndExt()); iLogMode |= ELogToFile; } } } } if(aLogMode & ELogToPort) { // RDebug::Print will deal with the serial port, we don't do anything special here iLogMode |= ELogToPort; } }
void CBtraceReader::DecodeFrame(const TBtraceHeader& aHeader, const TDesC8& aFrame, TUint32) { if (aHeader.iCategory == BTrace::EKernPrintf) { TUint32 threadId = *(TUint32*)aFrame.Ptr(); TBuf<256> text; text.Copy(aFrame.Mid(4)); if (iDebugConsole) { iDebugConsole->Printf(_L("Kern::Printf (0x%08x) \'%S\'\r\n"), &threadId, &text); } } else if (aHeader.iCategory == RMemSampler::EBtraceCategory) { switch (aHeader.iSubCategory) { case RMemSampler::ENewChunk: { TUint32 address = *(TUint32*)aFrame.Ptr(); TInt maxSize = *((TUint32*)aFrame.Ptr() + 1); TFullName fullName; fullName.Copy(aFrame.Mid(8)); if (iDebugConsole) { iDebugConsole->Printf(_L("New chunk - %S\r\n\taddress: 0x%08x max size: %d\r\n"), &fullName, address, maxSize); } if (iMemoryView) { iMemoryView->HandleNewChunk(fullName, address, maxSize); } break; } case RMemSampler::EChangedChunk: { TUint32 address = *(TUint32*)aFrame.Ptr(); TUint32 size = *((TUint32*)aFrame.Ptr() + 1); TUint32 highWaterMark = *((TUint32*)aFrame.Ptr() + 2); if (iDebugConsole) { iDebugConsole->Printf(_L("Changed chunk - address: 0x%08x size: %d hwm: %d\r\n"), address, size, highWaterMark); } if (iMemoryView) { iMemoryView->HandleChangedChunk(address, size, highWaterMark); } break; } case RMemSampler::EDeletedChunk: { TUint32 address = *(TUint32*)aFrame.Ptr(); if (iDebugConsole) { iDebugConsole->Printf(_L("Deleted chunk - address: 0x%08x\r\n"), address); } if (iMemoryView) { iMemoryView->HandleDeletedChunk(address); } break; } } } }
void Getch() { if (cons) cons->Getch(); }