Exemple #1
0
void fCaptureScreen (char* sTitleLeftBound, char* sTitleRightBound){
	char * sLB;
	char * sRB;

	if((sLB = (char *)malloc((strlen(sTitleLeftBound) + strlen("LB/IC=") + 2)* sizeof(char))) == NULL){
		lr_error_message("Out of memory error");
		lr_exit(LR_EXIT_VUSER,LR_FAIL);
	}else{
		sprintf(sLB,"LB/IC=%s", sTitleLeftBound);
		lr_output_message("TIVMsg: LB:%s", sLB);

	}

	if((sRB = (char *)malloc((strlen(sTitleRightBound) + strlen("RB/IC=") + 2)* sizeof(char))) == NULL){
		lr_error_message("Out of memory error");
		lr_exit(LR_EXIT_VUSER,LR_FAIL);
	}else{
		sprintf(sRB,"RB/IC=%s", sTitleRightBound);
		lr_output_message("TIVMsg: RB:%s", sRB);
	}

	web_reg_save_param("cPageTitle",
		sLB,
		sRB,
		"Notfound=warning",
	LAST);

	free (sLB);
	free (sRB);
}
Exemple #2
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()
Exemple #3
0
lr_popen()
{
    long fp; // file/stream pointer
    int count; // number of characters that have been read from the stream.
    char buffer[BUFFER_SIZE]; // allocate memory for the output of the command.
 
    // "VER" outputs the version of Windows that is running.
    if (!(fp = popen("VER", "r"))) {
        lr_error_message("Error opening stream.");
        return -1;
    }
 
    count = fread(buffer, sizeof(char), BUFFER_SIZE, fp); // read up to 10KB
    if (feof(fp) == 0) {
        lr_error_message("Did not reach the end of the input stream when reading. Try increasing BUFFER_SIZE.");
        return -1;
    }
    if (ferror(fp)) {
        lr_error_message ("I/O error during read."); 
        return -1;
    } 
    buffer[count] = NULL;
 
    lr_output_message("The Windows version is: %s", buffer);
    pclose(fp);
    return 0;
}
Exemple #4
0
int vi_set_VTS3(){

	int rc=LR_PASS;
	
	// Using VTS3 (Virtual Table Service version 3) available since LR 11.52+:
	// See blog by its developer at http://h30499.www3.hp.com/t5/HP-LoadRunner-and-Performance/The-New-Virtual-Table-Server-VTS-in-LoadRunner-11-52/ba-p/6069435#.Ukt79rHnb4Y
	// HP Support article at http://support.openview.hp.com/selfsolve/document/KM305130

       LPCSTR_VTS_Host = lr_get_attrib_string("VTS_Host"); // from Run-time settings Attributes or command line.
 	if(LPCSTR_VTS_Host==NULL){                 // Not specified in Run-Time Settings Attributes or command line.
 	          VTS_Host_string="localhost"; // VTS_Host_default; // such as "localhost"; 

			wi_startPrintingInfo();
		    lr_output_message(">> Attribute \"VTS_Host\" not specified in command-line or run-time settings. Default to \"%s\"."
					,VTS_Host_string
					);
			wi_stopPrinting();
    }else{
		sprintf( VTS_Host_string ,"%s",LPCSTR_VTS_Host);
	} // if(LPCSTR_VTS_Host==NULL)
       

       LPCSTR_VTS_Port = lr_get_attrib_string("VTS_Port"); // from Run-time settings Attributes or command line.
 	if(LPCSTR_VTS_Port==NULL){             // Not specified in Run-Time Settings Attributes or command line.
 	             nPort=8787; // nVTS_Port_default; // such as 8787 or 8888;
		    wi_startPrintingInfo();
		    lr_output_message(">> Attribute \"VTS_Port\" not specified in command-line or run-time settings. Default to \"%d\"."
					,nPort 
					);
			wi_stopPrinting();
    }else{
     	nPort = atoi(LPCSTR_VTS_Port); 
	} // if(LPCSTR_VTS_Port==NULL)

    /// Connect using LoadRunner native functions:
 		pvci = vtc_connect( VTS_Host_string , nPort , VTOPT_KEEP_ALIVE ); // VTS_Host_string
	if( pvci <= 0){
	    wi_startPrintingDebug();
		lr_error_message(">> VTS pvci=%d (non-zero).", pvci);
		wi_stopPrinting();
	}else{
		rc = vtc_get_last_error(pvci);
		if( rc != LR_PASS ) {
		    wi_startPrintingDebug();
			lr_error_message(">> rc from vtc_get_last_error(pvci)=%d for VTC connection to %s port .", rc, VTS_Host_string,nPort);
			wi_stopPrinting();
			return LR_FAIL; // FAIL
		}

		// Count rows in VTS table:
		vtc_column_size(pvci, "web", &nVTS_row_count);
		wi_startPrintingInfo();
		lr_output_message(">> nVTS_row_count=%d.", nVTS_row_count);
		wi_stopPrinting();
	}

	return rc;
} // vi_set_VTS3()
Exemple #5
0
wi_load_kernel32_dll(){
	int rc=LR_PASS;
    static int is_kernel32_dll_loaded = FALSE; // A static C variable inside a function retains its value between invocations.
                                 // The FALSE value is assigned only on the first invocation.

	#ifdef  USING_WINDOWS

	char* dll_name = "KERNEL32.DLL"; // In C:/Windows/System32 that comes with Windows.
			// Its File Description: "Windows NT BASE API Client DLL".

	if (is_kernel32_dll_loaded == FALSE) {
        rc = lr_load_dll(dll_name);
        if (rc == 0) {
			is_kernel32_dll_loaded = TRUE;
        }else{
			is_kernel32_dll_loaded = FALSE;
            lr_error_message(">> Error loading %s.", dll_name);
            // lr_abort();
        }
    }

	#endif // USING_WINDOWS

	return rc;
}
Exemple #6
0
/**
 * Gets the process ID of the mmdrv.exe process running the VuGen script calling this function.
 *
 * @return    This function returns the process ID of the calling process.
 *
 * Example code:
 *     // Print the vuser's process ID
 *     int vuser_pid; vuser_pid = wi_get_vuser_pid();
 *     lr_output_message("vuser_pid: %d", vuser_pid);
 *
 * Note: This function only works on Windows.
 * From lr-libc.
 */
