发布新日志

  • String Manipulation Functions

    2012-06-05 17:34:10

    String Manipulation functions allow you to manipulate or compare strings. These functions begin with the str prefix. Expand the category to view a list of the available functions.

    Function Name

    Description

    strcat

    Concatenates two strings.

    strchr

    Returns the pointer to the first occurrence of a character in a string.

    strcmp

    Compares two strings to determine the alphabetic order.

    strcpy

    Copies one string to another.

    strdup

    Duplicates a string.

    stricmp

    Performs a case-insensitive comparison of two strings.

    strlen

    Returns the length of a string.

    strlwr

    Converts a string to lower case.

    strncat

    Concatenates n characters from one string to another.

    strncmp

    Compares the first n characters of two strings.

    strncpy

    Copies the first n characters of one string to another.

    strnicmp

    Performs a case-insensitive comparison of n strings.

    strrchr

    Finds the last occurrence of a character in a string.

    strset

    Fills a string with a specific character.

    strspn

    Returns the length of the leading characters in a string that are contained in a specified string.

    strstr

    Returns the first occurrence of one string in another.

    strtok

    Returns a token from a string delimited by specified characters.

    strupr

    Converts a string to upper case.

     

     

     

    strdup //字符串复制

    strlwr //转换为小写字符

    strupr // 转换为大写字符

    strncat// 连接n个字符到另一字符串

     

    strcat

    //char *strcat(char *to,const char *from);

    char fullpath[1024],*filename="logfile.txt";

    strcpy(fullpath,"c:\\tmp\\");//字符串复制

    strcat(fullpath,filename);//字符串连接

    lr_output_message("Full path of file is %s",fullpath);

     

     

    strchr

    strrchr

    char *string ="His Excellency the Duke of Exeter";

    char *first_x,*last_x;

    //获取搜索字符第一次出现的位置以后的字符串,如:xcellency the Duke of Exeter

    first_x=(char *)strchr(string,'x');

    lr_output_message("The first occurrence of x: %s",first_x);

    //获取搜索字符最后一次出现的位置以后的字符串,如:xeter

    last_x=(char *)strrchr(string,'x');

    lr_output_message("The last occurrence of x: %s",last_x);

     

    strlen

        int is_digit, i = 0;

        char * str = "1234567k89";

        unsigned int len = strlen(str);

     

        do {

            if (i == len) {

                lr_output_message ("No letters found in string");

                return -1;

            }

                       //isdigit函数,返回十进制数非0(true),返回0(false)

            is_digit = isdigit(str[i++]);

        }

              //当为0是循环条件终止

        while (is_digit);

            lr_output_message ("The first letter appears in character %d of string", i);}

    strcmp

    stricmp

    strncmp

    strnicmp

    int result;

    char tmp[20];

    char string1[]="The quick brown dog jumps over the lazy fox";

    char string2[]="The QUICK brown dog jumps over the lazy fox";

     

    //大小写敏感(小写>大写)

    result = strcmp(string1,string2);

    if(result>0)

         strcpy(tmp, "greater than");

        else if(result < 0)

         strcpy(tmp, "less than");

        else

         strcpy(tmp, "equal to");

    lr_output_message("strcmpString1 is %s string2",tmp);

    //大小写不敏感(小写=大写)

    result = stricmp(string1,string2);

    if( result > 0 )

            strcpy( tmp, "greater than" );

        else if( result < 0 )

            strcpy( tmp, "less than" );

        else

            strcpy( tmp, "equal to" );

    lr_output_message( "stricmp: String 1 is %s string 2", tmp);

              // 比较string1string230个字符,大小写敏感

        result = strncmp( string1, string2 , 30);

        if (result > 0 )

            strcpy(tmp, "greater than");

        else if (result < 0)

            strcpy(tmp, "less than");

        else

            strcpy(tmp, "equal to");

    lr_output_message ("strncmp: String 1 is %s string 2", tmp);

              // 比较string1string230个字符,大小写不敏感

              result = strnicmp( string1, string2 , 30); 

        if (result > 0 )

            strcpy( tmp, "greater than");

        else if (result < 0)

            strcpy(tmp, "less than");

        else

            strcpy(tmp, "equal to");

        lr_output_message ("strnicmp: String 1 is %s string 2", tmp);

     

    strset

              char str[16];

        strcpy(str, "Fill me in");

        lr_output_message ("Before strset str=%s", str);

              lr_output_message("%d",strlen(str));//字符串长度为10

              // 用字符'x'填充

        strset(str, 'x');

        lr_output_message ("After strset str=%s", str);

     

    strspn

       char * str = "corroborative";

        int rc;

              //返回字符串'corroborative'首位是否包含'ro'

        if ((rc = strspn(str, "ro")) == 0)

            lr_output_message ("No o's or r's found");

        else

            lr_output_message ("%d of %d characters are an o or an r", rc, strlen(str));

              //返回字符串'corroborative'首位+1是否包含'ro'

        if ((rc = strspn(str + 1, "ro")) == 0)

            lr_output_message ("No o's or r's found");

        else

            lr_output_message ("%d of %d characters are an o or an r", rc, strlen(str));

     

    strstr

      int offset;

        char * position;

        char * str = "The quick brown dog jumps over the lazy fox";

        char * search_str = "dog";

              //返回搜索字符串'dog'str中的第一个位置

        position = (char *)strstr(str, search_str);

        // strstr has returned the address. Now calculate * the offset from the beginning of str

              //按照内存中的相对位置计算offset

        offset = (int)(position - str + 1);

        lr_output_message ("The string \"%s\" was found at position %d", search_str, offset);

     

     

    strtok

    extern char * strtok(char * string, const char * delimiters ); // Explicit declaration

        char path[] = "c:\\mercury\\lrun\\bin\\wlrun.exe";

              \\分隔符号为.\

        char separators[] = ".\\";

        char * token;

        token = (char *)strtok(path, separators); // 获取第一个token

        if (!token) {

            lr_output_message ("No tokens found in string!");

            return( -1 );

        }

        while (token != NULL ) {

                       //打印有效的token

            lr_output_message ("%s", token );

                       // 获取下一个token,后续调用必须传递NULL作为字符串parameter.

            token = (char *)strtok(NULL, separators);

  • Buffer Manipulation Functions

    2012-06-05 15:12:47

    Buffer Manipulation functions allow you to manipulate or compare characters stored in data buffers. These functions begin with the mem prefix. Expand the category to view a list of the available functions.

     

    Function Name

    Description

    memchr

    Searches for a character in a buffer.

    memcmp

    Compares two buffers.

    memcpy

    Copies n characters from one buffer into another.

    memmove

    Moves a number of bytes from one buffer to another.

    memset

    Sets n bytes of a buffer to a given character.

     

    memchr

    void *memchr(const void *s,int c,size_t n);

    s: The name of the buffer.

    c: The character to search for in the buffer.

    n:The number of characters at the beginning of the buffer to search.

     

    //以下的例子是在字符串"Example string"中搜索字符'x'出现的第一个位置

        char * p;

        char str[] = "Example xtring";

             //获取第一个字符在内存中的位置

             lr_output_message("The first character is at buffer %d",str);

             //搜索整个字符串,获取'x'在内存中的位置

        p = (char *)memchr(str, 'x', strlen(str));

        if (p) {

      //打印出获取'x'在内存中的位置

      lr_output_message ("Character x is at buffer %d\n", p);

      //打印出获取'x'在字符串中的位置,'x'的位置是内存中相对位置+1

      lr_output_message ("Character x is at position %d\n", p - str + 1);

      }

        else

            lr_output_message ("Character x was not found");

     

    memcmp

    int memcmp(const viod *s1,const void *s2,size_t n);

    s1: The name of a buffer.

    Se: The name of a buffer.

    n:The number of characters to search at the beginning of the buffer.

     

    //以下的例子是用memcmp来比较两个字符串是否相等。

    char *s1="access to shared transmission";

    char *s2="access to transmission";

    int rc;

    //通过memcmp返回值与0比较大写来确认字符串大小

    rc =memcmp(s1,s2,strlen(s1));

    if(rc>0)

    lr_output_message("'%s' is greater than '%s'",s1,s2);//s1>s2

    else if (rc<0)

    lr_output_message("'%s' is less than '%s'",s1,s2);//s1<s2

    else

    lr_output_message("'%s' is equal to '%s'",s1,s2);//s1=s2

     

     

    memcpy

    Void *memcpy(void *dest,const void *src,size_t n);

    dest: Destination buffer where the data is copied

    src: The name of the source buffer from which from the data is copied.

    n: The number of bytes to copy

     

    char s1[] = "Sample string",s3[]="Just testing";

    char s2[40],s4[40];

    /* +1是为了复制s1的结束符号(NULLterminator) */

    memcpy(s2, s1, strlen(s1)+1);

    lr_output_message("s1=%s s2=%s", s1, s2);

    /* -1使得s4比比s3少一位*/

    memcpy(s4, s3, strlen(s3)-1);

    lr_output_message("s3=%s s4=%s", s3, s4);

     

    memmove

    void *memmove(void *dest,const void *src,size_t n);

    dest:Destination buffer where the data is copied.

    src:The name of the source buffer from which the data is copied.

    n:The number of bytes to copy.

     

    char buffer[80];

    strcpy(buffer,"abcde");

    //'abcde'的前四位'abcd'拼接到自身字符串从第二位开始的位置''

    memmove(buffer+1,buffer,4);

    lr_output_message("New string: %s\n",buffer);

     

     

    memset

    void *memset(void *buffer,int c,size_t n);

    buffer:Pointer to block of data to be filled with c.

    c:The character placed in buffer.

    n:The number of bytes in buffer set as c.

    //在初始化之前memset填充结构about_app中所有元素为0

             //定义结构about_app

             struct about_app {

                       char *version;

                       int field1;

                       int field2;

             }a;

             //赋值

             a.field1=12;

             a.field2=13;

             //使用0填充所有的fields

             memset(&a,0,sizeof(struct about_app));

             //打印出所有的fields查看是否为0

             lr_output_message("After memset field1=%d field2=%d",a.field1,a.field2);

             //初始化结构,并赋初值。

             a.version="app version1.0";

             a.field1=5;

             a.field2=6;

             lr_output_message("Now,field1=%d field2=%d",a.field1,a.field2);

  • Data Type Conversion Functions

    2012-06-05 00:07:40

    Data Type Conversion functions allow you to convert strings from one data type to another. These functions contain the to phrase. Expand the category to view a list of the available functions.

    Click one of the following functions for more information:

    Function Name

    Description

    atof

    Converts a string to a floating point value.

    atoi

    Converts a string to an integer value.

    atol

    Converts a string to a long integer value.

    itoa

    Converts an integer to a string. Windows only.

    strtol

    Converts a string to a long integer using a given radix.

     

     

           例子:转换字符串s的初始部分为float数据

           double atof(const char *string);/* Explicit declaration */ //显示声明

           float x;

           char *s = "7.2339 by these hilts or I am a villain else";

           //转换为实型数据并以保留两位小数输出到输出窗口

           x=atof(s);

           lr_output_message("%.2f",x);

     

     

        例子:转换字符串s的初始部分为int数据

        int i;

        char * s = "7 dollars";

        //转换为整型数据

        i = atoi(s);

        lr_output_message ("Price $%d", i);

     

     

       //例子:转换字符串s的初始部分为long数据

        long atol(const char * s); // Explicit declaration  //显示声明

        long i;

        char * s = "2147483647 dollars";

        //转换为长整型

        i = atol(s);

        lr_output_message ("Price $%ld", i);

     

    例子:转换字整型把数据卫字符串数据

    int i=56;

    char filename[64].file_index[32];

    if(!itoa(i,file_index,10)

    lr_output_message("Cannot convert i to ascii char");

    else {

    sprintf(filename,"log_%s.txt",file_index);

    lr_output_message("New file name %s",filename);

    }

     

  • Character Classification and Conversion Functions

    2012-06-04 16:47:04

    Character Classification and Conversion Functions

     

    Character Classification and Conversion functions allow you to convert characters within a string. Expand the category to view a list of the available functions.

    Click one of the following functions for more information:

    Function Name

    Description

    tolower

    Converts a string to lowercase.

    toupper

    Converts a string to uppercase.

    isdigit

    Checks if a string is a decimal digit.

    isalpha

    Checks if a string is a letter.

     

    例子

    char character_set[]={'A','5','$','z','c'};

    int i;

    //将所有字符转换为大写

    for (i=0;i<5;i++) {

             lr_output_message("%c ",toupper(character_set[i]));

    }

    //将所有字符转换为小写

    for (i=0;i<5;i++) {

    lr_output_message("%c ",tolower(character_set[i]));

             }

     

    例子

    //Checks if a string is a decimal digit (characters `0' to `9').

    if(isdigit(55))

             lr_output_message("The value 55 is the digit %c",55);

    else

             lr_output_message("Value 55 is not a digit. It's the character %c",55);

    ////Checks if a string is a decimal digit (characters `0' to `9').

    if(isdigit(109))

             lr_output_message("The value 109 is the digit %c",109);

    else

             lr_output_message("Value 109 is not a digit. It's the character %c.",109);

     

    //The function isalpha checks to see if the value of interger falls within the ranges A - Z or a - z.

    if(isalpha(107))

             lr_output_message("The value 107 is %c",107);

    else

             lr_output_message("Value 107 is not alphabetic.It's the digit %d",107);

    //The function isalpha checks to see if the value of interger falls within the ranges A - Z or a - z.

    if(isalpha(22))

             lr_output_message("The value 22 is %c",22);

    else

             lr_output_message("The value 22 is not alphabetic. It's the digit %d",22);

     

  • LR File Manipulation Functions examples

    2012-06-04 16:01:24

    File Manipulation functions allow you to manipulate directories. Expand the category to view a list of the available functions.

    Click one of the following functions for more information:

    Function Name

    Description

    chdir

    Changes the current directory to the given path.

    chdrive

    Switches to another drive.

    getcwd

    Returns the name of the current working directory.

    getdrive

    Returns the name of the current drive.

    mkdir

    Creates a directory using the given path name.

    remove

    Deletes the specified file.

    rmdir

    Deletes the specified directory.

     

     

     

     

    例子:The following example uses mkdir to create a new directory, xyz. It then moves to the new directory.

    #ifdef unix

    char new_dir[]="/tmp/xyz"

    #else

    char new_dir[]="C:\\xyz";

    #endif

     

    //加载外部函数

    lr_load_dll("D:\Accessdll.dll");

    //动态文件中包含如下函数

    /*int file_exists(char *filename)

    return (access(filename,0)==0);*/

     

    //判断目录是否存在可以用

    if(file_exists(new_dir)) {

    lr_output_message("%s directory exists",new_dir);

    rmdir(new_dir);

    }

    //root目录下创建xyz目录,并设置其为当前目录

    if (mkdir(new_dir)) {

             lr_output_message("Create directory %s failed",new_dir);

             return -1;

    }

     

    else

    lr_output_message("Created new directory %s",new_dir);

     

    //变更目录

    if (chdir(new_dir)) {

             lr_output_message("Unable to change to dir %s",new_dir);

             return -1;

    }

    else

    lr_output_message("Changed to new dir %s",new_dir);*/

     

     

     

    例子:The following example uses chdrive to move to all available drives on the file system.

    It saves the original drive in curdrive, so it can be restored later.

    int drive,curdrive;

    //获取当前的盘符

    curdrive=getdrive();

    lr_output_message("Available drives are:");

    //循环读取本系统中所有的盘符

    for(drive=1;drive<=26;drive++)

             if(!chdrive(drive))

                lr_output_message("%c:",drive + 'A'-1);

             chdrive(curdrive);

     

     

     

    例子:This example uses getcwd to save the current directory, before moving to a new directory.

    It then moves back to the first directory.

    #define DIR_LEN 512

    char original_dir[DIR_LEN];

    #ifdef unix

    char new_dir[]="/tmp";

    #else

    char new_dir[]="C:\\";

    #endif

    //getcwd如果成功返回当前的字符串,否则返回空值

    if (!getcwd(original_dir,DIR_LEN)) {

    lr_output_message("getcwd error");

    return -1;

    }

    else

    lr_output_message("The current dir is: %s",original_dir);

    if (chdir(new_dir)) {

             lr_output_message("Unable to locate directory:%s",new_dir);

             return -1;

    }

    else

    lr_output_message("Changed dir to %s",new_dir);

    if (chdir(original_dir)) {

             lr_output_message("Cannot move back to #s",original_dir);

             return -1;

    }

    else

    lr_output_message("Move back to %s",original_dir);

     

     

     

    例子:/*The system function executes a dir command.

    The output of the command is written (using `>) to the newly created file.

    The content of the file should be a list of the contents of the C drive.

    It then deletes the new file with remove*/

     

    char filename[1024],command[1024];

    char new_dir[]="C:\\xyz";

    extern int errno;

     

    //root下创建xyz目录,并设为当前目录

    if(mkdir(new_dir))

             lr_output_message("Create directory %s failed",new_dir);

    else

    lr_output_message("Created new directory %s",new_dir);

    //filename赋值为C:\xyz\newfile.txt

    sprintf(filename,"%s\\%s",new_dir,"newfile.txt");

    //command赋值为dir C:\ > C:\xyz\newfile.txt /w

    sprintf(command,"dir /b C:\\ > %s /w",filename);

    //运行命令:dir /b C:\ > C:\xyz\newfile.txt /w

    system(command);

    lr_output_message("Create new file %s",filename);

     

    //删除已经建立的文件

    if (remove(filename) == 0)

            lr_output_message ("Removed new file %s", filename);

        else

            lr_output_message ("Unable to remove %s error %d", filename, errno);

     

    例子:/*在windows系统,用LR中的system函数执行系统命令,在LR中利用C函数建立文件,写文件,读文件。
      主要相关函数:sprintf/fopen/fgetc/fread/fclose*/
      int count,total=0,i;
         char buffer[1000];
         long file_stream;
         char filename[1024], command[1024],line[100];
         char new_dir[] = "C:\\test";
         if (mkdir(new_dir))
              lr_output_message("Create directory %s failed", new_dir);
         else
              lr_output_message("Created new directory %s", new_dir);
         sprintf (filename, "%s\\%s", new_dir, "newfile.txt");
         sprintf (command, "dir /b c:\\ > %s /w", filename );
         system(command);//通过DOS管道命令创建TXT文件
         lr_output_message("Created new file %s", filename);
      //以只读方式打开文件
       if((file_stream=fopen(filename,"r"))==NULL)
           {
           lr_error_message("can not open %s",filename);
           return -1;
       }
       //逐行读取TXT文件中的字符串
       for(i=1;i<10;i++)
        {
           if (fgets(line, 100, file_stream) == NULL)
              lr_output_message("fgets error" );
         else 
              lr_output_message( "The line%d is: %s",i,line);
        }
    //如果已经到文件结尾,计算总得字节数
        while(!feof(file_stream))
                  {
          count=fread(buffer,sizeof(char),1000,file_stream);
           lr_output_message("%3d read",count);

     //Checks if any error has occurred during file I/0.
        if(ferror(file_stream))
                  {
        lr_output_message("error reading file %s",filename);
        break;
            }
    //把计算后的Count赋值给total
       total+=count;
            }
          lr_output_message("Total number of bytes read = %d",total);

         if(fclose(file_stream))//关闭文件
          lr_error_message("Error closing file %s",filename);

  • LR文件输入输出函数

    2012-06-03 11:18:36

    Input Output functions allow you to read and write to files. Most of these functions begin with an f prefix. Expand the category to view a list of the available functions.

     

    Function Name

    Description

    fclose

    Closes a file.

    feof

    Checks if the end of file has occurred on a stream.

    ferror

    Checks if any error has occurred during file I/0.

    fgetc

    Gets a character from a stream.

    fgets

    Reads a string from a file.

    fopen

    Opens a file for buffered I/0.

    fprintf

    Writes formatted output to a file.

    fputc

    Writes a character to a stream.

    fread

    Reads unformatted data from a stream into a buffer.

    fscanf

    Reads formatted input from a stream.

    fseek

    Sets the current position in a file to a new location.

    fwrite

    Write unformatted data from a buffer to a stream.

    rewind

    Rewinds a file.

    sprintf

    Writes formatted output to a string.

    sscanf

    Reads formatted input from a string.

     

     

     

     

    例子:The following example opens a log file and writes the string to it using fputc.

        //预处理命令之条件编译,如果已经定义了#define,取#ifdef,现取#else部分

        #ifdef unix

            char * filename = "/tmp/logfile.txt";

        #else

            char * filename = "D:\\logfile.txt"; //运行前现在路径下建立文件

        #endif

     

        long file; //使用long来取代文件指针File *fp来声明变量

        char * p, str[] = "this is the first line of the log file";

        int c;

     

        //创建新文件

        //通过判断file的值与NULL是不是相等来验证文件是否正常打开

        if ((file=fopen(filename,"w+"))==NULL) {

            lr_output_message("Unable to create %s",filename);

            return -1;

        }

        //向文件中写入字符串

        p = str; //p指针指向数组str的第一个字符

        //文本文件结束标记EOF,十进制为-1,十六进制为oxffwhile后跟一空语句

        while ((*p != NULL) && fputc(*(p++), file) != -1);

        fclose(file);

     

     

       例子:The following example, for Windows platforms, opens a file and reads 3 characters into a buffer using fgetc.

       #define NUM_CHARS 3

       int i,total=0;

       char buffer[100],ch;

       long file;

       char *filename="D:\\readme.txt";

       //只读方式打开文件,并且file指向文件,如果为NULL,文件为正常打开

       if((file=fopen(filename,"r"))==NULL) {

           lr_error_message ("Cannot open %s", filename);

            return -1;

       }

       //feof未读取到文件末尾返回0,否则返回非零值

       for (i=0; (i<NUM_CHARS) && (feof(file) == 0); i++) {

           ch=fgetc(file);

           buffer[i]=ch;

       }

     

       buffer[i]=NULL;

       lr_output_message("First %d characters of file %s are \"%s\"",NUM_CHARS,filename,buffer);

       if (fclose(file))//文件关闭成功返回0,否则返回EOF

       lr_error_message ("Error closing file %s", filename);

     

     

     

       例子:The following example, for Windows platforms, opens a file and reads the first line using fgets.

        int i,total=0;

        char line[100],ch;

        long file;

        char *filename ="D:\\readme.txt";

        ////通过判断   file的值与NULL是不是相等来验证文件是否正常打开

        if((file=fopen(filename,"r"))==NULL) {

            lr_error_message("Cannot open %s",filename);

            return -1;

        }

        //获得文件中第一行字符串

        if((fgets(line,100,file)==NULL))

           lr_output_message("fgets error");

        else

            lr_output_message("The first line is \"%s\"",line);

        if(fclose(file))

            lr_error_message("Error closing file %s",filename);

     

       例子:The following example opens a log file and writes the id number and group name of the Virtual User to it using fprintf.

       //预处理命令之条件编译,如果已经定义了#define,取#ifdef,现取#else部分

        #ifdef unix

            char * filename = "/tmp/logfile.txt";

        #else

            char * filename = "D:\\logfile.txt";

        #endif

     

        long file;

        int id;

        char * groupname;

        // <span style='fon

  • 编译预处理#define

    2012-06-02 12:18:29

    编译预处理在Loadrunner应用的例子:
     
    例一:结果1
    #define SQR(X) X*X
    int a=10,k=2,m=1;
    a/=SQR(k+m)/SQR(k+m);
    //printf("%d",a);
    lr_output_message("%d",a);
     
    例二:结果48
    #define N 3
    #define Y(n) ((N+1)*n)
    lr_output_message("%d",2*(N+Y(5+1)));
     
    例三:结果8
    #define MA(X)  X*(X-1)
    int a=1,b=2;
    lr_output_message("%d",MA(1+a+b));
     
    例四:结果97,c
    #define STR "%d,%c"
    #define A 97
    lr_output_message(STR,A,A+2);
    例五:结果9911
     
    #define PR(ar) lr_output_message("%d",ar)
     int j,a[]={1,3,5,7,9,11,13,15},*p=a+5;
    for (j=3;j;j--) {
     switch (j) {
     case 1:
     case 2: PR(*p++);break;
     case 3: PR(*(--p));
     }
    }
    例六:结果7
    #define MAX(x,y) (x)>(y)?(x):(y)
    int a=5,b=2,c=3,d=3,t;
    t=MAX(a+b,c+d)*10;
    lr_output_message("%d\n",t);
     
    例七:结果9
    #define POWER(x) (x)*(x)
    int a=1,b=2,t;
    t=POWER(a+b);
    lr_output_message("%d\n",t);
     
    例八:结果10
    #define A 2
    #define B 3*A
    #define C B+A
    lr_output_message("%d\n",C*2);
     
     
     
     
     
     
     
     

     
  • LR耗时统计函数例子

    2012-05-30 16:22:23


    /*********************************
    说明:LoadRunner中每一步都是需要消耗时间的。
    所谓耗时(Wasted Time)解释如下:
    Wasted time is time spent on activities whose purpose is to support test analysis, but would never be performed by a browser user, for example, time spent keeping transaction statistics for later reporting. Wasted time is calculated internally by LoadRunner. Your script. can also add wasted time with lr_wasted_time.

    Sometimes, you may enter activities in a script. that your do not want reported as part of the transaction statistics. Generally, these are activities related to record keeping, logging, or custom analysis. If you enhance the script. with steps whose durations should not be included in the test statistics, you can track the time used by these steps with lr_start_timer and lr_end_timer. Then, the function lr_wasted_time is used for adding this user-determined time to the internally generated wasted time.

    You can retrieve the total wasted time (both that generated by LoadRunner automatically and that added with lr_wasted_time) with the function lr_get_transaction_wasted_time, or with lr_get_trans_instance_wasted_time, as appropriate. *///*******************************

    Action()
    {
        int i, baseIter = 1000;
        char dude[1000];
        double wasteTime, actualElapsedTime;
        merc_timer_handle_t MasterT, timer;

        // Examine the total elapsed time of the action
     // MasterT以秒为单位并以此为开始计算时长起点(秒)
        MasterT = lr_start_timer();
     
        lr_start_transaction("Demo"); //Start transaction

        // Create some elapsed time for the transaction
        for (i=0; i< (10 * baseIter); ++i)
                sprintf(dude,
                    "This is the way we create elapsed time artificially = %d", i);       

     // Add some think time
        lr_think_time(0.5);

        // Create some wasted time and record it with timer
        timer = lr_start_timer(); ////timer以秒为单位并以此为计算时长起点(秒)。
        for (i=0; i< (5 * baseIter); ++i)
                sprintf(dude,
                    "This is the way we waste time in a script. = %d", i);

        wasteTime = lr_end_timer(timer); //停止timer计时器,并返回消耗的时长(秒)。
        lr_output_message("User created waste time = %lf", wasteTime);
        lr_output_message("Before lr_waste_time: Duration = %lf - Waste = %lf",        
            lr_get_transaction_duration("Demo"),
            lr_get_transaction_wasted_time("Demo"));

        /* Convert Timer in seconds to wasted time in milliseconds
         and add to internally generated waste time */
        wasteTime *= 1000;
        lr_wasted_time(wasteTime);

        lr_output_message("After lr_waste_time: Duration = %lf - Waste = %lf",
                lr_get_transaction_duration("Demo"),
                lr_get_transaction_wasted_time("Demo"));

        lr_output_message("Think time = %lf",
            lr_get_transaction_think_time("Demo"));

        lr_end_transaction("Demo", LR_AUTO);
        actualElapsedTime = lr_end_timer(MasterT); //统计总耗时(秒)。
        lr_output_message("Total Elapsed time for Action = %lf", actualElapsedTime);

        return 0;

    }


     

  • 用脚本实现向Oracle表中插入数据

    2011-04-15 15:17:53


    首先,安装及环境配置

    1. 安装Oracle - OraClient10g_home2


    2. Net Configuration Assistant 配置步骤:

    假设数据库所在服务器IP地址为:  192.168.0.1

    数据库实例名为:ora92

    用户名: umap

    密码:umap

    第一步:打开配置程序

    位于:程序-->Oracle - OraClient10g_home2-->Configuration and Migration Tools-->Net Configuration Assistant ;

    第二步:选择配置项:

    打开程序后,出现的界面中有四个选项, 分别为(1)监听程序配置,(2)命名方法配置,(3)本地NET服务名配置,(4)目录使用配置. 这里我们选择第3个,点下一步

    第三步:根据需要选择操作内容,是添加还是对以前的配置进行修改或删除;

    第四步:根据您要连接的Oracle数据据库版本选择, 这里我们选择Oracle8i或更高版本数据库或服务;

    第五步:服务名,输入示例中的实例名;

    第六步:选择TCP;

    第七步:主机名:输入示例中的IP地址; 使用默认端口1521;

    第八步:使用您的登录帐户与密码进行连接测试,正常情况下测试通过。

    第九步:打开:程序-->Oracle - OraClient10g_home2-->Application Developer-->SQL Plus
    录入select * from dual;回车,有数据返回,则连接正常。

     

    然后,脚本录制

    第一步:打开Loadrunner,选择Oracle(2-Tier)协议
    Start Recording设置
    Application Type:Win32Applications
    Program to Record:选择sqlplus可执行程序的路径,如D:\oracle\product\10.2.0\client_2\BIN\sqlplusw.exe
    Record into Action:vuser_init

    第二步:开始录制
    输入:用户名(U),口令(P),主机字符串(H)
    点击确定按钮

    第三步:选择Action
    键入insert into lis.lcoldinfo (SERIALNO, CONTNO, PROPOSALCONTNO, CUSTOMERNO, CUSTOMERTYPE, NAME, SEX, BIRTHDAY, AGE, IDTYPE, IDNO, POLNO, RISKCODE, MAINPREM, PREM, PAYMONEY, HEALTHIMPARTFLAG, HEALTHIMPART1, HEALTHIMPART2, MANAGECOM, OERATOR, MAKEDATE, MAKETIME, MODIFYDATE, MODIFYTIME, STANDBYFLAG1, STANDBYFLAG2, STANDBYFLAG3, STANDBYFLAG4, STANDBYFLAG5)""values ('{Value_Pv}', '000', '6001237544', 'T000067060', '1', '李芬', '1', to_date('10-04-1983', 'dd-mm-yyyy'), 25, '0', '410103198304107040', '110600000004237', 'BENE11', 7680.00, 7680.00, 0.00, '3', '', '', '8660000000', '001', to_date('15-01-2009', 'dd-mm-yyyy'), '17:16:11', to_date('15-01-2009', 'dd-mm-yyyy'), '17:16:11', '', '', '', '', '';

    回车
    键入commit;回车

    第四步:选择vuser_end
    键入quit;回车
    停止录制

    第五步:修改Action部分脚本:
    Action()
    {

    int i;
    lr_output_message("当前时间为%s",lr_eval_string("{NewParam}"));


    for (i=0;i<4;i++) {

     char Value_P[20]="";
     char Value_Pv[20]="";
     char path[20]="";
     char separator[]=".";
     char * token;
     strcat(path,lr_eval_string("{DateTime}"));
     token = (char *)strtok(path,separator);
     if(!token){
      lr_output_message("No token found in string!);
            return(-1);
            }
     while(token != Null) {
      strcat(Value_P,lr_eval_string(token));
      token =(char*)strtok(NULL,separator);
            }
     strcat(Value_P,lr_eval_string("{VuserId}"));
     lr_eval_string(Value_P,"Value_Pv");
        lr_output_message( "当前流水号为 %s", lr_eval_string("{Value_Pv}") );

     //插入数据的过程中需要注意:ORA-00001:违反唯一约束条件-----------------------------------------------insert
      
    lrd_ora8_handle_alloc(OraEnv1, STMT, &OraStm7, 0);
    lrd_ora8_stmt(OraStm7, "insert into lis.lcoldinfo (SERIALNO, CONTNO, PROPOSALCONTNO, CUSTOMERNO, CUSTOMERTYPE, NAME, SEX, BIRTHDAY, AGE, IDTYPE, IDNO, POLNO, RISKCODE, MAINPREM, PREM, PAYMONEY, HEALTHIMPARTFLAG, HEALTHIMPART1, HEALTHIMPART2, MANAGECOM, OERATOR, MAKEDATE, MAKETIME, MODIFYDATE, MODIFYTIME, STANDBYFLAG1, STANDBYFLAG2, STANDBYFLAG3, STANDBYFLAG4, STANDBYFLAG5)"
    "values ('{Value_Pv}', '000', '6001237544', 'T000067060', '1', '李芬', '1', to_date('10-04-1983', 'dd-mm-yyyy'), 25, '0', '410103198304107040', '110600000004237', 'BENE11', 7680.00, 7680.00, 0.00, '3', '', '', '8660000000', '001', to_date('15-01-2009', 'dd-mm-yyyy'), '17:16:11', to_date('15-01-2009', 'dd-mm-yyyy'), '17:16:11', '', '', '', '', '')", 1, 32, 0);
      lrd_ora8_exec(OraSvc1, OraStm7, 1, 0, &uliRowsProcessed, 0, 0, 0, 0,  0);lrd_ora8_exec(OraSvc1, OraStm7, 1, 0, &uliRowsProcessed, 0, 0, 0, 0,  0);
    lrd_handle_free(&OraStm7, 0);
    }  //循环结束

    lr_output_message("当前时间为%s",lr_eval_string("{NewParam}"));
    return 0;

    }

    第六步:脚本完成


     

  • Loadrunner8.1 + JDK1.5如何解决System Exceptions: EXCEPTION_ACCESS_VIOLATION

    2011-04-14 15:38:40

    Java Vuser协议的遇到Exception was raised when calling abort-cleanup function in extension java_int.dll: System Exceptions: EXCEPTION_ACCESS_VIOLATION问题,现讲解下这个问题的解决方法。


    首先,保证纯净的操作系统


    我之前装的是Loadrunner9.5,准备配JDK1.6,最后怎么都是报错,然后采用Loadrunner8.1 + JDK1.5问题依旧,最后重装了系统,采用Loadrunner8.1 + JDK1.5问题解决。连网上说的A_lrunner_java_protocol_fixes_Feb_05.exe的补丁也未打。

    其次:确认JDK环境变量是否正确设置
    Windows xp下配置JDK环境变量:
          1.安装JDK,安装过程中可以自定义安装目录等信息,例如我们选择安装目录为D:\java\jdk1.5.0_08;
      2.安装完成后,右击“我的电脑”,点击“属性”;
          3.选择“高级”选项卡,点击“环境变量”;
          4.在“系统变量”中,设置3项属性,JAVA_HOME,PATH,CLASSPATH(大小写无所谓),若已存在则点击“编辑”,不存在则点击“新建”;
          5.JAVA_HOME指明JDK安装路径,就是刚才安装时所选择的路径D:\java\jdk1.5.0_08,此路径下包括lib,bin,jre等文件夹(此变量最好设置,因为以后运行tomcat,eclipse等都需要依*此变量);      
           Path使得系统可以在任何路径下识别java命令,设为:
    %JAVA_HOME%\bin;%JAVA_HOME%\jre\bin
        CLASSPATH为java加载类(class or lib)路径,只有类在classpath中,java命令才能识别,设为:
    .;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar (要加.表示当前路径)
      %JAVA_HOME%就是引用前面指定的JAVA_HOME;
           6.“开始”->;“运行”,键入“cmd”;
           7.键入命令“java -version”,“java”,“javac”几个命令,出现画面,说明环境变量配置成功;
          8. DOS中查看相关环境变量是否正常显示echo %path%,echo %classpath%,echo %java_home%。

    再则,相关的Class有没有Import进去。


    保证上面三步,就可以解决System Exceptions: CEPTION_ACCESS_VIOLATION报错问题。

  • XML Functions with Loadrunner

    2011-02-28 15:03:41

    XML Function

    Retrieves values of XML elements found by a query
    Sets the values of XML elements found by a query
    Extracts XML string fragments from an XML string
    Deletes fragments from an XML string
    Replaces fragments of an XML string
    Inserts a new XML fragment into an XML string
    Verifies that XML values are returned by a query
    Applies Extensible Stylesheet Language (XSL) Transformation to XML data

    如果要找到XML元素指定属性名,使用@attribute_name
    [@attribute_name=\"value\"].
    实例中节点:<employee level="manager">
    XMLQuery = /employee[@level=\"manager\"]


    lr_xml_get_values
    XML:the XML Input String to query
    ValueParam:the name of the output parameter which stores the result of the query,if not exist,it's created.
    Query:the XML Query or Fast Query on the input string XML.
    SelectAll:yes-Multiple Query Matching
    所有的XML函数都是返回找到的匹配数或者是0;

    例一(XML Query):
    #include "as_web.h"
    char *xml_input=
         "<employee>"
              "<name>John Smith</name>"
              "<cubicle>227</cubicle>"
         "</employee>";

    Action() {

         lr_save_string(xml_input, "XML_Input_Param"); // Save input as parameter

         lr_xml_get_values("XML={XML_Input_Param}",
              "ValueParam=OutputParam",
              "Query=/employee/name",
              LAST);

         lr_output_message(lr_eval_string("Query result = {OutputParam}"));

         return 0;
    }


    例二(Multiple Query Matching)
    在默认情况下,所有的函数都是返回第一个XML Query匹配的项。Multiple Query Matching可以
    处理每一个连续的匹配项,并且把每个匹配项写入到参数集合中(Parameter Set)
    Param_1, Param_2, Param_3, ...
    #include "as_web.h"
    char * xml_input =
    "<acme_org>"
         " <accounts_dept>"
              "<employee>"
                   " <name>John Smith</name>"
                   "<cubicle>227</cubicle>"
                   "<extension>2145</extension>"
              "</employee>"
         "</accounts_dept>"
         "<engineering_dept>"
              "<employee>"
                   "<name>Sue Jones</name>"
                   "<extension>2375</extension>"
              "</employee>"
         "</engineering_dept>"
    "</acme_org>";

    Action() {
         int i, NumOfValues;
         char buf[64];
         lr_save_string(xml_input, "XML_Input_Param"); // Save input as parameter
         NumOfValues= lr_xml_get_values("XML={XML_Input_Param}",
              "ValueParam=OutputParam",
              "Query=/acme_org/*/employee/extension",
              "SelectAll=yes", LAST);
         for ( i = 0; i < NumOfValues; i++) { /* Print multiple values of OutputParam */
              sprintf (buf, "Retrieved value %d : {OutputParam_%d}", i+1, i+1);
              lr_output_message(lr_eval_string(buf));
         }
         return 0;
    }

     

     

    lr_xml_set_values

    设置搜索到的XML元素的值。
    XML:the XML Input String to query
    ResultParam:the output parameter containing the XML data after setting the new value.(包含新值的输出参数)
    Query:the XML Query on the input string XML.
    Value:the string value to set as the XML element
    ValueParam:the parameter name containing the value to set as the XML element.(包含设置为XML元素值的参数名)
    SelectAll:yes-Multiple Query Matching

     

    例三(XML Set):
    #include "as_web.h"
    char * xml_input =
    "<acme_org>"
        " <accounts_dept>"
            "<employee>"
                " <name>John Smith</name>"
                "<cubicle>227</cubicle>"
                "<extension>2145</extension>"
            "</employee>"
        "</accounts_dept>"
        "<engineering_dept>"
            "<employee>"
                "<name>Sue Jones</name>"
                "<extension>2375</extension>"
            "</employee>"
        "</engineering_dept>"
    "</acme_org>";
    Action() {
        int i, NumOfValues;
        char buf[64];
        lr_save_string(xml_input, "XML_Input_Param"); // Save input as parameter
        lr_save_string("1111", "ExtensionParam_1");
        lr_save_string("2222", "ExtensionParam_2");
        lr_xml_set_values("XML={XML_Input_Param}",
           "ResultParam=NewXmlParam",
           "ValueParam=ExtensionParam",
           "SelectAll=yes",
           "Query=//extension",
           LAST);
     NumOfValues=lr_xml_get_values("XML={NewXmlParam}",
              "ValueParam=OutputParam",
              "Query=//extension",
              "SelectAll=yes",
              LAST);
     for(i=0;i<NumOfValues;i++) {/* Print the multiple values of MultiParam */

      sprintf(buf,"Retrived value %d:{OutputParam_%d}",i+1,i+1);
      lr_output_message(lr_eval_string(buf));
     
     }

     return 0;
    }

     

    lr_xml_extract
    Extracts XML fragments from an XML string.
    XML:the XML Input String to query.
    XMLFragmentParam:the name of the output parameter containing the extracted XML string fragment.(包含抽取的XML字符片段的输出参数)
    Query: the XML Query or Fast Query on the input string XML.
    SelectAll: If "yes", Multiple Query Matching
    ResolveNameSpaces:If "no", then XMLFragmentParam will contain the extracted string as it appears in the XML input. If "yes", then XMLFragmentParam will include full resolution of any namespace prefixes (e.g., "a:body") in the XML input string. The Default is "no".

    例四(XML Extract):
    #include "as_web.h"
    char * xml_input =
    "<acme_org>"
         " <accounts_dept>"
              "<employee>"
                   " <name>John Smith</name>"
                   "<cubicle>227</cubicle>"
                   "<extension>2145</extension>"
              "</employee>"
         "</accounts_dept>"
         "<engineering_dept>"
              "<employee level=\"manager\">"
                   "<name>Sue Jones</name>"
                   "<extension>2375</extension>"
              "</employee>"
         "</engineering_dept>"
    "</acme_org>";

    Action() {
         int i, NumOfValues;
         char buf[64];
         lr_save_string(xml_input, "XML_Input_Param"); // Save input as parameter
         lr_xml_extract("XML={XML_Input_Param}",
                        "XMLFragmentParam=Result",
         "Query=/acme_org/engineering_dept/employee",
         LAST);
         lr_output_message(lr_eval_string("Extracted: {Result}"));

         return 0;
    }

    lr_xml_delete
    The lr_xml_delete function queries the XML input string XML and deletes the fragments of the XML
    tree that match the Query criteria.you can delete elements by specifying the element name or its
    attribute in the XML Query.The output parameter ResultParam contains the modified XML string subsequent
    to deletion.
    XML: the XML Input String to query
    ResultParam: the name of the output parameter containing the XML data after deleting the fragment.
    Query: the XML Query on the input string XML.
    SelectAll: If "yes",Multiple Query Matching

    Note: After deleting the contents of an element, the empty element, e, is signified <e/>. For example, the string result after deleting the element c from the XML string "<a><b><c></c></b></a>" is:
    "<a><b/></a>"
    since the element b is now empty.

    例五(XML Delete):
    #include "as_web.h"
    char * xml_input =
    "<acme_org>"
         "<accounts_dept>"
              "<employee>"
                   " <name>John Smith</name>"
                   "<cubicle>227</cubicle>"
                   "<extension>2145</extension>"
              "</employee>"
         "</accounts_dept>"
    "</acme_org>";
    Action() {

        lr_save_string(xml_input, "XML_Input_Param"); // Save input as parameter
        lr_xml_delete("XML={XML_Input_Param}",
            "ResultParam=Result",
            "Query=/acme_org/accounts_dept/employee/extension",
      LAST);
        lr_output_message(lr_eval_string("String after deletion: {Result}"));
        return 0;

    }


    lr_xml_replace
    Replaces fragments of an XML string.
    XML: the XML Input String to query
    ResultParam: the name of the output parameter containing the XML data after replacing the new value
    Query: the XML Query on the input string XML.
    XmlFragment: the string value to use as replacement of the query match—an element or an attribute.
    XmlFragmentParam: the name of the parameter containing the string value to use as replacement
    SelectAll: If "yes",Multiple Query Matching


    The lr_xml_replace function queries the XML input string XML for values matching the Query criteria
    and replaces them either with XMLFragment or XMLFragmentsParam as the value of the elements matched by
    the query, you can replace elements by specifying either its element name or attribute in the XML Query

    If there is more than one value to be replaced, then pass the "XmlFragmentParam=" specification. Save the values in a series of parameters with the names:
    Param_1, Param_2, Param_3, ...

    例六(XML Replace):
    #include "as_web.h"
    char *xml_input =
    "<acme_org>"
         "<employee>"
              " <name>John Smith</name>"
              "<cubicle>227</cubicle>"
              "<extension>2145</extension>"
         "</employee>"
    "</acme_org>";
    Action() {

         lr_save_string(xml_input, "XML_Input_Param");
      lr_xml_replace("XML={XML_Input_Param}",
         "ResultParam=Result",
         "Query=/acme_org/employee/extension",
         "XmlFragment=<extension>4444</extension>",
         LAST);
      lr_output_message(lr_eval_string("String after replacement:{Result}"));
      return 0;
    }


    lr_xml_insert
    Inserts a new XML fragment into an XML string
    The lr_xml_insert function queries the xml input string XML for values matching the Query criteria.
    It then insets XmlFragment or XmlFragmentParam at the position in the XML string returned by the Query.

    XML: the XML Input String to query
    ResultParam: The output parameter containing the XML data after inserting the new fragment.
    Query: the XML Query on the input string XML.
    XmlFragment: the string to insert. It can be a new element or a attribute of an existing element.
    XmlFragmentParam: the name of the parameter containing the string value to insert
    SelectAll: If "yes",Multiple Query Matching
    Position: the position to insert the XML fragment. Choose one of:
    - before: place the fragment before the tag returned
                   by a Query
    - after: place the fragment after the tag returned
                   by a Query (this is the default value)
    - child: place the fragment as a child of the tag
               returned by a Query
    - attribute: indicates an attribute of an element
                   returned by a Query

    Postion specifies whether the insertion is done before or after the point returned.Additionally, the child Position specifies that the fragment is inserted before the end of the tag found by the query. For example, if the input string is
    <a>53</a>
    an inserted fragment ("<b>ZZ</b>") in the child position will result in the string:
    <a>53<b>ZZ</b></a>

    例七(XML Insert):
    #include "as_web.h"
    char *xml_input =
    "<acme_org>"
         "<employee>"
              " <name>John Smith</name>"
              "<cubicle>227</cubicle>"
         "</employee>"
    "</acme_org>";
    Action() {
     lr_save_string(xml_input, "XML_Input_Param");
     lr_xml_insert("XML={XML_Input_Param}",
                      "ResultParam=Result",
                      "XmlFragment=<extension>2145</extension>",
                      "Query=/acme_org/employee",
          "Position=child",
          LAST);
    lr_output_message(lr_eval_string("String after insertion: {Result}"));

         return 0;
    }

     

     

    lr_xml_find
    Verifies that XML values are returned by a query
    Query: the XML Query or Fast Query on the input string XML.
    XML: the XML Input String to query
    Value: the string to find. This can be the element value or its attribute value.
    ValueParam: the parameter name containing the string to find.
    SelectAll: If "yes",Multiple Query Matching
    IgnoreCase:If "yes", the search will ignore the difference between uppercase and lowercase characters of Value or ValueParam and query results. Default is "no".
    UseRegExp: If "yes", Value and ValueParam can be regular expressions that the function will search for. For more information
    NotFound: Specifies whether the script. fails or continues if the search value is not found. Value is "continue" or "error". If NotFound is not specified, the script. fails.

    The lr_xml_find function queries the XML input string XML for values matching the Query criteria(Value or ValueParam)and returns the number of occurrences.If SelectAll is "no", lr_xml_find returns either 1 or 0.
    例八(XML Find):
    #include "as_web.h"
    char *xml_input =
    "<acme_org>"
        "<employee level=\"manager\">John Smith"
            "<cubicle>227</cubicle>"
        "</employee>"
    "</acme_org>";
    Action() {
    int find_cnt;
        lr_save_string(xml_input, "XML_Input_Param");
        /* Verify that employee John Smith exists */
        find_cnt = lr_xml_find("XML={XML_Input_Param}",
               "Value=John Smith",
               "Query=/acme_org/employee",
               LAST);
        if (find_cnt >0)
    {
            /* Now insert John Smith's telephone extension number */
            lr_xml_insert("XML={XML_Input_Param}", "ResultParam=Result",
            "XmlFragment=<extension>2145</extension>",
            "Query=/acme_org/employee",
            "Position=child", LAST);
            lr_output_message(lr_eval_string("String after insertion: {Result}"));
        } // end if find_cnt > 0
    return 0;
    }


    lr_xml_transform
    The lr_xml_transform. function transforms the XML input string XML using the Extensible Stylesheet Language (XSL) specifications in Stylesheet and saves the resulting formatted data in ResultParam,
    XML: the XML Input String to query
    Stylesheet: the XSL specifications. Has the format of an XSL string.
    ResultParam: the name of the output parameter containing the XML formatted data after XSL transformation

    例九(XML Transfer):
    #include "as_web.h"
    char *xml_input =
    "<?xml version=\"1.0\" ?>"
         "<sales>"
              "<summary>"
                   "<heading>Acme Organization</heading>"
                   "<subhead>IT Management Report</subhead>"
                   "<description>Report by Department</description>"
              "</summary>"
         "</sales>";

    char *stylesheet =
    "<?xml version=\"1.0\"?>"
    "<xsl:stylesheet xmlns:xsl=\"
    http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">"
    "<xsl:output method=\"html\"/>"
    "<xsl:template match=\"/\">"
         "<HTML>"
              "<HEAD>"
                   "<TITLE><xsl:value-of select=\"//summary/heading\"/></TITLE>"
              "</HEAD>"
              "<BODY>"
                   "<h1><xsl:value-of select=\"//summary/heading\"/></h1>"
                   "<h2><xsl:value-of select=\"//summary/subhead\"/></h2>"
                   "<p><xsl:value-of select=\"//summary/description\"/></p>"
              "</BODY>"
         "</HTML>"
    "</xsl:template>"
    "</xsl:stylesheet>";

    Action() {

         lr_save_string(xml_input, "XML_Input_Param"); // Save to a parameter
         lr_save_string(stylesheet, "XML_StyleSheet_Param");// Save to a parameter
         lr_xml_transform("XML={XML_Input_Param}", "ResultParam=Result",
           "Stylesheet={XML_StyleSheet_Param}",
           LAST);
         lr_output_message(lr_eval_string("String after transformation: {Result}"));
         return 0;
    }

     

  • LoadRunner项目脚本

    2010-11-03 11:17:03

    保险系统LoadRunner项目脚本

    详见附件

  • LR tips_1(advance)

    2010-10-18 23:26:35

    Files Generated During Recording

    vuser.usr

    vuser.bak

    default.cfg

    default.usp

    init.c

    run.c

    end.c

    data.prm

    data.prm.

     

    \Data Dir

    ­RequestHeader

    ResponseHeader

    CorrelationLog

    RecrodingLog

     

    Recording Scrit include

    Vuser_init

    ­Actions

    Vuser end

    Vuser.usr:Contains information about the virtual user:type,AUT,action files,and so forth.

    [General]

    Type=QTWeb

    DefaultCfg=default.cfg

    AppName=NO_APP_IGNORE

    BuildTarget=

    ParamRightBrace=}

    ParamLeftBrace={

    NewFunctionHeader=1

    LastActiveAction=Action

    CorrInfoReportDir=

    DevelopTool=Vugen

    MajorVersion=8

    MinorVersion=0

    ParameterFile=

    GlobalParameterFile=

    LastModifyVer=8.0

    [Transactions]

    "find flights"=

    [TransactionsOrder]

    Order="find flights"

    [Actions]

    vuser_init=vuser_init.c

    Action=Action.c

    Login_System=Login_System.c

    flights=flights.c

    vuser_end=vuser_end.c

    [Recorded Actions]

    vuser_init=0

    Action=0

    Login_System=1

    flights=1

    vuser_end=0

    [Replayed Actions]

    vuser_init=0

    Action=0

    Login_System=0

    flights=0

    vuser_end=0

    [VuserProfiles]

    Profiles=Default Profile

    [CfgFiles]

    Default Profile=default.cfg

    [RunLogicFiles]

    Default Profile=default.usp

     

    vuser.bak:A copy of Vuser.usr before the last save operation.Changed and saved

    Data.prm:Contains the parameters data

    Data.prm.bak:A copy of Data.prm before the last save operation

     

    Default.cfg:Contains a listing of run-time settings as defined in the VuGen applicatin(think time,

    iterations,log,web)

    [General]

    automatic_nested_transactions=1

    XlBridgeTimeout=120

    DefaultRunLogic=default.usp

    [ThinkTime]

    Options=NOTHINK

    Factor=1

    LimitFlag=0

    Limit=1

     

    [Iterations]

    NumOfIterations=1

    IterationPace=IterationASAP

    StartEvery=60

    RandomMin=60

    RandomMax=90

     

    [Log]

    LogOptions=LogBrief

    MsgClassData=0

    MsgClassParameters=0

    MsgClassFull=0

     

    [WEB]

    SearchForImages=1

    WebRecorderVersion=5

    BrowserType=Microsoft Internet Explorer 4.0

    HttpVer=1.1

    CustomUserAgent=Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; CIBA)

    ResetContext=True

    UseCustomAgent=1

    KeepAlive=Yes

    EnableChecks=0

    AnalogMode=0

    ProxyUseBrowser=0

    ProxyUseProxy=0

    ProxyHTTPHost=

    ProxyHTTPSHost=

    ProxyHTTPPort=0

    ProxyHTTPSPort=0

    ProxyUseSame=0

    ProxyNoLocal=0

    ProxyBypass=

    ProxyUserName=

    ProxyPassword=

    ProxyUseAutoConfigScript=0

    ProxyAutoConfigScriptURL=

    ProxyUseProxyServer=0

    SaveSnapshotResources=0

    UTF8InputOutput=0

     

  • LR Controller tips

    2010-10-17 13:47:34

    LoadRunner Advantages

    1.with virtual user reduces personnel requirements and machinery required.

    2.easily and effectively control all the Vusers with Controller

    3.monitors application performance online.

    4.automatically records variety graphs and reports performance data.

    5.offer the delay occurs information to help you improve performance.

    6.easily repeat loadrunner tests as often as you need.

     

     

    The LoadRunner Testing Process

    Step I: Planning the Test

    Step II: Creating the Vuser Scripts

    Step III: Creating the Scenario

    Step IV: Running the Scenario

    Step V: Monitoring a Scenario

    Step VI: Analyzing Test Results

     

     

     

    About Load Test Planning

    1.Build test scenarios.

    2.Understand which resources are required.

    3.Define success criteria in measurable terms

     

    Analyzing the Application

    Thoroughly familiar with the hardware and software components, the system configuration, and the typical usage model. This analysis ensures that the testing environment you create using LoadRunner will accurately reflect the environment and configuration of the application under test.

     

     

    tool bar in design view

    create a new scenario

    open

    save

    Load Generator

    VuGen

    Analysis

     

     

    Schedule Builder

    Initialize Vusers

    Run Vuser

    Gradually stop Vusers

    Stop Vusers

    Analyze Results

     

    Load Generator rules???

     

     

  • LR Monitor tips

    2010-10-17 13:47:34

    Web Resource Monitor

    Get the web server information:

    Hit per second

    You can compare this gragh to the Transaction Response Time gragh to see how the

    number of hits affects transaction performace.

    Throughput

    The Throughput graph shows the amount of throughput on the Web server.You can compare this graph to the Transaction Response Time graph to see how the throughput affects transaction performance.

    throughput decreases, the transaction response time also decreases.

    HTTP responses per Second

    The HTTP Responses per Second graph shows the number of HTTP status codeswhich indicate the status of HTTP requests,

    Pages Download per Second

    This graph helps you evaluate the amount of load Vusers generate, in terms of the number of pages downloaded. Throughput graph can compared with the Pages Downloaded per Second graph.

    Retries per second

    Connections

    The Connections graph shows the number of open TCP/IP connections (y-axis) at each point in time of the scenario or session step (x-axis).

    Connections per Second

    The Connections Per Second graph shows the number of new TCP/IP connections (y-axis) opened and the number of connections that are shut down each second of the scenario or session step (x-axis).

    SSL per Second

    The SSL Connections per Second graph shows the number of new and reused SSL Connections (y-axis) opened in each second of the scenario or session step (x-axis). An SSL connection is opened by the browser after a TCP/IP connection has been opened to a secure server

     

     

     

    Run-Time Graphs

    Running Vusers

    Error Statistics

    Vusers with Error Statistics

     

    Transaction Monitor Graphs

    Transaction Response Time

    Transactions per Second (Passed)

    Transactions per Second (Failed, Stopped)

    Total Transactions per Second (Passed)

     

     

    About System Resource Monitoring

    A primary factor in a transaction's response time is its system resource usage.A machine during a scenario or session step run, and determine why a bottleneck occurred on a particular machine.

     

  • LR Message Functions tips

    2010-10-17 13:47:34

    Message Functions

    lr_output_message

    sends a message to the log file and output window.

    The message is sent to the output windows and the vuser log file when a script

    is run in VuGen,the output file is output.txt.

     

    It is not recommended that you send a message to the output window in the middle of a transaction, as it will lengthen the execution time. To send a message to the output file,you must enable logging in the run-time setting, and select Always send messages. If you select Send messages only when an error occurs, there is no output from this function.

     

     

    lr_debug_message  Sends a debug message to the output. 

    lr_error_message  Sends an error message to the Output window. 

     

    lr_log_message  Sends a message to the Vuser log file. 

     

    lr_message  Sends a message to the Vuser log and Output window. 

    lr_output_message  Sends a Vuser message to the Output window and the Vuser log with location information. 

     

     

    Group Name

    Group Name replaces the parameter with the name of the Vuser Group. You specify the name of the Vuser Group when you create a scenario. When you run a script. from VuGen, the Group name is always None.

  • LR tips_2(advance)

    2010-10-17 13:47:34

    Default.usd:Contains the script's run logic,including how the actions sections run.

    [RunLogicRunRoot:flights]

    MercIniTreeSectionName="flights"

    RunLogicObjectKind="Action"

    Name="flights"

    RunLogicActionType="VuserRun"

    MercIniTreeFather="RunLogicRunRoot"

    [RunLogicEndRoot:vuser_end]

    MercIniTreeSectionName="vuser_end"

    RunLogicObjectKind="Action"

    Name="vuser_end"

    MercIniTreeFather="RunLogicEndRoot"

    RunLogicActionType="VuserEnd"

    [RunLogicInitRoot:vuser_init]

    MercIniTreeSectionName="vuser_init"

    RunLogicObjectKind="Action"

    Name="vuser_init"

    MercIniTreeFather="RunLogicInitRoot"

    RunLogicActionType="VuserInit"

    [RunLogicRunRoot:Login_System]

    MercIniTreeSectionName="Login_System"

    RunLogicObjectKind="Action"

    Name="Login_System"

    RunLogicActionType="VuserRun"

    MercIniTreeFather="RunLogicRunRoot"

    [RunLogicRunRoot:Action]

    MercIniTreeSectionName="Action"

    RunLogicObjectKind="Action"

    Name="Action"

    MercIniTreeFather="RunLogicRunRoot"

    RunLogicActionType="VuserRun"

    [Profile Actions]

    Profile Actions name=vuser_init,Action,Login_System,flights,vuser_end

    MercIniTreeSectionName="Profile Actions"

    MercIniTreeFather=""

    [RunLogicRunRoot]

    RunLogicActionOrder="Action,Login_System,flights"

    MercIniTreeFather=""

    MercIniTreeSons="Action,Login_System,flights"

    RunLogicNumOfIterations="1"

    Name="Run"

    RunLogicRunMode="Sequential"

    RunLogicObjectKind="Group"

    RunLogicActionType="VuserRun"

    MercIniTreeSectionName="RunLogicRunRoot"

    [RunLogicEndRoot]

    RunLogicActionOrder="vuser_end"

    MercIniTreeFather=""

    MercIniTreeSons="vuser_end"

    RunLogicNumOfIterations="1"

    Name="End"

    RunLogicRunMode="Sequential"

    RunLogicObjectKind="Group"

    RunLogicActionType="VuserEnd"

    MercIniTreeSectionName="RunLogicEndRoot"

    [RunLogicInitRoot]

    RunLogicActionOrder="vuser_init"

    MercIniTreeFather=""

    MercIniTreeSons="vuser_init"

    RunLogicNumOfIterations="1"

    Name="Init"

    RunLogicRunMode="Sequential"

    RunLogicObjectKind="Group"

    RunLogicActionType="VuserInit"

    MercIniTreeSectionName="RunLogicInitRoot"

     

     

     

    Files Generated During Replay

    This section describes what occurs when the Vuser is replayed.

     

    The options.txt file is created

    The file pre_cci.c is created   defined in options.txt 

    The file logfile.log is created defined in options.txt

    The output.txt file is created  contains all the output messages of run.

    The file Vuser.c is created.    contains 'includes' to all the relevant .c and .h

    logfile:This file should be empty if there are no problems with the preprocessing stage.

     

    options.txt

    -+

    -DCCI

    -D_IDA_XL

    -DWINNT

    -IC:\Documents and Settings\weibin\桌面\flithts\practice

    -IC:\Program Files\Mercury Interactive\Mercury LoadRunner\include

    -ec:\documents and settings\weibin\桌面\flithts\practice\\logfile.log

    c:\documents and settings\weibin\桌面\flithts\practice\\combined_practice.c

    c:\documents and settings\weibin\桌面\flithts\practice\\pre_cci.c

     

     

    vugen.dat

    This Vugen.dat file resides in the data directory and contains general information about VuGen,

    to be used by both the VuGen and Controller.

    mdrv.dat

    mdrv.dat=execute log

     

    mdrv_cmd:
    -usr "C:\Documents and Settings\weibin\桌面\flithts\practice\practice.usr" -qt_result_dir "C:\Documents and Settings\weibin\桌面\flithts\practice\result1" -correlation_files  -file "C:\Documents and Settings\weibin\桌面\flithts\practice\practice.ci" -drv_log_file "C:\Documents and Settings\weibin\桌面\flithts\practice\mdrv.log"  -product_name vugen -extra_ext vugdbg_ext -cci_elevel -msg_suffix_enable 0 -vugen_win 131670 -vugen_animate_delay 0 -out "C:\Documents and Settings\weibin\桌面\flithts\practice\"

     

    The mdrv.dat (create Vuser type)file contains a separate section for each protocol defining the location of the

    library files and driver executables

     

     

     

    Calling External Functions

    Call functions that are defined in external DLLs

     

    Loading a DLLLocally
    You use the lr_load_dll function to load the DLL in your Vuser script.Once the DLL is loaded,

    you can call any function defined within the DLL,without having to declare it in your script.

     

    Loading a DLLGlobally

    You can load a DLL globally.

    Add a list of the DLLs you want to load to the appropriate section of the mdrv.dat file, located in the LoadRunner/dat directory.

    Use the following syntax,

     

    PLATFORM_DLLS=my_dll1.dll, my_dll2.dll, ...

     

    replacing the word PLATFORM. with your specific platform. For a list of platforms, see the beginning section of the mdrv.dat file.

     

  • 调试信息函数

    2010-05-24 22:55:14

    int lr_set_debug_message (unsigned int message_level, unsigned int on_off);


    中文解释:lr_set_debug_message函数设置脚本执行的调试消息级别message_lvl.通过设置消息级别,可以确定发送哪些信息。 启动设置的方法是将LR_SWITCH_ON作为on_off传递,禁用设置的方法是传递LR_SWITCH_OFF.参数message_level说明:

     日志级别

     C语言标志

     值

     Runtime-setting - Log操作

     Disabled  LR_MSG_CLASS_DISABLE_LOG  0  不勾选Enable logging
     Brief  LR_MSG_CLASS_BRIEF_LOG  1  勾选Standard log
     Extended Log  LR_MSG_CLASS_EXTENDED_LOG  16  勾选Extended log
     Result Data  LR_MSG_CLASS_RESULT_DATA  2  勾选Data returned by server
     Parameter Substitution  LR_MSG_CLASS_PARAMETERS  4  勾选Parameter substitution
     Full Run-Time Trace  LR_MSG_CLASS_FULL_TRACE  8  勾选 Advanced trace
     Only on error  LR_MSG_CLASS_JIT_LOG_ON_ERROR  512  勾选send messages only when an error occurs

    参数on_off说明:
     
      「LR_SWITCH_ON」启用设置
     
      「LR_SWITCH_OFF」禁用设置

    lr_get_debug_message返回的int数其实是所有勾选操作的代表值相加!

    例子:

    Action()
    {
    //设置runtime-setting的日志选项【不勾选Enable logging】
     char *a;
     a = "ABC";
     lr_set_debug_message (LR_MSG_CLASS_EXTENDED_LOG |LR_MSG_CLASS_PARAMETERS,LR_SWITCH_ON);
     //打开Runtime-setting Log 的Parameter substitution设置
     lr_debug_message(LR_MSG_CLASS_PARAMETERS,"打开参数保存的系统日志");
     lr_save_string("aa",a);
     lr_debug_message(LR_MSG_CLASS_PARAMETERS,"关闭参数保存的系统日志");
     lr_set_debug_message (LR_MSG_CLASS_EXTENDED_LOG |LR_MSG_CLASS_PARAMETERS,LR_SWITCH_OFF);
     //关闭Runtime-setting Log 的Parameter substitution设置

     return 0;
    }

     

       因为设置了runtime-setting不打印任何日志,所以正常运行脚本应该没有任何日志输出;
     
      但是使用lr_set_debug_message函数打开了日志的设置(输出保存参数操作的日志)
     
      因此脚本运行到lr_save_string("aa",a)时,就输出了日志如下:
     
      打开参数保存的系统日志
     
      Action.c(7): Notify: Saving Parameter "ABC = aa".关闭参数保存的系统日志

     

    注:页面的runtime-settings更为方便,推荐使用F4


  • loadrunner编写脚本5

    2010-05-24 16:35:16

    VUser_Init部分

    这里是Vuser_init部分的一些例子:

    操作系统的User ID

    下面显示了使用advapi32.dll的GetUserNameA函数获得的操作系统的用户ID

           char   sUserID[1024]; // Maximum possible UserID length.

           long   lUserIDSize = sizeof(sUserID)-1;

           int   rc;


           rc=lr_load_dll("advapi32.dll");

           if( rc != 0 ){

                  lr_error_message("lr_load_dll of advapi32.dll failed. Aborted for rc=%d",rc);

                  lr_abort();

           }else{

                  GetUserNameA(sUserID, &lUserIDSize);

                  lr_message("UserID='%s'", sUserID);

           }

    所有的变量声明需要一块放到最上方。在vuser_init部分创建的本地C变量(如int或char)对其他部分的脚本是不可见的。所以使用lr_save_string函数来创建对所有脚本可用的全局参数。例子:

     

    char *itoa ( int value, char *str, int radix );

    vuser_init(){

           int x = 10;

           char buffer[10];

           lr_save_string(itoa( x, buffer, 10) , "pX" );

           lr_message ( "int x = %s", lr_eval_string("{pX}" ));

    return 0;

    }

     

    运行时设置的附加属性(Additional Attribute)

    8.0版本引进了一个非常有价值的特性:在运行时设置中指定属性,这个属性可以对不同的虚拟用户组设置不同的值。


    下面的代码是从运行时设置的附加属性中读取名为“usertype”的参数。然后使用参数值来对应的设置全局的"thinktime1"变量。

     

    int thinktime1=0;


    vuser_init(){


    LPCSTR strUsertype; // Define *str.

    str Usertype =lr_get_attrib_string("usertype");

    if (strUsertype==NULL){

    lr_output_message("### Run-time Settings Additional Attribute usertype not specified. Cannot continue.");


    lr_abort();


    }

    else{

     


    lr_message("### Run-time Settings Additional Attribute usertype=\"%s\"", strUsertype );

    if( strcmp( strUsertype,"advanced") == 0 )

    { thinktime1=2; }
    else
    if


    ( strcmp( strUsertype,"intermediate") == 0 ){ thinktime1=4; }


    else
    }

    if( strcmp( strUsertype,"basic") == 0 )

    { thinktime1=8; }

    else

    {

    lr_error_message("### ERROR: Value not recognized. Aborting run." );

    lr_abort();

    }

    }
    return 0;

    }


    Time Structure Fix(不知道怎么翻译,呵呵,“时间结构的解决“?)

    根据知识库34195的文章,默认当前时间戳的毫秒部分不被更新,除非ftime使用的时间结构被重新定义:


      

    typedef long time_t;

    struct _timeb {

      time_t time;

      unsigned short millitm;

      short timezone;

      short dstflag;

    };

    struct _timeb t;

    _tzset(); \\使用ftime设置变量

    _ftime( &t );

    lr_message( "Plus milliseconds: %u", t.millitm );

    控制信息的显示:

    在运行时,当脚本的事务失败后继续,你怎么知道哪个用户失败了?

    在每个失败的事务之后,发出一个能够唯一确定该用户的信息。

    Loadrunner提供了一些函数来在运行时显示信息:

     

    ·//往输出日志上发送消息,这个消息前边会带有action的名称和行数

    lr_output_message("an output message");


    --------------------------------------------------------------------------------

     

      例子:

    ·Actions.c (4): an output message

    ·//往输出日志和虚拟用户日志上发消息:

     

    ·  lr_message("*** a message"

    +"\r"+"A new line."

    );

    把");"放到另一行,这样可以容易的在命令上添加或者删除代码项。

      在UNIX/Linux机器上,使用"\n"来添加一个换行。

      在Windows机器上,使用"\r"来添加一个换行。

    //往输出日志上发送不带action名称和行数的信息
    lr_log_message("number\t"+ numvar +"\t");


    //只给控制器上的虚拟用户状态区域发送信息(当在VuGen中运行时,只是简单的显示):lr_vuser_status_message("a vuser status message");


    //给LoadRunner控制器或者Tuning模块的控制台输出窗口显示一个红色高亮度显示的-17999信息。lr_error_message("an error message");

     

  • Loadrunner脚本编程4-数据类型操作和字符串操作

    2010-05-24 16:31:16

    一,数据类型转换

    没有使用过C编程的LoadRunner脚本编写者会发现在数据类型转化方面比较困难。下面介绍这方面的知识。

    1. 相似函数的输出在不同的位置

    象很多C函数一样,使用atoi函数的结果即为返回值

    如intResult = atoi( charY );

    而:itoa的返回结果为第二个参数。

    itoa( intX, charY, 10);

       第一个参数是需要转换的数字,第二个参数是转换后存储的字符数组,需要注意的是数组必须定义为固定的长度,如:char chary[20];

    数组的最大长度为32064(32K),否则会出现“too many variables”编译错误。

    如果定义为变长的字符串如char *charY,则程序会出错。

       第三个参数不是数组的长度,而是数字的基数,10进制是最常用的,其他还有二进制,八进制,十六进制。

    2. 有一些函数实现了同样的功能

    itoa不是一个标准的ANSI C函数但是是C的stdlib.h中的一个函数。所以它不被包括在unix机器上的LibC中。我们可以使用标准的sprintf函数来代替:

    sprintf(charY,“%d”,intX);

    sprintf

    Writes formatted output to a string.

    3. 是用%X来转换一个十六进制数

    int intNum;

    sscanf(“ffff”,“%X”,&Num);

    lr_output_message(“%d”,intNum); // 打印65535 ,ffff的整数值

    sscanf

    Reads formatted input from a string.

    4. 从文本中提取数字的规则

    如果第一个字符不是数字或者为空,atoi返回0,即“e24”会返回0

    atoi 转换一个非数字的字符会返回组成这个字符的数字,如“-3.2”返回-3.0。“123XXX345”返回123。

    Converts a string to an integer value.

    atoi reads the initial portion of the string only, by stopping at the first non-numerical character.

    5. LoadRunner脚本中的参数必须转换成C字符串。有两种方式来转化LR的参数为C语言的数字。

    i = atoi( lr_eval_string("{pX}") );

    sprintf( intX, "%d", lr_eval_string("{pX}") );

    lr_eval_string

    Returns the string argument after evaluating embedded parameters.

    The lr_eval_string function returns the input string after evaluating any embedded parameters. If string argument contains only a parameter, the function returns the current value of the parameter.

    Embedded parameters must be in brackets.

    6. 参数的算术运算

    LoadRunner没有提供对参数的算术运算的函数。所以LR的参数必须:

    1) 转换成C的整数

    2) 使用C的函数来运算最后返回一个C的字符串

    3) 把返回的字符串保存成参数


    view plaincopy to clipboardprint?
    char cBuf[10];    
      
    int i;    
      
    // 1. 转换成C的整数:   
      
    i = atoi( lr_eval_string("{pNum_in}") );   
      
    // 2. 使用C的函数来运算最后返回一个C的字符串:   
      
    sprintf( cBuf, "%d", i+1);    
      
    // 3.把返回的字符串保存成参数:   
      
    lr_save_string( cBuf, "pNum_out");    
      
    //Print out the parameter value after incrementing it.   
      
    lr_message("**** Parameter from %s to %s",   
      
         lr_eval_string("{pNum_in}"));    
      
         lr_eval_string("{pNum_out}"));  
    char cBuf[10];

    int i;

    // 1. 转换成C的整数:

    i = atoi( lr_eval_string("{pNum_in}") );

    // 2. 使用C的函数来运算最后返回一个C的字符串:

    sprintf( cBuf, "%d", i+1);

    // 3.把返回的字符串保存成参数:

    lr_save_string( cBuf, "pNum_out");

    //Print out the parameter value after incrementing it.

    lr_message("**** Parameter from %s to %s",

         lr_eval_string("{pNum_in}"));

         lr_eval_string("{pNum_out}"));

    zibeike注:除了对于数字类型的参数的运算之外,对于文本形式的参数的操作,可以参考我的另一篇文章的内容:http://www.51testing.com/?34866/action_viewspace_itemid_75592.html

    二.字符串操作

    在C语言中,字符串是固定长度的,因为他们本身由独立的字符组成的字符数组。数组是只读的。任何修改字符串长度的函数调用都会报错:

    Error: "C interpreter runtime error - memory violation error during replay.

    在LoadRunner的as_web.h库中的字符串函数可以使用“prototyping”声明的方式读写内存:

    char *strtok(char *, char *); // tokenizer prototype
    char *strstr(char *, char *); // substring prototype
    char *strdup(char *); // String duplication prototype
    float atof(); // alpha to return float datatype
    #include "as_web.h"
    char *strtok(char *, char *); // prototype function call.

    ActionX()
    {
       char aBuffer[256]; // input string to be parsed.
        char *cToken; // individual token from strtok.
       char cSeparator[] = " "; // blank separator.
       int i; // incrementer
       char val[3][20]; // output array of strings.
       char modified_val[20];
       
       // 创建一个参数pDate:
       lr_save_string("January 2, 2001", "pDate");
    // 把参数放到字符串缓冲Put parameter into a string buffer:
       //strcpy:Copies one string to another.
    //lr_eval_string:Returns the string argument after evaluating embedded parameters.
       strcpy( aBuffer,lr_eval_string("{pDate}"));

       //在调试中显示这个buffer Show the buffer for debugging:
    //lr_output_message:Sends a message to the log file and Output window
       lr_output_message("%s\n",aBuffer);

       // get first word (to the first blank):
    //strtok:Returns a token from a string delimited by specified characters.
        cToken = strtok( aBuffer,cSeparator);
       i = 1;

       if(!token) { // first token was not found:
               lr_output_message("No tokens found in string!");
               return( -1 );
       } else {
               while( cToken != NULL) { // tokens are not NULL:
                       lr_output_message("Token=%s", cToken);

                       // Stuff in another array:
                       strcpy( val[i], cToken );

                       // Get next token:
                       cToken = strtok( NULL, cSeparator);
                       i++; // increment
               }
               lr_output_message("Val #1 is: %s", val[1]);
               lr_output_message("Val #2 is: %s", val[2]);
               lr_output_message("Val #2 is: %s", val[3]);

               strncpy( modified_val, val[2], 1 );
               modified_val[2] = '\0';
               while (modified_val[2] != NULL) {
                       lr_output_message("===>%s", modified_val);
                       modified_val[2] = strtok(NULL, " ");
               }
       }
       return 0;
    }

    strcat 连接两个字符串

    strchr 返回指向第一个要查找的字符出现的位置的指针

    strcmp 比较两个字符

    strcpy 复制字符串到另一个

    stricmp 执行一个大小写敏感的比较

    其他还有strdup,strncat,strncpy,strnicmp,strrchr,strset,strspn,strstr等字符串操作的函数。

    zibeike注:关于更多字符串操作的脚本编写,可以参考我的另一篇文章:

    http://www.51testing.com/?34866/action_viewspace_itemid_75428.html

    zibeike翻译自:http://www.wilsonmar.com/1lrscrīpt.htm

    LoadRunner中常用的字符串操作函数有:

                   strcpy(destination_string, source_string);

                   strcat(string_that_gets_appended, string_that_is_appended);

                   atoi(string_to_convert_to_int); //returns the integer value

                   itoa(integer_to_conver_to_string, destination_string, base); // base is 10

                   strcmp(string1, string2); // returns 0 if both strings are equal

    对各函数的定义:

                 strcpy( ):拷贝一个字符串到另一个字符串中.

                 strcat( ):添加一个字符串到另一个字符串的末尾。

                strcmp( ):比较两个字符串,如果相等返回0。

                atoi():转换一个ASCII字符串为一个整型。

                itoa():根据给定的进制,转换一个整型数据为ASCII字符串

    下面的例子使用了上面这些函数:


    view plaincopy to clipboardprint?
                    
      
    Actions()   
      
    {   
      
            char MyString1[20] = "";   
      
            char MyString2[20] = "";   
      
            char MyString3[20] = "Mercury2";   
      
            char Cstring[10] = "12345";   
      
            int Cint;   
      
        
      
        
      
            // MyString1 is empty    
      
            //   
      
            lr_output_message(">>>>>>>>>> MyString1 = %s",MyString1);   
      
        
      
            // copy "Mercury1" into MyString1   
      
            //   
      
            strcpy(MyString1,"Mercury1");   
      
        
      
            // Now MyString1 contains "Mercury1"   
      
            //   
      
            lr_output_message(">>>>>>>>>> MyString1 = %s",MyString1);   
      
        
      
        
      
            // Copy MyString3 into MyString2   
      
            //   
      
            lr_output_message(">>>>>>>>>> MyString2 = %s",MyString2);   
      
            strcpy(MyString2,MyString3);   
      
            lr_output_message(">>>>>>>>>> MyString2 = %s",MyString2);   
      
        
      
        
      
            // Catenate MyString2 to MyString1   
      
            //   
      
            strcat(MyString1,MyString2);   
      
            lr_output_message(">>>>>>>>>> MyString1 = %s",MyString1);   
      
        
      
            // Cstring is converted to integer Cint   
      
            //   
      
            lr_output_message(">>>>>>>>>> Cstring = %s",Cstring);   
      
            Cint = atoi(Cstring);   
      
            lr_output_message(">>>>>>>>>> Cint = %d",Cint);   
      
        
      
            // Cint is converted to string   
      
            Cint = 100;   
      
            itoa(Cint,Cstring,10);   
      
            lr_output_message(">>>>>>>>>> Cstring = %s",Cstring);   
      
        
      
            return 0;   
      
    }
                

    Actions()

    {

            char MyString1[20] = "";

            char MyString2[20] = "";

            char MyString3[20] = "Mercury2";

            char Cstring[10] = "12345";

            int Cint;

            // MyString1 is empty

            //

            lr_output_message(">>>>>>>>>> MyString1 = %s",MyString1);

            // copy "Mercury1" into MyString1

            //

            strcpy(MyString1,"Mercury1");

            // Now MyString1 contains "Mercury1"

            //

            lr_output_message(">>>>>>>>>> MyString1 = %s",MyString1);

            // Copy MyString3 into MyString2

            //

            lr_output_message(">>>>>>>>>> MyString2 = %s",MyString2);

            strcpy(MyString2,MyString3);

            lr_output_message(">>>>>>>>>> MyString2 = %s",MyString2);

            // Catenate MyString2 to MyString1

            //

            strcat(MyString1,MyString2);

            lr_output_message(">>>>>>>>>> MyString1 = %s",MyString1);

            // Cstring is converted to integer Cint

            //

            lr_output_message(">>>>>>>>>> Cstring = %s",Cstring);

            Cint = atoi(Cstring);

            lr_output_message(">>>>>>>>>> Cint = %d",Cint);

            // Cint is converted to string

            Cint = 100;

            itoa(Cint,Cstring,10);

            lr_output_message(">>>>>>>>>> Cstring = %s",Cstring);

            return 0;

    }

    //To send an error message to the LoadRunner output window or Application Management agent log,
    use the lr_error_message function.
    It is not recommended that you send a message to the output window or agent log in the middle of a transaction,
    as it will lengthen the execution time. To send a message to the Vuser execution log or Application Management Web site,
    but not to the Output window, use lr_log_message.

251/212>
Open Toolbar