SSNGenerator(char* param_name, char* ssnNoSpace)
{
    int randSSN[3];
    char EmployeeDep1SSN[100];
    char EmployeeDep1SSN_1[100];
    char p_SSN_1[100];

    randSSN[0] = RandomRange(100,999);
    randSSN[1] = RandomRange(10,99);
    randSSN[2] = RandomRange(1000,9999);

    lr_save_int(randSSN[0],"pSSN1dep1_1");
    lr_save_int(randSSN[1],"pSSN2dep1_1");
    lr_save_int(randSSN[2],"pSSN3dep1_1");

    sprintf(EmployeeDep1SSN, "%s-%s-%s", lr_eval_string("{pSSN1dep1_1}"), lr_eval_string("{pSSN2dep1_1}"), lr_eval_string("{pSSN3dep1_1}"));
    sprintf(EmployeeDep1SSN_1, "%s%s%s", lr_eval_string("{pSSN1dep1_1}"), lr_eval_string("{pSSN2dep1_1}"), lr_eval_string("{pSSN3dep1_1}"));

    lr_save_string(EmployeeDep1SSN, "EmployeeDep1SSN");

    lr_save_string(EmployeeDep1SSN, param_name);
    lr_save_string(EmployeeDep1SSN_1, ssnNoSpace);

    return 0;
}
SplitStringCalculations()
{
	int iValue;
	char cBuffer[1024]="";
	char cConcatenatedOutput[1024]="";
	
	web_save_timestamp_param("sLoadRunnerTimeStamp", LAST);
	lr_output_message( "Current UNIX time in milliseconds is #%s", lr_eval_string( "{sLoadRunnerTimeStamp}" ) ); 

	//Splits the saved string {sLoadRunnerTimeStamp} into two parts, first 7 and remainder
	//fSplitString function is declared in  vuser_init
	fSplitString(lr_eval_string("{sLoadRunnerTimeStamp}"),7);
	
   	//Convert {sRightString} to integer iValue to perform calculation
   	//In this case subtract 1000 milliseconds to get timestamp from one second ago
	iValue = atoi(lr_eval_string("{sRightString}"));
	iValue = iValue-1000;
	sprintf(cBuffer, "%d", iValue);
	
	//Save Right part of the string
	lr_save_string(cBuffer, "sCalculatedRightString");
	
	//Copy {sLeftString} into cConcatenatedOutput, then concatenate (append) {sCalculatedRightString} 
	strcpy(cConcatenatedOutput, lr_eval_string("{sLeftString}"));
	strcat(cConcatenatedOutput, lr_eval_string("{sCalculatedRightString}"));
	
	lr_output_message("Epoch time minus 1000 milliseconds is:[%s]",cConcatenatedOutput);
	
	return 0;
}
Beispiel #3
0
Action()
{
	int iDebug;
	
	web_cleanup_cookies( );
		
	lr_start_transaction("_TIVApp_001_My_Test");
	
	lr_save_string("TIVApp_001_001_Homepage", "pTransactionName");
	
	web_reg_find("Fail=NotFound",
		"Search=Body",
		"Text=Test site.",
		LAST);

	web_reg_save_param("cServerName",
	    "LB=Set-Cookie: ROUTEID=.",
	    "RB=;",
	    "Notfound=warning",
	    LAST);
	
	web_reg_save_param("cVersion",
	    "LB=version\">",
	    "RB=<",
	    "Notfound=warning",
	    LAST);
	
	lr_start_transaction(lr_eval_string("{pTransactionName}"));
	
	web_url("Homepage", 
		"URL=http://{pURL}/", 
		"Resource=0", 
		"RecContentType=text/html", 
		"Referer=", 
		"Snapshot=t1.inf", 
		"Mode=HTML", 
		LAST);
	// Log Levels:
	// LR_MSG_CLASS_DISABLE_LOG
	// LR_MSG_CLASS_BRIEF_LOG
	// LR_MSG_CLASS_EXTENDED_LOG
	// LR_MSG_CLASS_RESULT_DATA
	// LR_MSG_CLASS_PARAMETERS
	// LR_MSG_CLASS_FULL_TRACE
	iDebug = lr_get_debug_message();

	lr_output_message("TIVMsg: Msg Level was: %d", iDebug);
	
	lr_set_debug_message(LR_MSG_CLASS_EXTENDED_LOG, LR_SWITCH_ON);
	
	lr_debug_message(LR_MSG_CLASS_EXTENDED_LOG | LR_MSG_CLASS_RESULT_DATA,"TIVMsg: %s loaded via server: %s", lr_eval_string("{pTransactionName}"), lr_eval_string("{cServerName}"));
	
	lr_set_debug_message(iDebug, LR_SWITCH_ON);
	
	lr_end_transaction(lr_eval_string("{pTransactionName}"), LR_AUTO);
	
	lr_end_transaction("_TIVApp_001_My_Test", LR_AUTO);
	
	return 0;
}
Beispiel #4
0
/*! \brief Detect low disk space situations on the generator and turn all logging off if not enough space is left.

When called, this function will check the amount of space left on the generator's "output" device / directory. 
If the percentage of free space is lower than the treshold percentage, it will generate an error transaction "---DISK SPACE LOW IN LOG FOLDER FOR {y_hostname_generator}---" and turn all further logging off until the end of the test, using y_log_turn_off_permanently().

\note Scripts that call lr_debug_message() or the various y_lib() toggle functions to turn the loglevel back up may ignore this restriction.

Loadrunner does not protect the generators' disks from overflowing, even if the test is writing out a lot of information to the logs really quickly.
If a disk fills up on the generator or the disk the controller uses for results collation overflows there is no graceful recovery. Collation will fail and test results may be hard or impossible to recover.
This kind of situation can occur when temporary service disruptions happen (triggering a flood of 'log on error' messages), but also if runtime settings are incorrect and the test was configured to log *everything*.

In order to prevent this from happening scripts should regularly call to both y_disk_space_guard() and y_disk_space_usage_guard() with some reasonable limits.

\param [in] max_free_percentage The amount of free diskspace as a percentage of total space that will cause the logging to turn off.

\author Floris Kraak
*/
void y_disk_space_guard(double max_free_percentage)
{
    char* hostname;
    static int disk_space_warning_given = 0;
    double free_space_percentage;
    char* log_folder = lr_get_attrib_string("out");

    // check already fired once before.
    if( disk_space_warning_given )
    {
        // guard against accidental re-enablement of the logs by turning them off explicitly.
        y_log_turn_off_permanently();
        return;
    }

    free_space_percentage = y_get_free_disk_space_percentage(log_folder);

    // data point
    hostname = lr_get_host_name();
    lr_save_string(hostname, "y_hostname_generator");
    lr_user_data_point( lr_eval_string("disk_space_{y_hostname_generator}_free_percentage"), free_space_percentage);

    if( free_space_percentage < max_free_percentage )
    {
        y_setup();
        lr_set_transaction(lr_eval_string("---DISK SPACE LOW IN LOG FOLDER FOR {y_hostname_generator}---"), 0, LR_FAIL);
        lr_error_message("Diskspace low on %s in folder %s. %.2lf%% remaining, exceeding the limit of %.21f%% Logging turned off for user id %d for the remainder of the test!", 
                         hostname, log_folder, free_space_percentage, max_free_percentage, y_virtual_user_id);
        disk_space_warning_given = 1; // turn off further warnings.
        y_log_turn_off_permanently();
    }
}
	int WriteToFile(char *cDOSPath, char * cDOS)
	{
    //Save Epoch time to an array
	web_save_timestamp_param("sEpochMilliseconds", LAST);
    strcpy(cEpochTime, lr_eval_string("{sEpochMilliseconds}"));

	//Save the unique filename in the format C:\temp\x_yyyyyyyyyyyyy.txt where x is vUserID and yyyyyyyyyyyyy is Current EpochTime
    lr_save_string("C:\\temp\\", "FilePath");
	lr_save_string(".txt", "FileType");
	strcpy(file_path, lr_eval_string("{FilePath}"));
	strcat(file_path, lr_eval_string("{pVuser}"));
	strcat(file_path, "_");
	strcat(file_path, cEpochTime);
	strcat(file_path, lr_eval_string("{FileType}"));

//	Uncomment the following line for debugging - output current filepath
//	lr_output_message("File Path - %s", file_path);

	//This is the command thich will write data to the external file.
	//It starts by writing the DOS command into a string called "command"
	sprintf(cCommand, "%s%s > %s", cDOSPath, cDOS ,file_path); 

	lr_output_message("cCommand - %s", cCommand);
	lr_output_message("cDOS - %s", cDOS);
	lr_output_message("file_path - %s", file_path);


//	Uncomment the following line for debugging - output current command
	lr_output_message("command - %s", cCommand);

	//Execute the DOS command "command"
    system(cCommand); 
	}