int wi_get_vuser_pid() {
    int rc=LR_PASS; // return code
    int pid=0; // the process id (usually 4 digits)
    static int is_msvcrt_dll_loaded = FALSE; // A static variable inside a function keeps its value between
                                   // invocations. The FALSE value is assigned only on the first
                                   // invocation.
    char* dll_name = "MSVCRT.DLL"; // This DLL contains the _getpid() function. It is a standard
                                   // Windows DLL, usually found in C:\WINDOWS\system32.
                                   // On Windows platforms, if a path is not specified,
                                   // lr_load_dll searches for the DLL using the standard sequence.

 	#ifdef  USING_WINDOWS

    // Only load the DLL the first time this function is called:
    if (is_msvcrt_dll_loaded == FALSE) {
        rc = lr_load_dll(dll_name);
        if (rc == 0) {
	        is_msvcrt_dll_loaded = TRUE;
		    pid = _getpid();
        }else{
	        is_msvcrt_dll_loaded = FALSE;
		    lr_error_message(">> Error loading %s to get WIN32 pid in wi_get_vuser_pid.", dll_name);
            // lr_abort();
        }
    }

	#endif // USING_WINDOWS

	return pid;
} // wi_get_vuser_pid
Exemple #7
0
/**
 * Gets the process ID of the mmdrv.exe process that is running the VuGen script that called
 * this function.
 *
 * @return    This function returns the process ID of the calling process.
 *
 * Example code:
 *     // Print the vuser's process ID
 *     int vuser_pid; vuser_pid = wi_get_vuser_pid();
 *     lr_output_message("vuser_pid: %d", vuser_pid);
 *
 * Note: This function only works on Windows.
 * From lr-libc.
 */
