​在LoadRunner中查找和替换字符串​

参考《Search & Replace function for LoadRunner》:

http://ptfrontline.wordpress.com/2009/03/13/search-replace-function-for-lr/


LoadRunner中没有直接的函数支持查找并替换字符串,因此可以封装一个lr_replace函数出来:

// ----------------------------------------------------------------------------
//
// Description:
// Search for and replace text within a string.
//
// Parameters:
// src (in) - pointer to source string
// from (in) - pointer to search text
// to (in) - pointer to replacement text
//
// Returns:
// Returns a pointer to dynamically-allocated memory containing string
// with occurences of the text pointed to by 'from' replaced by with
// the text pointed to by 'to'.
//
// Notes:
// Do not use this directly in scripts unless you are a more advanced
// user who knows C and string handling. See below for the function you
// should use!
//
// ----------------------------------------------------------------------------
char *strReplace(const char *src, const char *from, const char *to)
{
char *value;
char *dst;
char *match;
int size;
int fromlen;
int tolen;

// Find out the lengths of the source string, text to replace, and
// the replacement text.
size = strlen(src) + 1;
fromlen = strlen(from);
tolen = strlen(to);

// Allocate the first chunk with enough for the original string.
value = (char *)malloc(size);

// We need to return 'value', so let's make a copy to mess around with.
dst = value;

// Before we begin, let's see if malloc was successful.
if ( value != NULL )
{
// Loop until no matches are found.
for ( ;; )
{
// Try to find the search text.
match = (char *) strstr(src, from);
if ( match != NULL )
{
// Found search text at location 'match'.
// Find out how many characters to copy up to the 'match'.
size_t count = match - src;

// We are going to realloc, and for that we will need a
// temporary pointer for safe usage.
char *temp;

// Calculate the total size the string will be after the
// replacement is performed.
size += tolen - fromlen;

// Attempt to realloc memory for the new size.
//
// temp = realloc(value, size);
temp = (char *)realloc(value, size);

if ( temp == NULL )
{
// Attempt to realloc failed. Free the previously malloc'd
// memory and return with our tail between our legs.
free(value);
return NULL;
}

// The call to realloc was successful. But we'll want to
// return 'value' eventually, so let's point it to the memory
// that we are now working with. And let's not forget to point
// to the right location in the destination as well.
dst = temp + (dst - value);
value = temp;

// Copy from the source to the point where we matched. Then
// move the source pointer ahead by the amount we copied. And
// move the destination pointer ahead by the same amount.
memmove(dst, src, count);
src += count;
dst += count;

// Now copy in the replacement text 'to' at the position of
// the match. Adjust the source pointer by the text we replaced.
// Adjust the destination pointer by the amount of replacement
// text.
memmove(dst, to, tolen);
src += fromlen;
dst += tolen;
}
else // No match found.
{
// Copy any remaining part of the string. This includes the null
// termination character.
strcpy(dst, src);
break;
}
} // For Loop()
}
return value;
}

// ----------------------------------------------------------------------------
//
// Description:
// Find and replace text within a LoadRunner string.
//
// Parameters:
// lrparam (in) - pointer to LoadRunner Parameter Name
// findstr (in) - pointer to text top search for
// replacestr (in) - pointer to text to use as replacement
//
// Returns:
// Returns an integer. 0=Error, 1=Success.
//
// Example:
// lr_save_string( "This is a small test of the search and replace function", "LRParam");
// lr_replace( "LRParam", "a", "-x-" );
// lr_output_message( "%s", lr_eval_string("{LRParam}") );
//
// ----------------------------------------------------------------------------
int lr_replace( const char *lrparam, char *findstr, char *replacestr )
{
int res = 0;
char *result_str;
char lrp[1024];

// Finalize the LR Param Name
sprintf( lrp, "{%s}", lrparam);

// Do the Search and Replace
result_str = strReplace( lr_eval_string(lrp), findstr, replacestr );

// Process results
if (result_str != NULL )
{
lr_save_string( result_str, lrparam );
free( result_str );
res = 1;
}
return res;
} // EOF



在脚本中引用包括上面代码的头文件“lr_replace.h”,使用lr_replace函数的例子如下所示:



#include "lr_replace.h"

Action()
{

// Store a string into "MyPar" parameter
lr_save_string("This is a string", "MyPar");

// For examples sake, convert it to URL encoded format
web_convert_param( "MyPar",
"SourceEncoding=PLAIN",
"TargetEncoding=URL", LAST);

// Output the current result
lr_output_message("%s", lr_eval_string("{MyPar}"));

// Replace the ? characters with %20
lr_replace("MyPar", "+", "%20" );

// Output new result
lr_output_message("%s", lr_eval_string("{MyPar}"));


return 0;
}


