近来对Perl有点兴趣,就写了个小程序,刚好有软工作业,于是分别用白黑盒测试了下,效果还是不错的!!!以后写网页表单验证可以用到。
说明下,身份证分一代证15位与二代证18位,其中前六位地区码,(这个没有验证)18位多的就是年份是四位,15位的年份两位,前两位默认为“19”,18位的最后一位为校验码,具体算法请看程序,其中前17位每一位都有权值,算出总和后模11算出对应的校验码即可。
更多说明请Google之。。。
其中带#标记的是用来标记白盒测试路径点,不知道是否合理,但是,一个正则表达式就搞定很多情况啊!!!
其中输入为,相信是看得懂的^_^
./cardValidate.pl -c [your id card number] -s [your sex]
#!/usr/bin/perl use strict; use Getopt::Long; sub validate_birth{ my ($year,$month,$day) = @_; if($year lt 1900 or $year gt 2011){#9 10 die "Bitrhday error year!\n"; } if($month eq "00" or $month gt 12){#11 12 die "Bitrhday error month!\n"; } my %days = ( "01" => 31,"03" => 31,"04" => 30,"05" => 31,"06" => 30,"07" => 31,"08" => 31,"09" => 30,"10" => 31,"11" => 30,"12" => 31 ); if($year % 400 eq 0 or ($year % 4 eq 0 and $year % 100 ne 0)){#13 #14 $days{"02"} = 28; }else{#16 $days{"02"} = 29; } if($days{$month} lt $day or $day eq "00"){#17 #18 die "Bitrhday error date!\n"; } return 1; } ################### begin ###################### our $code; our $sex; Getoptions("c=s" => \$code,"s=s" => \$sex);#1 if($code eq "" or $sex eq ""){#2 3 print "Usage: ./cardValidate.pl -c [your id card number] -s [your sex]\n"; die "\tNote: the length of your id number should be 15 or 18\n"; } our $code_len = length $code;#4 ################## basic rule and length ################## if($code !~ m/(^\d{15}$)|(\d{17}(\d|x|X)$)/){#5 die "Error code!\n"; } ################### birthday and sex ###################### my $sex_num; if($code_len eq 15){#6 &validate_birth("19".substr($code,6,2),substr($code,8,10,2));#8 $sex_num = substr($code,14,1) % 2; }elsif($code_len eq 18){#7 &validate_birth(substr($code,4),12,16,1) % 2; ################# validate last character ################## my @wight = (7,9,5,4,2,1,3,7,2);#权值 my @validate = ('1','0','x','9','8','7','6','5','4','3','2');#对应的校验码 my $sum = 0; for(my $i = 0;$i < 17;$i++){ $sum += @wight[$i] * substr($code,$i,1); } if(@validate[$sum % 11] ne lc substr($code,17,1)){#19 die "Error while validate the last character!,it should be ".@validate[$sum % 11]."\n"; } } ################# sex ###################### if(($sex_num eq 1 and $sex eq "女") or ($sex_num eq 0 and $sex eq "男")){#20 21 die "Wrong sex number!\n"; } print "Success!\n";#22
然后是用来测试的程序:
将身份证号码与0表示女,1表示男输入到文件中,比如:”7837838484884 0“ 就可以
每行一条数据,然后将文件名当作参数传入即可,当然,上面的程序需要放在同目录下。于是白黑盒测试的数据可以放一起全部测试
#!/usr/bin/perl use strict; open FILE,"< ",$ARGV[0] or die "id file not exist!\n"; my @lines = <FILE>; foreach(@lines){ if(~/^([\w\d]+) (\d)/){ my $sex = ($2 eq 0?"女":"男"); print "Test $1 with sex $sex\n"; system("./cardValidate.pl -c $1 -s $sex"); print "\n"; } }我想,脚本的魅力就是简洁高效吧,如果我用C去写,白盒测试可真是要命啊!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。