int wi_get_vuser_pid() {
    int rc=LR_PASS; // return code
    int pid=0; // the process id (usually 4 digits)
    static int is_msvcrt_dll_loaded = FALSE; // A static variable inside a function keeps its value between
                                   // invocations. The FALSE value is assigned only on the first
                                   // invocation.
    char* dll_name = "MSVCRT.DLL"; // This DLL contains the _getpid() function. It is a standard
                                   // Windows DLL, usually found in C:\WINDOWS\system32.
                                   // Note: on Windows platforms, if you do not specify a path,
                                   // lr_load_dll searches for the DLL using the standard sequence
                                   // used by the C++ function, LoadLibrary.

    // Only load the DLL the first time this function is called:
    if (is_msvcrt_dll_loaded == FALSE) {
        rc = lr_load_dll(dll_name);
        if (rc != 0) {
            lr_error_message("Error loading %s.", dll_name);
            lr_abort();
        }
        is_msvcrt_dll_loaded = TRUE;
    }

    pid = _getpid();

    return pid;
} // wi_get_vuser_pid
Exemple #8
0
/*!
\brief Split a string into 2 parts using the search string. Save the right part into the result parameter.
\param [in] original_parameter The parameter to search.
\param [in] search The text preceding the text we're looking for.
\param [in] result_parameter The name of the parameter to store the result in.

\b Example:
\code
lr_save_string("AstrixObelixIdefix", "Test");
lr_message(lr_eval_string("Original: {Test}\n"));    // {Test}=AstrixObelixIdefix
y_right( "Test", "Obelix", "Test4" );
lr_message(lr_eval_string("New Param: {Test4}\n"));    //    {Test4}=Idefix
\endcode
\author Floris Kraak
*/
void y_right( const char *original_parameter, const char *search, const char *result_parameter)
{
    char* original = y_get_parameter_or_null(original_parameter);
    if( original == NULL )
    {
        lr_error_message("y_right(): Error: Parameter %s does not exist!", original_parameter);
        lr_abort();
    }
    else if( search == NULL || strlen(search) == 0 )
    {
        lr_save_string(original, result_parameter);
        lr_log_message("Warning: Empty search parameter passed to y_right()");
        return;
    }
    else
    {
        char* posPtr = (char *)strstr(original, search);
        //int pos = (int)(posPtr - original);
        //lr_log_message("y_right: original=%s, search=%s, resultParam=%s", original, search, result_parameter);
    
        if( posPtr == NULL )
        {
            lr_save_string(original, result_parameter);
            return;
        }
        //lr_log_message("pos = %d", pos);
        posPtr = posPtr + strlen(search);
        lr_save_string(posPtr, result_parameter);
    }
}
Exemple #9
0
/*!
\brief Split a string into 2 parts using the search string. Save the left part into the result parameter.
\param [in] original_parameter The parameter to search.
\param [in] search The text after the text we're looking for.
\param [in] result_parameter The name of the parameter to store the result in.

\b Example:
\code
lr_save_string("AstrixObelixIdefix", "Test");
lr_message(lr_eval_string("Original: {Test}\n"));    // {Test}=AstrixObelixIdefix
y_left( "Test", "Obelix", "Test2" );
lr_message(lr_eval_string("New Param: {Test2}\n"));    // {Test2}=Astrix
\endcode
\author Floris Kraak
*/
void y_left( const char *original_parameter, const char *search, const char *result_parameter )
{
    char *original = y_get_parameter_or_null(original_parameter);
    if( original == NULL )
    {
        lr_error_message("y_left(): Error: Parameter %s does not exist!", original_parameter);
        lr_abort();
    }
    else if( search == NULL || strlen(search) == 0 )
    {
        lr_save_string(original, result_parameter);
        lr_log_message("Warning: Empty search parameter passed to y_left()");
        return;
    }
    else
    {
        char *buffer;
        char *posPtr = (char *)strstr(original, search);
        int pos = (int)(posPtr - original);
        //lr_log_message("y_left: original=%s, search=%s, resultParam=%s", original, search, resultParam);

        if( posPtr == NULL )
        {
            lr_save_string(original, result_parameter);
            return;
        }
        //lr_log_message("pos = %d", pos);

        // Copy the original to a temporary buffer
        buffer = y_strdup(original);
        buffer[pos] = '\0'; // make the cut
        lr_save_string(buffer, result_parameter); // save the result
        free(buffer);
    }
}
Exemple #10
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();
    }
}
Exemple #11
0
/*!
\brief Save a substring of a parameter into a new parameter.
Search for a specific substring inside a parameter using left and right boundaries and save that into a new parameter.

\param [in] original_parameter The parameter to search.
\param [in] result_parameter The name of the parameter to store the result in.
\param [in] left The left boundary - the text immediately preceding the substring in question.
\param [in] right The right boundary.

\b Example:
\code
char* str = "LorumIpsumLipsum";
lr_save_string(str, "param");
y_substr("param", "param", "Lorum", "Lipsum");
lr_log_message(lr_eval_string("{param}")); // Prints "Ipsum".
\endcode
\author André Luyer, Marcel Jepma & Floris Kraak
*/
void y_substr(const char *original_parameter, const char *result_parameter, const char *left, const char *right)
{
    char *p1;
    char *str = y_get_parameter_or_null(original_parameter);
    if( str == NULL )
    {
        lr_error_message("y_substr(): Error: Parameter %s does not exist!", original_parameter);
        lr_abort();
    }

    // zoek start
    if (left) {
        p1 = strstr(str, left);
        if (p1) str = p1 + strlen(left);
        // else start is positie 0...
    }

    // zoek eind
    if (right) {
        p1 = strstr(str, right);
        if (p1) {
            lr_param_sprintf(result_parameter, "%.*s", p1 - str, str); // of sprintf
            return;
        }
    }
    lr_save_string(str, result_parameter);
}
Exemple #12
0
void OnErrorCB0 (const char* connectionID,
				  const char * message,
				  int length)
{
		lr_error_message(">> WebSocket ID=%s error occured. Error message = %s [at OnErrorCB0]"
	                  , connectionID, message);
}
Exemple #13
0
/*!
\brief Get the content of a parameter without embedded null bytes (\0 characters) from the named parameter, if any.
In some cases we want to fetch the content of a parameter but the parameter contains embedded NULL characters which make further processing harder. 
This will fetch a parameter but "cleanse" it from such contamination, leaving the rest of the data unaltered before returning it.

\warning The return value of this function needs to be freed using lr_eval_string_ext_free().

\param [in] param_name The parameter to cleanse of nulls.
\param [in] replacement A character that replaces any embedded nulls found.
\returns The resulting parameter content.

\b Example:
\code
{
   char buffer[11] = { '\0', 'b', '\0', 'r','o', '\0', 'k', 'e', 'n', '\0', '\0' };
   char *tmp;
   lr_save_var(buffer, 11, 0, "broken");
   tmp = y_get_cleansed_parameter("broken", '!');
   lr_log_message("Result: %s", tmp); // Prints "Result: !b!ro!ken!!".
   free(tmp);
}
\endcode
*/
char* y_get_cleansed_parameter(const char* param_name, char replacement)
{
   char* result;
   unsigned long result_size;
   size_t param_eval_size = strlen(param_name) +3; // parameter name + "{}" + '\0' (end of string)
   char* param_eval_string = y_mem_alloc(param_eval_size);
   //lr_log_message("y_cleanse_parameter(%s)", param_name );

   // Get the contents of the parameter using lr_eval_string_ext() - we can't use the
   // regular version if we expect to find NULL in there.
   snprintf( param_eval_string, param_eval_size, "{%s}", param_name );
   lr_eval_string_ext(param_eval_string, param_eval_size-1, &result, &result_size, 0, 0, -1);
   if( strcmp(param_eval_string, result) == 0 )
   {
       lr_error_message("y_get_cleansed_parameter: Parameter %s does not exist.", param_name);
       lr_abort();
   }
   free(param_eval_string);

   //lr_log_message("Cleansing param %s, result starts with '%-*.*s' and contains %d bytes.", param_name, result_size, result_size, result, result_size);
   if (result_size) {
      char *ptr;
	  for(ptr = result; result_size--; ptr++)
	     if (*ptr == 0) *ptr = replacement;	  
	  
	  /*
      // Now replace NULL bytes (NULL) in the input with something else..
      for( result_strlen = strlen(result); result_strlen < result_size; result_strlen = strlen(result))
      {
         result[result_strlen] = replacement;
         //lr_log_message("Cleansing param %s, result now '%-*.*s' and contains %d bytes.", param_name, result_size, result_size, result, result_size);
      }*/
   }
   return result;
}
Exemple #14
0
/*!
\brief Copy a string into a ::malloc'd piece of memory using ::strdup(), and lr_abort() if the allocation fails.
See the ::strdup() C documentation for what it does. 
This is just a simple wrapper around it that catches the strdup return value and handles any errors by aborting the script.

\param [in] source The string to copy.
\returns A copy of the string, allocated via ::strdup().
\author Floris Kraak
*/
char* y_strdup(char* source)
{
    char* result = strdup(source);
    if (!result)
    {
        lr_error_message("Out of memory while calling strdup()");
        lr_abort();
    }
    return result;
}
Exemple #15
0
/*!
\brief Convert the content of a parameter to UPPERCASE. 

This will replace the content of the paramenter named in 'param_name' with the uppercased version.
Does not affect non-alphabetic characters.

\param [in] param_name The parameter to convert to uppercase.

\b Example:
\code
lr_save_string("aBcDeFgHiJ &*45#$@#)!({}", "Test");
lr_message(lr_eval_string("Original: {Test}\n"));
y_uppercase_parameter("Test");
lr_message(lr_eval_string("Altered: {Test}\n")); // prints "Altered: ABCDEFGHIJ &*45#$@#)!({}".
\endcode
\author Floris Kraak
*/
void y_uppercase_parameter(const char* param_name)
{
    char *result = y_get_parameter_or_null(param_name);
    if(result == NULL)
    {
        lr_error_message("Nonexistant parameter %s passed to y_uppercase_parameter(): Aborting.", param_name);
        lr_abort();
    }
    strupr(result);
    lr_save_string(result, param_name);
}
Exemple #16
0
// --------------------------------------------------------------------------------------------------
// Allocates a block of memory for a string
// Adds some simple checks to catch common errors.
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//        example usage:
//            char *test = y_mem_alloc(999);
//            ..
//            free(test);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
char *y_mem_alloc(const int size)
{
    char *buff;
    int mem = size * sizeof(char);
    
    if(mem <= 0)
    {
        lr_error_message("Requested non positive amounts (%d) of memory! Bailing out ..", mem);
        return NULL;
    }
    //lr_output_message("Dynamic allocation of %d bytes of memory", mem);
    
    if ((buff = (char *)malloc(mem)) == NULL) 
    {
        // Fixme: implement some generic error handling facility to send this stuff to.
        lr_error_message("Insufficient memory available, requested %d", mem);
        // If this happens you're pretty much screwed anyway.
        lr_abort();
    }
    return buff;
}
Exemple #17
0
/*!
\brief Allocates a character array and initializes all elements to zero
As ::y_mem_alloc(), but using the '::calloc' function, rather than '::malloc()'.

\param [in] length Expected number of characters.
\param [in] size How much space a single character requires. Usually this should contain "sizeof char".
\returns A pre-zeroed block of memory of the requisite size allocated using ::calloc().
\warning The memory resulting from this call will need to be freed using ::free().
\sa ::y_mem_alloc(), ::calloc()
*/
char *y_array_alloc(size_t length, size_t size)
{
    char *buff;
	buff = calloc(length, size);
    if (!buff)
    {
        lr_error_message("Insufficient memory available, requested %u * %u bytes", length, size);
        // If this happens you're pretty much screwed anyway.
        lr_abort();
    }
    return buff;
}
Exemple #18
0
// --------------------------------------------------------------------------------------------------
// create a random number (integer), between two values, including the boundaries(!)
// So, y_rand_between(0,4) can result in these values: 0,1,2,3,4
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//     example usage:
//         int random;        
//         random = y_rand_between(0, 10);        // generate a random number between 0 and 10.
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int y_rand_between(int lowerbound, int upperbound)
{
    int roll;

    if ((lowerbound>upperbound) || ((upperbound - lowerbound) == 0))
    {
        lr_error_message("y_rand called with nonsensical arguments. (lowerbound should be less than upperbound)");
        return -1;    //    hmmm. is this correct?
    }
    roll = y_rand() % ((upperbound + 1 - lowerbound)) + lowerbound;
    return roll;
}
Exemple #19
0
void fTestMe(char* sVar){
	char * sBuf;

	if((sBuf = (char *)malloc((strlen(sVar) + strlen(" was a bar fighter") + 2)* sizeof(char))) == NULL){
		lr_error_message("Out of memory error");
	}else{
		sprintf(sBuf,"%s was a bar fighter", sVar);
		lr_output_message(sBuf);
		
	}
	
	free(sBuf);
}
	int ReadFromFile()
	{
    //The rest of the script is responsible for reading in data from the external file created above and then deleting that file.
	//This IF statement checks that the file_path is valid and that the file can be opened.
	if ((file_stream = fopen(file_path, "r")) == NULL ) 
		{ 
        lr_error_message("Cannot open %s", file_path); 
        return -1; 
        } 

		//This IF statement returns the string which has been read into LoadRunner and saves it as "line"
		//Unless the End Of File is reached or if a reading error occurred. 
		if (fgets(cLine, 100, file_stream) == NULL) 
    		lr_output_message("fgets error"); 
	
		else 
		//Uncomment the following line for debugging - output contents of "cLine" array including trailing \n
        //lr_output_message( "Data from the external file is [%s]", cLine); 

		//This function writes the data from the external file without the trailing \n into a new array called cExtData 
		strncat ( cExtData, cLine, (strlen(cLine)-1) );
        lr_output_message( "Data from the external file is [%s]", cExtData); 

		//This IF statement returns an error if LoadRunner cannot close the external file.
		if (fclose(file_stream)) 
        lr_error_message("Error closing file %s", file_path); 

	//This is the command thich will delete the external temporary file
	//It starts by writing the DOS command into a string called "command"
	sprintf(cCommand, "del %s", file_path); 

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

	//Execute the DOS command "cCommand"
	system(cCommand); 

	}