​为LoadRunner写一个lr_save_float函数​

LoadRunner中有lr_save_int() 和lr_save_string() 函数,但是没有保存浮点数到变量的lr_save_float函数。《lr_save_float() function for LoadRunner》这篇文章介绍了如何写一个这样的函数:

http://ptfrontline.wordpress.com/2010/01/27/lr_save_float-function-for-loadrunner/

void lr_save_float(const float value, const char *param, const int decimals)
// ----------------------------------------------------------------------------
// Saves a float into a lr variable, much like lr_save_int() saves an integer
//
// Parameters:
// value Float value to store
// param Loadrunner variable name
// decimals Number of decimals in the result string
//
// Returns:
// N/A
//
// Example:
// lr_save_float(123.456, "myVar", 2); // myVar = 123.46 (includes rounding)
//
// ----------------------------------------------------------------------------
{
char buf[64]; // if more>63 digits -> your problem <IMG class="wp-smiley" alt=:) src="http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif">
char formatbuf[16]; // 16 chars should be adequate

sprintf( formatbuf, "%%.%df", decimals); // Build the "%?.f" format string
sprintf( buf, formatbuf, value); // sprintf the value
lr_save_string( buf, param); // store in variable
}



使用例子如下:

#include "lr_save_float.h"

vuser_init()
{
lr_save_float(123.456, "myVar", 2);
lr_output_message(lr_eval_string("{myVar}"));
return 0;
}



​LoadRunner中调用SHA1算法加密字符串​

 

​在LoadRunner中转换字符串大小写的C语言函数​

封装ConvertToXXX函数:
//ConvertToUpper function
int ConvertToUpper(char * sInput, char * sNew)
{
sInput = (char *)strupr(sInput);
lr_save_string(sInput,sNew);
}

//ConvertToLower function
int ConvertToLower(char * sInput, char * sNew)
{
sInput = (char *)strlwr(sInput);
lr_save_string(sInput,sNew);
}

//ConvertToTitle function
int ConvertToTitle(char * sInput, char * sNew)
{
int i = 0, s = 0, l = 0;
char buf1[50];
char buf2[2];
char n;

// Copy a single character into the address of [n]
strncpy(&n,sInput+i,1);
// Copy the single character into buf2
sprintf(buf2,"%c",n);
// Convert the contents of buf2 to uppercase
strupr(buf2);
// Overwrite the contents of buf1 with buf2
strcpy(buf1,buf2);
i++;
while(i < strlen(sInput))
{
// Overwrite buf2 with one character
strncpy(&n,sInput+i,1);
sprintf(buf2,"%c",n);
// If the previous character was a space then make the current character upper case
if(s == 1){
strupr(buf2);
strcat(buf1,buf2);
s = 0;
}
// Otherwise convert to lower case and concatenate the current character into the string buf1
else{
strlwr(buf2);
strcat(buf1,buf2);
}
// If the current character is a space set the value of [s] to [1] so that the next character gets capitalised
if(strcmp(" ",buf2)==0)
{
s = 1;
}
i++;
}
lr_save_string(buf1,sNew);
}

使用ConvertToXXX转换函数:
Action()
{
lr_save_string("testing is believing","str");
ConvertToUpper(lr_eval_string("{str}"),"UpperStr");
lr_output_message(lr_eval_string("{UpperStr}"));

ConvertToLower(lr_eval_string("{str}"),"LowerStr");
lr_output_message(lr_eval_string("{LowerStr}"));

ConvertToTitle(lr_eval_string("{str}"),"TitleStr");
lr_output_message(lr_eval_string("{TitleStr}"));

return 0;
}

输出:
Virtual User Script started at : 2010-01-30 17:53:13
Starting action vuser_init.
Web Turbo Replay of LoadRunner 9.50 SP1 for WINXP; WebReplay96 build 7045 (May 27 2009 14:28:58) [MsgId: MMSG-27143]
Run Mode: HTML [MsgId: MMSG-26000]
Run-Time Settings file: "D:/xlsoft/LR/MyTest/ConvertToXXXX//default.cfg" [MsgId: MMSG-27141]
Ending action vuser_init.
Running Vuser...
Starting iteration 1.
Starting action Action.
Action.c(63): TESTING IS BELIEVING
Action.c(66): testing is believing
Action.c(69): Testing Is Believing
Ending action Action.
Ending iteration 1.
Ending Vuser...
Starting action vuser_end.
Ending action vuser_end.
Vuser Terminated.

参考:
http://www.bish.co.uk/index.php?option=com_content&view=article&id=68%3Aloadrunner-c-functions-to-convert-the-case-of-a-captured-string&catid=34%3Arecent&Itemid=1