Beispiel #6
0
update_shorturl_in_VTS(){
	// Store the shorturl generated into the VTS table so the same value is not generated again.
	
	int rc=LR_PASS;
	
	if( iUpdate_shorturl_in_VTS == 1 ){
		// Operating on the current VTS index:
		rc = vtc_send_if_unique(pvci, "shorturl", lr_eval_string("{pShortURL}"), &status);

		wi_startPrintingTrace();
	    lr_output_message(">> update_shorturl_in_VTS rc=%d pShortURL=%s, rc=%d, status=%d (1=Pass, 0=Fail)."
		        ,nURLtoShorten_done 
				,lr_eval_string("{pShortURL}")
				,rc
				,status
				);
		wi_stopPrinting();
		if( status == 1 ){
			rc=LR_PASS;
		}else{
			rc=LR_FAIL;
		}
	}

    return rc;
} // update_shorturl_in_VTS()
Beispiel #7
0
Action()
{
    GetSourceDataRegister();
    
    if( strcmp( lr_eval_string("{first_name}"), "") != 0)
	{
    // {first_name} is not null
     lr_output_message("%s %s Registered as a new customer", 
                      lr_eval_string("{first_name}"),
                      lr_eval_string("{last_name}"));
    
    lr_think_time(5);
    
    OutputUsedDataRegister();
    lr_output_message("New Customer %s %s is now awaiting approval", 
                      lr_eval_string("{first_name}"),
                      lr_eval_string("{last_name}"));
    
    lr_think_time(5);
	}
    
else
	{
    // {first_name} is null, wait for more data
    lr_output_message("No data for user login...waiting for 50 seconds.");
    lr_think_time(50);
    	
    lr_exit(LR_EXIT_ITERATION_AND_CONTINUE, LR_PASS);
	}   


    
    return 0;
}
Beispiel #8
0
get_google_access_token(){
		int rc=LR_PASS;
	char sOut[256]; // used by wi_EncodePlainToURL()

	rc=get_pJWTAssertion(); // into parameter pJWTAssertion used by this function.
	if( rc != LR_PASS ){ return rc; } // No input data to process.

		if( stricmp("Token",LPCSTR_RunType ) == FOUND ){ // "Token" or "TOKEN" specified in Run-time Attribute "RunType" or command line option "-RunType".
			wi_startPrintingTrace();
		    lr_output_message(">> RunType=\"%s\". JWT=%s."
					,LPCSTR_RunType 
					,lr_eval_string("{pJWTAssertion}")
					);
			wi_stopPrinting();
			return LR_PASS;
		}

	    web_add_header("Content-Type","application/x-www-form-urlencoded");
	    web_add_header("X-Frame-Options","deny"); // to protect against drag'n drop clickjacking attacks in older browsers.
	    web_reg_save_param_ex("ParamName=pAccessToken","LB=\"access_token\" : \"","RB=\"",SEARCH_FILTERS,"Scope=body",LAST);

	    // Example: "Body=grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion={pJWTAssertion}",
	    wi_EncodePlainToOAuth("grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=",sOut );
	    lr_save_string(sOut,"pJWTAssertion_request");
			wi_startPrintingTrace();
		    lr_output_message(">> sOut=\"%s\"."
					,lr_eval_string("{pJWTAssertion_request}")
					);
			wi_stopPrinting();
				
		// TODO: 15. If you want to, change the transaction name suffix for access authorization requests.
		sprintf( 	   tempString1, "%s_1access", lr_eval_string("{pTransSequence}") );
		lr_save_string(tempString1,"pTransName");
	    wi_start_transaction();
	    // web_rest("Token",
	    web_custom_request("Token",
                       "URL=https://accounts.google.com/o/oauth2/token",
                       "Method=POST",
                       //"ResType=JSON",
                       "Body={pJWTAssertion_request}{pJWTAssertion}",
                       LAST);
                       // The %3A are urlencoded from colons. (but %2D for the dash causes an "Invalid request" response):
                       // "Body=grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion={pJWTAssertion}",
                       // 		Common name for "jwt-bearer" is JWT Bearer Token Grant Type Profile for OAuth 2.0
                       // 		Defined at http://tools.ietf.org/html/draft-ietf-oauth-jwt-bearer-04
	    rc = wi_end_transaction();
	    // "Error -27796: Could not resolve address of hot accounts.google.com" is issued if there in no internet connection.
	    // Google API does not issue "error_description" such as "Audience validation failed".

		/* The response should look something like:
		{
  			"access_token" : "1/_5pUwJZs9a545HSeXXXXXuNGITp1XtHhZXXxxyyaacqkbc",
			"token_type" : "Bearer",
			"expires_in" : 3600
		}
		*/
		
    return rc;
} // get_google_access_token()
Beispiel #9
0
/*! \brief Detect excessive disk usage by the test and turn all further logging off if more than a specific limit number of mebibytes has been used.

When called, this function will check the amount of space used on the generator's "output" device / directory since the first call to this function.
If the amount of used space exceeds the treshold it will generate an error transaction "---DISK SPACE LOW IN LOG FOLDER FOR {y_hostname_generator}---" and turn all further logging off until the end of the test, using y_log_turn_off_permanently().

\note Scripts that call lr_debug_message() or the various y_lib() toggle functions to turn the loglevel back up may ignore this restriction.

Loadrunner does not protect the generators' disks from overflowing, even if the test is writing out a lot of information to the logs really quickly.
If a disk fills up on the generator or the disk the controller uses for results collation overflows there is no graceful recovery. Collation will fail and test results may be hard or impossible to recover.
This kind of situation can occur when temporary service disruptions happen (triggering a flood of 'log on error' messages), but also if runtime settings are incorrect and the test was configured to log *everything*.

\note Because of the way this measurement is done, it may also trigger if some other process on the same machine starts writing large amounts of data to the same device.

In order to prevent this from happening scripts should regularly call to both y_disk_space_guard() and y_disk_space_usage_guard() with some reasonable limits.

\note The contents of the generator's output folder will be transferred to the controller during collation. If the sum of the output directories for the generators exceed the size of that filesystem collation will fail, even if there is enough space on the generators. Therefore, set this low enough to make sure that if all generators output folders get filled to the limit the controller will still have enough space for it's collation process.

\param [in] limit_mebibytes_used The amount of mebibytes the test is allowed to used on the generator's target directory. 

\author Floris Kraak
*/
void y_disk_space_usage_guard(double limit_mebibytes_used)
{
    char* hostname;
    char* log_folder = lr_get_attrib_string("out");
    double free_mebibytes;
    static double max_free_mebibytes = -1;
    double mebibytes_used;
    static int disk_space_warning_given = 0;

    // check already fired once before.
    if( disk_space_warning_given )
    {
        // guard against accidental re-enablement of the logs by turning them off explicitly.
        y_log_turn_off_permanently();
        return;
    }

    free_mebibytes = y_get_free_disk_space_in_mebibytes(log_folder);
    lr_log_message("y_disk_space_usage_guard: current free: %f MB, max free: %f MB, limit: %f MB used in folder: %s",
                   free_mebibytes, max_free_mebibytes, limit_mebibytes_used, log_folder);

    if(max_free_mebibytes < 0)
    {
        lr_log_message("Storing free space as detected maximum");
        max_free_mebibytes = free_mebibytes;
        return;
    }
    else if(max_free_mebibytes < free_mebibytes)
    {
        lr_output_message("Warning: Free disk space increased from %f to %f, test disk space usage measurements may have become unreliable.", max_free_mebibytes, free_mebibytes);
        max_free_mebibytes = free_mebibytes;
        return;
    }

    // Ok, so we used *something*. Now let's see if it exceeds our limit.
    mebibytes_used = max_free_mebibytes - free_mebibytes;

    // data points
    hostname = lr_get_host_name();
    lr_save_string(hostname, "y_hostname_generator");
    lr_user_data_point( lr_eval_string("disk_space_{y_hostname_generator}_free_mebibytes"), free_mebibytes);
    lr_user_data_point( lr_eval_string("disk_space_{y_hostname_generator}_used_mebibytes"), mebibytes_used);

    if( mebibytes_used >= limit_mebibytes_used ) 
    {
        y_setup();
        lr_set_transaction(lr_eval_string("---DISKSPACE USAGE TOO HIGH IN LOG FOLDER FOR {y_hostname_generator}---"), 0, LR_FAIL);
        lr_output_message("Disk space used on host %s in folder %s was %f mebibytes, reaching the limit of %f. Logging turned off for user id %d for the remainder of the test!",
                           hostname, log_folder, mebibytes_used, limit_mebibytes_used, y_virtual_user_id);
        disk_space_warning_given = 1; // turn off further warnings.
        y_log_turn_off_permanently();
    }
}
//**************************************************
// created by Mark Sibley
// modified by Richard Bishop
// Saves left and right parts of a string into two separate strings
// Similar to Excel LEFT() and RIGHT() functions
//--------------------------------------------------
int SplitString(char * StringToSplit, int iLeftSplit)
{
   int iSLenA, iSLenB, iLoopLen;
   int iLooper = 0;
   char sStringB[200], sFullString[200], sParam[2000], n, sCharacter[200];

   //--------------------------------------------------
   // This saves the left hand x characters of the account number string
    strncpy(sStringB, StringToSplit, iLeftSplit);
   lr_save_string(lr_eval_string(sStringB),"sLeftString");
   //--------------------------------------------------
   // this calculates the string lengths
   iSLenA = strlen(lr_eval_string(StringToSplit));
   iSLenB = strlen(lr_eval_string("{sLeftString}"));
   iLoopLen = iSLenA - iSLenB;
   //--------------------------------------------------
   // this saves the right hand characters of the account string
   sprintf(sParam,"%s",lr_eval_string(StringToSplit));
   for (iLooper = iSLenB; iLooper < iSLenA; iLooper++)
   {
      sscanf(sParam+iLooper, "%c", &n);
      sprintf(sCharacter,"%c",n);
      strcat(sFullString, sCharacter);
   }
   lr_save_string(lr_eval_string(sFullString),"sRightString");
   //--------------------------------------------------
   // used when debugging this function
   
   lr_output_message("Original string:[%s]",lr_eval_string(StringToSplit));
   lr_output_message("Left hand split:[%s]",lr_eval_string("{sLeftString}"));
   lr_output_message("Right hand split:[%s]",lr_eval_string("{sRightString}"));
      
   //--------------------------------------------------
}
GenerateSSNs()
{
	SSNGenerator("EmployeeSpouseSSN");
	
		lr_output_message(lr_eval_string("{EmployeeSpouseSSN}"));
	
	SSNGenerator("EmployeeChildOneSSN");
	
		lr_output_message(lr_eval_string("{EmployeeChildOneSSN}"));
		
	SSNGenerator("EmployeeChildTwoSSN");
	
		lr_output_message(lr_eval_string("{EmployeeChildTwoSSN}"));	
	return 0;
}
GenerateSSNs()
{
    SSNGenerator("Assisted_SSN");

    lr_output_message(lr_eval_string("{Assisted_SSN}"));
    return 0;
}
Beispiel #13
0
Action()
{
	char *results = NULL;
	int   rescnt  = 0;

	lr_save_string("199.35.107.2","DnsServer");	// Set DNS server IP Address
	lr_save_string("www.merc-int.com", "Hostname");	// Set hostname to resolve

	// Perform DNS Query
	results = (char *) ms_dns_query("DnsQuery",
			"URL=dns://{DnsServer}",
			"QueryHost={Hostname}",
		LAST);

	// List all the results... (if more than one)
	while (*results) {
		rescnt++;
		lr_log_message(
			lr_eval_string("(%d) IP address for {Hostname} is %s"),
			rescnt, 
			results);
		results = (char *) ms_dns_nextresult(results);
	}
	return 0;
}
Beispiel #14
0
Action()
{
	lr_save_datetime("%y%j", DATE_NOW, "JulianDate"); 
	lr_output_message("Today's Julian Date is %s",lr_eval_string("{JulianDate}"));
	
	return 0;
}
vuser_init()
{

    srand(atoi(lr_eval_string("{MillisSeed}")));

    return 0;
}
Beispiel #16
0
// --------------------------------------------------------------------------------------------------
// y_breadcrumb();
//         Adds a string to the parameter {breadcrumb}.
//      Use this to keep track of the steps taken by the script. Very useful is you have a script which
//      does things in a random order and you want to know (in the end) which order it used.
//      You can, ofcourse, write this to a (log)file.
//      Don't forget to use y_breadcrumb_reset() to clear the parameter at the start of the script.
// @author: Raymond de Jongh
// Example:
//        y_breadcrumb_reset();    // clean the breadcrumb-variable. (previous data in {breadcrumb} is deleted.
//        y_breadcrumb("start");
//        .... some code....
//        y_breadcrumb("processing data")
//        ... some code ....
//        y_breadcrumb("finished")
//      The result is that {breadcrumb} contains "start;processing data;finished"
// --------------------------------------------------------------------------------------------------
void y_breadcrumb(char *breadcrumb)
{
    lr_message("---------------------------------------------------------------------------------");

    if ((strcmp(lr_eval_string("{breadcrumb}"), "{breadcrumb}") == 0) || ((strcmp(breadcrumb, "") == 0)))
    {
        lr_save_string("", "breadcrumb");
        lr_save_string(breadcrumb, "y_breadcrumb_temp");
        lr_save_string(lr_eval_string("{y_breadcrumb_temp}"), "breadcrumb");
    }
    else
    {
        lr_save_string(breadcrumb, "y_breadcrumb_temp");
        lr_save_string(lr_eval_string("{breadcrumb};{y_breadcrumb_temp}"), "breadcrumb");
    }
}
Beispiel #17
0
set_oauthhelper_dll(){ // Called by get_pJWTAssertion() interations:

	int retVal = 0; // used for return from oauth_load_privatekey().

	// *** No need to change the rest of this file:
	
	lr_param_sprintf("pTimeExpire","%d",time(0)); // create initial seed where (now 10-digit) 1379510581 is for Sep. 18, 2013 at 7:24AM MT.
	lr_load_dll("oauthhelper.dll"); // Written by [email protected].
		// TODO: 20. In Run-time Settings > Miscellaneous, set to run as "Process" rather than "Thread".
		// TODO: 21. Specify in vugen.dat file in "C:\Program Files (x86)\HP\LoadRunner\dat" to load DLL globally for use by all Vuser scripts.
			// file mdrv.dat 
			// [HTTP] section 
			// WINNT_DLLS=kernel32.dll,vtclient.dll,user32.dll

		// TODO: 22. If loading from the script’s directory, specify the DLL is listed in the Controller’s Design View -> Details -> More -> Files.
		// If errors are only from Controller, copy the DLL to the same directory on all Load Generator machines.

	// Using values obtained from Google APIs Console for Project X Client ID associated with {GoogleAPIServiceEmail}:
	retVal = oauth_load_privatekey(lr_eval_string("{pServicePrivateKeyFile}"),"notasecret"); // Done only once.
	if( retVal != 0 ){
 		if( retVal == -1 ){
			lr_error_message(">> oauth_load_privatekey Failed to open p12 file, file not found, path incorrect.");
 		}else if( retVal == -2 ){
			lr_error_message(">> oauth_load_privatekey Error reading the PKCS#12 file, file permissions.");
 		}else if( retVal == -3 ){
			lr_error_message(">> oauth_load_privatekey Error parsing the PKCS#12 file, invalid certificate or invalid password.");
 		}else if( retVal == -4 ){
			lr_error_message(">> oauth_load_privatekey Key not set.");
 		}else{
			lr_error_message(">> oauth_load_privatekey retVal=%d.",retVal);
 		}
 	}

	return retVal;
} // set_oauthhelper_dll()
Beispiel #18
0
// --------------------------------------------------------------------------------------------------
// Get the content of the parameter named "paramName" and return it as a char *
//
// Todo: Make a derivative function getParameterNoZeroes() which uses lr_eval_string_ext()
// and replaces all \x00 characters in the result with something else, like y_array_get_no_zeroes() does.
// Then every user of this function should start using it.
// Alternative: Make a function that cleans parameters of embedded null bytes and tell users to use that
// before doing anything else with possible tainted values.
// I think I like that one better to be honest. For the Array_ subset it's not that bad given the better
// memory management but for this one .. muh.
//
// @author Floris Kraak
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//        example usage:
//                char *test;
//                lr_save_string("test123", "TestParam");        // save the string "test123" into parameter {TestParam}
//                test=y_get_parameter("TestParam");
//                lr_message("Test: %s", test);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
char* y_get_parameter(const char* paramName)
{
   char *tmp = y_get_parameter_eval_string(paramName);
   char *parameter = lr_eval_string(tmp);
   free(tmp);
   
   return parameter;
}
Beispiel #19
0
Action()
{

	char chQuery[128];

	MYSQL *Mconn; 
    
	lr_load_dll("libmysql.dll"); 

	Mconn = lr_mysql_connect(MYSQLSERVER, MYSQLUSERNAME, MYSQLPASSWORD, MYSQLDB, atoi(MYSQLPORT));

	lr_save_string(lr_eval_string("{pTransactionName}"),"sTransactionName");
	lr_save_string(lr_eval_string("{pResult}"),"sResult");
	lr_save_string(lr_eval_string("{pRandom}"),"sResponseTime");

	lr_save_datetime("%H:%M:%S", TIME_NOW, "sTime"); 

	sprintf(chQuery, "insert into test.sample_writes (sqTransactionName, sqResult, sqResponseTime, sqTime) values ('%s','%s','%s','%s');",
				lr_eval_string("{sTransactionName}"),
				lr_eval_string("{sResult}"),
				lr_eval_string("{sResponseTime}"),
				lr_eval_string("{sTime}"));

	lr_mysql_query(Mconn, chQuery);

	lr_mysql_disconnect(Mconn);


	return 0;
}
Beispiel #20
0
// --------------------------------------------------------------------------------------------------
// Test if the given parameter is empty or not yet set (these are two different things..)
// 
// @author Floris Kraak
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//        example usage:
// 
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int y_is_empty_parameter(const char *param_name)
{
    char *param_eval_string = y_get_parameter_eval_string(param_name);
    char *param = lr_eval_string(param_eval_string);
    
    int result = strlen(param) == 0 || strcmp(param, param_eval_string) == 0;
    free(param_eval_string);

    return result;
}
Beispiel #21
0
Action()
{
	//Saves the string (normally this would be a correlated value hence the "c" prefix - cParameterToSplit
	lr_save_string("1234567890abcdefghijklmnopqrstuvwxyz","cParameterToSplit");

	//Splits the saved string into two parts, first x characters as declared in "iLeftSplit" and remainder
	SplitString(lr_eval_string("{cParameterToSplit}"),10);
	
	return 0;
}
Beispiel #22
0
Action()
{

	lr_start_transaction("kp");


	web_service_call( "StepName=electronInvoice_102",
		"SOAPMethod=ElectronInvoiceSer|ElectronInvoiceSerHttpPort|electronInvoice",
		"ResponseParam=response",
		"Service=ElectronInvoiceSer",
		"ExpectedResponse=SoapResult",
		"Snapshot=t1457769024.inf",
		"BEGIN_ARGUMENTS",
		"xml=<ElectronInvoiceInput><UNI_BSS_HEAD><ORIG_DOMAIN>PTIS</ORIG_DOMAIN><SERVICE_NAME>ElectronInvoiceSer</SERVICE_NAME><OPERATE_NAME>electronInvoice</OPERATE_NAME><ACTION_CODE>0</ACTION_CODE><ACTION_RELATION>0</ACTION_RELATION><ROUTING><ROUTE_TYPE>36</ROUTE_TYPE><ROUTE_VALUE>18674453342</ROUTE_VALUE></ROUTING><PROC_ID>seq00001</PROC_ID><TRANS_IDO>seq00001</TRANS_IDO><TRANS_IDH></TRANS_IDH><PROCESS_TIME>201603111704001</PROCESS_TIME><RESPONSE><RSP_TYPE></RSP_TYPE><RSP_CODE></RSP_CODE><RSP_DESC></RSP_DESC></RESPONSE><COM_BUS_INFO><OPER_ID>yanff</OPER_ID><PROVINCE_CODE>0002</PROVINCE_CODE><EPARCHY_CODE>地市代码表</EPARCHY_CODE><CITY_CODE>区县编码</CITY_CODE><CHANNEL_ID>渠道编码</CHANNEL_ID><ACCESS_TYPE>1</ACCESS_TYPE><ORDER_TYPE>1</ORDER_TYPE></COM_BUS_INFO><SP_RESERVE><TRANS_IDC>ECIP0002seq00001</TRANS_IDC><CUTOFFDAY>20080608</CUTOFFDAY><OSNDUNS>0002</OSNDUNS><HSNDUNS>1100</HSNDUNS><CONV_ID>ECIP0002seq00001200806081200111</CONV_ID></SP_RESERVE><TEST_FLAG>0</TEST_FLAG><MSG_SENDER>1100</MSG_SENDER><MSG_RECEIVER>1101</MSG_RECEIVER></UNI_BSS_HEAD><UNI_BSS_BODY><ELECTRON_INVOICE_REQ><INVOICE_REQ_ID>lyl{lsh}</INVOICE_REQ_ID><MAKE_INVOICE_TYPE>0</MAKE_INVOICE_TYPE><SELLER_TAXPAYER_ID>440300568519737</SELLER_TAXPAYER_ID><SELLER_NAME>电子发票测试</SELLER_NAME><SELLER_ADD>深圳市南山区南海大道1057号科技大厦二期A栋601房</SELLER_ADD><SELLER_PHONE>0755-26027907</SELLER_PHONE><SELLER_BANK_ACCOUNT>31001669701052502638</SELLER_BANK_ACCOUNT><BUYER_TAXPAYER_ID></BUYER_TAXPAYER_ID><BUYER_NAME>张三</BUYER_NAME><BUYER_ADD>深圳市南山区深南大道1057号科技大厦二期A栋6888房</BUYER_ADD><BUYER_BANK_ACCOUNT>98888888701052502638</BUYER_BANK_ACCOUNT><BUYER_PHONE>18888888888</BUYER_PHONE><BUYER_EMAIL>[email protected]</BUYER_EMAIL><WRITE_MANAGER>admin</WRITE_MANAGER><RECE_FEE_MANAGER>admin</RECE_FEE_MANAGER><CHECK_MANAGER>admin</CHECK_MANAGER><ORG_INVOICE_CODE></ORG_INVOICE_CODE><ORG_INVOICE_NUM></ORG_INVOICE_NUM><TOTAL_PRICE_TAX>117</TOTAL_PRICE_TAX><TOTAL_FEE>100</TOTAL_FEE><TOTAL_TAX_PAY>17</TOTAL_TAX_PAY><PROJECT_INFO><INVOICE_COMPANY_NATURE>0</INVOICE_COMPANY_NATURE><PROJECT_NAME>洗衣粉</PROJECT_NAME><UNIT>袋</UNIT><MODEL>500克</MODEL><PROJECT_COUNT>1</PROJECT_COUNT><PROJECT_UNIT_PRICE>100</PROJECT_UNIT_PRICE><PROJECT_FEE>100</PROJECT_FEE><TAX_RATE>0.17</TAX_RATE><TAX_PAY>17</TAX_PAY></PROJECT_INFO><PARA><PARA_ID>保留字段ID</PARA_ID><PARA_VALUE>保留字段值</PARA_VALUE></PARA></ELECTRON_INVOICE_REQ></UNI_BSS_BODY><UNI_BSS_ATTACHED><MEDIA_INFO></MEDIA_INFO></UNI_BSS_ATTACHED></ElectronInvoiceInput>",
		"END_ARGUMENTS",
		"BEGIN_RESULT",
		"out=Param_out",
		"END_RESULT",
		"LAST");

lr_save_string( lr_eval_string("{Param_out}"),"a" );
	lr_replace("a","&lt;","<" );
	lr_replace( "a","&gt;",">" );
	lr_output_message("result:%s", lr_eval_string("{a}"));
   	lr_xml_get_values("XML={a}","FastQuery=/ElectronInvoiceOutput/UNI_BSS_BODY/ELECTRON_INVOICE_RSP/RESP_CODE", "ValueParam=strXml","LAST");
    lr_output_message("result:%s", lr_eval_string("{strXml}"));

	if(atoi(lr_eval_string("{strXml}"))==0){
      lr_output_message("result:%s", "交易成功");
      
	lr_end_transaction("kp", 2);

	}
	else{
      lr_error_message("result:%s", "交易失败");
      
	lr_end_transaction("kp", 2);

	}
   
return 0;
}
Beispiel #23
0
int vi_set_pURLtoShorten_file_recs(){
	
	int UserIds_file_rec=2; // beging looping from second row after saving first row's value:
	lr_save_string(lr_eval_string("{UserIds_userid}"),"UserIds_userid_first");
	lr_advance_param("UserIds_use"); // Increment one row.

	// Loop through file until the first value appears again:
	while( 1==1 ){ // true
		// Catch if cycled back to first row:
		if( stricmp( lr_eval_string("{UserIds_userid_first}"),lr_eval_string("{UserIds_userid_first}") ) == FOUND ){
			// lr_output_message(">> {UserIds_userid_first}=%s", lr_eval_string("{UserIds_userid_first}") );
			return UserIds_file_rec - 1;
		}else{
			lr_advance_param("pURLtoShorten"); // Increment file one record.
			UserIds_file_rec = UserIds_file_rec + 1;
			// lr_output_message(">> UserIds_file_rec=%d UserIds_userid_first=%s", UserIds_file_rec, lr_eval_string("{UserIds_userid_first}"));
		}
	}
	return LR_FAIL; // drop-out after exhausting values in table.
} // vi_set_pURLtoShorten_file_recs()
Beispiel #24
0
wi_show_user_agent(){
	// This makes use of the request_header captured by this invoked before a call:
	//    web_save_header(REQUEST,"request_header");
	// Which only needs to be done once if the client Agent String does not change during a run.
	
	char * headers = lr_eval_string("{request_header}");
 
 	lr_save_param_regexp(headers,
        strlen(headers),
   		"RegExp=User-Agent: (.+)\\r\\n",
   		"ResultParam=userAgent",
   		LAST );

	// {userAgent} is one of the run conditions shown one time for whole run:
		wi_startPrintingInfo();
 	lr_output_message(">> {userAgent}=%s.", lr_eval_string("{userAgent}"));
	// TODO: Intrepret raw agent string to summarize the browser name and version.
		wi_resetPrinting();

	return 0;
}
Beispiel #25
0
int vi_set_pURLtoShorten_file_recs(){
	
	int nURLtoShorten_file_rec=2; // beging looping from second row after saving first row's value:
	lr_save_string(lr_eval_string("{pURL_long}"),"pURLtoShorten_first");
	lr_advance_param("pURLtoShorten"); // Increment file one record.

	// Loop through file until the first value appears again:
	while( 1==1 ){ // true
		// Catch if cycled back to first row:
		if( stricmp( lr_eval_string("{pURLtoShorten_first}"),lr_eval_string("{pURL_long}") ) == FOUND ){
			// lr_output_message(">> pURLtoShorten=%s", lr_eval_string("{pURL_long}") );
			return nURLtoShorten_file_rec - 1;
		}else{
			lr_advance_param("pURLtoShorten"); // Increment file one record.
			nURLtoShorten_file_rec = nURLtoShorten_file_rec + 1;
			// lr_output_message(">> nURLtoShorten_file_rec=%d pURLtoShorten=%s", nURLtoShorten_file_rec, lr_eval_string("{pURL_long}"));
		}
	}
	
	return LR_FAIL;
} // vi_set_pURLtoShorten_file_recs()
Beispiel #26
0
/*!
\brief Get the content of a parameter and return it as a char *, or return NULL if it wasn't set.

This will return null in the most typical case: A parameter saved with web_reg_save_param(), but never filled.
The actual check employed here is a test that looks if the parameter content matches the parameter name surrounded by brackets.

If the parameter was never filled, lr_eval_string() will return that. However, in many more elaborate cases we really need to know
if it was never filled to begin with. This function mimics the behaviour we really want to see in LR, but don't have.
(At least, not in LR 11.05, the version I'm working with.)

It would be really nice if there was a loadrunner built-in that did this.

\param [in] param_name The name of the parameter to fetch.
\returns A char* buffer containing the contents of the parameter, allocated by lr_eval_string(), or NULL.
\warning This returns memory allocated by lr_eval_string(). It is likely to disappear (get freed) at the end of the iteration.
\warning If the content of the parameter matches the name of the parameter surrounded by brackets this function will return NULL even if it's not empty.

\b Example:
\code
char *test;
lr_save_string("test123", "TestParam");        // save the string "test123" into parameter {TestParam}
test=y_get_parameter("TestParam");
lr_message("Test: %s", test);
\endcode
\sa y_get_parameter(), y_is_empty_parameter()
\author Floris Kraak
*/
char* y_get_parameter_or_null(const char* param_name)
{
    char* param_eval_string = y_get_parameter_eval_string(param_name);
    char* param = lr_eval_string(param_eval_string);

    int exists = strcmp(param, param_eval_string) != 0; // Result doesn't match the param eval string (eg: '{param}')
    //lr_log_message("y_get_parameter_or_null for param_name %s, pre-eval string is %s, lr_eval_string result is %s, exists: %d", param_name, param_eval_string, param, exists);
    free(param_eval_string);
    //lr_abort();

	return exists ? param: NULL;
}
Beispiel #27
0
Action()
{
	//Sample code taken from Kim at - http://ptfrontline.wordpress.com/2010/01/27/lr_save_float-function-for-loadrunner/
	//Kim's comments....
	//LoadRunner has lr_save_int() and lr_save_string() but the float saving function is missing so I just quickly
	//whipped up the following code. It’s by no means perfect when it comes to checking for errors, but it will 
	//work >90% of the times (as long as the scripter knows what he/she is doing).. Enjoy
	
	lr_save_float(123.456, "myVar", 2);
	lr_output_message("%s",lr_eval_string("{myVar}"));  //Rounds floating point number to two decimal places
	
	return 0;
}
Beispiel #28
0
wi_start_transaction(){
	static float	floatThinkTimeSecs; // defined in wi_set_Think_Time().

	// lr_save_string( strTransName,"pTransName" ); // defined in Action().
	lr_start_transaction(lr_eval_string("{pTransName}"));
	
	// lr_get_transaction_duration(lr_eval_string("{pTransName}"));
	web_reg_save_param_ex("ParamName=pJSONResponse","LB={","RB=}", "Notfound=warning", LAST); // captures JSON

	lr_think_time( floatThinkTimeSecs );
		
    return LR_PASS;
} // wi_start_transaction
Beispiel #29
0
void OnMessageCB0 (const char* connectionID,
				  int isbinary,
				  const char * data,
				  int length)
{

int isupdate;

	
//		if (isbinary) {
//			lr_output_message("WebSocket ID = %s. [%d] bytes binary message received.", connectionID, length);
//		}
//		else {
//			lr_output_message("WebSocket ID = %s. [%d] bytes text message received.", connectionID, length);
//			lr_output_message("\r\n===\r\n%s\r\n===", data);
//		}

	OnMessageCB0_entries = OnMessageCB0_entries + 1;

// The first response after connect downloads JavaScript:  function setPhase,  c,d,z,n,r,p, error(cod, ph, tbl, msg), start, end, loop, retry, bw, convert.

   isupdate = strncmp(data,"d(",2); // as in data=d(1,8,1,'5.57','00:45:50','4.89','19500','5.57','5.58','25000',4);
if(isupdate != 0) {
   		// Display what is NOT handled as a message:
		lr_output_message(">> Among %d entries, OnMessageCB0_updates=%d with data=%s [at OnMessageCB0]"
		                  , OnMessageCB0_entries, OnMessageCB0_updates, data);
   }else{
	// message= z(1,10,'ELE Manufacturing','7.37','00:45:47','-3.15','49500','7.37','7.38','18000','5.97','9.11','7.61','7.7');
	//		    z(1,2,'Ations Europe','14.91','00:45:47','-7.33','47500','14.91','14.93','35000','12.62','19.43','16.09','16.2');
	
	    OnMessageCB0_updates = OnMessageCB0_updates + 1;
	if( OnMessageCB0_updates == 1 ){
		lr_set_transaction("T04_first_CB0_update", dTime_elapsed, LR_PASS); // Create successful transaction with a duration of seconds.
		lr_output_message(">> Among %d entries, OnMessageCB0_updates=%d with data=%s [at OnMessageCB0]"
		                  , OnMessageCB0_entries, OnMessageCB0_updates, data);
	}

	lr_save_param_regexp (
        			data,
        			length,
					myvalue_regexp,	
					"Ordinal=All",					
        			"ResultParam=myValue",
        			LAST );	
			
	if (atoi(lr_eval_string("{myValue_count}"))>0) {
		lr_message(">> [%s]: '%s'= [%s]$"
	    	           ,lr_eval_string("{ts}")
	    	           ,lr_eval_string("{COMPANY}")
	    	           ,lr_eval_string("{myValue_1}")
	    	          );
		lr_user_data_point(lr_eval_string("{COMPANY} stock value")
	    	           ,atof(lr_eval_string("{myValue_1}"))
	    	           );
	}
}
	
}
Beispiel #30
0
int wi_end_transaction(){
	int rc=LR_PASS;
	
	/* Defined as globals at top of vuser_init():
	int 			  intHttpRetCode;
	int 			  intHttpMilliseconds;
	float 			floatHttpMilliseconds;
	int 			  intHttpSize;
	float 			floatHttpKBytes;
	*/

	// Using pTransName saved in wi_start_transaction before the transaction:
    lr_end_transaction(lr_eval_string("{pTransName}"),LR_AUTO);

    // Verify bad 400 HTTP return code from server and associated response such as "{error : invalid_grant}"
    // using LoadRunner internal function web_get_int_property():
	    intHttpRetCode 		= web_get_int_property(HTTP_INFO_RETURN_CODE);
  	    intHttpSize 		= web_get_int_property(HTTP_INFO_DOWNLOAD_SIZE);
	    intHttpMilliseconds = web_get_int_property(HTTP_INFO_DOWNLOAD_TIME);
	  floatHttpMilliseconds = (float)intHttpMilliseconds / 1000; // Convert from milliseconds to seconds.

	if (intHttpRetCode == 200 // no problem! OK
	||  intHttpRetCode == 304 // Already cached.
	){
		// move on.
	}else{
		wi_startPrintingError();
    	lr_error_message(">> HTML Return Code=%d, pJSONResponse=%s." 
		                 , intHttpRetCode
		                 , lr_eval_string("{pJSONResponse}") 
		                 );
		wi_stopPrinting();
		rc=LR_FAIL;
	}

    return rc;
} // wi_end_transaction