Exemple #21
0
/*!
\brief Clean a parameter by replacing any embedded NULL (null) characters with a replacement character.

This would normally only happen if you have used to web_reg_save_param() and the result contains one or more null-character(s).
Any such characters are replaced with replacement_char and the result is stored in the original parameter.
When no null-character is found, the result is unaltered.

\warning Since the return value is allocated with malloc(), it will need to be freed using free() at some point.

\param [in] param_name The parameter to cleanse of nulls.
\param [in] replacement A character that replaces any embedded nulls found.
\warning Since this changes existing parameters be careful what types of parameters you use this on.

\b Example:
\code
{
   char buffer[11] = { '\0', 'b', '\0', 'r','o', '\0', 'k', 'e', 'n', '\0', '\0' };
   lr_save_var(buffer, 11, 0, "broken");
   y_cleanse_parameter_ext("broken", '!'); // will save "!b!ro!ken!!" into the "broken" parameter.
}
\endcode
*/
void y_cleanse_parameter_ext(const char* param_name, char replacement)
{
    if( param_name && strlen(param_name) )
    {
        char* result = y_get_cleansed_parameter(param_name, replacement);
        lr_save_string(result, param_name);
        lr_eval_string_ext_free(&result);
    }
    else
    {
        lr_error_message("Empty or NULL parameter name passed to y_cleanse_parameter_ext(): %s", param_name);
        lr_abort();
    }
}
Exemple #22
0
int wi_WriteDataToFile(char *szFileName, const char *szBuf, int len){
	
	// This code is explained at http://motevich.blogspot.com/2007/10/loadrunner-save-download-file-server.html?m=1
	// Used as an example at     http://www.pha.com.au/kb/index.php/Downloading_and_Saving_a_File_Using_LoadRunner
	
	int hFile;
    
	// lr_output_message(">> file=%s of %d. hFile=%d.",szFileName, len, hFile); // for debugging.
    hFile = fopen(szFileName,"wb");
    if (hFile == NULL){
        lr_error_message("Cannot create or open the file: %s of len=%d", szFileName, len);
        return LR_FAIL;
    }
    fwrite(szBuf, len, 1, hFile);
    fclose(hFile);

    return LR_PASS;
}  //wi_WriteDataToFile
Exemple #23
0
//
// Roll a random number between (and including) 0 and randMax, and tell us if that number falls 
// between the lower and upper bounds or not. (attention: boundaries are included!)
//
// Zero = No.
// One = Yes.
// Negative return values are errors and generally mean that arguments make no sense
//
// This is useful for pathing decisions: Say that at point P in a script a choice has to be made
// between continuing with actions A, B, and C. The decision is made based on a percentage:
// A = 10% chance, B = 50% chance, C = 40% chance. This function was written to support the code
// that would make this decision.
//
// Note: Mathematically speaking this approach has flaws.  A better method would roll the number
// just once, and then apply the boundary constraints to it repeatedly to make the decision.
// This needs further work (tm).
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//     example usage:
//         y_rand_in_sliding_window(1, 10, 20);
//         // Returns 1 if the random number rolled is 4, and 0 if the random number was 11.
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int y_rand_in_sliding_window(int lowerbound, int upperbound, int randMax)
{
    int roll;

    if( (0>lowerbound) || (lowerbound>upperbound) || (upperbound > randMax) || (randMax <= 0))
    {
        lr_error_message("y_rand_in_sliding_window called with nonsensical arguments: ( 0 <= %d < %d <= %d ) == FALSE",
                        lowerbound, upperbound, randMax);
        return -1;
    }

    roll = y_rand_between(0, randMax);
    if( (roll >= lowerbound) && (roll <= upperbound) )
    {
        return 1;
    }

    return 0;
}
Exemple #24
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;
}
Exemple #25
0
vuser_init()
{
	char * sBuf;
	int iid;
	int	isid;
	char *sGroupname;
	
	lr_whoami(&iid, &sGroupname, &isid);

	if((sBuf = (char *)malloc((strlen(sGroupname) + 7)* sizeof(char))) == NULL){
		lr_error_message("Out of memory error");
	}else{
		sprintf(sBuf,"%s:%d",sGroupname, iid);
		lr_save_string(sBuf,"pVUID");
	}
	
	lr_output_message("TIVMsg: Group name: %s", sBuf);
	
	free(sBuf);
	
	return 0;
}
Exemple #26
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
Exemple #27
0
Portfolio()
{
	lr_think_time(1);
	lr_start_transaction("Portfolio");


	status = web_url("Portfolio2",
		"URL=http://{Server}/TRADE/portfolio.aspx",
		"Resource=0",
		"RecContentType=text/html",
		"Referer=http://{Server}/trade2/Order.aspx",
		"Snapshot=t81.inf",
		"Mode=HTTP",
		LAST);
if (status == LR_FAIL)
{
     lr_error_message("Error: %s", "Portfolio Failed - Aborted VU");
     lr_abort();
}


lr_end_transaction("Portfolio", LR_AUTO);
return 0;
}
Exemple #28
0
// --------------------------------------------------------------------------------------------------
// y_write_to_file()
//       writes content (a string) to a file.
// @author: Raymond de Jongh
// Example:
//      y_write_to_file("c:\\test.txt", "Write this to a file!");
// --------------------------------------------------------------------------------------------------
int y_write_to_file(char *filename, char *content)
{
   long file;
   int result;

   lr_message("LOGGING: %s", content);

   if ((file = fopen(filename, "at")) == NULL)
   { 
       lr_error_message ("Cannot write to file >>%s<<", filename); 
       return -1;             // failed to open file...
   } 
   if (result = fprintf(file, "%s\n", content) <0)
   {
       return result;        // failed to write to file...
   }

   if (result = fclose(file)!=0)
   {
       return result;        // failed to close file...
   }

   return 0;                // everything worked great!
}
Exemple #29
0
/*!
\brief Split a string into 2 parts using the search string. Save the rightmost part into the result parameter.
This is almost the same as y_right(), but doesn't stop at the first match - instead, it uses the *last* match.
It's pretty much the difference between 'greedy' and 'not greedy' in a regular expression..

\param [in] original_parameter The parameter to search.
\param [in] search The text preceding the text we're looking for.
\param [in] result_parameter The name of the parameter to store the result in.

\b Example:
\code
lr_save_string("AstrixObelixIdefix", "Test");
lr_message(lr_eval_string("Original: {Test}\n"));    // {Test}=AstrixObelixIdefix
y_right( "Test", "Obelix", "Test4" );
lr_message(lr_eval_string("New Param: {Test4}\n"));    //    {Test4}=Idefix
\endcode
\author Floris Kraak
*/
void y_last_right( const char *original_parameter, const char *search, const char *result_parameter)
{
    char *result = y_get_parameter_or_null(original_parameter);
    if( result == NULL )
    {
        lr_error_message("y_last_right(): Error: Parameter %s does not exist!", original_parameter);
        lr_abort();
    }
    else if( search == NULL || strlen(search) == 0 )
    {
        lr_save_string(result, result_parameter);
        lr_log_message("Warning: Empty search parameter passed to y_last_right()");
        return;
    }
    else
    {
        char *posPtr;
        //lr_log_message("y_last_right: original=%s, search=%s, resultParam=%s", original, search, resultParameter);
        do 
        {
            posPtr = (char *)strstr(result, search);
            //pos = (int)(posPtr - result);
            //lr_log_message("pos = %d", pos);
    
            // not found, save what we have as the result.
            if( posPtr == NULL )
            {
                lr_save_string(result, result_parameter);
                return;
            }
            // found, update the result pointer and go find more..
            result = posPtr + strlen(search);
        } 
        while(1);
    }
}
Exemple #30
0
MySQLTemplate()
{
	int rc = 0;

    MYSQL *db_connection; 
    MYSQL_RES *query_result; 
    MYSQL_ROW result_row; 
    
    char *server = "localhost";
    char *user = "******";
    char *password = "******"; 
    char *database = "LRDB";
    int port = 3306; // default MySQL port

	//static char *server_options[] = { "mysql_test", "--defaults-file=my.cnf" };
	//int num_elements = sizeof(server_options)/ sizeof(char *);
    
    lr_whoami(&vuser_id, &vuser_group, &scid);
	lr_message( "Group: %s, vuser id: %d, scenario id %d", vuser_group, vuser_id, scid);

	if (vuser_id == -1) {
		vuser_id = 1;
	}

	rc = lr_load_dll("C:\\Program Files\\MySQL\\MySQL Server 5.0\\lib\\opt\\libmysql.dll");
    // You should be able to find the MySQL DLL somewhere in your MySQL install directory.
    if (rc != 0) {
        lr_error_message("Could not load libmysql.dll");
        lr_abort();
    }
    
    // Allocate and initialise a new MySQL object
    db_connection = mysql_init(NULL);
    if (db_connection == NULL) {
        lr_error_message("Insufficient memory");
        return -1;
    }

	  // Connect to the database
    if (mysql_real_connect(db_connection, server, user, password, database, port, NULL, 0) == NULL) {
		lr_error_message("error on connect: %s\n", mysql_error(db_connection));
		return -1;
	}

    if (mysql_query(db_connection, "SELECT * FROM LATLogin;")!= 0) {
		lr_error_message("error on query: %s\n", mysql_error(db_connection));
		return -1;
	}

	if ((query_result = mysql_store_result(db_connection)) == NULL) {
		lr_error_message("error on store: %s\n", mysql_error(db_connection));
		return -1;
	}

    while (result_row = mysql_fetch_row(query_result)) {
		lr_output_message("%s - %s", result_row[0]);
	}
	mysql_free_result(query_result);
	

    // Free the MySQL object created by mysql_init
    mysql_close(db_connection);
	mysql_server_end();

	return 0;
}