友善交流技术...

发布新日志

  • httperf web压力测试工具

    2012-04-24 14:34:35

    #安装httperf

     apt-get install httperf

    #测试请求数

    httperf --hog --client=0/1 --server=www.51testing.com --port=80 --uri=/ --send-buffer=4096 --recv-buffer=16384 --num-conns=10 --num-calls=1000

    #测试结果


    httperf: warning: open file limit > FD_SETSIZE; limiting max. # of open files to FD_SETSIZE
    Maximum connect burst length: 1

    Total: connections 10 requests 1010 replies 1000 test-duration 43.431 s

    Connection rate: 0.2 conn/s (4343.1 ms/conn, <=1 concurrent connections)
    Connection time [ms]: min 3465.5 avg 4343.1 max 6153.7 median 3720.5 stddev 1054.4
    Connection time [ms]: connect 27.7
    Connection length [replies/conn]: 100.000

    Request rate: 23.3 req/s (43.0 ms/req)
    Request size [B]: 68.0

    Reply rate [replies/s]: min 14.4 avg 23.0 max 28.8 stddev 5.4 (8 samples)
    Reply time [ms]: response 43.2 transfer 0.0
    Reply size [B]: header 260.0 content 0.0 footer 2.0 (total 262.0)
    Reply status: 1xx=0 2xx=0 3xx=1000 4xx=0 5xx=0

    CPU time [s]: user 10.46 system 32.97 (user 24.1% system 75.9% total 100.0%)
    Net I/O: 7.4 KB/s (0.1*10^6 bps)

    Errors: total 10 client-timo 0 socket-timo 0 connrefused 0 connreset 10
    Errors: fd-unavail 0 addrunavail 0 ftab-full 0 other 0

  • ajax-truClient & web 协议对比测试结果

    2012-04-20 17:48:46

      近来无事,做一次 ajax-truClient & web 协议,测试相同的功能模块性能对比

    测试的功能为:

    1)url1: http://www.51testing.com/?uid-132585 

    2)url2: http://www.51testing.com/?uid-132585-action-viewpro-showpro-1 

    测试场景:

       star Vusers :每2秒上15个用户

       duration:10并发,持续运行2分钟

       stop:每秒停止5个用户

    测试结果

     

    Save this table to a CSV file               
      Transaction Name 响应最小(s)

    响应平均(s)

    响应最大(s) Std. Deviation 90 Percent 成功事务 Fail Stop
    [-] 51testing                
      web_TP 0.841 1.51 12.446 1.208 2.966 1,090 0 5
      ajax-truClient 1.264 2.351 22.401 1.753 4.484 525 0 9

    测试疑问:

    1、测试结果相差1倍性能

      为什么在相同的配置,相同的场景,相同的网络情况下,测试的性能数据为什么差别这么多呢?

      loadrunner的问题,还是服务器的问题 ,还是网络的问题? loadrunner这个工具里面有多少是不为人知的东西呢?它的真实性让人怀疑?

    2、ajax TruClient 代码放那了?

       为什么这个协议录制后的脚本在 void main()函数里面看不到代码,这样设计又是为什么呢?

     

  • loadrunner性能分析-线程holding(死锁)

    2012-04-18 14:29:36

    性能分析-线程holding状态,系统无反映

    测试系统:公司开发的平台系统

    开发语言:java+c

    数据库  :mysql

    测试描述:

      测试功能:测试5个接口

      并发用户:20并发,运行30分钟

    实际结果

    1、监控tomcat 发现大量的线程 holding 状态

    2、java 线程都处于等待状态(应该是死锁),线程池被使用完。

    经过分析通过几个修改方案

    分析方法:脚本拆分法,确定那个功能引起的线程holding

      将loadrunner脚本一个一个运行,结果发现任务的接口都可以引起线程holding状态的出现,这说明了不是一个接口出现了问题,而是所有的接口都会引起线程holding的出现,进而分析可能的原因:

       共同的功能模块出现问题:共同的模块应该是锁或是DB调用的公共模块出现问题。和开发一起分析,现在只有JAVA有锁,通过JNI调用C,这说明JAVA锁出现了问题。分析到这后,尝试的解决办法是:

       a)修改JAVA锁 -》结果验证失败

       b)增加C语言中超时时间,设置10秒自动断开链接->结果失败  

       c)让C来进行加锁来实现-》结果成功 

    经验总结:

       综合场景发现了问题,不太容易定位问题是那个功能或是接口引起时,建议单接口进行压力测试,如果再次出现本问题说明了:公共模块出现了问题,让开发注意公共模块,一般都是锁或是DB调用什么的。

     

  • loadruner 学习资源(转)

    2012-04-18 10:12:56

    Read First

    What is Load Testing (10 Pages)
    C:\Program Files\HP\LoadRunner\help\Learn_More_Testing.pdf

    HP LoadRunner Quick Start (30 Pages)
    C:\Program Files\HP\LoadRunner\tutorial\LR_QuickStart.pdf

    Tutorial (150 Pages)
    C:\Program Files\HP\LoadRunner\tutorial\Tutorial.pdf

    User Guides

    Virtual User Generator (1420 Pages)
    C:\Program Files\HP\LoadRunner\help\vugen.pdf

    Controller (552 Pages)
    C:\Program Files\HP\LoadRunner\help\Cntrl_pc.pdf

    Analysis (676 Pages)
    C:\Program Files\HP\LoadRunner\help\analysis.pdf

    Online Monitoring Reference (402 Pages)
    C:\Program Files\HP\LoadRunner\help\online.pdf

    Additional Reading

    Installation Guide (80 Pages)
    C:\Program Files\HP\LoadRunner\help\install.pdf

    Monitoring Best Practices (248 Pages)
    C:\Program Files\HP\LoadRunner\help\Monitoring_BP.pdf

    Flex Protocol Enhancements (12 Pages)
    C:\Program Files\HP\LoadRunner\dat\Flex.pdf

    Thats 3580 Pages of information on LR – How many pages have you gone through? (I probably did less than 1500)

    The above can also be found in Compiled Help Files. A couple like the Automation and Function reference are not found in the PDFs above, so it makes sense to list out the locations of these.

    CHM Files

    Everything from the above PDF listing
    C:\Program Files\HP\LoadRunner\bin\online.chm

    Function Reference
    C:\Program Files\HP\LoadRunner\bin\FuncRef.chm

    C Language function ref
    C:\Program Files\HP\LoadRunner\bin\c_language_FuncRef.chm

    Automation Reference (dont even go there)
    C:\Program Files\HP\LoadRunner\bin\automation.chm

    Well thats with the Documentation on your PC.

    ————————————————————-

    Now for the online stuff. Remember, many of your queries can be solved by using the search functionality at any of the following sites. Make it a habit to devote time every week to go through the latest posts, and it will make quite a good difference in your learning path.

    Email Lists:
    http://tech.groups.yahoo.com/group/loadrunner/
    http://groups.google.com/group/LR-LoadRunner
    http://tech.groups.yahoo.com/group/Advanced-LoadRunner/ (very little activity there – only for experienced users)

    Discussion Boards:
    http://www.sqaforums.com/postlist.php?Cat=0&Board=UBB6 (ofcourse!)
    http://forums13.itrc.hp.com/service/forums/categoryhome.do?categoryId=915 (HP Perf Center Forum)
    http://www.bish.co.uk/forum/index.php?board=2.0 (Richard Bishop)

    White Papers / Presentations:
    HP LoadRunner tips and tricks
    https://h10078.www1.hp.com/bto/download/loadrunner-configuration.pdf
    Performance Center New Features:
    http://hpbroadband.com/(S(vlbj3h3h2ej4qane0gsonc55))/program.aspx?key=5831MtEPC7May2009
    LR Compiler
    http://www.loadtester.com/under-hood-loadrunner-compiler

    Blogs:
    Official HP Blog: http://www.communities.hp.com/online/blogs/loadrunner/default.aspx
    Scott Moore, Tim Chase et al http://www.loadtester.com/blog
    Alexander Podelko http://www.testingreflections.com/blog/67
    Stuart Moncrieff http://www.myloadtest.com/ & http://www.jds.net.au/tag/loadrunner/
    Dmitry Motevich http://motevich.blogspot.com/ (includes video tutorials)
    papayamilkshake/Hwee Seong Tan http://www.loadrunnertnt.com/tag/loadrunner/
    Kim Sandell http://ptfrontline.wordpress.com/category/loadrunner/
    Richard Bishop http://www.bish.co.uk/index.php?option=com_content&view=category&id=34:recent&Itemid=1

    Wilson Mar: (deserves a seperate heading of his own – not a blog – but additional reading)
    LoadRunner Architecture http://www.wilsonmar.com/1loadrun.htm
    VUScripting http://www.wilsonmar.com/1lrscript.htm
    VTS http://www.wilsonmar.com/1mercvts.htm
    AJAX RIA web app load testing using LoadRunner http://www.wilsonmar.com/ajax_rec.htm
    Results Explorer http://www.wilsonmar.com/lrexplore.htm

    Twitter Feeds
    Coming Soon

    Protocol & Application Specific Resources

    AJAX c & s
    http://www.wilsonmar.com/ajax_rec.htm

    Flex, AMF
    http://hpbroadband.com/(S(3uelw04503pkjo55saxzlofd))/program.aspx?key=5831LoadRunner24March10

    CITRIX
    CITRIX document (for LR7.51)
    http://www.ccaheaven.com/wps/Mercury%20Interactive’s%20LoadRunner%20for%20Citrix.pdf
    Tim Chase CITRIX Scripting Best Practices
    http://www.loadtester.com/whitepapers/Citrix_LoadRunner.pdf
    Scott Moore’s CITRIX Scripting Tips
    http://www.loadtester.com/citrix-tips-2007-part-1

    Remedy ARS
    From JDS http://www.jds.net.au/tech-tips/vugen-scripting-for-remedy/

    Misc stuff
    LoadRunner VuGen to JMeter conversion
    http://www.performanceengineer.com/blog/lr2jm-convert-loadrunner-scripts-to-jmeter/
    Various Links : http://loadtester.tumblr.com/

    Certification Information:
    http://h20546.www2.hp.com/main/americas/certification/?sitepick=PT (General Info)
    http://www.hp.com/partnerlearning/learner_id.html (HP Learner ID)
    https://ibt1.prometric.com/index.asp?ibt=9710657000& (Prometric Id)
  • Python 获取当前时间

    2012-04-17 12:10:06

    Python 获取当前时间

    1、获取当前时间:具体的代码实现

    import time
    ntime=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    print ntime

    2012-04-17 12:08:31  

     

    2、时间转换成毫米

      时间格式为: 10:45:34:750 转换成毫米。具体的代码实现

        def timeopf(self,ftime):
            import time ,datetime,string
            tt=ftime.split(":")
            sum=((int(tt[0])*3600+int(tt[1])*60+int(tt[2]))*1000 + int(tt[3]))
            return sum

     

     

  • python list操作

    2012-04-13 13:05:51

    python list操作

    list操作:快速创建list、新增item、删除item、重新赋值item、颠倒item顺序、检索item

    快捷创建list,两种方式:split方法、list函数和range函数配合使用。
     

    split方法。写一个字符串,字符之间以空格分隔,然后对该字符串使用split方法。
    a_list = 'a b c d e f g'.spit() //创建列表['a','b','c','d','e','f','g'],但这种写法要简洁很多

    list函数和range函数配合使用。可以快速地创建一个非常大的列表。
    a_list = list(range(100))  //很方便地创建一个0到99的列表

    新增item,四种方式:concatenation、append、extend、insert,后三种方式都是列表的方法。
    示例列表a_list = ['a']:
    concatenation添加。它添加的是另外一个列表,两个列表组合成一个新的列表:
    a_list = a_list + [2.0,3]  //列表较长时,可能会消耗大量内存

    append方法添加。它在原列表末尾添加一个item,item类型可以是任意的:
    a_list.append('hello') //在原有列表末尾添加一个类型为字符串的item
    a_list.append(['hello'])  //在原有列表末尾添加一个类型为列表的item

    extend方法添加。它类似于concatenation,只接受列表参数,并把列表中的item分解,然后添加到原有的列表:
    a_list.extend('hello') //在原有列表末尾添加5个字符item,因为它把hello视为列表
    a_list.extend(['hello'])  //在原有列表末尾添加1个item

    insert方法添加。在原有列表中插入item:
    a_list.insert(0,'c')  //在原有列表的0位置添加一个字符
    a_list.insert(0.['c'])  //在原有列表的0位置添加一个列表


    删除item,三种方式:del、remove、pop,后两种方式都是列表的方法。
    示例列表:a_list = ['a','b','c','hello']:
    del删除。它按item的索引值或切片进行删除:
    del a_list[0]   //删除列表的第一个值
    del a_list[:2]  //删除列表的前两个值。(为什么不是前三个呢?因为python的列表切片,包含前一个索引,但不包括后一个索引)

    remove方法删除。它不按item索引,而是按照item的值进行删除:
    a_list.remove('a')  //把a从列表中删除

    pop方法删除。它按item索引值进行删除,同时返回被删除的item值;若不指定索引,默认删除最后一个item:
    a_list.pop(1)  //删除列表的第二个值,并返回被删除的值
    a_list.pop()  //删除列表的最后一个值,并返回被删除的值


    重新赋值item,对指定索引使用assignment符号进行赋值:
    示例列表:a_list = ['a','b','c','hello']:
    a_list[1] = 'bbb' //列表的第二个值b,将被替换为bbb


    颠倒列表的item顺序,reverse方法:
    示例列表:a_list = ['a','b','c','hello']:
    a_list.reverse() //列表的item顺序将被从后到前重新排列,更改为['hello','c','b','a']


    检索列表的值,四种方式:in、not in、count、index,后两种方式是列表的方法。
    示例列表:a_list = ['a','b','c','hello']:
    判断值是否在列表中,in操作符:
    'a' in a_list  //判断值a是否在列表中,并返回True或False

    判断值是否不在列表,not in操作符:
    'a' not in a_list  //判断a是否不在列表中,并返回True或False

    统计指定值在列表中出现的次数,count方法:
    a_list.count('a')  //返回a在列表中的出现的次数

  • 性能分析常见图形

    2012-04-13 12:42:44

    Loadrunner 常见性能图形

    罗列出常见的性能图表。

  • Linux: Too many open filee 解决办法

    2012-04-06 17:29:30

    Linux系统默认最大打开文件数为1024个。

    1
    、相关命令:
    ulimit –a //
    查看当前设置
    ulimit –n 2048 //
    即设成2048,按实际需要设置,只是本shell生效的。重启或是重新链接都失效的。


    2
    、用户环境参数文件配置:
    /etc/profile中加入如下内容:

    if [ $SHELL = "/bin/ksh" ]; then 
    ulimit -p 16384 ulimit -n 65536 
    else 
    ulimit -u 16384 -n 65536 
    fi

    最好的解决办法,写入环境参数中来

    source /etc/profile 马上就可以生效的。

    ulimit -a 就可以看到修改后的数据

  • 删除7天前并大于1G的日志shell命令

    2012-04-05 11:03:42

    删除7天前并大于1G的日志shell命令

    1、脚本log.sh

    #!/bin/sh
    find /usr/local/apache-tomcat-6.0.20/logs -name "*log*"  -ctime +7 -size +1000000 | xargs rm -rf

    2、增加到执行计划中

    crontab -e

    30 23     * * *   /root/log.sh

    crontab -l 查看增加是否成功

     

  • find 命令常用集合

    2012-03-30 23:16:50

    通用格式:find pathname -options [-print -exec -ok]
    例子:
    find / -name filename 再根目录里面搜索文件名为filename的文件
    find /etc -name *s*在目录里面搜索带有s的文件
    find /etc -name *S 在目录里面搜索以s结尾的文件
    find /etc -name s*在目录里面搜索以s开头的文件
    find / -amin -10在系统中搜索最后10分钟访问的文件
    find / -atime -2查找在系统中最后48小时访问的文件
    find / -empty 查找在系统中为空的文件或者是文件夹
    find / -group groupname 查找在系统中属于groupname的文件
    find / -mmin -5查找在系统中最后5分钟修改过的文件
    find / -mtime -1查找在系统中最后24小时修改过的文件
    find /-nouser查找在系统中属于费用户的文件
    find / -user username 查找在系统中属于username的文件
    find / -ctime -1查找在系统中最后24小时被改变状态的文件
    find / -fstype type查找在系统中文件类型为?的文件
    find / -user user1name -or -user user2name查找在系统中属于user1name或着属于user2name的文件
    find / -user user1name -and -user2name在系统中查找既属于user1name又属于user2name用户的文件.

    一、find 命令格式


    1、find命令的一般形式为;

    find pathname -options [-print -exec -ok ...]


    2、find命令的参数;

    pathname: find命令所查找的目录路径。例如用.来表示当前目录,用/来表示系统根目录。
    -print: find命令将匹配的文件输出到标准输出。
    -exec: find命令对匹配的文件执行该参数所给出的shell命令。相应命令的形式为'command' { } \;,注意{ }和\;之间的空格。
    -ok: 和-exec的作用相同,只不过以一种更为安全的模式来执行该参数所给出的shell命令,在执行每一个命令之前,都会给出提示,让用户来确定是否执行。


    3、find命令选项

    -name
    按照文件名查找文件。
    -perm
    按照文件权限来查找文件。
    -prune
    使用这一选项可以使find命令不在当前指定的目录中查找,如果同时使用-depth选项,那么-prune将被find命令忽略。
    -user
    按照文件属主来查找文件。
    -group
    按照文件所属的组来查找文件。
    -mtime -n +n
    按照文件的更改时间来查找文件, - n表示文件更改时间距现在n天以内,+ n表示文件更改时间距现在n天以前。find命令还有-atime和-ctime 选项,但它们都和-m time选项。
    -nogroup
    查找无有效所属组的文件,即该文件所属的组在/etc/groups中不存在。
    -nouser
    查找无有效属主的文件,即该文件的属主在/etc/passwd中不存在。
    -newer file1 ! file2
    查找更改时间比文件file1新但比文件file2旧的文件。
    -type
    查找某一类型的文件,诸如:
    b - 块设备文件。
    d - 目录。
    c - 字符设备文件。
    p - 管道文件。
    l - 符号链接文件。
    f - 普通文件。
    -size n:[c] 查找文件长度为n块的文件,带有c时表示文件长度以字节计。
    -depth:在查找文件时,首先查找当前目录中的文件,然后再在其子目录中查找。
    -fstype:查找位于某一类型文件系统中的文件,这些文件系统类型通常可以在配置文件/etc/fstab中找到,该配置文件中包含了本系统中有关文件系统的信息。
    -mount:在查找文件时不跨越文件系统mount点。
    -follow:如果find命令遇到符号链接文件,就跟踪至链接所指向的文件。
    -cpio:对匹配的文件使用cpio命令,将这些文件备份到磁带设备中。

    另外,下面三个的区别:
      -amin n
      查找系统中最后N分钟访问的文件
      -atime n
      查找系统中最后n*24小时访问的文件
      -cmin n
      查找系统中最后N分钟被改变文件状态的文件
      -ctime n
      查找系统中最后n*24小时被改变文件状态的文件
       -mmin n
      查找系统中最后N分钟被改变文件数据的文件
      -mtime n
      查找系统中最后n*24小时被改变文件数据的文件

  • mysqldumpslow命令查看mysql 慢查询日志 

    2012-03-30 16:12:42

    MYSQL服务器有一项功能,可以检测到哪条sql语句查询得比较慢,就是慢查询slowlog,现在介绍如何开启。
    在[mysqld]下面增加如下代码:

    1. long_query_time = 1
    2. log-slow-queries = /usr/local/mysql/data/slow.log
    3. log-queries-not-using-indexes

    long_query_time = 1 #定义超过1秒的查询计数到变量Slow_queries。
    log-slow-queries = /usr/local/mysql/data/slow.log #定义慢查询日志路径。
    log-queries-not-using-indexes #未使用索引的查询也被记录到慢查询日志中(可选)。
    mysql自带了一个查看慢日志的工具mysqldumpslow。
    执行mysqldumpslow –h可以查看帮助信息。
    主要介绍两个参数-s和-t
    -s 这个是排序参数,可选的有:
    al: 平均锁定时间
    ar: 平均返回记录数
    at: 平均查询时间
    c: 计数
    l: 锁定时间
    r: 返回记录
    t: 查询时间

    -t n 显示头n条记录。
    实例:
    mysqldumpslow -s c -t 20 host-slow.log
    mysqldumpslow -s r -t 20 host-slow.log
    上述命令可以看出访问次数最多的20个sql语句和返回记录集最多的20个sql。
    mysqldumpslow -t 10 -s t -g “left join” host-slow.log
    这个是按照时间返回前10条里面含有左连接的sql语句。
    用了这个工具就可以查询出来那些sql语句是性能的瓶颈,进行优化,比如加索引,该应用的实现方式等。

  • python xml 读操作

    2012-03-30 15:02:44

    1、导入库

    from xml.etree.ElementTree import ElementTree
    from xml.etree.ElementTree import Element
    from xml.etree.ElementTree import SubElement
    from xml.etree.ElementTree import dump
    from xml.etree.ElementTree import Comment
    from xml.etree.ElementTree import tostring
    '''
    <?xml version="1.0"?>
    <PurchaseOrder>
      <account refnum="2390094"/>
      <item sku="33-993933" qty="4">
        <name>Potato Smasher</name>
        <description>Smash Potatoes like never before.</description>
      </item>
    </PurchaseOrder>
    '''

    2、读文件的内容
    root=ElementTree(file='d:\\book.xml').getroot()
    print root.find('item/description').text
    print root.find('item').get('sku')
    print root.find('item').get('qty')

    3、输出想要的结果

  • python 链接oracle

    2012-03-29 11:31:34

    1、python 链接oracle 代码

    import cx_Oracle
    class Oracle():
        con = cx_Oracle.connect('system','tester','localhost:1521/ORCL')
        cursor = con.cursor()
        def select(self,sqselect):
            sqselect="""SELECT * FROM fang"""
            self.cursor.execute(sqselect)
            row=self.cursor.fetchall()
            print row[0][0]
            self.cursor.close()
            self.con.close()

        def insert(self,sqlinsert):
            sqlinsert=""" insert into fang values(10000,'fang',30) """
            self.cursor.execute(sqlinsert)
            self.cursor.close()
            self.con.commit()
            self.con.close()

        def update(self,sqlupdate):
            sqlupdate=""" update fang set id=110 where name='fang' """
            self.cursor.execute(sqlupdate)
            self.cursor.close()
            self.con.commit()
            self.con.close()

        def createtable(self,sqlcreate):
            sqlcreate=""" create table fang(id int ,name varchar(10),age int) """
            self.cursor.execute(sqlcreate)
            self.cursor.close()
            self.con.commit()
            self.con.close()

    oracle=Oracle()
    print oracle.select('')

    2、cx_Oracle 下载

    http://cx-oracle.sourceforge.net/ 

     

  • python 匹配文件内容后,拆分文件

    2012-03-22 23:46:32

    import os,sys,re
    #获取匹配的列表
    def audioReceList(filename):
        f1=open(filename,'rb')
        p1=re.compile('(Received RTP piece type=\[258\], DispatchID=\[[0-9]*\])')
        li=[]
        li2=[]
        for a in f1:
            m1=p1.search(a)
            if m1:
                li.append(m1.group(0))
        li={}.fromkeys(li).keys()
        for a in li:
            b=a.replace('[','\[')
            b=b.replace(']','\]')
            li2.append(b)
        f1.close()
        return li2
     
    #将匹配的内容分别放置在不同的文件中,拆分文件
    def filesplit(sfile,li2,filename):
        #li2=videoReceList(sfile)
        i=0
        for ab in li2:
            fp=open(sfile,'rb')
            f1=open(filename+'_'+str(i),'wb')
            ab='(.*)('+ab+')(.*)'
            print ab
            p=re.compile(ab)
            for aa in fp:
                m=p.search(aa)
                if m:
                    f1.writelines(aa)
                else:
                    pass
            i=i+1
            f1.close()
            fp.close()
     

     
  • python 文件操作技巧

    2012-03-21 23:40:38

    #获回文件的列表

      def fileList(self,filePath):
            li=''
            li2=[]
            li=os.listdir(filePath)
            for a in li:
                li2.append(filePath+'\\'+a)
            return li2

     

    读写文件(转)

    # ! /usr/bin/python
    #
     -*- coding: utf8 -*- 

    spath
    = " D:/download/baa.txt "
    f
    = open(spath, " w " #  Opens file for writing.Creates this file doesn't exist.
    f.write( " First line 1.\n " )
    f.writelines(
    " First line 2. " )

    f.close()

    f
    = open(spath, " r " #  Opens file for reading

    for  line  in  f:
        
    print ( " 每一行的数据是:%s " % line)

    f.close()

    '''
        知识点: 如何读写文件
    '''



     



     

    遍历文件夹和文件



     

    import  os
    import  os.path
    #  os,os.path里包含大多数文件访问的函数,所以要先引入它们.
    #
     请按照你的实际情况修改这个路径
    rootdir  =   " d:/download "
    for  parent, dirnames, filenames  in  os.walk(rootdir):
        
    # case 1:
         for  dirname  in  dirnames:
            
    print  ( " parent is: "   +  parent)
            
    print  ( " dirname is: "   +  dirname)
        
    # case 2
         for  filename  in  filenames:
            
    print  ( " parent is: "   +  parent)
            
    print  ( " filename with full path : "   +  os.path.join(parent, filename))

    ''' 知识点:

        * os.walk返回一个三元组.其中dirnames是所有文件夹名字(不包含路径),filenames是所有文件的名字(不包含路径).parent表示父目录.
        * case1 演示了如何遍历所有目录.
        * case2 演示了如何遍历所有文件.
        * os.path.join(dirname,filename) : 将形如"/a/b/c"和"d.java"变成/a/b/c/d.java".
    '''


     


    分割路径和文件名

    import  os.path
    # 常用函数有三种:分隔路径,找出文件名.找出盘符(windows系统),找出文件的扩展名.
    #
    根据你机器的实际情况修改下面参数.
    spath = " D:/download/repository.7z "

    #  case 1:
    p,f = os.path.split(spath);
    print ( " dir is: " + p)
    print ( " file is: " + f)

    #  case 2:
    drv,left = os.path.splitdrive(spath);
    print ( " driver is: " + drv)
    print ( " left is: " + left)
    #  case 3:
    f,ext = os.path.splitext(spath);
    print ( " f is: " + f)
    print ( " ext is: " + ext)
    '''
        知识点:    这三个函数都返回二元组.
        * case1 分隔目录和文件名
        * case2 分隔盘符和文件名
        * case3 分隔文件和扩展名
    '''



    总结:5个函数

    • os.walk(spath)
    • os.path.split(spath)
    • os.path.splitdrive(spath)
    • os.path.splitext(spath)
    • os.path.join(path1,path2)


     


    复制文件


     

    import  shutil
    import  os
    import  os.path

    src
    = " d:\\download\\test\\myfile1.txt "
    dst
    = " d:\\download\\test\\myfile2.txt "
    dst2
    = " d:/download/test/测试文件夹.txt "

    dir1
    = os.path.dirname(src)

    print ( " dir1 %s " % dir1)

    if (os.path.exists(src) == False):
        os.makedirs(dir1)       

    f1
    = open(src, " w " )
    f1.write(
    " line a\n " )
    f1.write(
    " line b\n " )
    f1.close()


    shutil.copyfile(src, dst)
    shutil.copyfile(src, dst2)
    f2
    = open(dst, " r " )
    for  line  in  f2:
        
    print (line)

    f2.close()

    # 测试复制文件夹树
    try :
        srcDir
    = " d:/download/test "
        dstDir
    = " d:/download/test2 "
        
    # 如果dstDir已经存在,那么shutil.copytree方法会报错!
         # 这也意味着你不能直接用d:作为目标路径.
        shutil.copytree(srcDir, dstDir)
    except  Exception as err:
        
    print  (err)
        
    '''
        知识点:
        * shutil.copyfile:如何复制文件
        * os.path.exists:如何判断文件夹是否存在
        * shutil.copytree:如何复制目录树    
    '''


    总结:4个函数

    • os.path.dirname(path)
    • os.path.exists(path)
    • shutil.copyfile(src, dst)
    • shutil.copytree(srcDir, dstDir)


     


    实战:文件备份小程序


     

    import  os
    import  shutil
    import  datetime

    '''
    作用:将目录备份到其他路径。
    实际效果:
    假设给定目录"/media/data/programmer/project/python" ,
    备份路径"/home/diegoyun/backup/“ ,
    则会将python目录备份到备份路径下,形如:
    /home/diegoyun/backup/yyyymmddHHMMSS/python/xxx/yyy/zzz..

    用法:更改这两个参数.
    backdir:备份目的地.
    copydirs:想要备份的文件夹.
    '''


    def  mainLogic():
        
    # add dirs you want to copy
        backdir = " d:\\test "
        
    print (backdir)

        copydirs
    = []
        copydirs.append(
    " d:\\temp " );
        
    # copydirs.append("d:\\test");
        
        

        
    print ( " Copying files  =================== " )
        start
    = datetime.datetime.now()

        
    # gen a data folder for backup
        backdir = os.path.join(backdir,start.strftime( " %Y-%m-%d " ))
        
    # print("backdir is:"+backdir)

        
        kc
    = 0
        
    for  d  in  copydirs:
            kc
    = kc + copyFiles(d,backdir)

        end
    = datetime.datetime.now()
        
    print ( " Finished! =================== " )
        
    print ( " Total files :  "   +  str(kc) )
        
    print ( " Elapsed time :  "   +  str((end - start).seconds) + "  seconds " )

    def  copyFiles(copydir,backdir):
        prefix
    = getPathPrefix(copydir)
        
    # print("prefix is:"+prefix )   

        i
    = 0
        
    for  dirpath,dirnames,filenames  in  os.walk(copydir):
            
    for  name  in  filenames:
                oldpath
    = os.path.join(dirpath,name)
                newpath
    = omitPrefix(dirpath,prefix)
                
    print ( " backdir is: " + backdir )           
                newpath
    = os.path.join(backdir,newpath)
                
    print ( " newpath is: " + newpath)

                
    if  os.path.exists(newpath) != True:
                    os.makedirs(newpath)  
                newpath
    = os.path.join(newpath,name)
                
    print ( " From: " + oldpath + "  to: " + newpath)
                shutil.copyfile(oldpath,newpath)
                i
    = i + 1
        
    return  i    

    def  getPathPrefix(fullpath):
        
    # Giving /media/data/programmer/project/ , get the prefix
         # /media/data/programmer/
        l = fullpath.split(os.path.sep)
        
    # print(str(l[-1]=="")    
         if  l[ - 1 ] == "" :
            tmp
    = l[ - 2 ]
        
    else :
            tmp
    = l[ - 1 ]
        
    return  fullpath[0:len(fullpath) - len(tmp) - 1 ]

    def  omitPrefix(fullpath,prefix):
        
    # Giving /media/data/programmer/project/python/tutotial/file/test.py ,
         # and prefix is Giving /media/data/programmer/project/,
         # return path as python/tutotial/file/test.py
         return  fullpath[len(prefix) + 1 :]

    mainLogic()

     

  • 测试经理工作

    2012-03-21 22:59:36

    测试经理的工作:
       如何成为一个合格的测试经理,没有一个严格的定义,个人感觉做好测试经理需要几个方面的能力
     
    1、测试专业知识
     
       功能测试,性能测试,安全等等,至少在一方面强于他人
       过强的专业知识是自己带领团队的基础,这样手下干活的人,也比较佩服你,
       如果你的专业知识二把刀,估计管理起来也是一个二把刀。
       
    2、管理能力:
      
       组建团队的能力,带领团队的能力,面试的招聘专业测试人员的能力
       管理本部门的人,钱与资源的分配问题
       项目的测试计划,风险评估功能
     
    3、沟通协调能力
     
       本部门内部的沟通能力,能留住核心人员,经常与自己的下手谈谈心,了解下面的人心里想的
       部门之间的沟通能力,处理好测试与开发之间的协助关系
       与BOSS之间的沟通能力,是一个承上启下的能力
     
    4、风险意识
       对于领导必须要知识什么是对的,什么是错误的。大家都说:
       领导是关心事情是不是做对了,而下面的人关心事情是不是做正确了
       是不是做对了,就说明是一个方向的问题,如果方向错了,就是事情本身做正确又有什么意义呢?
       领导培养自己的风险意识
     
    5、质量意识
      
       已经做测试5年多了,接触的测试领导也不少,但是自己感觉好多的测试经理对产品的质量不是很重视的
       1)测试不充分,早早上线,最后出问题了,版本下线或是被老板骂了半天
       2)测试时间不够,也没有提出风险。
       3)提前摘清责任,说不是自己的责任
       4)产品上线不是测试说了算,最后有经理经理确定
       5)测试问题开发重视度低,测试经理没有对这个问题引起重视
       等等的问题,个人感觉测试经理要有质量意识很重要。
     
    6、为他人着想
     
       把公司的事情当成自己的事情来做,而不是当别人的事情做,这样你为公司着想,才能将自己的能力发挥出来
       将自己的能力展示出来,这样不但可以为公司节省钱,时间,还有资源同时还得到了公司的赏识,真是双赢
       为自己的手下人着想,知识他们内心的世界,要不突然有一天一个人给你说想离开公司,很突然
       你没有准备的情况下,测试资源可能就会有问题。更重要的是,如果对自己的手下好一点
       他们如果换工作了也会记得你的好,到别的公司也一样可以推荐你的,我深有感触的。
       我为人人,人人为我!
     
      时间不早了,感觉自己说了一堆的费话,但还是职场很有用的东西。
     
      
     
     
     
     
     
     
  • python socket实现

    2012-02-16 14:48:45

    import socket
    import re
    import time
    #毫秒级别
    def furl(str):
        tstart=time.time()*1000
    #链接服务器
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect(('192.168.37.122', 2322))
    #请求的数据
        
    str='GET /xxx/xxx/ HTTP/1.1\r\nHost:192.168.37.122:2322\r\nConnection:Keep-Alive\r\n\r\n'
        sock.send(str)
        recv=sock.recv(1024)
    #匹配满足要求的数据(billingCode)
        p=re.compile(r'[a-z][0-9]{5,9}')
        m=p.search(recv)
        #print m.group(0)

    #关闭socket
        sock.close()

        tend=time.time()*1000
        print  tend-tstart
        return m.group(0)

    print furl('')

  • python 按匹配的内容来拆分成满足要件的子文件

    2012-02-16 14:45:30

    # 拆分文件(按匹配的关键词来拆分文件)

    import sys, os, stat
    import re
    from os.path import join, getsize

    mydict={}
    p = re.compile(r'(http-9081-[0-9]{1,3})')
    path='E:\\test\\'   #文件路径

    for line in open('e:\\catalina.out','r'):

        m=p.search(line)
        if m:
            #print m.group()
            if  not mydict.has_key(m.group()):    #字典取重
                s=path + '\\' + m.group()         #取文件的绝对路径
                print s
                mydict[m.group(1)] = open(s, 'w') #打开文件
            mydict[m.group(1)].write(line)        #写文件


     

  • python 操作mysql

    2012-02-16 14:41:43

    class cmysql(object):

        def mysqlselect(self,ahost,auser,apasswd,adb,acode,sql):
            import sys,string,os
            import MySQLdb
            conn=MySQLdb.connect(host=ahost,user=auser,passwd=apasswd,db=adb,charset=acode)

            cursor=conn.cursor()
            #sql = "select * from product"
            cursor.execute(sql)
            alldata = cursor.fetchall()
            if alldata:
                for rec in alldata:
                    print rec[0],rec[1]

            cursor.close()
            conn.close()

        def mysqlalterdate(self,ahost,auser,apasswd,adb,acode,sql):
            import sys,string,os
            import MySQLdb
            conn=MySQLdb.connect(host=ahost,user=auser,passwd=apasswd,db=adb,charset=acode)

            cursor=conn.cursor()
            flag = cursor.execute(sql)
            conn.commit()
            if flag:
                print 'Alter Data  Sucess!'
            cursor.close()
            conn.close()

        #定义一个函数,查询SQL语句的函数

    ms = cmysql()


    host='localhost'
    user='root'
    passwd='tester'
    db='test'
    charset='utf8'

    sql_select = "select * from T1"
    sql_insert = 'INSERT INTO T1 VALUES (0003,\'fang\')'
    sql_update = 'UPDATE T1 SET ID =1999 where name=\'xiao\''
    sql_delete='delete from t1 where id=1999'

    #更新语句
    ms.mysqlalterdate(host,user,passwd,db,charset,sql_insert)

    #更新数据
    ms.mysqlalterdate(host,user,passwd,db,charset,sql_update)

    #清理数据
    ms.mysqlalterdate(host,user,passwd,db,charset,sql_delete)

    #查询语句
    ms.mysqlselect(host,user,passwd,db,charset,sql_select)

  • python 访问URL

    2012-02-16 14:39:48

    import pycurl
    import StringIO
    import re

    url = "http://www.baidu.com/"
    crl = pycurl.Curl()
    crl.setopt(pycurl.VERBOSE,1)
    crl.setopt(pycurl.FOLLOWLOCATION, 1)
    crl.setopt(pycurl.MAXREDIRS, 5)
    crl.fp = StringIO.StringIO()
    crl.setopt(pycurl.URL, url)
    crl.setopt(crl.WRITEFUNCTION, crl.fp.write)
    crl.perform()

    #只打印出<body>部分

    p=re.compile(r'(<body>.*)(.*</body>)', re.DOTALL)
    #p=re.compile(r'(<a href=\".*\">)', re.DOTALL)
    m=p.search(crl.fp.getvalue())
    if m:
        print m.group(0)

     

     

1713/9<123456789>
Open Toolbar