From 508b19b7434f7d72a21850e2d8c57663d356144e Mon Sep 17 00:00:00 2001 From: hou Date: Wed, 24 May 2023 15:32:33 +0800 Subject: [PATCH 01/20] =?UTF-8?q?=E6=8F=90=E4=BA=A4coreutils=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=E5=A5=97=E6=A8=A1=E6=9D=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hou --- coreutils/testcase/.tc-mkdir-01.sh.swm | Bin 0 -> 4096 bytes coreutils/testcase/.tc-mkdir-01.sh.swn | Bin 0 -> 12288 bytes coreutils/testcase/.tc-mkdir-01.sh.swo | Bin 0 -> 12288 bytes coreutils/testcase/tc-mkdir-01.sh | 52 +++++++++++++++++++------ coreutils/tst_common | 1 - 5 files changed, 41 insertions(+), 12 deletions(-) create mode 100644 coreutils/testcase/.tc-mkdir-01.sh.swm create mode 100644 coreutils/testcase/.tc-mkdir-01.sh.swn create mode 100644 coreutils/testcase/.tc-mkdir-01.sh.swo delete mode 160000 coreutils/tst_common diff --git a/coreutils/testcase/.tc-mkdir-01.sh.swm b/coreutils/testcase/.tc-mkdir-01.sh.swm new file mode 100644 index 0000000000000000000000000000000000000000..15f78cd4f7c8ba56fdd7a4b412d502e2ddec1c05 GIT binary patch literal 4096 zcmeIuu?oU46a~=t1A-_x*E%<8>*6msIO-mg(1xaclEi-#zrl~vIv0d)!hO@@!o9<} zmY3rxJBXS-w6r!oF@p0)BV$0WX=;a<66q9kuhcdD_mNH!)nG*WZ0 z_vCz(W1>~GGU=l4j0;6siP%o8Ac6n{<_RolUsvVW-R0YCy*kgEK??#9fB*y_009U< K00I#BOMy24SS1kv literal 0 HcmV?d00001 diff --git a/coreutils/testcase/.tc-mkdir-01.sh.swn b/coreutils/testcase/.tc-mkdir-01.sh.swn new file mode 100644 index 0000000000000000000000000000000000000000..8f197eb6a5989c02b4e3694be6b37b4ad174edc4 GIT binary patch literal 12288 zcmeI2+iM*~9LJ}=)Yiln#Wx=&n?p$|=bEOe(Mp7>1e;V%+LscKo3nFrmh3G%voWzL zic+nKLhyn`q*c7MT4K~-g+`--ihqFM<-xx6oD;!EAARtDFHGtaj3))-!gMCm1=nYRFfE=ATM9a7X;DbplZNRhGuad`ZP1HqQVJ*qHm5*4 z>B(g?p>L1typPd%b-ba0WaNOi%(301b42KidfT z4qO6DU>?kY0C3=gA~*~l20dUmxN-|2zk?sZ_uv%}fF5uMXaiSv67mc98LWcKUDc$E?kd_5~KDkpRzP*%Ph`l!(1D!y{09d({aWe z%7a3Iab658YgYE*F(Yy|i*XDtbP;fjgiiR(qsb|%4b6@`dYGD=I4WP{Bos3uAnH-1DRFPQEd?vsv2njX5k z>4|@3N4o1Afka;T0i(xhmL}O0KF6YgwC3fgqmNrG%!|PU^KH|?15TYHmprfpZ{(+u z9;%JFc4WqBQ6{!#hFsLOABN<*Wy$V1Ex5L4A%vk}W(bgX1K|ZCC1ymNkfzmgf8EUs z=h8@Yz4N-oM%{(W%ZX+ir?2w)!us;-)zw!kXWxomq|$Qz$wRkEtPDzX_wC7I?Fbf4 zt!aQ#)Ph0N0r%7LG;ieG)J2p>y8iXz`a3U0i$#Wvg0|QUS#C2<^wRq%oH&s1R-IN!X%kvi^ zarj1+fuY8dMyA)V4UUb;lZ7GgA~kE<(m^fJWlsubV>>XqHJtF=+KX^E@Ud@bi4&tE zqxsR1{OFNK4h=qbG97NpSo5~)q%CtCXS%~%oZXfiC7Uq?&Bi+`oAF$vv&CP|y`?3b ziO+P)(?tp4y0GUuI;v1hWVG&dDy3m|$7%8@G_?3>bd2uVgPme)C*Daq=|J_h3s=_` zs-Lcw&o1;+Y=`U5ebs2My!}FTX|2D}P`!MX4|9%2{x&k)SD8Id(KXBmh4-0W@BPg z6s1}dh2RSokycULYKc*T6&j5SDt-XLmkWE-b4~;={Q&-VcF$W)5khW?v*dTq?(Fl- zGxLAu84@yu%#%aI^k6DSaP1}Jr&ZgyOf*tBPl)fjB5eMz%W{jlRdTsV$veZfb<^3z zDedXSDSeXhq+nc_&Sbji`YaHp#nWL+QRgfzib;FQF#TjEo8qNSdQnYE0j0p!6lf>C zxojr%?bJHxop&7DS~to|DWDWk3Md7X0!jg;fKosypcJ?%6%gJI@*GBfOFa6K_>1F5nYv2l42A9Am z;2kgzrod4!0{X!{U?12CuI(b^V=x0O@CX-R7(tMWP3aB#4kI9;_{gYe1~SD2b(7Si5Uc(%nRGY!9#>!jOwKpnf-;G|R(sKRDL$^t+3`%nkbY-!21dFED zG(ah8(V*#o`)PTaH*#+3BFZD(_-1M2{a2&KB11;OTJmYQ$R`&XiEo2O164D;LVAFAdP%MpJp|wd#e>2C&D~&$l;T4jmq# pxlFD%)0f+y%;vHO`ZCD_{r6@M_UHCzwtqey>4NE`3p&o%{{!-HmbCx? literal 0 HcmV?d00001 diff --git a/coreutils/testcase/tc-mkdir-01.sh b/coreutils/testcase/tc-mkdir-01.sh index 0875eb7..bab9497 100755 --- a/coreutils/testcase/tc-mkdir-01.sh +++ b/coreutils/testcase/tc-mkdir-01.sh @@ -1,6 +1,6 @@ #!/bin/bash ############################################################################### -# @用例ID: 20230106-200139-207891169 +# @用例ID: 20230524-121650-679187240 # @用例名称: tc-mkdir-01 # @用例级别: 3 # @用例标签: @@ -17,28 +17,58 @@ g_tmpdir="$(mktemp -d)" tc_setup() { msg "this is tc_setup" - # @预置条件: 系统已安装coreutils软件包 - return 0 + # 启动MySQL + sudo service mysql start + + #检查MySQL是否成功启动 + status=$(service mysql status) + + if echo "$status" | grep -q "MySQL running";then + echo "MySQL started successfully." + return 0 + else + echo "Failed to start MySQL." + return 1 + fi } do_test() { msg "this is do_test" - # @测试步骤:1: 创建目录验证mkdir命令基础功能 - # @预期结果:1: 目录创建成功,符合参数设置预期 - assert_true mkdir "$g_tmpdir/mkdir.test" - assert_true test -d "$g_tmpdir/mkdir.test" - assert_true rm -rv "$g_tmpdir/mkdir.test" + # 运行MySQL测试 + cd /usr/local/mysql/mysql-test + ./mysql-test-run 2>&1 | tee test_output.txt + + #检查测试结果 - assert_true mkdir -p "$g_tmpdir/mkdir.test/child" - assert_true test -d "$g_tmpdir/mkdir.test/child" - assert_true rm -rv "$g_tmpdir/mkdir.test" + if grep -q "All tests" "test_output.txt"; then + echo "All tests passed" + elif grep -q "Not all tests completed" "test_output.txt";then + echo "Some tests failed" + else + echo "Unable to determine test results" + fi + + assert_true [ 1 -eq 1 ] return 0 } tc_teardown() { msg "this is tc_teardown" + #关闭MySQL + sudo service mysql stop + + #等待MySQL关闭 + sleep 10 + + #检查MySQL是否关闭成功 + status=$(sudo service mysql status) + if echo "status" | grep -q "MySQL running";then + echo "Failed to stop the mysql." + else + echo "The mysql has been successfully stopped." + fi rm -rfv "$g_tmpdir" || return 1 return 0 } diff --git a/coreutils/tst_common b/coreutils/tst_common deleted file mode 160000 index 432a241..0000000 --- a/coreutils/tst_common +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 432a2418e8ca5665011e641fd02b25a3af194002 -- Gitee From 9ac42bdbb782bd437d93344ea6a48e3d106cddef Mon Sep 17 00:00:00 2001 From: hou Date: Wed, 24 May 2023 22:38:19 +0800 Subject: [PATCH 02/20] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E7=94=A8=E4=BE=8Btc-mkdir-01=E9=AA=8C=E8=AF=81mkdir=E5=91=BD?= =?UTF-8?q?=E4=BB=A4=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hou --- coreutils/testcase/tc-mkdir-01.sh | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/coreutils/testcase/tc-mkdir-01.sh b/coreutils/testcase/tc-mkdir-01.sh index bab9497..1d458ae 100755 --- a/coreutils/testcase/tc-mkdir-01.sh +++ b/coreutils/testcase/tc-mkdir-01.sh @@ -36,7 +36,14 @@ do_test() { msg "this is do_test" # 运行MySQL测试 - cd /usr/local/mysql/mysql-test + #cd /usr/local/mysql/mysql-test + MYSQL_TEST_RUN=$(witch mysql-test-run) + if [-x "$MYSQL_TEST_RUN"];then + mysql_test_run_dir=$(dirname "$MYSQL_TEST_RUN") + cd "$mysql_test_run_dir" + else + echo "mysql-test-run not found" + fi ./mysql-test-run 2>&1 | tee test_output.txt #检查测试结果 -- Gitee From b5649b062f6fa8584988caf17e4cd5db57c4e5fb Mon Sep 17 00:00:00 2001 From: hou Date: Thu, 25 May 2023 02:29:13 +0000 Subject: [PATCH 03/20] =?UTF-8?q?=E6=B5=8B=E8=AF=95=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E4=B8=BAmysql-test.sh?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hou --- coreutils/testcase/mysql-test.sh | 87 ++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 coreutils/testcase/mysql-test.sh diff --git a/coreutils/testcase/mysql-test.sh b/coreutils/testcase/mysql-test.sh new file mode 100644 index 0000000..c311502 --- /dev/null +++ b/coreutils/testcase/mysql-test.sh @@ -0,0 +1,87 @@ +#!/bin/bash +############################################################################### +# @用例ID: 20230525-101210-083410876 +# @用例名称: mysql-test +# @用例级别: 3 +# @用例标签: +# @用例类型: 功能 +############################################################################### +[ -z "$TST_TS_TOPDIR" ] && { + TST_TS_TOPDIR="$(realpath "$(dirname "$0")/..")" + export TST_TS_TOPDIR +} +source "${TST_TS_TOPDIR}/tst_common/lib/common.sh" || exit 1 +############################################################################### + +g_tmpdir="$(mktemp -d)" + +tc_setup() { + msg "this is tc_setup" + # 启动MySQL + sudo service mysql start + + #检查MySQL是否成功启动 + status=$(service mysql status) + + if echo "$status" | grep -q "MySQL running";then + echo "MySQL started successfully." + return 0 + else + echo "Failed to start MySQL." + return 1 + fi +} + +do_test() { + msg "this is do_test" + + # 运行MySQL测试 + cd /usr/local/mysql/mysql-test + #MYSQL_TEST_RUN=$(which mysql-test-run) + #if [-x "$MYSQL_TEST_RUN"];then +# mysql_test_run_dir=$(dirname "$MYSQL_TEST_RUN") +# cd "$mysql_test_run_dir" + # else +# echo "mysql-test-run not found" + # fi + # ./mysql-test-run 2>&1 | tee test_output.txt + + #检查测试结果 + + if grep -q "All tests" "test_output.txt"; then + echo "All tests passed" + elif grep -q "Not all tests completed" "test_output.txt";then + echo "Some tests failed" + else + echo "Unable to determine test results" + fi + + assert_true [ 1 -eq 1 ] + + return 0 +} + + +tc_teardown() { + msg "this is tc_teardown" + #关闭MySQL + sudo service mysql stop + + #等待MySQL关闭 + sleep 10 + + #检查MySQL是否关闭成功 + status=$(sudo service mysql status) + if echo "status" | grep -q "MySQL running";then + echo "Failed to stop the mysql." + else + echo "The mysql has been successfully stopped." + fi + rm -rfv "$g_tmpdir" || return 1 + return 0 +} + + +############################################################################### +tst_main "$@" +############################################################################### -- Gitee From 399da69c6778c1b9ac196966be3479c3634ea78d Mon Sep 17 00:00:00 2001 From: hougit1 Date: Thu, 25 May 2023 10:37:58 +0800 Subject: [PATCH 04/20] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E7=94=A8=E4=BE=8Bmysql-test.sh?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hougit1 --- coreutils/testcase/.tc-mkdir-01.sh.swm | Bin 4096 -> 0 bytes coreutils/testcase/.tc-mkdir-01.sh.swn | Bin 12288 -> 0 bytes coreutils/testcase/.tc-mkdir-01.sh.swo | Bin 12288 -> 0 bytes coreutils/testcase/mysql-test.sh | 2 +- coreutils/testcase/tc-mkdir-01.sh | 59 +++++-------------------- 5 files changed, 12 insertions(+), 49 deletions(-) delete mode 100644 coreutils/testcase/.tc-mkdir-01.sh.swm delete mode 100644 coreutils/testcase/.tc-mkdir-01.sh.swn delete mode 100644 coreutils/testcase/.tc-mkdir-01.sh.swo mode change 100644 => 100755 coreutils/testcase/mysql-test.sh diff --git a/coreutils/testcase/.tc-mkdir-01.sh.swm b/coreutils/testcase/.tc-mkdir-01.sh.swm deleted file mode 100644 index 15f78cd4f7c8ba56fdd7a4b412d502e2ddec1c05..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4096 zcmeIuu?oU46a~=t1A-_x*E%<8>*6msIO-mg(1xaclEi-#zrl~vIv0d)!hO@@!o9<} zmY3rxJBXS-w6r!oF@p0)BV$0WX=;a<66q9kuhcdD_mNH!)nG*WZ0 z_vCz(W1>~GGU=l4j0;6siP%o8Ac6n{<_RolUsvVW-R0YCy*kgEK??#9fB*y_009U< K00I#BOMy24SS1kv diff --git a/coreutils/testcase/.tc-mkdir-01.sh.swn b/coreutils/testcase/.tc-mkdir-01.sh.swn deleted file mode 100644 index 8f197eb6a5989c02b4e3694be6b37b4ad174edc4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 12288 zcmeI2+iM*~9LJ}=)Yiln#Wx=&n?p$|=bEOe(Mp7>1e;V%+LscKo3nFrmh3G%voWzL zic+nKLhyn`q*c7MT4K~-g+`--ihqFM<-xx6oD;!EAARtDFHGtaj3))-!gMCm1=nYRFfE=ATM9a7X;DbplZNRhGuad`ZP1HqQVJ*qHm5*4 z>B(g?p>L1typPd%b-ba0WaNOi%(301b42KidfT z4qO6DU>?kY0C3=gA~*~l20dUmxN-|2zk?sZ_uv%}fF5uMXaiSv67mc98LWcKUDc$E?kd_5~KDkpRzP*%Ph`l!(1D!y{09d({aWe z%7a3Iab658YgYE*F(Yy|i*XDtbP;fjgiiR(qsb|%4b6@`dYGD=I4WP{Bos3uAnH-1DRFPQEd?vsv2njX5k z>4|@3N4o1Afka;T0i(xhmL}O0KF6YgwC3fgqmNrG%!|PU^KH|?15TYHmprfpZ{(+u z9;%JFc4WqBQ6{!#hFsLOABN<*Wy$V1Ex5L4A%vk}W(bgX1K|ZCC1ymNkfzmgf8EUs z=h8@Yz4N-oM%{(W%ZX+ir?2w)!us;-)zw!kXWxomq|$Qz$wRkEtPDzX_wC7I?Fbf4 zt!aQ#)Ph0N0r%7LG;ieG)J2p>y8iXz`a3U0i$#Wvg0|QUS#C2<^wRq%oH&s1R-IN!X%kvi^ zarj1+fuY8dMyA)V4UUb;lZ7GgA~kE<(m^fJWlsubV>>XqHJtF=+KX^E@Ud@bi4&tE zqxsR1{OFNK4h=qbG97NpSo5~)q%CtCXS%~%oZXfiC7Uq?&Bi+`oAF$vv&CP|y`?3b ziO+P)(?tp4y0GUuI;v1hWVG&dDy3m|$7%8@G_?3>bd2uVgPme)C*Daq=|J_h3s=_` zs-Lcw&o1;+Y=`U5ebs2My!}FTX|2D}P`!MX4|9%2{x&k)SD8Id(KXBmh4-0W@BPg z6s1}dh2RSokycULYKc*T6&j5SDt-XLmkWE-b4~;={Q&-VcF$W)5khW?v*dTq?(Fl- zGxLAu84@yu%#%aI^k6DSaP1}Jr&ZgyOf*tBPl)fjB5eMz%W{jlRdTsV$veZfb<^3z zDedXSDSeXhq+nc_&Sbji`YaHp#nWL+QRgfzib;FQF#TjEo8qNSdQnYE0j0p!6lf>C zxojr%?bJHxop&7DS~to|DWDWk3Md7X0!jg;fKosypcJ?%6%gJI@*GBfOFa6K_>1F5nYv2l42A9Am z;2kgzrod4!0{X!{U?12CuI(b^V=x0O@CX-R7(tMWP3aB#4kI9;_{gYe1~SD2b(7Si5Uc(%nRGY!9#>!jOwKpnf-;G|R(sKRDL$^t+3`%nkbY-!21dFED zG(ah8(V*#o`)PTaH*#+3BFZD(_-1M2{a2&KB11;OTJmYQ$R`&XiEo2O164D;LVAFAdP%MpJp|wd#e>2C&D~&$l;T4jmq# pxlFD%)0f+y%;vHO`ZCD_{r6@M_UHCzwtqey>4NE`3p&o%{{!-HmbCx? diff --git a/coreutils/testcase/mysql-test.sh b/coreutils/testcase/mysql-test.sh old mode 100644 new mode 100755 index c311502..cb07a96 --- a/coreutils/testcase/mysql-test.sh +++ b/coreutils/testcase/mysql-test.sh @@ -44,7 +44,7 @@ do_test() { # else # echo "mysql-test-run not found" # fi - # ./mysql-test-run 2>&1 | tee test_output.txt + ./mysql-test-run 2>&1 | tee test_output.txt #检查测试结果 diff --git a/coreutils/testcase/tc-mkdir-01.sh b/coreutils/testcase/tc-mkdir-01.sh index 1d458ae..0875eb7 100755 --- a/coreutils/testcase/tc-mkdir-01.sh +++ b/coreutils/testcase/tc-mkdir-01.sh @@ -1,6 +1,6 @@ #!/bin/bash ############################################################################### -# @用例ID: 20230524-121650-679187240 +# @用例ID: 20230106-200139-207891169 # @用例名称: tc-mkdir-01 # @用例级别: 3 # @用例标签: @@ -17,65 +17,28 @@ g_tmpdir="$(mktemp -d)" tc_setup() { msg "this is tc_setup" - # 启动MySQL - sudo service mysql start - - #检查MySQL是否成功启动 - status=$(service mysql status) - - if echo "$status" | grep -q "MySQL running";then - echo "MySQL started successfully." - return 0 - else - echo "Failed to start MySQL." - return 1 - fi + # @预置条件: 系统已安装coreutils软件包 + return 0 } do_test() { msg "this is do_test" - # 运行MySQL测试 - #cd /usr/local/mysql/mysql-test - MYSQL_TEST_RUN=$(witch mysql-test-run) - if [-x "$MYSQL_TEST_RUN"];then - mysql_test_run_dir=$(dirname "$MYSQL_TEST_RUN") - cd "$mysql_test_run_dir" - else - echo "mysql-test-run not found" - fi - ./mysql-test-run 2>&1 | tee test_output.txt - - #检查测试结果 + # @测试步骤:1: 创建目录验证mkdir命令基础功能 + # @预期结果:1: 目录创建成功,符合参数设置预期 + assert_true mkdir "$g_tmpdir/mkdir.test" + assert_true test -d "$g_tmpdir/mkdir.test" + assert_true rm -rv "$g_tmpdir/mkdir.test" - if grep -q "All tests" "test_output.txt"; then - echo "All tests passed" - elif grep -q "Not all tests completed" "test_output.txt";then - echo "Some tests failed" - else - echo "Unable to determine test results" - fi - - assert_true [ 1 -eq 1 ] + assert_true mkdir -p "$g_tmpdir/mkdir.test/child" + assert_true test -d "$g_tmpdir/mkdir.test/child" + assert_true rm -rv "$g_tmpdir/mkdir.test" return 0 } tc_teardown() { msg "this is tc_teardown" - #关闭MySQL - sudo service mysql stop - - #等待MySQL关闭 - sleep 10 - - #检查MySQL是否关闭成功 - status=$(sudo service mysql status) - if echo "status" | grep -q "MySQL running";then - echo "Failed to stop the mysql." - else - echo "The mysql has been successfully stopped." - fi rm -rfv "$g_tmpdir" || return 1 return 0 } -- Gitee From 06c271bf87a6fddf124b2e8647371af0b0a6eca3 Mon Sep 17 00:00:00 2001 From: hougit1 Date: Thu, 25 May 2023 10:51:36 +0800 Subject: [PATCH 05/20] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E7=94=A8=E4=BE=8B=E8=87=AA=E5=8A=A8=E5=AF=BB=E5=9D=80=E5=8A=9F?= =?UTF-8?q?=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hougit1 --- coreutils/testcase/mysql-test.sh | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/coreutils/testcase/mysql-test.sh b/coreutils/testcase/mysql-test.sh index cb07a96..548da4e 100755 --- a/coreutils/testcase/mysql-test.sh +++ b/coreutils/testcase/mysql-test.sh @@ -36,9 +36,11 @@ do_test() { msg "this is do_test" # 运行MySQL测试 - cd /usr/local/mysql/mysql-test - #MYSQL_TEST_RUN=$(which mysql-test-run) - #if [-x "$MYSQL_TEST_RUN"];then + mysql_install_path=$(which mysql) + cd $(dirname $(which mysql)/mysql-test +# cd /usr/local/mysql/mysql-test +# MYSQL_TEST_RUN=$(which mysql-test-run) +# if [-d "$MYSQL_TEST_RUN"];then # mysql_test_run_dir=$(dirname "$MYSQL_TEST_RUN") # cd "$mysql_test_run_dir" # else -- Gitee From c7db672eebd0cf991f6f62a0080e7e123ec53390 Mon Sep 17 00:00:00 2001 From: hougit1 Date: Thu, 25 May 2023 10:55:34 +0800 Subject: [PATCH 06/20] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E7=94=A8=E4=BE=8B=E8=87=AA=E5=8A=A8=E5=AF=BB=E5=9D=80=E5=8A=9F?= =?UTF-8?q?=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hougit1 --- coreutils/testcase/mysql-test.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/coreutils/testcase/mysql-test.sh b/coreutils/testcase/mysql-test.sh index 548da4e..55ee01f 100755 --- a/coreutils/testcase/mysql-test.sh +++ b/coreutils/testcase/mysql-test.sh @@ -37,7 +37,9 @@ do_test() { # 运行MySQL测试 mysql_install_path=$(which mysql) - cd $(dirname $(which mysql)/mysql-test + cd $(dirname $(which mysql)) + cd .. + cd mysql-test # cd /usr/local/mysql/mysql-test # MYSQL_TEST_RUN=$(which mysql-test-run) # if [-d "$MYSQL_TEST_RUN"];then -- Gitee From 72c0e286e07157ede7a422ef6206aafa6c142dfd Mon Sep 17 00:00:00 2001 From: hougit1 Date: Thu, 25 May 2023 13:11:28 +0800 Subject: [PATCH 07/20] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E9=AA=8C=E8=AF=81?= =?UTF-8?q?=E6=98=AF=E5=90=A6=E5=AE=89=E8=A3=85mysql=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hougit1 --- coreutils/testcase/mysql-test.sh | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/coreutils/testcase/mysql-test.sh b/coreutils/testcase/mysql-test.sh index 55ee01f..b2b38ff 100755 --- a/coreutils/testcase/mysql-test.sh +++ b/coreutils/testcase/mysql-test.sh @@ -17,6 +17,17 @@ g_tmpdir="$(mktemp -d)" tc_setup() { msg "this is tc_setup" + + #检查是否安装了MySQL + + if ! command -v mysql >/dev/null 2>&1; then + echo "MySQL not installed." + return 1 + else + mysql_version=$(mysql -V |awk '{print $3}' | awk -F, '{print $1}') + echo “MySQL version: $mysql_version” + fi + # 启动MySQL sudo service mysql start @@ -36,18 +47,12 @@ do_test() { msg "this is do_test" # 运行MySQL测试 + + #查找安装路径 mysql_install_path=$(which mysql) cd $(dirname $(which mysql)) cd .. cd mysql-test -# cd /usr/local/mysql/mysql-test -# MYSQL_TEST_RUN=$(which mysql-test-run) -# if [-d "$MYSQL_TEST_RUN"];then -# mysql_test_run_dir=$(dirname "$MYSQL_TEST_RUN") -# cd "$mysql_test_run_dir" - # else -# echo "mysql-test-run not found" - # fi ./mysql-test-run 2>&1 | tee test_output.txt #检查测试结果 @@ -57,7 +62,8 @@ do_test() { elif grep -q "Not all tests completed" "test_output.txt";then echo "Some tests failed" else - echo "Unable to determine test results" + echo "Test failed!" + return 1 fi assert_true [ 1 -eq 1 ] @@ -80,6 +86,7 @@ tc_teardown() { echo "Failed to stop the mysql." else echo "The mysql has been successfully stopped." + return 1 fi rm -rfv "$g_tmpdir" || return 1 return 0 -- Gitee From a3ac150ac9754fb626969ac19d6a94d32d4cd050 Mon Sep 17 00:00:00 2001 From: hougit1 Date: Thu, 25 May 2023 13:17:14 +0800 Subject: [PATCH 08/20] =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hougit1 --- coreutils/tst_common/.gitignore | 33 + coreutils/tst_common/LICENSE | 824 ++++++++++++++++++ coreutils/tst_common/Makefile | 27 + coreutils/tst_common/Makefile.common | 2 + coreutils/tst_common/README.md | 21 + coreutils/tst_common/cmd/Makefile | 20 + coreutils/tst_common/cmd/tsuite.c | 6 + coreutils/tst_common/docs/API-C.md | 24 + coreutils/tst_common/docs/API-Python.md | 62 ++ coreutils/tst_common/docs/API-Shell.md | 68 ++ coreutils/tst_common/kmod/Makefile | 28 + coreutils/tst_common/kmod/kmod_common.c | 14 + coreutils/tst_common/lib/Makefile | 20 + coreutils/tst_common/lib/benchmark.c | 389 +++++++++ coreutils/tst_common/lib/benchmark.h | 81 ++ coreutils/tst_common/lib/benchmark.py | 304 +++++++ coreutils/tst_common/lib/common.c | 597 +++++++++++++ coreutils/tst_common/lib/common.h | 139 +++ coreutils/tst_common/lib/common.py | 755 ++++++++++++++++ coreutils/tst_common/lib/common.sh | 734 ++++++++++++++++ coreutils/tst_common/lib/common_func.sh | 88 ++ coreutils/tst_common/lib/main.h | 12 + coreutils/tst_common/lib/sched.py | 129 +++ coreutils/tst_common/lib/tst_ts_setup | 55 ++ coreutils/tst_common/lib/tst_ts_teardown | 47 + .../tst_common/lib/tsuite-completion.bash | 51 ++ coreutils/tst_common/lib/tsuite_func.sh | 497 +++++++++++ coreutils/tst_common/testcase/Makefile | 20 + .../tst_common/testcase/test_c_testcase.c | 35 + .../tst_common/testcase/test_perf_tools.py | 51 ++ .../testcase/test_python_testcase.py | 38 + .../testcase/test_shell_testcase.sh | 47 + coreutils/tst_common/tsuite | 17 + 33 files changed, 5235 insertions(+) create mode 100644 coreutils/tst_common/.gitignore create mode 100644 coreutils/tst_common/LICENSE create mode 100644 coreutils/tst_common/Makefile create mode 100644 coreutils/tst_common/Makefile.common create mode 100644 coreutils/tst_common/README.md create mode 100644 coreutils/tst_common/cmd/Makefile create mode 100644 coreutils/tst_common/cmd/tsuite.c create mode 100644 coreutils/tst_common/docs/API-C.md create mode 100644 coreutils/tst_common/docs/API-Python.md create mode 100644 coreutils/tst_common/docs/API-Shell.md create mode 100644 coreutils/tst_common/kmod/Makefile create mode 100644 coreutils/tst_common/kmod/kmod_common.c create mode 100644 coreutils/tst_common/lib/Makefile create mode 100644 coreutils/tst_common/lib/benchmark.c create mode 100644 coreutils/tst_common/lib/benchmark.h create mode 100644 coreutils/tst_common/lib/benchmark.py create mode 100644 coreutils/tst_common/lib/common.c create mode 100644 coreutils/tst_common/lib/common.h create mode 100644 coreutils/tst_common/lib/common.py create mode 100644 coreutils/tst_common/lib/common.sh create mode 100644 coreutils/tst_common/lib/common_func.sh create mode 100644 coreutils/tst_common/lib/main.h create mode 100644 coreutils/tst_common/lib/sched.py create mode 100755 coreutils/tst_common/lib/tst_ts_setup create mode 100755 coreutils/tst_common/lib/tst_ts_teardown create mode 100644 coreutils/tst_common/lib/tsuite-completion.bash create mode 100644 coreutils/tst_common/lib/tsuite_func.sh create mode 100644 coreutils/tst_common/testcase/Makefile create mode 100644 coreutils/tst_common/testcase/test_c_testcase.c create mode 100755 coreutils/tst_common/testcase/test_perf_tools.py create mode 100755 coreutils/tst_common/testcase/test_python_testcase.py create mode 100755 coreutils/tst_common/testcase/test_shell_testcase.sh create mode 100755 coreutils/tst_common/tsuite diff --git a/coreutils/tst_common/.gitignore b/coreutils/tst_common/.gitignore new file mode 100644 index 0000000..8e67438 --- /dev/null +++ b/coreutils/tst_common/.gitignore @@ -0,0 +1,33 @@ +# Build and Release Folders +bin-debug/ +bin-release/ +[Oo]bj/ +[Bb]in/ + +# Other files and folders +.settings/ + +# Executables +*.swf +*.air +*.ipa +*.apk + +# Project files, i.e. `.project`, `.actionScriptProperties` and `.flexProperties` +# should NOT be excluded as they contain compiler settings and other important +# information for Eclipse / Flash Builder. +.idea/ +logs/ +__pycache__/ +*.o +*.a +*.d +*.cmd +*.test +*.log +*.ko +*.mod +*.mod.c +Module.symvers +modules.order +compile_commands.json diff --git a/coreutils/tst_common/LICENSE b/coreutils/tst_common/LICENSE new file mode 100644 index 0000000..d06cc9f --- /dev/null +++ b/coreutils/tst_common/LICENSE @@ -0,0 +1,824 @@ +Tencent is pleased to support the open source community by making OpenCloudOS Kernel Stream available. + +Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. The below software in this distribution may have been modified by THL A29 Limited ("Tencent Modifications"). All Tencent Modifications are Copyright (C) THL A29 Limited. + +OpenCloudOS Kernel Stream is licensed under the the Mulan Permissive Software License 2.0 except for the third-party components listed below. + + +Terms of the Mulan Permissive Software License 2.0: +-------------------------------------------------------------------- + 木兰宽松许可证, 第2版 + +2020年1月 http://license.coscl.org.cn/MulanPSL2 + +您对“软件”的复制、使用、修改及分发受木兰宽松许可证,第2版(“本许可证”)的如下条款的约束: + +0. 定义 + +“软件”是指由“贡献”构成的许可在“本许可证”下的程序和相关文档的集合。 + +“贡献”是指由任一“贡献者”许可在“本许可证”下的受版权法保护的作品。 + +“贡献者”是指将受版权法保护的作品许可在“本许可证”下的自然人或“法人实体”。 + +“法人实体”是指提交贡献的机构及其“关联实体”。 + +“关联实体”是指,对“本许可证”下的行为方而言,控制、受控制或与其共同受控制的机构,此处的控制是指有受控方或共同受控方至少50%直接或间接的投票权、资金或其他有价证券。 + +1. 授予版权许可 + +每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的版权许可,您可以复制、使用、修改、分发其“贡献”,不论修改与否。 + +2. 授予专利许可 + +每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的(根据本条规定撤销除外)专利许可,供您制造、委托制造、使用、许诺销售、销售、进口其“贡献”或以其他方式转移其“贡献”。前述专利许可仅限于“贡献者”现在或将来拥有或控制的其“贡献”本身或其“贡献”与许可“贡献”时的“软件”结合而将必然会侵犯的专利权利要求,不包括对“贡献”的修改或包含“贡献”的其他结合。如果您或您的“关联实体”直接或间接地,就“软件”或其中的“贡献”对任何人发起专利侵权诉讼(包括反诉或交叉诉讼)或其他专利维权行动,指控其侵犯专利权,则“本许可证”授予您对“软件”的专利许可自您提起诉讼或发起维权行动之日终止。 + +3. 无商标许可 + +“本许可证”不提供对“贡献者”的商品名称、商标、服务标志或产品名称的商标许可,但您为满足第4条规定的声明义务而必须使用除外。 + +4. 分发限制 + +您可以在任何媒介中将“软件”以源程序形式或可执行形式重新分发,不论修改与否,但您必须向接收者提供“本许可证”的副本,并保留“软件”中的版权、商标、专利及免责声明。 + +5. 免责声明与责任限制 + +“软件”及其中的“贡献”在提供时不带任何明示或默示的担保。在任何情况下,“贡献者”或版权所有者不对任何人因使用“软件”或其中的“贡献”而引发的任何直接或间接损失承担责任,不论因何种原因导致或者基于何种法律理论,即使其曾被建议有此种损失的可能性。 + +6. 语言 + +“本许可证”以中英文双语表述,中英文版本具有同等法律效力。如果中英文版本存在任何冲突不一致,以中文版为准。 + +条款结束 + +如何将木兰宽松许可证,第2版,应用到您的软件 + +如果您希望将木兰宽松许可证,第2版,应用到您的新软件,为了方便接收者查阅,建议您完成如下三步: + +1,请您补充如下声明中的空白,包括软件名、软件的首次发表年份以及您作为版权人的名字; + +2,请您在软件包的一级目录下创建以“LICENSE”为名的文件,将整个许可证文本放入该文件中; + +3,请将如下声明文本放入每个源文件的头部注释中。 + +Copyright (c) [Year] [name of copyright holder] [Software Name] is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. + +January 2020 http://license.coscl.org.cn/MulanPSL2 + +Your reproduction, use, modification and distribution of the Software shall be subject to Mulan PSL v2 (this License) with the following terms and conditions: + +0. Definition + +Software means the program and related documents which are licensed under this License and comprise all Contribution(s). + +Contribution means the copyrightable work licensed by a particular Contributor under this License. + +Contributor means the Individual or Legal Entity who licenses its copyrightable work under this License. + +Legal Entity means the entity making a Contribution and all its Affiliates. + +Affiliates means entities that control, are controlled by, or are under common control with the acting entity under this License, ‘control’ means direct or indirect ownership of at least fifty percent (50%) of the voting power, capital or other securities of controlled or commonly controlled entity. + +1. Grant of Copyright License + +Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable copyright license to reproduce, use, modify, or distribute its Contribution, with modification or not. + +2. Grant of Patent License + +Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable (except for revocation under this Section) patent license to make, have made, use, offer for sale, sell, import or otherwise transfer its Contribution, where such patent license is only limited to the patent claims owned or controlled by such Contributor now or in future which will be necessarily infringed by its Contribution alone, or by combination of the Contribution with the Software to which the Contribution was contributed. The patent license shall not apply to any modification of the Contribution, and any other combination which includes the Contribution. If you or your Affiliates directly or indirectly institute patent litigation (including a cross claim or counterclaim in a litigation) or other patent enforcement activities against any individual or entity by alleging that the Software or any Contribution in it infringes patents, then any patent license granted to you under this License for the Software shall terminate as of the date such litigation or activity is filed or taken. + +3. No Trademark License + +No trademark license is granted to use the trade names, trademarks, service marks, or product names of Contributor, except as required to fulfill notice requirements in Section 4. + +4. Distribution Restriction + +You may distribute the Software in any medium with or without modification, whether in source or executable forms, provided that you provide recipients with a copy of this License and retain copyright, patent, trademark and disclaimer statements in the Software. + +5. Disclaimer of Warranty and Limitation of Liability + +THE SOFTWARE AND CONTRIBUTION IN IT ARE PROVIDED WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED. IN NO EVENT SHALL ANY CONTRIBUTOR OR COPYRIGHT HOLDER BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO ANY DIRECT, OR INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING FROM YOUR USE OR INABILITY TO USE THE SOFTWARE OR THE CONTRIBUTION IN IT, NO MATTER HOW IT’S CAUSED OR BASED ON WHICH LEGAL THEORY, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +6. Language + +THIS LICENSE IS WRITTEN IN BOTH CHINESE AND ENGLISH, AND THE CHINESE VERSION AND ENGLISH VERSION SHALL HAVE THE SAME LEGAL EFFECT. IN THE CASE OF DIVERGENCE BETWEEN THE CHINESE AND ENGLISH VERSIONS, THE CHINESE VERSION SHALL PREVAIL. + +END OF THE TERMS AND CONDITIONS + + + +Other dependencies and licenses: + + +Open Source Software Licensed under the GPL v2.0 with Linux-syscall-note, and Other Licenses of the Third-Party Components therein: +The below software in this distribution may have been modified by THL A29 Limited ("Tencent Modifications"). All Tencent Modifications are Copyright (C) 2021 THL A29 Limited. +-------------------------------------------------------------------- +1. kernel +Copyright © kernel original author and authors + + +The Linux Kernel is provided under: + + SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + +Being under the terms of the GNU General Public License version 2 only, +according with: + + LICENSES/preferred/GPL-2.0 + +With an explicit syscall exception, as stated at: + + LICENSES/exceptions/Linux-syscall-note + +In addition, other licenses may also apply. Please see: + + Documentation/process/license-rules.rst + +for more details. + +All contributions to the Linux Kernel are subject to this COPYING file. + +Valid-License-Identifier: GPL-2.0 +Valid-License-Identifier: GPL-2.0-only +Valid-License-Identifier: GPL-2.0+ +Valid-License-Identifier: GPL-2.0-or-later +SPDX-URL: https://spdx.org/licenses/GPL-2.0.html +Usage-Guide: + To use this license in source code, put one of the following SPDX + tag/value pairs into a comment according to the placement + guidelines in the licensing rules documentation. + For 'GNU General Public License (GPL) version 2 only' use: + SPDX-License-Identifier: GPL-2.0 + or + SPDX-License-Identifier: GPL-2.0-only + For 'GNU General Public License (GPL) version 2 or any later version' use: + SPDX-License-Identifier: GPL-2.0+ + or + SPDX-License-Identifier: GPL-2.0-or-later +License-Text: + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. + +SPDX-Exception-Identifier: Linux-syscall-note +SPDX-URL: https://spdx.org/licenses/Linux-syscall-note.html +SPDX-Licenses: GPL-2.0, GPL-2.0+, GPL-1.0+, LGPL-2.0, LGPL-2.0+, LGPL-2.1, LGPL-2.1+, GPL-2.0-only, GPL-2.0-or-later +Usage-Guide: + This exception is used together with one of the above SPDX-Licenses + to mark user space API (uapi) header files so they can be included + into non GPL compliant user space application code. + To use this exception add it with the keyword WITH to one of the + identifiers in the SPDX-Licenses tag: + SPDX-License-Identifier: WITH Linux-syscall-note +License-Text: + + NOTE! This copyright does *not* cover user programs that use kernel + services by normal system calls - this is merely considered normal use + of the kernel, and does *not* fall under the heading of "derived work". + Also note that the GPL below is copyrighted by the Free Software + Foundation, but the instance of code that it refers to (the Linux + kernel) is copyrighted by me and others who actually wrote it. + + Also note that the only valid version of the GPL as far as the kernel + is concerned is _this_ particular version of the license (ie v2, not + v2.2 or v3.x or whatever), unless explicitly otherwise stated. + + Linus Torvalds + +For the licenses of other third parties, please refer to the following URL: +https://github.com/torvalds/linux/tree/v5.18-rc5/LICENSES + +Linux kernel licensing rules +The Linux Kernel is provided under the terms of the GNU General Public License version 2 only (GPL-2.0), as provided in LICENSES/preferred/GPL-2.0, with an explicit syscall exception described in LICENSES/exceptions/Linux-syscall-note, as described in the COPYING file. + +This documentation file provides a description of how each source file should be annotated to make its license clear and unambiguous. It doesn't replace the Kernel's license. + +The license described in the COPYING file applies to the kernel source as a whole, though individual source files can have a different license which is required to be compatible with the GPL-2.0: + +GPL-1.0+ : GNU General Public License v1.0 or later +GPL-2.0+ : GNU General Public License v2.0 or later +LGPL-2.0 : GNU Library General Public License v2 only +LGPL-2.0+ : GNU Library General Public License v2 or later +LGPL-2.1 : GNU Lesser General Public License v2.1 only +LGPL-2.1+ : GNU Lesser General Public License v2.1 or later +Aside from that, individual files can be provided under a dual license, e.g. one of the compatible GPL variants and alternatively under a permissive license like BSD, MIT etc. + +The User-space API (UAPI) header files, which describe the interface of user-space programs to the kernel are a special case. According to the note in the kernel COPYING file, the syscall interface is a clear boundary, which does not extend the GPL requirements to any software which uses it to communicate with the kernel. Because the UAPI headers must be includable into any source files which create an executable running on the Linux kernel, the exception must be documented by a special license expression. + +The common way of expressing the license of a source file is to add the matching boilerplate text into the top comment of the file. Due to formatting, typos etc. these "boilerplates" are hard to validate for tools which are used in the context of license compliance. + +An alternative to boilerplate text is the use of Software Package Data Exchange (SPDX) license identifiers in each source file. SPDX license identifiers are machine parsable and precise shorthands for the license under which the content of the file is contributed. SPDX license identifiers are managed by the SPDX Workgroup at the Linux Foundation and have been agreed on by partners throughout the industry, tool vendors, and legal teams. For further information see https://spdx.org/ + +The Linux kernel requires the precise SPDX identifier in all source files. The valid identifiers used in the kernel are explained in the section License identifiers and have been retrieved from the official SPDX license list at https://spdx.org/licenses/ along with the license texts. + +License identifier syntax +Placement: + +The SPDX license identifier in kernel files shall be added at the first possible line in a file which can contain a comment. For the majority of files this is the first line, except for scripts which require the '#!PATH_TO_INTERPRETER' in the first line. For those scripts the SPDX identifier goes into the second line. + + +Style: + +The SPDX license identifier is added in form of a comment. The comment style depends on the file type: + +C source: // SPDX-License-Identifier: +C header: /* SPDX-License-Identifier: */ +ASM: /* SPDX-License-Identifier: */ +scripts: # SPDX-License-Identifier: +.rst: .. SPDX-License-Identifier: +.dts{i}: // SPDX-License-Identifier: +If a specific tool cannot handle the standard comment style, then the appropriate comment mechanism which the tool accepts shall be used. This is the reason for having the "/* */" style comment in C header files. There was build breakage observed with generated .lds files where 'ld' failed to parse the C++ comment. This has been fixed by now, but there are still older assembler tools which cannot handle C++ style comments. + + +Syntax: + +A is either an SPDX short form license identifier found on the SPDX License List, or the combination of two SPDX short form license identifiers separated by "WITH" when a license exception applies. When multiple licenses apply, an expression consists of keywords "AND", "OR" separating sub-expressions and surrounded by "(", ")" . + +License identifiers for licenses like [L]GPL with the 'or later' option are constructed by using a "+" for indicating the 'or later' option.: + +// SPDX-License-Identifier: GPL-2.0+ +// SPDX-License-Identifier: LGPL-2.1+ +WITH should be used when there is a modifier to a license needed. For example, the linux kernel UAPI files use the expression: + +// SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note +// SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note +Other examples using WITH exceptions found in the kernel are: + +// SPDX-License-Identifier: GPL-2.0 WITH mif-exception +// SPDX-License-Identifier: GPL-2.0+ WITH GCC-exception-2.0 +Exceptions can only be used with particular License identifiers. The valid License identifiers are listed in the tags of the exception text file. For details see the point Exceptions in the chapter License identifiers. + +OR should be used if the file is dual licensed and only one license is to be selected. For example, some dtsi files are available under dual licenses: + +// SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause +Examples from the kernel for license expressions in dual licensed files: + +// SPDX-License-Identifier: GPL-2.0 OR MIT +// SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause +// SPDX-License-Identifier: GPL-2.0 OR Apache-2.0 +// SPDX-License-Identifier: GPL-2.0 OR MPL-1.1 +// SPDX-License-Identifier: (GPL-2.0 WITH Linux-syscall-note) OR MIT +// SPDX-License-Identifier: GPL-1.0+ OR BSD-3-Clause OR OpenSSL +AND should be used if the file has multiple licenses whose terms all apply to use the file. For example, if code is inherited from another project and permission has been given to put it in the kernel, but the original license terms need to remain in effect: + +// SPDX-License-Identifier: (GPL-2.0 WITH Linux-syscall-note) AND MIT +Another other example where both sets of license terms need to be adhered to is: + +// SPDX-License-Identifier: GPL-1.0+ AND LGPL-2.1+ +License identifiers +The licenses currently used, as well as the licenses for code added to the kernel, can be broken down into: + +Preferred licenses: + +Whenever possible these licenses should be used as they are known to be fully compatible and widely used. These licenses are available from the directory: + +LICENSES/preferred/ +in the kernel source tree. + +The files in this directory contain the full license text and Metatags. The file names are identical to the SPDX license identifier which shall be used for the license in source files. + +Examples: + +LICENSES/preferred/GPL-2.0 +Contains the GPL version 2 license text and the required metatags: + +LICENSES/preferred/MIT +Contains the MIT license text and the required metatags + +Metatags: + +The following meta tags must be available in a license file: + +Valid-License-Identifier: + +One or more lines which declare which License Identifiers are valid inside the project to reference this particular license text. Usually this is a single valid identifier, but e.g. for licenses with the 'or later' options two identifiers are valid. + +SPDX-URL: + +The URL of the SPDX page which contains additional information related to the license. + +Usage-Guidance: + +Freeform text for usage advice. The text must include correct examples for the SPDX license identifiers as they should be put into source files according to the License identifier syntax guidelines. + +License-Text: + +All text after this tag is treated as the original license text + +File format examples: + +Valid-License-Identifier: GPL-2.0 +Valid-License-Identifier: GPL-2.0+ +SPDX-URL: https://spdx.org/licenses/GPL-2.0.html +Usage-Guide: + To use this license in source code, put one of the following SPDX + tag/value pairs into a comment according to the placement + guidelines in the licensing rules documentation. + For 'GNU General Public License (GPL) version 2 only' use: + SPDX-License-Identifier: GPL-2.0 + For 'GNU General Public License (GPL) version 2 or any later version' use: + SPDX-License-Identifier: GPL-2.0+ +License-Text: + Full license text +SPDX-License-Identifier: MIT +SPDX-URL: https://spdx.org/licenses/MIT.html +Usage-Guide: + To use this license in source code, put the following SPDX + tag/value pair into a comment according to the placement + guidelines in the licensing rules documentation. + SPDX-License-Identifier: MIT +License-Text: + Full license text + +Deprecated licenses: + +These licenses should only be used for existing code or for importing code from a different project. These licenses are available from the directory: + +LICENSES/deprecated/ +in the kernel source tree. + +The files in this directory contain the full license text and Metatags. The file names are identical to the SPDX license identifier which shall be used for the license in source files. + +Examples: + +LICENSES/deprecated/ISC +Contains the Internet Systems Consortium license text and the required metatags: + +LICENSES/deprecated/GPL-1.0 +Contains the GPL version 1 license text and the required metatags. + +Metatags: + +The metatag requirements for 'other' licenses are identical to the requirements of the Preferred licenses. + +File format example: + +Valid-License-Identifier: ISC +SPDX-URL: https://spdx.org/licenses/ISC.html +Usage-Guide: + Usage of this license in the kernel for new code is discouraged + and it should solely be used for importing code from an already + existing project. + To use this license in source code, put the following SPDX + tag/value pair into a comment according to the placement + guidelines in the licensing rules documentation. + SPDX-License-Identifier: ISC +License-Text: + Full license text + +Dual Licensing Only + +These licenses should only be used to dual license code with another license in addition to a preferred license. These licenses are available from the directory: + +LICENSES/dual/ +in the kernel source tree. + +The files in this directory contain the full license text and Metatags. The file names are identical to the SPDX license identifier which shall be used for the license in source files. + +Examples: + +LICENSES/dual/MPL-1.1 +Contains the Mozilla Public License version 1.1 license text and the required metatags: + +LICENSES/dual/Apache-2.0 +Contains the Apache License version 2.0 license text and the required metatags. + +Metatags: + +The metatag requirements for 'other' licenses are identical to the requirements of the Preferred licenses. + +File format example: + +Valid-License-Identifier: MPL-1.1 +SPDX-URL: https://spdx.org/licenses/MPL-1.1.html +Usage-Guide: + Do NOT use. The MPL-1.1 is not GPL2 compatible. It may only be used for + dual-licensed files where the other license is GPL2 compatible. + If you end up using this it MUST be used together with a GPL2 compatible + license using "OR". + To use the Mozilla Public License version 1.1 put the following SPDX + tag/value pair into a comment according to the placement guidelines in + the licensing rules documentation: +SPDX-License-Identifier: MPL-1.1 +License-Text: + Full license text + +Exceptions: + +Some licenses can be amended with exceptions which grant certain rights which the original license does not. These exceptions are available from the directory: + +LICENSES/exceptions/ +in the kernel source tree. The files in this directory contain the full exception text and the required Exception Metatags. + +Examples: + +LICENSES/exceptions/Linux-syscall-note +Contains the Linux syscall exception as documented in the COPYING file of the Linux kernel, which is used for UAPI header files. e.g. /* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */: + +LICENSES/exceptions/GCC-exception-2.0 +Contains the GCC 'linking exception' which allows to link any binary independent of its license against the compiled version of a file marked with this exception. This is required for creating runnable executables from source code which is not compatible with the GPL. + +Exception Metatags: + +The following meta tags must be available in an exception file: + +SPDX-Exception-Identifier: + +One exception identifier which can be used with SPDX license identifiers. + +SPDX-URL: + +The URL of the SPDX page which contains additional information related to the exception. + +SPDX-Licenses: + +A comma separated list of SPDX license identifiers for which the exception can be used. + +Usage-Guidance: + +Freeform text for usage advice. The text must be followed by correct examples for the SPDX license identifiers as they should be put into source files according to the License identifier syntax guidelines. + +Exception-Text: + +All text after this tag is treated as the original exception text + +File format examples: + +SPDX-Exception-Identifier: Linux-syscall-note +SPDX-URL: https://spdx.org/licenses/Linux-syscall-note.html +SPDX-Licenses: GPL-2.0, GPL-2.0+, GPL-1.0+, LGPL-2.0, LGPL-2.0+, LGPL-2.1, LGPL-2.1+ +Usage-Guidance: + This exception is used together with one of the above SPDX-Licenses + to mark user-space API (uapi) header files so they can be included + into non GPL compliant user-space application code. + To use this exception add it with the keyword WITH to one of the + identifiers in the SPDX-Licenses tag: + SPDX-License-Identifier: WITH Linux-syscall-note +Exception-Text: + Full exception text +SPDX-Exception-Identifier: GCC-exception-2.0 +SPDX-URL: https://spdx.org/licenses/GCC-exception-2.0.html +SPDX-Licenses: GPL-2.0, GPL-2.0+ +Usage-Guidance: + The "GCC Runtime Library exception 2.0" is used together with one + of the above SPDX-Licenses for code imported from the GCC runtime + library. + To use this exception add it with the keyword WITH to one of the + identifiers in the SPDX-Licenses tag: + SPDX-License-Identifier: WITH GCC-exception-2.0 +Exception-Text: + Full exception text +All SPDX license identifiers and exceptions must have a corresponding file in the LICENSES subdirectories. This is required to allow tool verification (e.g. checkpatch.pl) and to have the licenses ready to read and extract right from the source, which is recommended by various FOSS organizations, e.g. the FSFE REUSE initiative. + +MODULE_LICENSE +Loadable kernel modules also require a MODULE_LICENSE() tag. This tag is neither a replacement for proper source code license information (SPDX-License-Identifier) nor in any way relevant for expressing or determining the exact license under which the source code of the module is provided. + +The sole purpose of this tag is to provide sufficient information whether the module is free software or proprietary for the kernel module loader and for user space tools. + +The valid license strings for MODULE_LICENSE() are: + +"GPL" Module is licensed under GPL version 2. This does not express any distinction between GPL-2.0-only or GPL-2.0-or-later. The exact license information can only be determined via the license information in the corresponding source files. +"GPL v2" Same as "GPL". It exists for historic reasons. +"GPL and additional rights" Historical variant of expressing that the module source is dual licensed under a GPL v2 variant and MIT license. Please do not use in new code. +"Dual MIT/GPL" The correct way of expressing that the module is dual licensed under a GPL v2 variant or MIT license choice. +"Dual BSD/GPL" The module is dual licensed under a GPL v2 variant or BSD license choice. The exact variant of the BSD license can only be determined via the license information in the corresponding source files. +"Dual MPL/GPL" The module is dual licensed under a GPL v2 variant or Mozilla Public License (MPL) choice. The exact variant of the MPL license can only be determined via the license information in the corresponding source files. +"Proprietary" The module is under a proprietary license. This string is solely for proprietary third party modules and cannot be used for modules which have their source code in the kernel tree. Modules tagged that way are tainting the kernel with the 'P' flag when loaded and the kernel module loader refuses to link such modules against symbols which are exported with EXPORT_SYMBOL_GPL(). \ No newline at end of file diff --git a/coreutils/tst_common/Makefile b/coreutils/tst_common/Makefile new file mode 100644 index 0000000..617a017 --- /dev/null +++ b/coreutils/tst_common/Makefile @@ -0,0 +1,27 @@ +export TST_COMMON_TOPDIR := $(shell pwd) +DIRS := cmd testcase kmod +LIBS := lib + +all: libs + @for d in $(DIRS); do \ + echo try make common $$d; \ + make -C $$d all; \ + done + +libs: + @for d in $(LIBS); do \ + echo try make common $$d; \ + make -C $$d all; \ + done + +clean: + @for d in $(DIRS) $(LIBS); do \ + echo try clean common $$d; \ + make -C $$d clean; \ + done + +cleanall: + @for d in $(DIRS) $(LIBS); do \ + echo try cleanall common $$d; \ + make -C $$d cleanall; \ + done diff --git a/coreutils/tst_common/Makefile.common b/coreutils/tst_common/Makefile.common new file mode 100644 index 0000000..80b47be --- /dev/null +++ b/coreutils/tst_common/Makefile.common @@ -0,0 +1,2 @@ +CFLAGS += -Wall -g -I$(TST_COMMON_TOPDIR)/lib +LDFLAGS += -lm -lrt -lpthread -lcommon -L$(TST_COMMON_TOPDIR)/lib diff --git a/coreutils/tst_common/README.md b/coreutils/tst_common/README.md new file mode 100644 index 0000000..315b9f9 --- /dev/null +++ b/coreutils/tst_common/README.md @@ -0,0 +1,21 @@ +# 概述 +本项目为自动化测试用例的公共代码库和框架代码,公共库接口函数见`docs/API-*.md`部分内容 +测试套应用请参考:https://gitee.com/opencloudos-stream/test-suite-example + +# 用法 +```shell +tsuite options sub_command sub_options + help: 显示帮助信息 + new case sh|c|py case_name [template]: 新增测试用例 + sh|c|py: 【必选】三选一,sh表示Shell脚本用例,c表示C用例,py表示Python脚本用例 + case_name: 【必选】要创建的用例名,同时用作文件名 + template: 【可选】不使用默认用例模板时,可以指定一个文件用作新用例模板 + list: 列出本测试套的测试用例 + compile: 编译测试套 + setup: 执行测试套setup + run [case_path|case_name]: 执行测试用例 + case_path|case_name: 【可选】不指定此参数时执行测试套所有用例,指定时执行指定用例 + teardown: 执行测试套teardown + clean: 执行make clean + cleanall: 执行make cleanall,在clean基础上删除所有临时文件等 +``` \ No newline at end of file diff --git a/coreutils/tst_common/cmd/Makefile b/coreutils/tst_common/cmd/Makefile new file mode 100644 index 0000000..7eec895 --- /dev/null +++ b/coreutils/tst_common/cmd/Makefile @@ -0,0 +1,20 @@ +export TST_COMMON_TOPDIR ?= $(shell pwd)/.. +include $(TST_COMMON_TOPDIR)/Makefile.common +ALL_SRC := $(wildcard *.c) +ALL_OBJ := $(patsubst %.c,%.o,$(ALL_SRC)) +ALL_BIN := $(patsubst %.o,%.cmd,$(ALL_OBJ)) +CFLAGS += +LDFLAGS += + +all: $(ALL_BIN) + +$(ALL_BIN):%.cmd:%.o + $(CC) $^ -o $@ $(LDFLAGS) + +$(ALL_OBJ):%.o:%.c + $(CC) $(CFLAGS) -c $^ -o $@ + +clean: + rm -rfv $(ALL_OBJ) $(ALL_BIN) + +cleanall: clean diff --git a/coreutils/tst_common/cmd/tsuite.c b/coreutils/tst_common/cmd/tsuite.c new file mode 100644 index 0000000..006dcf3 --- /dev/null +++ b/coreutils/tst_common/cmd/tsuite.c @@ -0,0 +1,6 @@ +#include "common.h" + +int main(void) { + dbg("hello world"); + return 0; +} diff --git a/coreutils/tst_common/docs/API-C.md b/coreutils/tst_common/docs/API-C.md new file mode 100644 index 0000000..988a482 --- /dev/null +++ b/coreutils/tst_common/docs/API-C.md @@ -0,0 +1,24 @@ +# 断言 +## assert_true +```C +// 原型:assert_true(expr) +// 功能:断言表达式返回真 +// 参数: +// expr -- 表达式 +// 返回值:无 +// 示例: +assert_true(1 == 2); +assert_true(a >= b); +``` + +## assert_false +```C +// 原型:assert_false(expr) +// 功能:断言表达式返回假 +// 参数: +// expr -- 表达式 +// 返回值:无 +// 示例: +assert_false(1 == 2); +assert_false(a >= b); +``` diff --git a/coreutils/tst_common/docs/API-Python.md b/coreutils/tst_common/docs/API-Python.md new file mode 100644 index 0000000..033c9f5 --- /dev/null +++ b/coreutils/tst_common/docs/API-Python.md @@ -0,0 +1,62 @@ +# 断言 +## assert_true +```Python +def assert_true(self, expr, message=None): + """ + 断言表达式返回真 + :param expr: 要断言的表达式 + :param message: 断言要输出的信息 + :return: None + 示例: + assert_true(1 == 2) + assert_true(a >= b) + """ + pass +``` + +## assert_false +```Python +def assert_false(self, expr, message=None): + """ + 断言表达式返回假 + :param expr: 要断言的表达式 + :param message: 断言要输出的信息 + :return: None + 示例: + assert_false(1 == 2) + assert_false(a >= b) + """ + pass +``` + +## skip_test、skip_if_true和skip_if_false +```Python +def skip_test(self, message=None): + """ + 标记用例为SKIP状态(当用例不需要测试时) + :param message: 要输出的信息 + :return: None + 示例: + skip_test(message='内核CONFIG_XXX未开,系统不支持此测试') + """ + +def skip_if_true(self, expr, message=None): + """ + 当表达式返回真或命令执行成功时,用例不满足测试条件,终止测试 + :param expr: 要判断的表达式 + :param message: 要输出的信息 + :return: None + 示例: + skip_if_true(1 == 2) + """ + +def skip_if_false(self, expr, message=None): + """ + 当表达式返回假或命令执行失败,用例不满足测试条件,终止测试 + :param expr: 要判断的表达式 + :param message: 要输出的信息 + :return: None + 示例: + skip_if_false(1 == 2) + """ +``` diff --git a/coreutils/tst_common/docs/API-Shell.md b/coreutils/tst_common/docs/API-Shell.md new file mode 100644 index 0000000..3aa1ab0 --- /dev/null +++ b/coreutils/tst_common/docs/API-Shell.md @@ -0,0 +1,68 @@ +# 断言 +## assert_true和assert_true_cont +```Shell +# 功能:断言表达式返回真或命令执行成功,'_cont'后缀的断言函数在断言失败后用例继续执行,不终止 +# 参数: +# $* -- 需要断言的表达式 +# 返回值: +# 0 -- 断言成功 +# 1 -- 断言失败 +# 示例: +assert_true [ $? -eq 0 ] +assert_true_cont grep "abc" /tmp/file +``` + +## assert_false和assert_false_cont +```Shell +# 功能:断言表达式返回假或命令执行失败,'_cont'后缀的断言函数在断言失败后用例继续执行,不终止 +# 参数: +# $* -- 需要断言的表达式 +# 返回值: +# 0 -- 断言成功 +# 1 -- 断言失败 +# 示例: +assert_false test -d /tmp/dir +assert_false_cont rmmod mykmod +``` + +## skip_test、skip_if_true和skip_if_false +```Shell +# skip_test +# 功能:标记用例为SKIP状态(当用例不需要测试时) +# 参数: +# $1 -- 对SKIP状态标记的描述 +# 返回值:无 +# 示例: +skip_test "内核CONFIG_XXXX未打开,系统不支持xxx功能" + +# skip_if_true +# 功能:当表达式返回真或命令执行成功时,用例不满足测试条件,终止测试 +# 参数: +# $* -- 需要断言的表达式 +# 返回值:无 +# 示例: +skip_if_true test -f /etc/xxx.conf + +# skip_if_false +# 功能:当表达式返回假或命令执行失败,用例不满足测试条件,终止测试 +# 参数: +# $* -- 需要断言的表达式 +# 返回值:无 +# 示例: +skip_if_false which ps +``` +# 工具 +## conv_unit +```Shell +# 功能:将K/M/G/T等单位互相转换 +# 参数:conv_unit [-i k|m|g|t] [-o k|m|g|t] value[_with_unit] +# -i k|m|g|t 【可选参数】输入数据的单位,可选参数,若不指定单位,则默认为1,或者输入的值后面带参数 +# -o k|m|g|t 【可选参数】输出数据的单位,若不指定单位,则默认为1 +# value[_with_unit] 【必选参数】需要转换的数据值,可以跟单位(只取单位第一个字母用于判断k|m|g|t) +# 返回值:标准输出转换后的结果 +# 0 -- 转换成功 +# 1 -- 转换失败 +# 示例: +conv_unit -o M 3G +conv_unit -o M -i G 3 +``` diff --git a/coreutils/tst_common/kmod/Makefile b/coreutils/tst_common/kmod/Makefile new file mode 100644 index 0000000..01632ef --- /dev/null +++ b/coreutils/tst_common/kmod/Makefile @@ -0,0 +1,28 @@ +# General Purpose Makefile for Linux Kernel module +# 以下编译适合于在内核代码树之外编译内核模块。 +# 整个过程会导致本Makefile文件被加载执行两遍。 +# 第一遍执行时,由于`KERNELRELEASE`没有被定义,所以先执行`else`下的逻辑。 +# `-C $(KERNEL_DIR)`指明跳转到内核源码目录下读取那里的Makefile; +# `M=$(CURDIR)`表明然后返回到当前目录继续读入当前的Makefile并执行之。此为第二遍执行。 +# 第二遍执行时,此时从内核源码目录返回时,KERNELRELEASE已被被定义, +# kbuild也被启动去解析kbuild语法的语句,make将继续读取else之前的内容。 +# else之前的内容为kbuild语法的语句, 指明模块源码中各文件的依赖关系,以及要生成的目标模块名。 + +CURDIR ?= $(shell pwd) +KERNEL_VER := $(shell uname -r) +KERNEL_DIR ?= /lib/modules/$(KERNEL_VER)/build +export ALL_SRC ?= $(filter-out %.mod.c, $(wildcard *.c)) +export ALL_OBJ ?= $(patsubst %.c,%.o,$(ALL_SRC)) +export ALL_MOD ?= $(patsubst %.o,%.ko,$(ALL_OBJ)) + +ifneq ($(KERNELRELEASE),) + obj-m += $(ALL_OBJ) +else +all: + $(MAKE) -C $(KERNEL_DIR) M=$(CURDIR) modules +endif + +clean: + $(MAKE) -C $(KERNEL_DIR) M=$(CURDIR) clean + +cleanall: clean diff --git a/coreutils/tst_common/kmod/kmod_common.c b/coreutils/tst_common/kmod/kmod_common.c new file mode 100644 index 0000000..41a779a --- /dev/null +++ b/coreutils/tst_common/kmod/kmod_common.c @@ -0,0 +1,14 @@ +#include + +static int __init kmod_common_init(void) { + printk("Hello, World!\n"); + return 0; +} +static void __exit kmod_common_exit(void) { + printk("Goodbye, World!\n"); +} + +module_init(kmod_common_init); +module_exit(kmod_common_exit); + +MODULE_LICENSE("GPL"); diff --git a/coreutils/tst_common/lib/Makefile b/coreutils/tst_common/lib/Makefile new file mode 100644 index 0000000..aaab40e --- /dev/null +++ b/coreutils/tst_common/lib/Makefile @@ -0,0 +1,20 @@ +export TST_COMMON_TOPDIR ?= $(shell pwd)/.. +include $(TST_COMMON_TOPDIR)/Makefile.common +ALL_SRC := $(wildcard *.c) +ALL_OBJ := $(patsubst %.c,%.o,$(ALL_SRC)) +LIB_STATIC := libcommon.a +CFLAGS += -Wformat=0 + +all: $(LIB_STATIC) + +$(LIB_STATIC): $(ALL_OBJ) + ar -rc $(LIB_STATIC) $(ALL_OBJ) + +$(ALL_OBJ):%.o:%.c + $(CC) $(CFLAGS) -c $^ -o $@ + +clean: + rm -rfv $(LIB_STATIC) $(ALL_OBJ) + +cleanall: clean + rm -rfv __pycache__ diff --git a/coreutils/tst_common/lib/benchmark.c b/coreutils/tst_common/lib/benchmark.c new file mode 100644 index 0000000..5ff07e0 --- /dev/null +++ b/coreutils/tst_common/lib/benchmark.c @@ -0,0 +1,389 @@ +// Time: 2022-06-30 11:10:49 +// Desc: 性能测试框架 + +#include +#include +#include +#include +#include + +#include "benchmark.h" + +long long tst_time_diff(struct tst_time *s, struct tst_time *e) { + return (long long) (e->ts.tv_sec - s->ts.tv_sec) * NS_PER_SEC + (e->ts.tv_nsec - s->ts.tv_nsec); +} + +int tst_get_time(struct tst_time *t) { + if (clock_gettime(CLOCK_MONOTONIC, &(t->ts)) != 0) { + return 1; + } + return 0; +} + +long long tst_time_since_now(struct tst_time *t) { + struct tst_time now; + (void) tst_get_time(&now); + return tst_time_diff(t, &now); +} + +struct tst_perf_ctrl *tst_alloc_ctrl(const char *name, tst_perf_func_t setup, tst_perf_func_t do_test, + tst_perf_func_t teardown, void *args, int warmup, int loop, enum value_type type, + enum key_item key) { + struct tst_perf_ctrl *c = NULL; + + if (name == NULL) { + printf("the name can't be NULL\n"); + return NULL; + } + if (do_test == NULL) { + printf("the do_test function can't be NULL\n"); + return NULL; + } + if (warmup < 0) { + printf("the warmup can't less then 0"); + return NULL; + } + if (loop <= 0) { + printf("the loop must greater then 0"); + return NULL; + } + if (type < LIB || type > HIB) { + printf("the type must in enum value_type"); + return NULL; + } + if (key < key_max || key > key_standard_deviation) { + printf("the key must in enum key_item"); + return NULL; + } + + c = (struct tst_perf_ctrl *) malloc(sizeof(struct tst_perf_ctrl)); + if (c == NULL) { + printf("malloc tst_perf_ctrl fail\n"); + return NULL; + } + (void) memset(c, 0, sizeof(struct tst_perf_ctrl)); + c->name = name; + c->perf_setup = setup; + c->perf_do_test = do_test; + c->perf_teardown = teardown; + c->args = args; + c->nr_warmup = warmup; + c->nr_loop = loop; + c->value_type = type; + c->key_item = key; + c->data = (long long *) calloc(c->nr_loop, sizeof(long long)); + if (c->data == NULL) { + printf("alloc memory for time data fail\n"); + free(c); + return NULL; + } + + return c; +} + +void tst_destroy_ctrl(struct tst_perf_ctrl **c) { + if (c == NULL || *c == NULL) { + return; + } + if ((*c)->data != NULL) { + free((*c)->data); + (*c)->data = NULL; + } + free(*c); + *c = NULL; +} + +int tst_perf_run(struct tst_perf_ctrl *c) { + int ret = 0; + int i; + struct tst_time t; + + if (c == NULL) { + return 1; + } + // 预热 + fprintf(stderr, "%s : start warmup %d\n", c->name, c->nr_warmup); + while (c->nr_warmup > 0) { + c->nr_warmup--; + + if (c->perf_setup) { + ret = c->perf_setup(c->args); + if (ret != 0) { + printf("the perf_setup return %d\n", ret); + return 1; + } + } + + ret = c->perf_do_test(c->args); + if (ret != 0) { + printf("the perf_do_test return %d\n", ret); + return 1; + } + + if (c->perf_teardown) { + ret = c->perf_teardown(c->args); + if (ret != 0) { + printf("the perf_teardown return %d\n", ret); + return 1; + } + } + } + + // 执行性能测试 + fprintf(stderr, "%s : start perf test loop %d\n", c->name, c->nr_loop); + for (i = 0; i < c->nr_loop; i++) { + if (c->perf_setup) { + ret = c->perf_setup(c->args); + if (ret != 0) { + printf("the perf_setup return %d\n", ret); + return 1; + } + } + + (void) tst_get_time(&t); + ret = c->perf_do_test(c->args); + if (ret != 0) { + printf("the perf_do_test return %d\n", ret); + return 1; + } + c->data[i] = tst_time_since_now(&t); + + if (c->perf_teardown) { + ret = c->perf_teardown(c->args); + if (ret != 0) { + printf("the perf_teardown return %d\n", ret); + return 1; + } + } + } + + return 0; +} + +int compare_time(const void *a, const void *b) { + return (int) (*(long long *) a - *(long long *) b); +} + +int statistic_data_base(long long *data, int len, struct tst_statistics_base *result) { + long double sum = 0; + long double step_20, step_100; + long double variance = 0; + int i; + + if (data == NULL || result == NULL || len <= 0) { + return 1; + } + + result->max = data[len - 1]; + result->min = data[0]; + result->median = data[(int) (len / 2)]; + step_20 = (long double) (result->max - result->min) / 20; + step_100 = (long double) (result->max - result->min) / 100; + + for (i = 0; i < len; i++) { + sum += data[i]; + if (step_20 > 0) { + result->dist_20[(int) ((data[i] - result->min) / step_20)]++; + } + if (step_100 > 0) { + result->dist_100[(int) ((data[i] - result->min) / step_100)]++; + } + } + + result->mean = sum / len; + + // 计算方差和 + for (i = 0; i < len; i++) { + variance += powl(data[i] - result->mean, 2); + } + // 计算标准差 + result->standard_deviation = sqrtl(variance / len); + + return 0; +} + +int statistic_data(struct tst_perf_ctrl *c) { + if (c == NULL) { + return 1; + } + int percent_5_start = (int) (c->nr_loop * 0.05); + int percent_5_len = (int) (c->nr_loop * 0.9); + + if (c->data == NULL) { + printf("the data is NULL\n"); + return 1; + } + + // 将时间数据排序 + qsort(c->data, c->nr_loop, sizeof(long long), compare_time); + (void) statistic_data_base(c->data, c->nr_loop, &(c->result.all)); + (void) statistic_data_base(&(c->data[percent_5_start]), percent_5_len, &(c->result.mid_90)); + + return 0; +} + +int show_result_json(struct tst_perf_ctrl *c) { + int i; + + if (statistic_data(c) != 0) { + return 1; + } + + printf("{"); + + printf("'name': '%s',", c->name); + printf("'type': '%s',", "LIB"); + printf("'unit': '%s',", "ns"); + printf("'key': '%s',", "mean"); + + printf("'data': {"); + + printf("100: {"); + printf("'max': %lld,", c->result.all.max); + printf("'min': %lld,", c->result.all.min); + printf("'mean': %Lf,", c->result.all.mean); + printf("'median': %lld,", c->result.all.median); + printf("'standard_deviation': %Lf,", c->result.all.standard_deviation); + printf("'dist_20': ["); + for (i = 0; i < NUM_20; i++) { + printf("%d,", c->result.all.dist_20[i]); + } + printf("],"); + printf("'dist_100': ["); + for (i = 0; i < NUM_100; i++) { + printf("%d,", c->result.all.dist_100[i]); + } + printf("],"); + printf("},"); + + printf("90: {"); + printf("'max': %lld,", c->result.mid_90.max); + printf("'min': %lld,", c->result.mid_90.min); + printf("'mean': %Lf,", c->result.mid_90.mean); + printf("'median': %lld,", c->result.mid_90.median); + printf("'standard_deviation': %Lf,", c->result.mid_90.standard_deviation); + printf("'dist_20': ["); + for (i = 0; i < NUM_20; i++) { + printf("%d,", c->result.mid_90.dist_20[i]); + } + printf("],"); + printf("'dist_100': ["); + for (i = 0; i < NUM_100; i++) { + printf("%d,", c->result.mid_90.dist_100[i]); + } + printf("],"); + printf("},"); + + // end of data + printf("},"); + + printf("}"); + + return 0; +} + + +int tst_test(const char *name, tst_perf_func_t setup, tst_perf_func_t do_test, tst_perf_func_t teardown, + void *args, int warmup, int loop, enum value_type type, enum key_item key) { + + struct tst_perf_ctrl *c = tst_alloc_ctrl(name, setup, do_test, teardown, args, warmup, loop, type, key); + if (c == NULL) { + return 1; + } + tst_perf_run(c); + show_result_json(c); + tst_destroy_ctrl(&c); + return 0; +} + +//////////////////////////////////////////////////////////////////////////////// +/* 下面的代码是示例 */ +#if 0 + +#define NR_LOOP_OPEN 100 +#define OPEN_PATH_LEN 128 +struct open_args { + int nr_opened; + char path[NR_LOOP_OPEN][OPEN_PATH_LEN]; + int fds[NR_LOOP_OPEN]; +}; + +int open_setup(void *args) { + int i; + struct rlimit r; + struct open_args *a = (struct open_args *) (args); + + r.rlim_cur = NR_LOOP_OPEN + 1024; + r.rlim_max = r.rlim_cur; + setrlimit(RLIMIT_NOFILE, &r); + memset(a, 0, sizeof(struct open_args)); + + system("rm -rf ./file.ops"); + system("mkdir ./file.ops"); + + for (i = 0; i < NR_LOOP_OPEN; ++i) { + snprintf(a->path[i], OPEN_PATH_LEN, "./file.ops/open.%08d.test", i); + } + return 0; +} + +int open_do_test(void *args) { + int i; + struct open_args *a = (struct open_args *) (args); + for (i = 0; i < NR_LOOP_OPEN; ++i) { + a->fds[i] = open(a->path[i], O_RDWR | O_CREAT | O_EXCL, 0600); + if (a->fds[i] < 0) { + printf("open the %s file fail\n", a->path[i]); + a->nr_opened = i; + return 1; + } + } + a->nr_opened = i; + return 0; +} + +int open_teardown(void *args) { + int i; + struct open_args *a = (struct open_args *) (args); + for (i = 0; i < a->nr_opened; ++i) { + if (a->fds[i] > 0) { + close(a->fds[i]); + a->fds[i] = 0; + } + } + system("rm -rf ./file.ops"); + return 0; +} + +int exec_do_test(void *args) { + pid_t pid = fork(); + pid_t wait; + if (pid == 0) { + execl("./simple.test", "./simple.test", NULL); + } else if (pid > 0) { + wait = waitpid(pid, NULL, 0); + if (wait == pid) { + return 0; + } + printf("waitpid(%d) return %d not as expect\n", pid, wait); + } else { + printf("fork fail\n"); + } + return 1; +} + + +int main(int argc, char **argv) { + struct open_args a; + printf("{"); + printf("'open': "); + tst_test("open.100", open_setup, open_do_test, open_teardown, &a, 100, 2000, LIB, key_mean); + printf(","); + printf("'exec': "); + tst_test("exec", NULL, exec_do_test, NULL, NULL, 100, 5000, LIB, key_mean); + printf(","); + printf("}\n"); + return 0; +} + +#endif \ No newline at end of file diff --git a/coreutils/tst_common/lib/benchmark.h b/coreutils/tst_common/lib/benchmark.h new file mode 100644 index 0000000..738eddb --- /dev/null +++ b/coreutils/tst_common/lib/benchmark.h @@ -0,0 +1,81 @@ +#ifndef TST_SUITE_COMMON_BENCHMARK_H +#define TST_SUITE_COMMON_BENCHMARK_H + + +#define NS_PER_SEC 1000000000 +#define NUM_20 20 +#define NUM_100 100 + +typedef int (*tst_perf_func_t)(void *); + +enum value_type { + // 越小越好(value_type.LIB) + LIB, + // 越大越好(value_type.HIB) + HIB +}; + +enum key_item { + // 最大值 + key_max, + // 最小值 + key_min, + // 平均值 + key_mean, + // 中位数 + key_median, + // 标准差 + key_standard_deviation +}; + +struct tst_time { + struct timespec ts; +}; + +struct tst_statistics_base { + // 时间单位都是ns + long long max; + long long min; + long double mean; + long long median; + long double standard_deviation; + int dist_20[NUM_20]; + int dist_100[NUM_100]; +}; + +struct tst_statistics_result { + struct tst_statistics_base all; + struct tst_statistics_base mid_90; +}; + +struct tst_perf_ctrl { + // 测试项名称 + const char *name; + // 初始化函数 + tst_perf_func_t perf_setup; + // 性能测试的对象函数 + tst_perf_func_t perf_do_test; + // 清理函数 + tst_perf_func_t perf_teardown; + // 性能测试函数的参数 + void *args; + // 预热循环次数 + int nr_warmup; + // 性能测试循环次数 + int nr_loop; + // 性能数据类型, + int value_type; + // 本性能指标最重要的统计数据项,例如最大值(key_item.max)、平均值(key_item.mean) + int key_item; + + // 性能测试数据 + long long *data; + // 性能数据统计结果 + struct tst_statistics_result result; +}; + +extern int tst_get_time(struct tst_time *t); + +extern long long tst_time_since_now(struct tst_time *t); + +#endif //TST_SUITE_COMMON_BENCHMARK_H diff --git a/coreutils/tst_common/lib/benchmark.py b/coreutils/tst_common/lib/benchmark.py new file mode 100644 index 0000000..22f9abb --- /dev/null +++ b/coreutils/tst_common/lib/benchmark.py @@ -0,0 +1,304 @@ +#!/usr/bin/env python3 +# coding: utf-8 +import abc +import json +import re +import subprocess +from _ctypes import PyObj_FromPtr +from enum import Enum + + +class ValueType(Enum): + # 越小越好(value_type.LIB) + LIB = 'LIB' + # 越大越好(value_type.HIB) + HIB = 'HIB' + + +class KeyItem(Enum): + # 最大值 + key_max = 'max' + # 最小值 + key_min = 'min' + # 平均值 + key_mean = 'mean' + # 中位数 + key_median = 'median' + # 标准差 + key_standard_deviation = 'standard_deviation' + + +class PerfResult: + def __init__(self, name: str, value_type: ValueType, key_item: KeyItem, unit: str): + self._result = { + "name": f'{name}', + "type": f'{value_type}', + "key": f'{key_item}', + "unit": f'{unit}', + "data": { + "100": { + "max": 0, + "min": 0, + "mean": 0, + "median": 0, + "standard_deviation": 0, + "dist_20": [0] * 20, + "dist_100": [0] * 100 + } + } + } + + @property + def result(self): + return self._result + + +class TSTPerf: + def __init__(self): + self._result = dict() + + @abc.abstractmethod + def run(self): + pass + + def add_result(self, result: PerfResult): + if result.result['name'] in self._result: + raise KeyError(f'the result with name {result.result["name"]} has existed') + self._result[result.result['name']] = result.result + + @property + def results(self): + return self._result + + def report(self): + print(json.dumps(self.results, indent=4, ensure_ascii=False)) + + +class PerfSysBench(TSTPerf): + def __init__(self, name: str, sysbench: str, testname: str, general_opt: str = None, test_opt: str = None): + super(PerfSysBench, self).__init__() + self.name = name + self.sysbench = sysbench + self.prepare = None + self.cleanup = None + self.testname = testname + self.general_opt = general_opt + self.test_opt = test_opt + self.command = f'{sysbench} {self.general_opt if self.general_opt else ""} {testname} ' \ + f'{self.test_opt if self.test_opt else ""} run' + self.outs = None + self.errs = None + + def run(self, timeout=None): + if self.prepare is not None and callable(self.prepare): + self.prepare() + proc = subprocess.Popen(self.command, shell=True, encoding='utf-8', stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + self.outs, self.errs = proc.communicate(timeout=timeout) + if self.cleanup is not None and callable(self.cleanup): + self.cleanup() + print(f'execute command [{self.command}] get exit code {proc.returncode}, output:') + print(self.outs) + if self.errs: + print('errors:') + print(self.errs) + self.parse_add_result() + + def get_cpu_result(self): + result = PerfResult(name=self.name, value_type=ValueType.LIB, key_item=KeyItem.key_mean, + unit='ms') + for line in self.outs.splitlines(): + if 'avg:' in line: + mean = float(line.split(':')[1].strip()) + result.result['data']['100']['mean'] = mean + return result + + def get_fileio_result(self, data_type): + result = PerfResult(name=f'{self.name}-{data_type}', value_type=ValueType.HIB, key_item=KeyItem.key_mean, + unit='MiB/s') + for line in self.outs.splitlines(): + if f'{data_type}:' in line: + mean = float((line.split('IOPS')[1]).split(' ')[1].strip()) + result.result['data']['100']['mean'] = mean + return result + + def get_memory_result(self): + result = PerfResult(name=self.name, value_type=ValueType.LIB, key_item=KeyItem.key_mean, + unit='MiB/s') + for line in self.outs.splitlines(): + if 'MiB/sec' in line: + mean = float((line.split('(')[1]).split('MiB')[0].strip()) + result.result['data']['100']['mean'] = mean + return result + def get_threads_result(self): + result = PerfResult(name=self.name, value_type=ValueType.LIB, key_item=KeyItem.key_mean, + unit='ms') + for line in self.outs.splitlines(): + if 'avg:' in line: + mean = float(line.split(':')[1].strip()) + result.result['data']['100']['mean'] = mean + return result + def get_mutex_result(self): + result = PerfResult(name=self.name, value_type=ValueType.LIB, key_item=KeyItem.key_mean, + unit='ms') + for line in self.outs.splitlines(): + if 'avg:' in line: + mean = float(line.split(':')[1].strip()) + result.result['data']['100']['mean'] = mean + return result + def parse_add_result(self): + if self.outs is None: + raise Exception('test output is None') + if self.testname == 'cpu': + self.add_result(self.get_cpu_result()) + elif self.testname == 'fileio': + if re.match(r'read:\s+IOPS=0.0', self.outs): + self.add_result(self.get_fileio_result('write')) + elif re.match(r'write:\s+IOPS=0.0', self.outs): + self.add_result(self.get_fileio_result('read')) + else: + self.add_result(self.get_fileio_result('read')) + self.add_result(self.get_fileio_result('write')) + elif self.testname == 'memory': + self.add_result(self.get_memory_result()) + elif self.testname == 'threads': + self.add_result(self.get_threads_result()) + elif self.testname == 'mutex': + self.add_result(self.get_mutex_result()) + else: + raise Exception(f'unknown test name {self.testname}') + +class PerfStream(TSTPerf): + def __init__(self, name: str, stream: str, general_opt: str = None): + super(PerfStream, self).__init__() + self.name = name + self.stream = stream + self.general_opt = general_opt + self.prepare = None + self.cleanup = None + self.command = f'{stream} {self.general_opt if self.general_opt else ""}' + self.outs = None + self.errs = None + + def run(self, timeout=None): + if self.prepare is not None and callable(self.prepare): + self.prepare() + proc = subprocess.Popen(self.command, shell=True, encoding='utf-8', stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + self.outs, self.errs = proc.communicate(timeout=timeout) + if self.cleanup is not None and callable(self.cleanup): + self.cleanup() + print(f'execute command [{self.command}] get exit code {proc.returncode}, output:') + print(self.outs) + if self.errs: + print('errors:') + print(self.errs) + self.parse_add_result() + + def get_stream_result(self, data_type): + result = PerfResult(name=f'{self.name}-{data_type}', value_type=ValueType.HIB, key_item=KeyItem.key_mean, + unit='MiB/s') + for line in self.outs.splitlines(): + if f'{data_type}:' in line: + mean = float((line.split(':')[1].strip()).split(' ')[0].strip()) + result.result['data']['100']['mean'] = mean + return result + def parse_add_result(self): + if self.outs is None: + raise Exception('test output is None') + if self.stream is not None: + self.add_result(self.get_stream_result('Copy')) + self.add_result(self.get_stream_result('Scale')) + self.add_result(self.get_stream_result('Add')) + self.add_result(self.get_stream_result('Triad')) + else: + raise Exception(f'unknown test item {self.stream}') + +class PerfHackbench(TSTPerf): + def __init__(self, name: str, hackbench: str, general_opt: str = None): + super(PerfHackbench, self).__init__() + self.name = name + self.hackbench = hackbench + self.general_opt = general_opt + self.prepare = None + self.cleanup = None + self.command = f'{hackbench} {self.general_opt if self.general_opt else ""}' + self.outs = None + self.errs = None + + def run(self, timeout=None): + if self.prepare is not None and callable(self.prepare): + self.prepare() + proc = subprocess.Popen(self.command, shell=True, encoding='utf-8', stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + self.outs, self.errs = proc.communicate(timeout=timeout) + if self.cleanup is not None and callable(self.cleanup): + self.cleanup() + print(f'execute command [{self.command}] get exit code {proc.returncode}, output:') + print(self.outs) + if self.errs: + print('errors:') + print(self.errs) + self.parse_add_result() + + def get_hackbench_result(self): + result = PerfResult(name=self.name, value_type=ValueType.LIB, key_item=KeyItem.key_mean, + unit='s') + for line in self.outs.splitlines(): + if 'Time:' in line: + mean = float(line.split(':')[1].strip()) + result.result['data']['100']['mean'] = mean + return result + def parse_add_result(self): + if self.outs is None: + raise Exception('test output is None') + if self.hackbench is not None: + self.add_result(self.get_hackbench_result()) + else: + raise Exception(f'unknown test item {self.hackbench}') + +class PerfLibMicro(TSTPerf): + def __init__(self, name: str, libmicro: str, general_opt: str = None, test_opt: str = None): + super(PerfLibMicro, self).__init__() + self.name = name + self.libmicro = libmicro + self.prepare = None + self.cleanup = None + self.general_opt = general_opt + self.test_opt = test_opt + self.command = f'{libmicro} {self.general_opt if self.general_opt else ""} ' \ + f'{self.test_opt if self.test_opt else ""}' + self.outs = None + self.errs = None + + def run(self, timeout=None): + if self.prepare is not None and callable(self.prepare): + self.prepare() + proc = subprocess.Popen(self.command, shell=True, encoding='utf-8', stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + self.outs, self.errs = proc.communicate(timeout=timeout) + if self.cleanup is not None and callable(self.cleanup): + self.cleanup() + print(f'execute command [{self.command}] get exit code {proc.returncode}, output:') + print(self.outs) + if self.errs: + print('errors:') + print(self.errs) + self.parse_add_result() + + def get_libmicro_result(self): + result = PerfResult(name=self.name, value_type=ValueType.LIB, key_item=KeyItem.key_mean, + unit='us') + for line in self.outs.splitlines(): + if 'mean' in line: + mean = float((line.split('mean')[1].strip()).split(' ')[0].strip()) + result.result['data']['100']['mean'] = mean + return result + def parse_add_result(self): + if self.outs is None: + raise Exception('test output is None') + if self.libmicro is not None: + self.add_result(self.get_libmicro_result()) + else: + raise Exception(f'unknown test item {self.libmicro} ') + diff --git a/coreutils/tst_common/lib/common.c b/coreutils/tst_common/lib/common.c new file mode 100644 index 0000000..9bb4f28 --- /dev/null +++ b/coreutils/tst_common/lib/common.c @@ -0,0 +1,597 @@ +// Time: 2022-04-18 14:07:49 +// Desc: C用例基础公共函数库 + +#include "common.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct tst_tc_control { + // 用例名 + char tc_name[PATH_MAX]; + // 用例参数 + int tc_argc; + char **tc_argv; + // 用例源文件路径 + char tc_source_path[PATH_MAX]; + // 用例可执行文件路径 + char tc_exec_path[PATH_MAX]; + // 执行用例文件时的目录 + char exec_cwd[PATH_MAX]; + // TST_TC_CWD 测试用例CWD + char tst_tc_cwd[PATH_MAX]; + // 用例开始执行的时间 + struct tst_time time_start; + // TST_TC_PID 测试用例主进程pid + pid_t tst_tc_pid; + // 标记tc_setup是否被调用 + int tc_setup_called; + // 用例执行状态 + int tc_stat; + // TST_TS_TOPDIR 测试套顶层目录 + char tst_ts_topdir[PATH_MAX]; + // TST_COMMON_TOPDIR common顶层目录 + char tst_common_topdir[PATH_MAX]; + // TST_TS_SYSDIR 测试套公共运行目录 + char tst_ts_sysdir[PATH_MAX]; + // TST_TC_SYSDIR 测试用例管理用临时目录 + char tst_tc_sysdir[PATH_MAX]; + // 测试套执行状态标记文件 + char tst_ts_setup_stat[PATH_MAX]; +}; + +struct tst_tc_control *g_tst_tc_control; + +void show_tc_control(void) { + dbg("tc_name: %s", g_tst_tc_control->tc_name); + dbg("tc_source_path: %s", g_tst_tc_control->tc_source_path); + dbg("tc_exec_path: %s", g_tst_tc_control->tc_exec_path); + dbg("exec_cwd: %s", g_tst_tc_control->exec_cwd); + dbg("tst_tc_cwd: %s", g_tst_tc_control->tst_tc_cwd); + dbg("tst_tc_pid: %d", g_tst_tc_control->tst_tc_pid); + dbg("tc_stat: %d", g_tst_tc_control->tc_stat); + dbg("tst_ts_topdir: %s", g_tst_tc_control->tst_ts_topdir); + dbg("tst_ts_sysdir: %s", g_tst_tc_control->tst_ts_sysdir); + dbg("tst_tc_sysdir: %s", g_tst_tc_control->tst_tc_sysdir); + dbg("tst_ts_setup_stat: %s", g_tst_tc_control->tst_ts_setup_stat); +} + +int _print(const char *format, ...) { + va_list ap; + int ret; + char buff[MAX_LOG_LEN] = {0}; + + va_start(ap, format); + ret = vsnprintf(buff, MAX_LOG_LEN - 1, format, ap); + va_end(ap); + + if (buff[ret - 1] != '\n') { + buff[ret] = '\n'; + buff[ret + 1] = '\0'; + } + fprintf(stderr, "%s", buff); + + return ret; +} + +static int _is_main_process(void) { + if (g_tst_tc_control->tst_tc_pid == getpid()) { + return 1; + } + return 0; +} + +static void _set_tcstat(int stat) { + g_tst_tc_control->tc_stat = stat; +} + +static int _get_tcstat(void) { + return g_tst_tc_control->tc_stat; +} + +void _tc_pass(void) { + // 只有初始状态的用例才能置为PASS,其他异常状态的用例不能从异常变为PASS + if (_get_tcstat() == TST_INIT) { + _set_tcstat(TST_PASS); + } +} + +void _tc_fail(void) { + if (_get_tcstat() != TST_FAIL) { + msg("the testcase first fail here"); + } + _set_tcstat(TST_FAIL); +} + +static char *_tcstat_to_str(int tcstat) { + switch (tcstat) { + case TST_PASS: + return "TST_PASS"; + case TST_FAIL: + return "TST_FAIL"; + case TST_INIT: + return "TST_INIT"; + case TST_SKIP: + return "TST_SKIP"; + default: + return "TST_UNKNOWN"; + } +} + +static int _tc_teardown(int argc, char **argv) { + int ret = 0; + + // 只有用例的主进程才能执行此函数 + if (!_is_main_process()) { + return 0; + } + if (tc_teardown) { + if (tc_teardown(argc, argv) == 0) { + msg("call tc_teardown success"); + } else { + err("call tc_teardown fail"); + ret = 1; + } + } else { + msg("tc_teardown not define"); + } + + return ret; +} + +static int _tc_teardown_common(int argc, char **argv) { + int ret = 0; + + // 只有用例的主进程才能执行此函数 + if (!_is_main_process()) { + return 0; + } + if (tc_teardown_common) { + if (tc_teardown_common(argc, argv) == 0) { + msg("call tc_teardown_common success"); + } else { + err("call tc_teardown_common fail"); + ret = 1; + } + } else { + msg("tc_teardown_common not define"); + } + + return ret; +} + +static void _tc_run_complete(int argc, char **argv) { + int ret = 0; + + // 只有用例的主进程才能执行此函数 + if (!_is_main_process()) { + return; + } + // tc_setup有调用时tc_teardown才会被调用 + if (g_tst_tc_control->tc_setup_called) { + if (_tc_teardown(argc, argv) == 0) { + msg("call _tc_teardown success"); + } else { + msg("call _tc_teardown fail"); + ret = 1; + } + } else { + msg("the tc_setup not called, so tc_teardown ignore"); + } + if (_tc_teardown_common(argc, argv) == 0) { + msg("call _tc_teardown_common success"); + } else { + msg("call _tc_teardown_common fail"); + ret = 1; + } + + // TCase自动化执行框架需要用这个输出判断用例是否支持完 + msg("Global test environment tear-down"); + switch (_get_tcstat()) { + case TST_PASS: + msg("RESULT : %s ==> [ PASSED ]", g_tst_tc_control->tc_name); + break; + case TST_FAIL: + msg("RESULT : %s ==> [ FAILED ]", g_tst_tc_control->tc_name); + ret = 1; + break; + case TST_INIT: + msg("RESULT : %s ==> [ NOTEST ]", g_tst_tc_control->tc_name); + ret = 1; + break; + case TST_SKIP: + msg("RESULT : %s ==> [ SKIP ]", g_tst_tc_control->tc_name); + ret = 0; + break; + default: + msg("RESULT : %s ==> [ UNKNOWN ]", g_tst_tc_control->tc_name); + ret = 1; + break; + } + msg("cost %.9Lf", (long double) tst_time_since_now(&(g_tst_tc_control->time_start)) / NS_PER_SEC); + + exit(ret); +} + +void _tst_assert(const char *expr, const char *file, int line, const char *func) { + msg("%s:%d %s assert '%s' fail", file, line, func, expr); + _tc_run_complete(g_tst_tc_control->tc_argc, g_tst_tc_control->tc_argv); +} + +void _skip_test(const char *message, const char *file, int line, const char *func) { + int tc_stat = _get_tcstat(); + + if ((tc_stat == TST_PASS) || (tc_stat == TST_INIT) || (tc_stat == TST_SKIP)) { + _set_tcstat(TST_SKIP); + msg("%s:%d %s: set testcase SKIP: %s", file, line, func, message); + } else { + msg("%s:%d %s: set testcase SKIP fail: %s", file, line, func, message); + err("the testcase stat is %s, can't set to SKIP", _tcstat_to_str(tc_stat)); + } + _tc_run_complete(g_tst_tc_control->tc_argc, g_tst_tc_control->tc_argv); +} + +static int _tc_setup_common(int argc, char **argv) { + int ret = 0; + + if (tc_setup_common) { + if (tc_setup_common(argc, argv) == 0) { + msg("call tc_setup_common success"); + } else { + err("call tc_setup_common fail"); + ret = 1; + } + } else { + msg("tc_setup_common not define"); + } + + return ret; +} + +static int _tc_setup(int argc, char **argv) { + int ret = 0; + + // 只有用例的主进程才能执行此函数 + if (!_is_main_process()) { + return 0; + } + g_tst_tc_control->tc_setup_called = 1; + if (tc_setup) { + if (tc_setup(argc, argv) == 0) { + msg("call tc_setup success"); + } else { + err("call tc_setup fail"); + ret = 1; + } + } else { + msg("tc_setup not define"); + } + + return ret; +} + +static int _do_test(int argc, char **argv) { + int ret = 0; + + // 只有用例的主进程才能执行此函数 + if (!_is_main_process()) { + return 0; + } + if (do_test) { + if (do_test(argc, argv) == 0) { + msg("call do_test success"); + } else { + err("call do_test fail"); + ret = 1; + } + } else { + err("do_test not define"); + ret = 1; + } + + return ret; +} + +static int _is_ts_setup_called(void) { + if (is_file(g_tst_tc_control->tst_ts_setup_stat)) { + return 1; + } + return 0; +} + +static int _get_ts_setup_stat(void) { + char buff[PAGE_SIZE]; + int read_size = read_line(g_tst_tc_control->tst_ts_setup_stat, 1, buff, PAGE_SIZE); + if (read_size <= 0) { + return TST_INIT; + } + return (int) strtol(buff, NULL, 0); +} + +// 功能:判断路径是否为文件并且存在 +// 参数: +// path -- 文件路径 +// 返回值: +// 0 -- 文件不存在 +// 1 -- 文件存在 +int is_file(const char *path) { + struct stat sb; + + if (stat(path, &sb) != 0) { + return 0; + } + if (S_ISDIR(sb.st_mode)) { + return 0; + } + return 1; +} + +// 功能:判断路径是否为目录并且存在 +// 参数: +// path -- 文件路径 +// 返回值: +// 0 -- 文件不存在 +// 1 -- 文件存在 +int is_dir(const char *path) { + struct stat sb; + + if (stat(path, &sb) != 0) { + return 0; + } + if (S_ISDIR(sb.st_mode)) { + return 1; + } + return 0; +} + +// 功能:判断路径是否存在 +// 参数: +// path -- 文件路径 +// 返回值: +// 0 -- 文件不存在 +// 1 -- 文件存在 +int is_exist(const char *path) { + if (access(path, F_OK) == 0) { + return 1; + } else { + return 0; + } +} + +// 功能:读文件内容到buff中 +// 参数: +// path -- 文件路径 +// buff -- 接收文件内容 +// size -- buff大小 +// 返回值: +// -1 -- 文件读取失败 +// 其他 -- 读取到的文件内容长度 +size_t read_file(const char *path, char *buff, size_t size) { + int fd = open(path, O_RDONLY); + if (fd < 0) { + return -1; + } + int ret = read(fd, buff, size) < 0; + if (ret < 0) { + close(fd); + return -1; + } + close(fd); + return ret; +} + +// 功能:读文本文件指定行的内容到buff中 +// 参数: +// path -- 文件路径 +// line -- 要读取内容的行号(从1开始) +// buff -- 接收文件内容 +// size -- buff大小 +// 返回值: +// -1 -- 文件读取失败 +// 其他 -- 读取到的文件内容长度 +size_t read_line(const char *path, int line, char *buff, size_t size) { + int i = 0; + FILE *file = NULL; + if (line <= 0) { + dbg("the line less then 0: %d", line); + return -1; + } + file = fopen(path, "r"); + if (file == NULL) { + dbg("open file %s fail, errno %d, error: %s", path, errno, strerror(errno)); + return -1; + } + while (i < line) { + i++; + if (fgets(buff, size, file) == NULL) { + if (i == line) { + // 刚好读到指定行的时候文件结束 + break; + } + // 文件读完了,但是行号还没有读到 + dbg("get line %d fail, buff: %s, errno %d, error: %s", i, buff, errno, strerror(errno)); + fclose(file); + return -1; + } + } + fclose(file); + return strlen(buff); +} + +// 功能:创建多层目录 +// 参数: +// dir -- 目录 +// mode -- 目录权限 +// 返回值: +// -1 -- 创建失败 +// 0 -- 创建成功 +int mkdirs(const char *dir, mode_t mode) { + int i; + char now_path[PATH_MAX]; + + for (i = 0; i < min(strlen(dir), PATH_MAX - 1); i++) { + if (dir[i] != '/') { + continue; + } + strncpy(now_path, dir, i + 1); + if (is_exist(now_path)) { + if (is_dir(now_path)) { + continue; + } else { + dbg("the path %s exist but not dir", now_path); + return -1; + } + } + if (mkdir(now_path, mode) != 0) { + dbg("mkdir %s fail, errno %d, error: %s", now_path, errno, strerror(errno)); + return -1; + } + } + if (mkdir(dir, mode) != 0) { + dbg("mkdir %s fail, errno %d, error: %s", dir, errno, strerror(errno)); + return -1; + } + if (!is_dir(dir)) { + dbg("mkdirs %s fail", dir); + return -1; + } + return 0; +} + +// 功能:执行命令 +// 参数: +// command_format -- 命令内容 +// 返回值:同system函数 +int command(const char *command_format, ...) { + va_list ap; + char cmd[MAX_CMD_LEN] = {0}; + + va_start(ap, command_format); + (void) vsnprintf(cmd, MAX_CMD_LEN, command_format, ap); + va_end(ap); + + return system(cmd); +} + +static int _tc_init(int argc, char **argv) { + size_t control_size = ((sizeof(struct tst_tc_control) / PAGE_SIZE) + 1) * PAGE_SIZE; + g_tst_tc_control = (struct tst_tc_control *) mmap(NULL, control_size, PROT_READ | PROT_WRITE, + MAP_SHARED | MAP_ANONYMOUS, -1, 0); + if (g_tst_tc_control == NULL) { + msg("mmap g_tst_tc_control fail, errno: %d, %s", errno, strerror(errno)); + return 1; + } + memset(g_tst_tc_control, 0, control_size); + if (tst_get_time(&(g_tst_tc_control->time_start)) != 0) { + msg("tst_get_time fail, errno: %d, %s", errno, strerror(errno)); + return 1; + } + strncpy(g_tst_tc_control->tc_name, basename(argv[0]), PATH_MAX); + g_tst_tc_control->tc_argc = argc; + g_tst_tc_control->tc_argv = argv; + + if (realpath(argv[0], g_tst_tc_control->tc_exec_path) == NULL) { + msg("get the realpath fail, errno: %d, %s", errno, strerror(errno)); + return 1; + } + + strncpy(g_tst_tc_control->tc_source_path, g_tst_tc_control->tc_exec_path, PATH_MAX); + strncat(g_tst_tc_control->tc_source_path, ".c", PATH_MAX); + + if (getcwd(g_tst_tc_control->exec_cwd, PATH_MAX) == NULL) { + msg("get cwd fail, errno: %d, %s", errno, strerror(errno)); + return 1; + } + + strncpy(g_tst_tc_control->tst_tc_cwd, g_tst_tc_control->tc_exec_path, PATH_MAX); + dirname(g_tst_tc_control->tst_tc_cwd); + + g_tst_tc_control->tst_tc_pid = getpid(); + g_tst_tc_control->tc_stat = TST_INIT; + + // 尝试获取TST_TS_TOPDIR + strncpy(g_tst_tc_control->tst_ts_topdir, g_tst_tc_control->tc_exec_path, PATH_MAX); + char path_tst_common[PATH_MAX]; + char path_cmd[PATH_MAX]; + char path_testcase[PATH_MAX]; + char path_tsuite[PATH_MAX]; + while (g_tst_tc_control->tst_ts_topdir[1] != '\0') { + snprintf(path_tst_common, PATH_MAX, "%s/tst_common", g_tst_tc_control->tst_ts_topdir); + snprintf(path_cmd, PATH_MAX, "%s/cmd", g_tst_tc_control->tst_ts_topdir); + snprintf(path_testcase, PATH_MAX, "%s/testcase", g_tst_tc_control->tst_ts_topdir); + snprintf(path_tsuite, PATH_MAX, "%s/tsuite", g_tst_tc_control->tst_ts_topdir); + if (is_dir(path_cmd) && is_dir(path_testcase) && is_file(path_tsuite)) { + if (is_dir(path_tst_common)) { + strncpy(g_tst_tc_control->tst_common_topdir, path_tst_common, PATH_MAX); + } else { + strncpy(g_tst_tc_control->tst_common_topdir, g_tst_tc_control->tst_ts_topdir, PATH_MAX); + } + break; + } + if (g_tst_tc_control->tst_ts_topdir[1] == '\0') { + memset(g_tst_tc_control->tst_ts_topdir, 0, PATH_MAX); + memset(g_tst_tc_control->tst_common_topdir, 0, PATH_MAX); + break; + } + dirname(g_tst_tc_control->tst_ts_topdir); + } + // TST_TS_TOPDIR成功获取后,TST_TS_SYSDIR和TST_TC_SYSDIR可以生成了 + if (g_tst_tc_control->tst_ts_topdir[0] != '\0') { + snprintf(g_tst_tc_control->tst_ts_sysdir, PATH_MAX, "%s/logs/.ts.sysdir", g_tst_tc_control->tst_ts_topdir); + snprintf(g_tst_tc_control->tst_tc_sysdir, PATH_MAX, "%s/logs/testcase/.tc.%d.sysdir", + g_tst_tc_control->tst_ts_topdir, g_tst_tc_control->tst_tc_pid); + snprintf(g_tst_tc_control->tst_ts_setup_stat, PATH_MAX, "%s/ts.setup.stat", g_tst_tc_control->tst_ts_sysdir); + } + + return 0; +} + +int tst_main(int argc, char **argv) { + int ret = 0; + + if (_tc_init(argc, argv) != 0) { + return 1; + } + if (chdir(g_tst_tc_control->tst_tc_cwd) != 0) { + msg("chdir to %s fail, errno: %d, %s", g_tst_tc_control->tst_tc_cwd, errno, strerror(errno)); + return 1; + } + + if (_is_ts_setup_called()) { + msg("tsuite setup executed, stat is %d", _get_ts_setup_stat()); + } else { + msg("tsuite setup may not executed"); + } + + _set_tcstat(TST_INIT); + + if (_tc_setup_common(argc, argv) == 0) { + if (_tc_setup(argc, argv) == 0) { + msg("call _tc_setup success"); + if (_do_test(argc, argv) == 0) { + msg("call _do_test success"); + } else { + err("call _do_test fail"); + ret = 1; + } + } else { + err("call _tc_setup success"); + ret = 1; + } + } else { + err("call _tc_setup_common success"); + ret = 1; + } + + _tc_run_complete(argc, argv); + + return ret; +} diff --git a/coreutils/tst_common/lib/common.h b/coreutils/tst_common/lib/common.h new file mode 100644 index 0000000..c9d6264 --- /dev/null +++ b/coreutils/tst_common/lib/common.h @@ -0,0 +1,139 @@ +#ifndef __COMMON_H__ +#define __COMMON_H__ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "benchmark.h" + +#define TST_PASS 0 +#define TST_FAIL 1 +#define TST_INIT 2 +#define TST_SKIP 3 + +#ifndef MAX_LOG_LEN +#define MAX_LOG_LEN 4096 +#endif /* MAX_LOG_LEN */ +#ifndef MAX_CMD_LEN +#define MAX_CMD_LEN 4096 +#endif /* MAX_CMD_LEN */ + +#ifndef PAGE_SHIFT +#define PAGE_SHIFT 12 +#endif /* PAGE_SHIFT */ +#ifndef PAGE_SIZE +#define PAGE_SIZE (1UL << PAGE_SHIFT) +#endif /* PAGE_SIZE */ +#ifndef PAGE_MASK +#define PAGE_MASK (~(PAGE_SIZE-1)) +#endif /* PAGE_MASK */ + +#define KB (1024) +#define MB (KB * KB) +#define GB (MB * KB) + +extern int _print(const char *format, ...); + +#define min(a, b) ((a) > (b) ? (b) : (a)) +#define max(a, b) ((a) < (b) ? (b) : (a)) + +#define dbg(format, ...) _print(format, ##__VA_ARGS__) +#define msg(format, ...) _print(format, ##__VA_ARGS__) +#define err(format, ...) \ + do{ \ + _tc_fail(); \ + _print("%s:%d %s: " format, __FILE__, __LINE__, __FUNCTION__, ##__VA_ARGS__); \ + }while(0) + +extern void _skip_test(const char *message, const char *file, int line, const char *func); + +#define skip_test(message) _skip_test(message, __FILE__, __LINE__, __FUNCTION__) + +#define skip_if_true(expr) \ + do{ \ + if(expr){ \ + skip_test("skip_if_true " #expr); \ + } \ + }while(0) + +#define skip_if_false(expr) \ + do{ \ + if(!(expr)){ \ + skip_test("skip_if_false " #expr); \ + } \ + }while(0) + +extern void _tc_pass(void); + +extern void _tc_fail(void); + +extern void _tst_assert(const char *expr, const char *file, int line, const char *func); + +// 功能:断言表达式返回真 +// 参数: +// expr -- 表达式 +// 返回值:无 +#define assert_true(expr) \ + do{ \ + if(expr){ \ + _tc_pass(); \ + }else{ \ + _tc_fail(); \ + _tst_assert(#expr, __FILE__, __LINE__, __FUNCTION__); \ + } \ + }while(0) + +// 功能:断言表达式返回假 +// 参数: +// expr -- 表达式 +// 返回值:无 +#define assert_false(expr) \ + do{ \ + if(!(expr)){ \ + _tc_pass(); \ + }else{ \ + _tc_fail(); \ + _tst_assert(#expr, __FILE__, __LINE__, __FUNCTION__); \ + } \ + }while(0) + + +extern void show_tc_control(void); + +extern int is_file(const char *path); + +extern int is_dir(const char *path); + +extern int is_exist(const char *path); + +extern size_t read_line(const char *path, int line, char *buff, size_t size); + +extern size_t read_file(const char *path, char *buff, size_t size); + +extern int mkdirs(const char *dir, mode_t mode); + +extern int command(const char *command_format, ...); + +extern int tc_setup_common(int argc, char **argv) __attribute__((weak)); + +extern int tc_setup(int argc, char **argv) __attribute__((weak)); + +extern int do_test(int argc, char **argv) __attribute__((weak)); + +extern int tc_teardown(int argc, char **argv) __attribute__((weak)); + +extern int tc_teardown_common(int argc, char **argv) __attribute__((weak)); + +#endif // __COMMON_H__ diff --git a/coreutils/tst_common/lib/common.py b/coreutils/tst_common/lib/common.py new file mode 100644 index 0000000..d9a1b97 --- /dev/null +++ b/coreutils/tst_common/lib/common.py @@ -0,0 +1,755 @@ +#!/usr/bin/env python3 +# coding: utf-8 +# Time: 2022-04-19 22:26:42 +# Desc: Python用例公共模块 + +import abc +import getpass +import os +import platform +import re +import shutil +import socket +import subprocess +import sys +import tempfile +import time +import traceback +import __main__ as main + +TST_PASS = 0 +TST_FAIL = 1 +TST_INIT = 2 +TST_SKIP = 3 +tst_tc_stat_dict = { + TST_PASS: 'TST_PASS', + TST_FAIL: 'TST_FAIL', + TST_INIT: 'TST_INIT', + TST_SKIP: 'TST_SKIP', +} + + +def command(cmd, timeout=20): + proc = subprocess.Popen(cmd, shell=True, encoding='utf-8') + try: + proc.communicate(timeout=timeout) + except subprocess.TimeoutExpired: + proc.kill() + return proc.wait() + + +def command_output(cmd, timeout=20): + proc = subprocess.Popen(cmd, shell=True, encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.PIPE) + outs = "" + errs = "" + try: + outs, errs = proc.communicate(timeout=timeout) + except subprocess.TimeoutExpired: + proc.kill() + code = proc.wait() + return outs, errs, code + + +def command_quiet(cmd, timeout=20): + proc = subprocess.Popen(cmd, shell=True, encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.PIPE) + try: + proc.communicate(timeout=timeout) + except subprocess.TimeoutExpired: + proc.kill() + code = proc.wait() + return code + + +def get_yum_provide(filename): + outs, errs, code = command_output(f'yum provides {filename}') + print(f'stdout:\n{outs}') + print(f'stderr:\n{errs}') + print(f'status: {code}') + if code != 0 or outs is None: + return None + for line in outs.splitlines(): + match = re.match(r'^([-\w.]+)-\d(\.\d+)+-.* : ', line) + if match: + package = match.groups()[0] + print(f'get file {filename} provide: {package}') + return package + return None + + +def try_install_command(cmd, package=None): + if command_quiet(f'which {cmd}') == 0: + return True + if package is None: + package = get_yum_provide(cmd) + if package is not None: + command(f'yum install -y {package}') + if command(f'which {cmd}') == 0: + return True + return False + + +def get_kernel_release(): + return platform.release() + + +def get_system_boot_time(): + with open('/proc/uptime', 'r') as f: + uptime = float(f.readline().split()[0]) + now_time = time.time() + boot_time = now_time - uptime + result = boot_time + + tsuite_tmpdir = os.path.join('/tmp', f'.tsuite-{getpass.getuser()}') + if not os.path.exists(tsuite_tmpdir): + os.makedirs(tsuite_tmpdir, mode=0o755, exist_ok=True) + boot_time_file = os.path.join(tsuite_tmpdir, 'boot-time') + if os.path.exists(boot_time_file): + # 如果系统启动的时间已经有记录,那么看看是否同一次启动 + with open(boot_time_file, 'r') as f: + old_boot_time = float(f.readline()) + # 如果记录的时间和当前计算的时间差别不大,那么就认为是同一次启动 + if abs(old_boot_time - boot_time) <= 10: + result = old_boot_time + else: + with open(boot_time_file, 'w') as f: + f.write(f'{boot_time}') + else: + with open(boot_time_file, 'w') as f: + f.write(f'{boot_time}') + return 'boot-time.' + time.strftime('%Y%m%d-%H%M%S', time.localtime(result)) + + +def get_os_release(): + release = None + if os.path.isfile('/etc/os-release'): + with open('/etc/os-release', 'r') as f: + for line in f.readlines(): + if re.match(r'PRETTY_NAME=', line, re.IGNORECASE): + release = re.sub(r'[^\w.]+', '-', line.split('=')[1].strip()) + if os.path.isfile('/etc/tencentos-release'): + with open('/etc/tencentos-release', 'r') as f: + for line in f.readlines(): + if re.match(r'TencentOS', line, re.IGNORECASE): + release = re.sub(r'[^\w.]+', '-', line.strip()) + if os.path.isfile('/etc/motd'): + with open('/etc/motd', 'r') as f: + for line in f.readlines(): + if re.match(r'version', line, re.IGNORECASE): + release = re.sub(r'[^\w.]+', '-', line.strip()) + if re.match(r'tlinux', line, re.IGNORECASE): + release = re.sub(r'[^\w.]+', '-', line.strip()) + if release is None: + return 'Unknown-Linux' + return release.strip('-') + + +def get_tst_test_env_ip(): + outs, _, _ = command_output('ifconfig eth1') + eth1_ip = get_ip_of_ifconfig(outs) + # 测试环境的eth1都是192.168.x.x + if (eth1_ip is None) or (not eth1_ip.startswith('192.168.')): + return None + env_main_ip_1 = re.sub(r'\.\d{1,3}$', '.11', eth1_ip) + # 获取测试环境主环境的IP + outs, _, _ = command_output(f'ssh root@{env_main_ip_1} ifconfig eth0', timeout=3) + env_main_ip_0 = get_ip_of_ifconfig(outs) + if env_main_ip_0 is None: + return None + return [env_main_ip_0, eth1_ip] + + +def get_ip_of_ifconfig(ifconfig_outs: str): + if ifconfig_outs is None: + return None + if not isinstance(ifconfig_outs, str): + return None + for line in ifconfig_outs.splitlines(): + if 'netmask' not in line: + continue + return re.search(r'\b(?:\d{1,3}\.){3}\d{1,3}\b', line).group() + return None + + +def get_host_ip(): + """ + 这个方法是目前见过最优雅获取本机服务器的IP方法了。没有任何的依赖,也没有去猜测机器上的网络设备信息。 + 而且是利用 UDP 协议来实现的,生成一个UDP包,把自己的 IP 放如到 UDP 协议头中,然后从UDP包中获取本机的IP。 + 这个方法并不会真实的向外部发包,所以用抓包工具是看不到的。但是会申请一个 UDP 的端口,所以如果经常调用也会比较耗时的, + 这里如果需要可以将查询到的IP给缓存起来,性能可以获得很大提升。 + + 作者:钟翦 + 链接:https://www.zhihu.com/question/49036683/answer/1243217025 + 来源:知乎 + 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 + + :return: + """ + _local_ip = None + s = None + try: + if not _local_ip: + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + s.connect(('8.8.8.8', 80)) + _local_ip = s.getsockname()[0] + return _local_ip + finally: + if s: + s.close() + + +def command_to_filename(cmd: str): + return re.sub(r'\W+', '.', cmd) + '.txt' + + +def get_commands_logs(cmd_list, logs_dir, timeout=60): + start_time = time.time() + exec_list = list() + index = 1 + for cmd in cmd_list: + # print(f'{index} execute command: {cmd}') + cmd_dict = { + 'index': index, + 'command': cmd, + 'timeout': timeout, + 'start_time': time.time(), + 'proc': subprocess.Popen(cmd, shell=True, encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.PIPE), + 'log_file': os.path.join(os.path.realpath(logs_dir), command_to_filename(cmd)), + 'end_time': None, + 'cost': None, + 'stdout': None, + 'stderr': None, + 'status': None + } + exec_list.append(cmd_dict) + index += 1 + + # 检查命令是否执行完 + while True: + all_command_ok = True + if time.time() - start_time > timeout: + break + for proc_dict in exec_list: + if proc_dict['status'] is not None: + continue + try: + proc_dict['stdout'], proc_dict['stderr'] = proc_dict['proc'].communicate(timeout=1) + except subprocess.TimeoutExpired: + all_command_ok = False + continue + proc_dict['status'] = proc_dict['proc'].returncode + proc_dict['end_time'] = time.time() + proc_dict['cost'] = proc_dict['end_time'] - proc_dict['start_time'] + # print(f'{proc_dict["index"]} command {proc_dict["command"]} end, status {proc_dict["status"]}') + if all_command_ok: + break + + # 记录命令执行结果,还没有结束的命令直接终止 + for proc_dict in exec_list: + if proc_dict['status'] is None: + proc_dict['proc'].kill() + proc_dict['stdout'], proc_dict['stderr'] = proc_dict['proc'].communicate(timeout=1) + proc_dict['status'] = proc_dict['proc'].returncode + proc_dict['end_time'] = time.time() + proc_dict['cost'] = proc_dict['end_time'] - proc_dict['start_time'] + print(f'{proc_dict["index"]} command {proc_dict["command"]} killed, status {proc_dict["status"]}') + with open(file=proc_dict['log_file'], mode='a', buffering=1, encoding='utf-8') as f: + f.write('=' * 60 + '\n') + f.write(f'### command: {proc_dict["command"]}\n') + f.write(f'### timeout: {proc_dict["timeout"]}\n') + f.write(f'### start_time: ' + f'{time.strftime("%Y-%m-%d %H:%M:%S %z", time.localtime(proc_dict["start_time"]))}\n') + f.write(f'### end_time: ' + f'{time.strftime("%Y-%m-%d %H:%M:%S %z", time.localtime(proc_dict["end_time"]))}\n') + f.write(f'### cost: {proc_dict["cost"]}\n') + f.write(f'### log_file: {proc_dict["log_file"]}\n') + f.write(f'### status: {proc_dict["status"]}\n') + f.write('=' * 60 + '\n') + f.write('### stdout:\n') + f.write(proc_dict["stdout"]) + f.write('=' * 60 + '\n') + f.write('### stderr:\n') + f.write(proc_dict["stderr"]) + f.write('=' * 60 + '\n') + print(f'### all command cost {time.time() - start_time}') + + +def sysinfo(log_dir, install_command=False, merge_files=True): + command_list = [ + "uname -a", + "ulimit -a", + "lscpu", + "lspci", + "lspci -k", + "lspci -vv", + "lspci -t -vv -nn", + "lsscsi", + "lsscsi --list --verbose --long", + "lsusb", + "lsusb --tree", + "lshw -short", + "lsmod", + "route -n", + "ifconfig -a", + "dmidecode", + "udevadm info --export-db", + "ipmitool sdr", + "ipmitool fru", + "ipmitool sensor", + "ipmitool sel", + "fdisk -l", + "mount", + "df -P", + "lsblk", + "lsblk -O", + "smartctl --scan" + "free", + "numastat -v", + "numastat -v -m", + "cpupower --cpu all frequency-info", + "cpupower --cpu all idle-info", + "sysctl -a", + "cat /etc/os-release", + "cat /etc/system-release", + "cat /etc/centos-release", + "cat /etc/redhat-release", + "cat /etc/system-release", + "cat /etc/tencentos-release", + "cat /etc/tlinux-release", + "cat /proc/cpuinfo", + "cat /proc/meminfo", + "cat /proc/buddyinfo", + "cat /proc/devices", + "cat /proc/interrupts", + "cat /proc/iomem", + "cat /proc/ioports", + "cat /proc/modules", + "cat /proc/module_md5_list", + "zcat /proc/config.gz", + "zcat /proc/bt_stat", + "zcat /proc/cgroups", + "zcat /proc/cmdline", + "zcat /proc/consoles", + "zcat /proc/crypto", + "zcat /proc/devices", + "zcat /proc/diskstats", + "zcat /proc/dma", + "zcat /proc/execdomains", + "zcat /proc/filesystems", + "zcat /proc/kallsyms", + "zcat /proc/loadavg", + "zcat /proc/loadavg_bt", + "zcat /proc/locks", + "zcat /proc/mdstat", + "zcat /proc/misc", + "zcat /proc/mtrr", + "zcat /proc/partitions", + "zcat /proc/sched_debug", + "zcat /proc/schedstat", + "zcat /proc/slabinfo", + "zcat /proc/softirqs", + "zcat /proc/stat", + "zcat /proc/swaps", + "zcat /proc/timer_list", + "zcat /proc/uptime", + "zcat /proc/version", + "zcat /proc/vmallocinfo", + "zcat /proc/vmstat", + "zcat /proc/zoneinfo", + "dmesg" + ] + if os.path.isfile('/proc/net/dev'): + with open(file='/proc/net/dev', mode='r') as f: + for line in f.readlines(): + if ':' not in line: + continue + dev = line.split(':')[0].strip() + command_list.append(f'ethtool {dev}') + command_list.append(f'ethtool -i {dev}') + if os.path.isfile('/proc/modules'): + with open(file='/proc/modules', mode='r') as f: + for line in f.readlines(): + module = line.split()[0].strip() + command_list.append(f'modinfo {module}') + outs, _, _ = command_output('smartctl --scan') + if outs: + for line in outs.splitlines(): + dev = line.split()[0].strip() + command_list.append(f'smartctl --xall {dev}') + command_list.append(f'hdparm {dev}') + + # 尝试安装命令 + if install_command: + for cmd in set([c.split()[0] for c in command_list]): + try_install_command(cmd) + + if not os.path.exists(log_dir): + os.makedirs(log_dir, mode=0o755, exist_ok=True) + get_commands_logs(command_list, log_dir) + # 将多个日志文本文件合并成一个文件 + if merge_files: + tmp_file = tempfile.mkstemp()[1] + with open(tmp_file, 'w') as f: + for txt_file in os.listdir(log_dir): + txt_path = os.path.join(log_dir, txt_file) + with open(txt_path, 'r') as tf: + f.write(tf.read()) + os.remove(txt_path) + shutil.move(tmp_file, os.path.join(log_dir, 'sysinfo.txt')) + + +def get_crash_path(): + result = None + if not os.path.exists('/etc/kdump.conf'): + return result + with open('/etc/kdump.conf', 'r') as f: + for line in f.readlines(): + if line.startswith('path '): + result = line.split()[1] + return result + + +def safe_repr(obj, short=False): + max_len = 120 + try: + result = repr(obj) + except Exception: + result = object.__repr__(obj) + if not short or len(result) < max_len: + return result + return result[:max_len] + ' [truncated]...' + + +def set_env(env, value): + if os.environ.get(env): + print(f"the env {env} has value {os.environ.get(env)}, don't set to {value}") + return + os.environ[env] = f"{value}" + + +def set_env_force(env, value): + if os.environ.get(env): + print(f"the env {env} has value {os.environ.get(env)}, now set to {value}") + os.environ[env] = value + + +def get_env(env): + return os.environ.get(env) + + +def get_env_default(env, default): + return os.environ.get(env, default) + + +def _is_main_process(): + return int(get_env_default('TST_TC_PID', '0')) == os.getpid() + + +class ExceptionSkip(Exception): + def __init__(self, message=""): + super(ExceptionSkip, self).__init__(self) + self.message = f'{message}' + + def __str__(self): + return self.message + + +def tcstat_to_str(tcstat): + tst_tc_stat_dict.get(tcstat, 'UNKNOWN') + + +class TestCase: + def __init__(self, *args): + # 用例文件路径 + self.tc_path = os.path.realpath(main.__file__) + # 用例名 + self.tc_name = self._get_tc_attr('用例名称') + # 执行用例文件时的目录 + self.exec_cwd = os.getcwd() + # TST_TC_CWD 测试用例CWD + self.tst_tc_cwd = os.path.dirname(self.tc_path) + set_env('TST_TC_CWD', self.tst_tc_cwd) + # TST_TC_PID 测试用例主进程pid + self.tst_tc_pid = os.getpid() + set_env('TST_TC_PID', self.tst_tc_pid) + # 用例执行状态 + self._tcstat = TST_INIT + # 用例退出码,0表示用例PASS或SKIP,其他表示异常 + self._exit_code = 0 + # TST_TS_TOPDIR 测试套顶层目录 + self.tst_ts_topdir = self._get_ts_topdir() + set_env('TST_TS_TOPDIR', self.tst_ts_topdir) + # TST_COMMON_TOPDIR common顶层目录 + self.tst_common_topdir = self._get_common_topdir() + set_env('TST_COMMON_TOPDIR', self.tst_common_topdir) + # 标记tc_setup是否被调用 + self._tc_setup_called = False + # TST_TS_SYSDIR 测试套公共运行目录 + self.tst_ts_sysdir = None if self.tst_ts_topdir is None \ + else os.path.join(self.tst_ts_topdir, 'logs', '.ts.sysdir') + set_env('TST_TS_SYSDIR', self.tst_ts_sysdir) + # TST_TC_SYSDIR 测试用例管理用临时目录 + self.tst_tc_sysdir = None if self.tst_ts_topdir is None \ + else os.path.join(self.tst_ts_topdir, 'logs', 'testcase', f'.tc.{self.tst_tc_pid}.sysdir') + set_env('TST_TC_SYSDIR', self.tst_tc_sysdir) + + def dbg(self, message): + print(message, file=sys.stderr) + + def msg(self, message): + print(message, file=sys.stderr) + + def err(self, message): + print(message, file=sys.stderr) + self._fail(message) + + def _get_tc_attr(self, attr): + with open(file=self.tc_path, mode='r', encoding='utf-8') as f: + for line in f.readlines(): + if f"@{attr}:" not in line: + continue + return re.sub(f'.*@{attr}:', '', line).strip() + return None + + def _get_ts_topdir(self): + result = self.tst_tc_cwd + while True: + if os.path.isdir(os.path.join(result, 'cmd')) and os.path.isdir(os.path.join(result, 'testcase')) and \ + os.path.isfile(os.path.join(result, 'tsuite')): + if os.path.isdir(os.path.join(result, '..', 'tst_common')): + return os.path.dirname(result) + return result + next_path = os.path.dirname(result) + if next_path == result: + return None + result = next_path + + def _get_common_topdir(self): + if self.tst_ts_topdir is None: + return None + if os.path.isdir(os.path.join(self.tst_ts_topdir, 'tst_common')): + return os.path.join(self.tst_ts_topdir, 'tst_common') + return self.tst_ts_topdir + + def _set_tcstat(self, stat): + self._tcstat = stat + + def _get_tcstat(self): + return self._tcstat + + def _get_tcstat_str(self): + return tcstat_to_str(self._tcstat) + + def _fail(self, message=None): + if self._tcstat != TST_FAIL: + self.msg("the testcase first fail here") + self._set_tcstat(TST_FAIL) + raise AssertionError(message) + + def _pass(self): + if self._get_tcstat() == TST_INIT: + self._set_tcstat(TST_PASS) + + def skip_test(self, message=None): + """ + 标记用例为SKIP状态(当用例不需要测试时) + :param message: 要输出的信息 + :return: None + 示例: + skip_test(message='内核CONFIG_XXX未开,系统不支持此测试') + """ + if self._get_tcstat() in (TST_PASS, TST_INIT, TST_SKIP): + self._set_tcstat(TST_SKIP) + raise ExceptionSkip(f'set testcase SKIP: {message}') + else: + self.msg(f'set testcase SKIP fail: {message}') + self._fail(f'the testcase stat is {self._get_tcstat_str()}, can\'t set to SKIP') + + def skip_if_true(self, expr, message=None): + """ + 当表达式返回真或命令执行成功时,用例不满足测试条件,终止测试 + :param expr: 要判断的表达式 + :param message: 要输出的信息 + :return: None + 示例: + skip_if_true(1 == 2) + """ + if expr: + self.skip_test(f'skip_if_true -> {safe_repr(expr)}: {message}') + + def skip_if_false(self, expr, message=None): + """ + 当表达式返回假或命令执行失败,用例不满足测试条件,终止测试 + :param expr: 要判断的表达式 + :param message: 要输出的信息 + :return: None + 示例: + skip_if_false(1 == 2) + """ + if not expr: + self.skip_test(f'skip_if_false -> {safe_repr(expr)}: {message}') + + def assert_true(self, expr, message=None): + """ + 断言表达式返回真 + :param expr: 要断言的表达式 + :param message: 断言要输出的信息 + :return: None + 示例: + assert_true(1 == 2) + assert_true(a >= b) + """ + if not expr: + self.msg(f"{safe_repr(expr)} is not true: {message}") + self._fail(message) + else: + self._pass() + + def assert_false(self, expr, message=None): + """ + 断言表达式返回假 + :param expr: 要断言的表达式 + :param message: 断言要输出的信息 + :return: None + 示例: + assert_false(1 == 2) + assert_false(a >= b) + """ + if expr: + self.msg(f"{safe_repr(expr)} is not false: {message}") + self._fail(message) + else: + self._pass() + + def _tc_setup_common(self, *args): + # 只有用例的主进程才能执行此函数 + if not _is_main_process(): + return None + try: + self.tc_setup_common(*args) + except Exception: + raise + + def tc_setup_common(self, *args): + self.msg("this is TestCase.tc_setup_common") + + def _tc_setup(self, *args): + # 只有用例的主进程才能执行此函数 + if not _is_main_process(): + return None + try: + self._tc_setup_called = True + self.tc_setup(*args) + except Exception: + raise + + def tc_setup(self, *args): + self.msg("this is TestCase.tc_setup") + + def _do_test(self, *args): + # 只有用例的主进程才能执行此函数 + if not _is_main_process(): + return None + try: + self.do_test(*args) + except Exception: + raise + + @abc.abstractmethod + def do_test(self, *args): + self.msg("this is TestCase.do_test") + + def _tc_teardown(self, *args): + # 只有用例的主进程才能执行此函数 + if not _is_main_process(): + return None + try: + self.tc_teardown(*args) + except Exception: + raise + + def tc_teardown(self, *args): + self.msg("this is TestCase.tc_teardown") + + def _tc_teardown_common(self, *args): + # 只有用例的主进程才能执行此函数 + if not _is_main_process(): + return None + try: + self.tc_teardown_common(*args) + except Exception: + raise + + def tc_teardown_common(self, *args): + self.msg("this is TestCase.tc_teardown_common") + + def _is_ts_setup_called(self): + if self.tst_ts_sysdir: + return os.path.isfile(os.path.join(self.tst_ts_sysdir, 'ts.setup.stat')) + else: + return False + + def _get_ts_setup_stat(self): + if self.tst_ts_sysdir: + ts_stat_file = os.path.join(self.tst_ts_sysdir, 'ts.setup.stat') + if not os.path.isfile(ts_stat_file): + return None + with open(file=ts_stat_file, mode='r', encoding='utf-8') as f: + line = f.readline() + return int(line) + else: + return None + + def tst_main(self, *args): + time_start = int(time.monotonic() * 1000000000) + if self._is_ts_setup_called(): + self.msg(f"tsuite setup executed, stat is {self._get_ts_setup_stat()}") + else: + self.msg("tsuite setup may not executed") + + try: + self._tc_setup_common(*args) + self.msg("call _tc_setup_common success") + self._tc_setup(*args) + self.msg("call _tc_setup success") + self._do_test(*args) + self.msg("call _do_test success") + except ExceptionSkip as e: + self._set_tcstat(TST_SKIP) + self.msg(e.message) + except Exception: + self._set_tcstat(TST_FAIL) + self.msg(traceback.format_exc()) + finally: + try: + if self._tc_setup_called: + self._tc_teardown(*args) + else: + self.msg("the tc_setup not called, so tc_teardown ignore") + self._tc_teardown_common(*args) + except ExceptionSkip as e: + self._set_tcstat(TST_SKIP) + self.msg(e.message) + except Exception: + self._set_tcstat(TST_FAIL) + self.msg(traceback.format_exc()) + + # TCase自动化执行框架需要用这个输出判断用例是否支持完 + self.msg("Global test environment tear-down") + if self._get_tcstat() == TST_PASS: + self.msg(f"RESULT : {self.tc_name} ==> [ PASSED ]") + self._exit_code = 0 + elif self._get_tcstat() == TST_FAIL: + self.msg(f"RESULT : {self.tc_name} ==> [ FAILED ]") + self._exit_code = 1 + elif self._get_tcstat() == TST_INIT: + self.msg(f"RESULT : {self.tc_name} ==> [ NOTEST ]") + self._exit_code = 1 + elif self._get_tcstat() == TST_SKIP: + self.msg(f"RESULT : {self.tc_name} ==> [ SKIP ]") + self._exit_code = 0 + else: + self.msg(f"RESULT : {self.tc_name} ==> [ UNKNOWN ]") + self._exit_code = 1 + time_end = int(time.monotonic() * 1000000000) + self.msg(f'cost {(time_end - time_start) / 1000000000:.9f}') + exit(self._exit_code) diff --git a/coreutils/tst_common/lib/common.sh b/coreutils/tst_common/lib/common.sh new file mode 100644 index 0000000..3c6baaa --- /dev/null +++ b/coreutils/tst_common/lib/common.sh @@ -0,0 +1,734 @@ +#!/bin/bash +# 所有shell脚本的测试用例都应该source此文件 +# 约定: +# 1、以下划线"_"开头的函数和变量用例不能直接调用 +# 2、环境变量全大写,全局变量加上"g_"前置,局部变量统一加"local"修饰 + +export LANG="en_US.UTF-8" +export LANGUAGE="en_US:en" + +if [ -d "$TST_TS_TOPDIR/tst_common" ]; then + export TST_COMMON_TOPDIR="$TST_TS_TOPDIR/tst_common" + # 先source测试用例自定义的公共文件 + source "$TST_TS_TOPDIR/tst_lib/ts_common.sh" || exit 1 + # 再source全局公共文件 + source "$TST_COMMON_TOPDIR/lib/common_func.sh" || exit 1 +elif [ -d "$TST_TS_TOPDIR/lib" ]; then + export TST_COMMON_TOPDIR="$TST_TS_TOPDIR" + # 只是tst_suite_common使用 + source "$TST_TS_TOPDIR/lib/common_func.sh" || exit 1 +else + echo "can't find the tsuite common file" + exit 1 +fi + +# 环境变量 +# TST_TS_TOPDIR 测试套顶层目录 +# TST_TS_SYSDIR 测试套公共运行目录 +[ -z "$TST_TS_SYSDIR" ] && export TST_TS_SYSDIR="$TST_TS_TOPDIR/logs/.ts.sysdir" +# TST_TC_SYSDIR 测试用例管理用临时目录 +# TST_TC_CWD 测试用例CWD +# TST_TC_PID 测试用例主进程pid +# 下面几个为用例结果状态 +export TST_PASS=0 +export TST_FAIL=1 +export TST_INIT=2 +export TST_SKIP=3 +# TST_TC_NAME 用例名称 +# TST_TC_FILE 用例文件 +# TST_VM_SUBNET 虚拟机子网 +if [ -z "$TST_VM_SUBNET" ]; then + TST_VM_SUBNET=$(ifconfig eth0 2>/dev/null | grep "netmask .* broadcast 192\.168\." | awk '{print $2}') + [ -z "$TST_VM_SUBNET" ] && TST_VM_SUBNET=$(ifconfig eth1 2>/dev/null | grep "netmask .* broadcast 192\.168\." | awk '{print $2}') + [ -z "$TST_VM_SUBNET" ] && TST_VM_SUBNET=$(ifconfig eth2 2>/dev/null | grep "netmask .* broadcast 192\.168\." | awk '{print $2}') + TST_VM_SUBNET=${TST_VM_SUBNET%.*} +fi +export TST_VM_SUBNET + +g_tst_case_start=$(get_up_time_ms) +g_tst_trap_signal=12 + +_tcstat_to_str() { + case "$1" in + "TST_PASS" | "$TST_PASS") + echo "TST_PASS" + ;; + "TST_FAIL" | "$TST_FAIL") + echo "TST_FAIL" + ;; + "TST_INIT" | "$TST_INIT") + echo "TST_INIT" + ;; + "TST_SKIP" | "$TST_SKIP") + echo "TST_SKIP" + ;; + *) + echo "TST_UNKNOWN" + ;; + esac +} + +# 获取用例属性 +# $1 -- 用例属性名称,例如:用例ID、用例名称 +_get_case_attr() { + grep "@${1}:" "$TST_TC_FILE_FULL" | head -n 1 | sed "s|.*@${1}:\s*||g" | sed "s|\s*$||g" +} +_get_case_preconditions() { + grep "@预置条件:" "$TST_TC_FILE_FULL" +} +_get_case_steps() { + grep "@测试步骤:" "$TST_TC_FILE_FULL" +} +_get_case_expect() { + grep "@预期结果:" "$TST_TC_FILE_FULL" +} + +# 功能:设置环境变量 +# 参数: +# $1 -- 环境变量名 +# $2 -- 环境变量值 +# 返回值: +# 0 -- 环境变量设置成功 +# 1 -- 环境变量设置失败 +setup_env_var() { + local _tst_var_name="$1" + local _tst_old_value + eval _tst_old_value=\"\$"${1}"\" + local _tst_new_value="$2" + + if ! echo "$_tst_var_name" | grep "^[A-Z_]\+$" >/dev/null; then + msg "the var name must be upper and '_'" + return 1 + fi + [ -n "$_tst_old_value" ] && msg "the environment variable $_tst_var_name has old value: $_tst_old_value" + eval export "$_tst_var_name"=\""$_tst_new_value"\" + echo "export $_tst_var_name=\"$_tst_new_value\"" >>"$TST_TS_SYSDIR/environment_variable" + return 0 +} + +# 功能:将K/M/G/T等单位互相转换 +# 参数:wait_proc_exit -p pid [-t timeout] [-s signal] +# -p pid 【必选参数】进程pid +# -t timeout 【可选参数】等待超时时间(单位:秒,不指定时默认等待60秒),如果等待超时进程仍未退出则返回失败 +# -s signal 【可选参数】必须配合-t参数使用,超时时间到期后发送-s指定信号到进程 +# 返回值: +# 0 -- 进程退出 +# 1 -- 等待失败 +wait_proc_exit() { + local _tst_all_args="$*" + local _tst_pid + local _tst_timeout + local _tst_signal + while [ $# -gt 0 ]; do + case "$1" in + "-p") + shift + _tst_pid="$1" + shift + ;; + "-t") + shift + _tst_timeout="$1" + shift + ;; + "-s") + shift + _tst_signal="$1" + shift + ;; + *) + msg "unknown args $1 in $_tst_all_args" + return 1 + ;; + esac + done + if [ -z "$_tst_pid" ]; then + msg "pid not set" + return 1 + fi + [ -z "$_tst_timeout" ] && _tst_timeout=60 + + local _tst_time_start + _tst_time_start="$(get_uptime)" + local _tst_time_now + _tst_time_now="$(get_uptime)" + while [ $((_tst_time_start + _tst_timeout)) -gt "$_tst_time_now" ]; do + [ -d "/proc/$_tst_pid" ] || return 0 + sleep 1 + _tst_time_now="$(get_uptime)" + done + [ -n "$_tst_signal" ] && kill -s "$_tst_signal" "$_tst_pid" + sleep 1 + [ -d "/proc/$_tst_pid" ] || return 0 + return 1 +} + +# 功能:获取系统启动后到现在的时间,单位:秒 +# 参数:无 +# 返回值:标准输出时间 +get_uptime() { + awk -F . '{print $1}' /proc/uptime +} + +# 功能:将K/M/G/T等单位互相转换 +# 参数:conv_unit [-i k|m|g|t] [-o k|m|g|t] value[_with_unit] +# -i k|m|g|t 【可选参数】输入数据的单位,可选参数,若不指定单位,则默认为1,或者输入的值后面带参数 +# -o k|m|g|t 【可选参数】输出数据的单位,若不指定单位,则默认为1 +# value[_with_unit] 【必选参数】需要转换的数据值,可以跟单位(只取单位第一个字母用于判断k|m|g|t) +# 返回值:标准输出转换后的结果 +# 0 -- 转换成功 +# 1 -- 转换失败 +conv_unit() { + local _tst_input_all + local _tst_input_value + local _tst_input_unit + local _tst_output_value + local _tst_output_unit + while [ $# -gt 0 ]; do + case "$1" in + "-i") + shift + _tst_input_unit="$1" + shift + ;; + "-o") + shift + _tst_output_unit="$1" + shift + ;; + *) + _tst_input_all="$_tst_input_all $1" + shift + ;; + esac + done + # shellcheck disable=SC2001 + _tst_input_value=$(echo "$_tst_input_all" | sed "s|^[[:blank:]]*\([0-9]\+\)[[:blank:]]*\(.*\)|\1|g") + # shellcheck disable=SC2001 + [ -z "$_tst_input_unit" ] && _tst_input_unit=$(echo "$_tst_input_all" | sed "s|^[[:blank:]]*\([0-9]\+\)[[:blank:]]*\(.*\)|\2|g" | head -c 1) + [ -z "$_tst_input_unit" ] && _tst_input_unit="b" + [ -z "$_tst_output_unit" ] && _tst_output_unit="b" + if [ -z "$_tst_input_value" ]; then + msg "no input value" + return 1 + fi + case "$_tst_input_unit" in + b | B) ;; + k | K) + _tst_input_value=$((_tst_input_value * 1024)) + ;; + m | M) + _tst_input_value=$((_tst_input_value * 1024 * 1024)) + ;; + g | G) + _tst_input_value=$((_tst_input_value * 1024 * 1024 * 1024)) + ;; + t | T) + _tst_input_value=$((_tst_input_value * 1024 * 1024 * 1024 * 1024)) + ;; + *) + msg "unknown input unit $_tst_input_unit" + return 1 + ;; + esac + case "$_tst_output_unit" in + b | B) + _tst_output_value=$_tst_input_value + ;; + k | K) + _tst_output_value=$((_tst_input_value / 1024)) + ;; + m | M) + _tst_output_value=$((_tst_input_value / 1024 / 1024)) + ;; + g | G) + _tst_output_value=$((_tst_input_value / 1024 / 1024 / 1024)) + ;; + t | T) + _tst_output_value=$((_tst_input_value / 1024 / 1024 / 1024 / 1024)) + ;; + *) + msg "unknown output unit $_tst_output_unit" + return 1 + ;; + esac + echo $_tst_output_value + return 0 +} + +# 功能:ssh到环境子网中指定机器上 +# 参数: +# $1 -- 需要登录的机器IP编号 +# $* -- 要远程执行的命令及参数 +# 返回值:同ssh +env_ssh() { + local _tst_ip="${TST_VM_SUBNET}.$1" + shift + msg "try ssh to $_tst_ip execute: $*" + timeout -s SIGTERM 60 ssh -q -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@"$_tst_ip" "$@" +} + +# 功能:scp本机的文件到到环境子网中指定机器的指定路径 +# 参数: +# $1 -- scp目标机器IP编号 +# $2 -- 远程机器的目标文件夹 +# $* -- 需要从本机拷贝到远端机器的文件,可以拷贝多个文件 +# 返回值:同scp +env_scpt() { + local _tst_ip="${TST_VM_SUBNET}.$1" + shift + local _tst_target="$1" + shift + msg "try scp $* to ${_tst_ip}:$_tst_target" + timeout -s SIGTERM 120 scp -rvq -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null "$@" root@"$_tst_ip":"$_tst_target" +} + +# 功能:scp指定机器的文件到本机路径 +# 参数: +# $1 -- scp目标机器IP编号 +# $2 -- 本机目标文件夹 +# $* -- 需要从远端机器拷贝到本机的文件,可以拷贝多个文件 +# 返回值:同scp +env_scpf() { + local _tst_ret=0 + local _tst_ip="${TST_VM_SUBNET}.$1" + shift + local _tst_target="$1" + shift + while [ -n "$1" ]; do + msg "try scp ${_tst_ip}:$1 to local $_tst_target" + timeout -s SIGTERM 120 scp -rvq -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@"$_tst_ip":"$1" "$_tst_target" || _tst_ret=1 + shift + done + return $_tst_ret +} + +# 功能:等待指定机器就绪,默认超时时间60秒 +# 参数: +# $1 -- 目标机器IP编号 +# $2 -- 【可选】等待的超时时间,默认等待60秒 +# 返回值: +# 0 -- 机器在超时前就绪 +# 1 -- 机器启动异常 +env_wait() { + local _tst_start_time + _tst_start_time=$(get_uptime) + local _tst_end_time + _tst_end_time=$(get_uptime) + local _tst_timeout + if [ -z "$2" ]; then + _tst_timeout=60 + else + _tst_timeout=$2 + fi + + local _tst_ip="${TST_VM_SUBNET}.$1" + msg "wait env $_tst_ip standby" + while [ $((_tst_start_time + _tst_timeout)) -ge "$_tst_end_time" ]; do + echo -n "." + sleep 3 + _tst_end_time=$(get_uptime) + ping -w 1 -W 1 -c 1 "$_tst_ip" >/dev/null 2>&1 || continue + if env_ssh "$1" test -d /proc; then + msg "the env with IP $_tst_ip ssh success, wait total $((_tst_end_time - _tst_start_time)) seconds" + return 0 + else + continue + fi + done + _tst_end_time=$(get_uptime) + msg "wait the env $_tst_ip timeout, wait total $((_tst_end_time - _tst_start_time)) seconds" + return 1 +} + +_assert_trap_exit() { + kill -s "$g_tst_trap_signal" "$TST_TC_PID" +} + +# 功能:标记用例为SKIP状态(当用例不需要测试时) +# 参数: +# $* -- 对SKIP状态标记的描述 +# 返回值:无 +skip_test() { + local _tst_tc_stat + _tst_tc_stat="$(_get_tcstat)" + + case "$_tst_tc_stat" in + "$TST_PASS" | "$TST_INIT" | "$TST_SKIP") + _set_tcstat "$TST_SKIP" + msg "set testcase SKIP: $*" + _assert_trap_exit + ;; + *) + msg "set testcase SKIP fail: $*" + err "the testcase stat is $(_tcstat_to_str "$_tst_tc_stat"), can't set to SKIP" + ;; + esac +} + +# 功能:当表达式返回真或命令执行成功时,用例不满足测试条件,终止测试 +# 参数: +# $* -- 需要断言的表达式 +# 返回值:无 +skip_if_true() { + local _tst_ret + "$@" + _tst_ret=$? + if [ $_tst_ret -eq 0 ]; then + skip_test "skip_if_true get (_tst_ret:$_tst_ret) ->" "$@" + fi +} + +# 功能:当表达式返回假或命令执行失败,用例不满足测试条件,终止测试 +# 参数: +# $* -- 需要断言的表达式 +# 返回值:无 +skip_if_false() { + local _tst_ret + "$@" + _tst_ret=$? + if [ $_tst_ret -ne 0 ]; then + skip_test "skip_if_false get (_tst_ret:$_tst_ret) ->" "$@" + fi +} + +# 功能:断言表达式返回真或命令执行成功,'_cont'后缀的断言函数在断言失败后用例继续执行,不终止 +# 参数: +# $* -- 需要断言的表达式 +# 返回值:无 +assert_true_cont() { + local _tst_ret + "$@" + _tst_ret=$? + if [ $_tst_ret -eq 0 ]; then + _tc_pass + return 0 + else + err "assert_true, but return ${_tst_ret}: $*" + return 1 + fi +} +assert_true() { + assert_true_cont "$@" || _assert_trap_exit +} + +# 功能:断言表达式返回假或命令执行失败,'_cont'后缀的断言函数在断言失败后用例继续执行,不终止 +# 参数: +# $* -- 需要断言的表达式 +# 返回值:无 +assert_false_cont() { + local _tst_ret + "$@" + _tst_ret=$? + if [ $_tst_ret -ne 0 ]; then + _tc_pass + return 0 + else + err "assert_false, but return ${_tst_ret}: $*" + return 1 + fi +} +assert_false_skip() { + assert_false_cont "$@" || _skip "expect false but true ->" "$@" +} +assert_false() { + assert_false_cont "$@" || _assert_trap_exit +} + +_set_tcstat() { + echo "$1" >"$TST_TC_SYSDIR/tcstat" +} + +_get_tcstat() { + cat "$TST_TC_SYSDIR/tcstat" 2>/dev/null +} + +_tc_pass() { + # 只有初始状态的用例才能置为PASS,其他异常状态的用例不能从异常变为PASS + if [ "$(cat "$TST_TC_SYSDIR/tcstat" 2>/dev/null)" == "$TST_INIT" ]; then + _set_tcstat $TST_PASS + fi +} + +_tc_fail() { + if [ "$(_get_tcstat)" != "$TST_FAIL" ]; then + echo "the testcase first fail here" + fi + _set_tcstat $TST_FAIL +} + +_tc_setup_common() { + local _tst_ret=0 + + # 只有用例的主进程才能执行此函数 + [ "$TST_TC_PID" != "$$" ] && return 0 + + # 对用例执行环境进行初始化设置 + mkdir -p "${TST_TC_SYSDIR}/core" + ulimit -c >"$TST_TC_SYSDIR/old.ulimit.c" + ulimit -c unlimited + cat /proc/sys/kernel/core_pattern >"$TST_TC_SYSDIR/old.proc.core_pattern" + is_root && echo "${TST_TC_SYSDIR}/core/core-e%e-p%p-i%i-s%s-g%g-u%u-t%t.dump" >/proc/sys/kernel/core_pattern + + if is_function tc_setup_common; then + msg "try call tc_setup_common" + if tc_setup_common "$@"; then + msg "call tc_setup_common success" + else + err "call tc_setup_common fail" + _tst_ret=1 + fi + else + msg "tc_setup_common not define" + fi + + return $_tst_ret +} + +_tc_setup() { + local _tst_ret=0 + + # 只有用例的主进程才能执行此函数 + [ "$TST_TC_PID" != "$$" ] && return 0 + touch "$TST_TC_SYSDIR/tc_setup_called" + if is_function tc_setup; then + msg "try call tc_setup" + if tc_setup "$@"; then + msg "call tc_setup success" + else + err "call tc_setup fail" + _tst_ret=1 + fi + else + msg "tc_setup not define" + fi + + return $_tst_ret +} + +_do_test() { + local _tst_ret=0 + + # 只有用例的主进程才能执行此函数 + [ "$TST_TC_PID" != "$$" ] && return 0 + if is_function do_test; then + msg "try call do_test" + if do_test "$@"; then + msg "call do_test success" + else + err "call do_test fail" + _tst_ret=1 + fi + else + err "do_test not define" + _tst_ret=1 + fi + + return $_tst_ret +} + +_tc_teardown() { + local _tst_ret=0 + + # 只有用例的主进程才能执行此函数 + [ "$TST_TC_PID" != "$$" ] && return 0 + if is_function tc_teardown; then + msg "try call tc_teardown" + if tc_teardown "$@"; then + msg "call tc_teardown success" + else + err "call tc_teardown fail" + _tst_ret=1 + fi + else + msg "tc_teardown not define" + fi + + return $_tst_ret +} + +_tc_teardown_common() { + local _tst_ret=0 + + # 只有用例的主进程才能执行此函数 + [ "$TST_TC_PID" != "$$" ] && return 0 + if is_function tc_teardown_common; then + msg "try call tc_teardown_common" + if tc_teardown_common "$@"; then + msg "call tc_teardown_common success" + else + err "call tc_teardown_common fail" + _tst_ret=1 + fi + else + msg "tc_teardown_common not define" + fi + + # 恢复用例执行前做的初始化设置 + ulimit -c "$(cat "$TST_TC_SYSDIR/old.ulimit.c")" + is_root && cat "$TST_TC_SYSDIR/old.proc.core_pattern" >/proc/sys/kernel/core_pattern + + return $_tst_ret +} + +_tc_trap_call() { + _tc_run_complete || exit 1 + exit 0 +} + +_tc_run_complete() { + local _tst_ret=0 + + # 只有用例的主进程才能执行此函数 + [ "$TST_TC_PID" != "$$" ] && return 0 + if [ -e "$TST_TC_SYSDIR/tc_setup_called" ]; then + if _tc_teardown "$@"; then + msg "call _tc_teardown success" + else + err "call _tc_teardown fail" + _tst_ret=1 + fi + else + msg "the tc_setup not called, so tc_teardown ignore" + fi + if _tc_teardown_common "$@"; then + msg "call _tc_teardown_common success" + else + err "call _tc_teardown_common fail" + _tst_ret=1 + fi + + # TCase自动化执行框架需要用这个输出判断用例是否执行完 + echo "Global test environment tear-down" + # 用例失败则收集系统日志上传到TCase用于定位 + case "$(_get_tcstat)" in + "$TST_PASS") + msg "RESULT : $TST_TC_NAME ==> [ PASSED ]" + rm -rf "$TST_TC_SYSDIR" + echo "case-result: PASS" >>"$TST_RESULT_FILE" + ;; + "$TST_FAIL") + msg "RESULT : $TST_TC_NAME ==> [ FAILED ]" + _tst_ret=1 + echo "case-result: FAIL" >>"$TST_RESULT_FILE" + ;; + "$TST_INIT") + msg "RESULT : $TST_TC_NAME ==> [ NOTEST ]" + _tst_ret=1 + echo "case-result: ABORT" >>"$TST_RESULT_FILE" + ;; + "$TST_SKIP") + msg "RESULT : $TST_TC_NAME ==> [ SKIP ]" + rm -rf "$TST_TC_SYSDIR" + _tst_ret=0 + echo "case-result: SKIP" >>"$TST_RESULT_FILE" + ;; + *) + msg "RESULT : $TST_TC_NAME ==> [ UNKNOWN ]" + _tst_ret=1 + echo "case-result: ABORT" >>"$TST_RESULT_FILE" + ;; + esac + local _tst_case_end + _tst_case_end=$(get_up_time_ms) + msg "cost $(diff_time_ms2sec "$g_tst_case_start" "$_tst_case_end")" + + { + echo "case-end-time: $(get_timestamp_ms)" + echo "" + } >>"$TST_RESULT_FILE" + + return $_tst_ret +} + +_set_ts_setup_stat() { + echo "$1" >"$TST_TS_SYSDIR/ts.setup.stat" +} + +_get_ts_setup_stat() { + cat "$TST_TS_SYSDIR/ts.setup.stat" 2>/dev/null +} + +_is_ts_setup_called() { + test -f "$TST_TS_SYSDIR/ts.setup.stat" +} + +_clean_ts_setup_stat() { + rm -rf "$TST_TS_SYSDIR/ts.setup.stat" +} + +tst_main() { + local _tst_ret=0 + + if [ -z "$TST_TS_TOPDIR" ]; then + msg "the TST_TS_TOPDIR not set" + return 1 + fi + if [ ! -d "$TST_TS_TOPDIR" ]; then + msg "the TST_TS_TOPDIR=$TST_TS_TOPDIR not dir" + return 1 + fi + + [ -f "$TST_TS_SYSDIR/environment_variable" ] && source "$TST_TS_SYSDIR/environment_variable" + export TST_TC_PID=$$ + TST_TC_CWD="$(realpath "$(dirname "$0")")" + export TST_TC_CWD + TST_TC_FILE_FULL="$(realpath "$0")" + export TST_TC_FILE_FULL + # shellcheck disable=SC2001 + TST_TC_FILE="$(echo "$TST_TC_FILE_FULL" | sed "s|^${TST_TS_TOPDIR}/*||g")" + export TST_TC_FILE + TST_TC_NAME="$(_get_case_attr "用例名称")" + export TST_TC_NAME + export TST_TC_SYSDIR="$TST_TS_TOPDIR/logs/testcase/.tc.${TST_TC_PID}.sysdir" + + # 用于断言,有的断言会终止测试活动 + trap _tc_trap_call "$g_tst_trap_signal" + + # 生成结果记录文件 + _get_tst_result_file + + { + echo "TESTCASE" + echo "case-name: $TST_TC_NAME" + echo "case-id: $(_get_case_attr "用例ID")" + echo "case-type: case-type" + echo "case-level: $(_get_case_attr "用例级别")" + echo "case-label: $(_get_case_attr "用例标签")" + echo "case-steps: $(_get_case_steps)" + echo "case-result-id: ${TST_TC_NAME}-result-${TST_RESULT_ID}" + echo "case-start-time: $(get_timestamp_ms)" + } >>"$TST_RESULT_FILE" + + if _is_ts_setup_called; then + msg "tsuite setup executed, stat is $(_get_ts_setup_stat)" + else + msg "tsuite setup may not executed" + fi + + cd "$TST_TC_CWD" || return 1 + mkdir -p "$TST_TC_SYSDIR" + _set_tcstat $TST_INIT + + if _tc_setup_common "$@"; then + if _tc_setup "$@"; then + msg "call _tc_setup success" + if _do_test "$@"; then + msg "call _do_test success" + else + err "call _do_test fail" + _tst_ret=1 + fi + else + err "call _tc_setup fail" + _tst_ret=1 + fi + else + err "call _tc_setup_common fail" + _tst_ret=1 + fi + + _tc_run_complete "$@" || _tst_ret=1 + + return $_tst_ret +} diff --git a/coreutils/tst_common/lib/common_func.sh b/coreutils/tst_common/lib/common_func.sh new file mode 100644 index 0000000..9217202 --- /dev/null +++ b/coreutils/tst_common/lib/common_func.sh @@ -0,0 +1,88 @@ +#!/bin/bash +# 所有shell脚本的测试用例都应该source此文件 +# 约定: +# 1、以下划线"_"开头的函数和变量用例不能直接调用 +# 2、环境变量全大写,全局变量加上"g_"前置,局部变量统一加"local"修饰 + +# Func: 输出调试级别用例日志 +dbg() { + echo "$@" 1>&2 +} + +# Func: 输出普通级别用例日志 +msg() { + echo "$@" 1>&2 +} + +# Func: 输出错误级别用例日志,如果是用例上下文,则标记用例为失败状态 +err() { + echo "$@" 1>&2 + # 只有用例上下文才设置用例状态 + is_function _tc_fail && _tc_fail +} + +is_function() { + type "$1" 2>&1 | head -n 1 | grep "$1 is a function" >/dev/null 2>&1 + return $? +} + +is_root() { + [ "$(id -u)" == "0" ] && return 0 + return 1 +} + +get_up_time_sec() { + awk -F . '{print $1}' /proc/uptime +} + +get_up_time_ms() { + local _tst_uptime + _tst_uptime=$(awk '{print $1}' /proc/uptime | tr -d '.') + echo -n "${_tst_uptime}0" +} + +# 获取时间戳 +get_timestamp_sec() { + date +%s +} +get_timestamp_ms() { + date +%s%N | sed "s|......$||g" +} + +# 输出时间差,并将ms转换为sec +# $1 -- start time: ms +# $2 -- end time: ms +diff_time_ms2sec() { + local _tst_diff_time=$(($2 - $1)) + local _tst_time_sec=$((_tst_diff_time / 1000)) + local _tst_time_ms=$((_tst_diff_time % 1000)) + printf "%d.%03d" $_tst_time_sec $_tst_time_ms +} + +# 获取测试套名 +get_suite_name() { + basename "$TST_TS_TOPDIR" +} + +# 获取测试结果文件 +_get_tst_result_file() { + if [ -z "$TST_RESULT_FILE" ]; then + local test_index=0 + while [ $test_index -lt 10000 ]; do + test_index=$((test_index + 1)) + [ -f "$TST_TS_TOPDIR/logs/${test_index}.result" ] && continue + break + done + export TST_RESULT_ID="$test_index" + TST_RESULT_FILE="$TST_TS_TOPDIR/logs/${test_index}.result" + export TST_RESULT_FILE + { + echo "TESTSUITE" + echo "suite-name: $(get_suite_name)" + echo "suite-start-time: $(get_timestamp_ms)" + echo "suite-end-time:" + echo "" + } >>"$TST_RESULT_FILE" + fi + echo "$TST_RESULT_FILE" +} diff --git a/coreutils/tst_common/lib/main.h b/coreutils/tst_common/lib/main.h new file mode 100644 index 0000000..7a2ca85 --- /dev/null +++ b/coreutils/tst_common/lib/main.h @@ -0,0 +1,12 @@ +#ifndef __MAIN_H__ +#define __MAIN_H__ + +#include "common.h" + +extern int tst_main(int argc, char **argv); + +int main(int argc, char **argv) { + return tst_main(argc, argv); +} + +#endif // __MAIN_H__ diff --git a/coreutils/tst_common/lib/sched.py b/coreutils/tst_common/lib/sched.py new file mode 100644 index 0000000..09e3972 --- /dev/null +++ b/coreutils/tst_common/lib/sched.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +# coding: utf-8 +# Time: 2022-08-24 12:22:09 +# Desc: 系统调度 + +import os, time +from multiprocessing import Process, cpu_count + + +def exec_cpu(cpu: int, rate: float, interval: int, timeout: int) -> None: + t_start = time.time() + while time.time() - t_start < timeout: + if ((time.time() - t_start) / interval) % 1 < rate: + pass + else: + time.sleep((1 - rate) * interval) + print(f'cpu {cpu} execute terminated') + + +def set_cpu_rate_of_system(rate: float, interval: int = 1, timeout: int = 10) -> None: + """ + 设置系统CPU使用率到指定值 + :param rate: 系统CPU使用率百分比, [0, cpu_num] + :param interval: 设置使用率的采样间隔时间 + :param timeout: 设置使用率的时间 + :return: None + """ + cpu_num = cpu_count() + if (rate < 0 or rate > cpu_num): + print(f'Input usage rate is {rate}, which must be a float value between 0 and {cpu_num}!') + return + if (interval <= 0): + print(f'Input interval is {interval}, which must be a positive number!') + return + if (timeout <= 0): + print(f'Input timeout is {timeout}, which must be a positive number!') + return + + ps_list = [] + cpu_rate = rate / cpu_num + for i in range(0, cpu_num): + ps_list.append(Process(target = exec_cpu, args = (i, cpu_rate, interval, timeout))) + for p in ps_list: + p.start() + for p in ps_list: + p.join() + print("all cpus execute over") + + +def exec_on_specific_cpu(cpu: int, rate: float, interval: int, timeout: int) -> None: + pid = os.getpid() + os.sched_setaffinity(pid, {cpu}) + t_start = time.time() + while time.time() - t_start < timeout: + if ((time.time() - t_start) / interval) % 1 < rate: + pass + else: + time.sleep((1 - rate) * interval) + print(f'cpu {cpu} execute terminated') + + +def set_cpu_rate_of_cpu(cpu_index: int, rate: float, interval: int = 1, timeout : int = 10) -> Process: + """ + 设置某个CPU的使用率到指定值 + :param cpu_index: cpu编号 + :param rate: CPU使用率百分比, [0, 1] + :param interval: 设置使用率的采样间隔时间 + :param timeout: 设置使用率的时间 + :return: None + """ + if (rate < 0 or rate > 1): + print(f'Input usage rate is {rate}, which must be a float value between 0 and 1!') + return + if (interval <= 0): + print(f'Input interval is {interval}, which must be a positive number!') + return + if (timeout <= 0): + print(f'Input timeout is {timeout}, which must be a positive number!') + return + pid = os.getpid() + eligible_cpu_set = os.sched_getaffinity(pid) + if (cpu_index not in eligible_cpu_set): + print(f'Input cpu index is {cpu_index}, which is not valid! ' + + f'The eligible cpu set is {eligible_cpu_set}') + return + + print(f'Set cpu usage of cpu{cpu_index} to {rate}') + + p = Process(target = exec_on_specific_cpu, args = (cpu_index, rate, interval, timeout)) + p.start() + return p + + +def set_cpu_rate_of_task(rate: float, interval: int = 1, timeout : int = 10) -> None: + """ + 设置进程的使用率到指定值 + :param rate: 进程CPU使用率百分比, [0, 1] + :param interval: 设置使用率的采样间隔时间 + :param timeout: 设置使用率的时间 + :return: None + """ + if (rate < 0 or rate > 1): + print(f'Input usage rate is {rate}, which must be a float value between 0 and 1!') + return + if (interval <= 0): + print(f'Input interval is {interval}, which must be a positive number!') + return + if (timeout <= 0): + print(f'Input timeout is {timeout}, which must be a positive number!') + return + + pid = os.getpid() + print(f'set cpu usage of pid {pid} to {rate}') + t_start = time.time() + + while time.time() - t_start < timeout: + if ((time.time() - t_start) / interval) % 1 < rate: + pass + else: + time.sleep((1 - rate) * interval) + +if __name__ == '__main__': + # set_cpu_rate_of_system(4, 1, 60) + p = set_cpu_rate_of_cpu(1, 0.3, 1, 30) + print('joining') + p.join() + print('cpu test finished') + # set_cpu_rate_of_task(1.5, 1, 20) + diff --git a/coreutils/tst_common/lib/tst_ts_setup b/coreutils/tst_common/lib/tst_ts_setup new file mode 100755 index 0000000..17bd646 --- /dev/null +++ b/coreutils/tst_common/lib/tst_ts_setup @@ -0,0 +1,55 @@ +#!/bin/bash +# Time: 2022-04-19 22:44:25 +# Desc: 测试套公共ts_setup + +if [ -d "$TST_TS_TOPDIR/tst_common" ]; then + # 先source测试用例自定义的公共文件 + source "$TST_TS_TOPDIR/tst_lib/ts_common.sh" || exit 1 + # 再source全局公共文件 + source "$TST_TS_TOPDIR/tst_common/lib/common.sh" || exit 1 +elif [ -d "$TST_TS_TOPDIR/lib" ]; then + # 只是tst_suite_common使用 + source "$TST_TS_TOPDIR/lib/common.sh" || exit 1 +else + echo "can't find the tsuite common file" + exit 1 +fi + +_ts_setup() { + if _is_ts_setup_called; then + if [ "$(_get_ts_setup_stat)" == "$TST_PASS" ]; then + echo "the ts_setup executed passed yet" + return 0 + else + echo "the ts_setup executed yet, but fail" + return 1 + fi + fi + + local _tst_ret=0 + + if [ -f "$TST_TS_TOPDIR/tst_lib/ts_setup" ]; then + if [ -x "$TST_TS_TOPDIR/tst_lib/ts_setup" ]; then + msg "try execute $TST_TS_TOPDIR/tst_lib/ts_setup" + if "$TST_TS_TOPDIR/tst_lib/ts_setup"; then + msg "execute ts_setup success" + _set_ts_setup_stat "$TST_PASS" + else + msg "execute ts_setup fail" + _set_ts_setup_stat "$TST_FAIL" + _tst_ret=1 + fi + else + msg "the $TST_TS_TOPDIR/tst_lib/ts_setup can't execute" + _set_ts_setup_stat "$TST_FAIL" + _tst_ret=1 + fi + else + msg "ts_setup not exist" + _set_ts_setup_stat "$TST_PASS" + fi + + return $_tst_ret +} + +_ts_setup diff --git a/coreutils/tst_common/lib/tst_ts_teardown b/coreutils/tst_common/lib/tst_ts_teardown new file mode 100755 index 0000000..c3ae1ba --- /dev/null +++ b/coreutils/tst_common/lib/tst_ts_teardown @@ -0,0 +1,47 @@ +#!/bin/bash +# Time: 2022-04-19 22:44:25 +# Desc: 测试套公共ts_teardown + +if [ -d "$TST_TS_TOPDIR/tst_common" ]; then + # 先source测试用例自定义的公共文件 + source "$TST_TS_TOPDIR/tst_lib/ts_common.sh" || exit 1 + # 再source全局公共文件 + source "$TST_TS_TOPDIR/tst_common/lib/common.sh" || exit 1 +elif [ -d "$TST_TS_TOPDIR/lib" ]; then + # 只是tst_suite_common使用 + source "$TST_TS_TOPDIR/lib/common.sh" || exit 1 +else + echo "can't find the tsuite common file" + exit 1 +fi + +_ts_teardown() { + local _tst_ret=0 + + if ! _is_ts_setup_called; then + msg "the ts_setup may not execute, we'll not execute the ts_teardown" + return 1 + fi + + if [ -f "$TST_TS_TOPDIR/tst_lib/ts_teardown" ]; then + if [ -x "$TST_TS_TOPDIR/tst_lib/ts_teardown" ]; then + msg "try execute $TST_TS_TOPDIR/tst_lib/ts_teardown" + if ts_teardown; then + msg "execute ts_teardown success" + else + msg "execute ts_teardown fail" + _tst_ret=1 + fi + else + msg "the $TST_TS_TOPDIR/tst_lib/ts_teardown exist, but can't execute" + _tst_ret=1 + fi + else + msg "ts_teardown not exist" + fi + _clean_ts_setup_stat + + return $_tst_ret +} + +_ts_teardown diff --git a/coreutils/tst_common/lib/tsuite-completion.bash b/coreutils/tst_common/lib/tsuite-completion.bash new file mode 100644 index 0000000..e1d3e4c --- /dev/null +++ b/coreutils/tst_common/lib/tsuite-completion.bash @@ -0,0 +1,51 @@ +# bash/zsh completion support for tsuite. + +# To use these routines: +# +# 1) Copy this file to somewhere (e.g. ~/.tsuite-completion.bash). +# 2) Add the following line to your .bashrc/.zshrc: +# source ~/.tsuite-completion.bash + +_tsuite_completion() { + local cur prev + + cur=${COMP_WORDS[COMP_CWORD]} + prev=${COMP_WORDS[COMP_CWORD - 1]} + + case ${COMP_CWORD} in + 1) + COMPREPLY=($(compgen -W "help new list compile setup run teardown clean cleanall" -- ${cur})) + ;; + 2) + case ${prev} in + new) + COMPREPLY=($(compgen -W "case" -- ${cur})) + ;; + run) + local arr i file + arr=($(grep --include \*.c --include \*.sh --include \*.py -Ril "@用例名称:" testcase/)) + COMPREPLY=() + for ((i = 0; i < ${#arr[@]}; ++i)); do + file=${arr[i]} + if [[ -d $MEMO_DIR/$file ]]; then + file=$file/ + fi + COMPREPLY[i]=$file + done + ;; + esac + ;; + 3) + case ${prev} in + case) + COMPREPLY=($(compgen -W "sh c py" -- ${cur})) + ;; + esac + ;; + *) + COMPREPLY=() + ;; + esac +} + +complete -F _tsuite_completion tsuite diff --git a/coreutils/tst_common/lib/tsuite_func.sh b/coreutils/tst_common/lib/tsuite_func.sh new file mode 100644 index 0000000..054cc21 --- /dev/null +++ b/coreutils/tst_common/lib/tsuite_func.sh @@ -0,0 +1,497 @@ +#!/bin/bash +# 测试套管理工具 + +export LANG=en_US.UTF-8 + +if [ -d "$TST_TS_TOPDIR/tst_common" ]; then + source "$TST_TS_TOPDIR/tst_common/lib/common.sh" || exit 1 +elif [ -d "$TST_TS_TOPDIR/lib" ]; then + # 只是tst_suite_common使用 + source "$TST_TS_TOPDIR/lib/common.sh" || exit 1 +else + echo "can't find the tsuite common file" + exit 1 +fi + +[ -z "$TST_TS_SYSDIR" ] && export TST_TS_SYSDIR="$TST_TS_TOPDIR/logs/.ts.sysdir" + +tsuite_usage() { + echo -e "" + echo -e "./tsuite options sub_command sub_options" + echo -e " help: 显示帮助信息" + echo -e " new case sh|c|py case_name [template]: 新增测试用例" + echo -e " sh|c|py: 【必选】三选一,sh表示Shell脚本用例,c表示C用例,py表示Python脚本用例" + echo -e " case_name: 【必选】要创建的用例名,同时用作文件名" + echo -e " template: 【可选】不使用默认用例模板时,可以指定一个文件用作新用例模板" + echo -e " list: 列出本测试套的测试用例" + echo -e " compile: 编译测试套" + echo -e " setup: 执行测试套setup" + echo -e " run options: 执行测试用例,options可选参数如下:" + echo -e " null: 不指定时默认执行所有用例" + echo -e " case_path: 执行指定用例" + echo -e " -l level: 执行指定级别的用例,例如:0,1,2" + echo -e " -f case_list: 执行指定列表文件的用例" + echo -e " teardown: 执行测试套teardown" + echo -e " clean: 执行make clean" + echo -e " cleanall: 执行make cleanall,在clean基础上删除所有临时文件等" + echo -e "" +} + +get_all_testcase() { + local _tst_case_dir=./testcase + if [ ! -d "$_tst_case_dir" ]; then + echo "no testcase dir" + return 1 + fi + touch "$TST_TS_SYSDIR/all_testcase.list" + grep -r "@用例名称:" $_tst_case_dir | awk -F : '{print $1}' | sort | uniq >"$TST_TS_SYSDIR/all_testcase.list" +} + +# 获取用例属性 +# $1 -- 属性名称 +# $2 -- 用例文件 +get_case_attr() { + grep "@${1}:" "$2" 2>/dev/null | head -n 1 | sed "s|.*@${1}:\s*||g" | sed "s|\s*$||g" +} + +tsuite_list() { + local _tst_index=1 + + get_all_testcase + local _tst_nr_all_case + _tst_nr_all_case=$(wc -l <"$TST_TS_SYSDIR/all_testcase.list") + + echo "" + for i in $(seq "$_tst_nr_all_case"); do + local _tst_case_file + local _tst_case_name + _tst_case_file="$(sed -n "${i}p" "$TST_TS_SYSDIR/all_testcase.list")" + _tst_case_name=$(get_case_attr "用例名称" "$_tst_case_file") + printf "%4d : %-30s : %s\n" $_tst_index "$_tst_case_name" "$_tst_case_file" + _tst_index=$((_tst_index + 1)) + done + echo "" + echo "total $_tst_nr_all_case testcase" + echo "" +} + +# 执行单个用例 +# $1 -- 用例文件,Shell和Python用例直接执行脚本文件,C可以是源码文件,也可以是二进制文件(两个文件要同名,后缀不同) +tsuite_run_one() { + local _tst_input_file="$1" + shift + + local _tst_ret=0 + local _tst_log_dir="$TST_TS_TOPDIR/logs/testcase" + + local _tst_exec_file + local _tst_case_file + # C用例 + if file "$_tst_input_file" | grep -w "ELF" >/dev/null; then + _tst_exec_file="$_tst_input_file" + _tst_case_file="${_tst_exec_file%.test}" + _tst_case_file="${_tst_case_file}.c" + elif file "$_tst_input_file" | grep -w "C source" >/dev/null; then + _tst_exec_file="${_tst_input_file%.c}" + _tst_exec_file="${_tst_exec_file}.test" + _tst_case_file="${_tst_input_file}" + else + _tst_exec_file="${_tst_input_file}" + _tst_case_file="${_tst_input_file}" + fi + local _tst_case_name + _tst_case_name=$(get_case_attr "用例名称" "$_tst_case_file") + + mkdir -p "$_tst_log_dir" + + echo "execute $_tst_case_name: $_tst_exec_file $*" + "$_tst_exec_file" "$@" || _tst_ret=1 + + return $_tst_ret +} + +# 执行指定列表文件的用例 +# $1 -- 要执行的用例列表文件,每行一个用例,井号'#'表示忽略对应用例 +tsuite_run_some() { + if [ ! -f "$1" ]; then + echo "testcase list file '$1' not exist" + fi + local _tst_run_list="$TST_TS_SYSDIR/run.list" + local _tst_run_result="$TST_TS_SYSDIR/run.result" + rm -rf "$_tst_run_list" "$_tst_run_result" + # 去掉注释行和空行,删掉行前的空格 + grep -v "^[[:blank:]]*#" "$1" | grep -v "^[[:blank:]]*$" | sed "s|^[[:blank:]]\+||g" >"$_tst_run_list" + + local _tst_ret=0 + local _tst_nr_pass=0 + local _tst_nr_skip=0 + local _tst_nr_fail=0 + local _tst_index=1 + local _tst_nr_all_case + _tst_nr_all_case=$(wc -l <"$_tst_run_list") + local _tst_case_time_start + local _tst_case_time_end + local _tst_case_cost + + printf "\n %-30s ==>" "ts_setup" + if tsuite_setup >"$TST_TS_TOPDIR/logs/ts_setup.log" 2>&1; then + echo " PASS" + else + echo " FAIL" + fi + mkdir -p "$TST_TS_TOPDIR/logs/testcase" + for i in $(seq "$_tst_nr_all_case"); do + local _tst_case_file + local _tst_case_name + local _tst_case_result + _tst_case_file="$(sed -n "${i}p" "$_tst_run_list")" + _tst_case_name=$(get_case_attr "用例名称" "$_tst_case_file") + local _tst_case_log="$TST_TS_TOPDIR/logs/testcase/${_tst_case_name}.log" + printf "%4d/%-4d : %-30s ==>" $_tst_index "$_tst_nr_all_case" "$_tst_case_name" + _tst_case_time_start=$(get_up_time_ms) + tsuite_run_one "$_tst_case_file" >"$_tst_case_log" 2>&1 + _tst_case_time_end=$(get_up_time_ms) + _tst_case_cost=$(diff_time_ms2sec "$_tst_case_time_start" "$_tst_case_time_end") + _tst_case_result=$(grep "RESULT : .* ==> \[ [A-Z]\+ \]" "$_tst_case_log" | + tail -n 1 | sed "s|.* ==> \[ \([A-Z]\+\) \].*|\1|g") + case "$_tst_case_result" in + "PASSED") + _tst_nr_pass=$((_tst_nr_pass + 1)) + echo "$_tst_index/$_tst_nr_all_case $_tst_case_name PASS cost:$_tst_case_cost" >>"$_tst_run_result" + echo " PASS (cost $_tst_case_cost)" + ;; + "SKIP") + _tst_nr_skip=$((_tst_nr_skip + 1)) + echo "$_tst_index/$_tst_nr_all_case $_tst_case_name SKIP cost:$_tst_case_cost" >>"$_tst_run_result" + echo " SKIP (cost $_tst_case_cost)" + ;; + *) + _tst_nr_fail=$((_tst_nr_fail + 1)) + echo "$_tst_index/$_tst_nr_all_case $_tst_case_name FAIL cost:$_tst_case_cost" >>"$_tst_run_result" + echo " FAIL (cost $_tst_case_cost)" + _tst_ret=1 + ;; + esac + _tst_index=$((_tst_index + 1)) + done + printf " %-30s ==>" "ts_teardown" + if tsuite_teardown >"$TST_TS_TOPDIR/logs/ts_teardown.log" 2>&1; then + echo " PASS" + else + echo " FAIL" + fi + + echo "" + echo "total: $_tst_nr_all_case" + echo " pass: $_tst_nr_pass" + echo " skip: $_tst_nr_skip" + echo " fail: $_tst_nr_fail" + echo "" + + return $_tst_ret +} + +tsuite_run_all() { + get_all_testcase + tsuite_run_some "$TST_TS_SYSDIR/all_testcase.list" +} + +tsuite_compile() { + local _tst_ret=0 + + echo "try cleanall before compile" + make -C "$TST_TS_TOPDIR" cleanall || _tst_ret=1 + echo "compile the testsuite" + if which bear; then + bear -- make -C "$TST_TS_TOPDIR" all || _tst_ret=1 + else + make -C "$TST_TS_TOPDIR" all || _tst_ret=1 + fi + + return $_tst_ret +} + +tsuite_setup() { + local _tst_ret=0 + + echo "tsuite try execute ts_setup" + if [ -f "$TST_TS_TOPDIR/tst_common/lib/tst_ts_setup" ]; then + "$TST_TS_TOPDIR/tst_common/lib/tst_ts_setup" || _tst_ret=1 + elif [ -f "$TST_TS_TOPDIR/lib/tst_ts_setup" ]; then + # 只是tst_suite_common使用 + "$TST_TS_TOPDIR/lib/tst_ts_setup" || _tst_ret=1 + else + echo "the tst_ts_setup not found" + _tst_ret=1 + fi + + return $_tst_ret +} + +tsuite_run() { + local _tst_ret=0 + + # 生成结果记录文件 + _get_tst_result_file + + if [ -z "$1" ]; then + tsuite_run_all || _tst_ret=1 + elif [ "$1" == "-f" ]; then + echo "Try run testcases in list file '$2'" + tsuite_run_some "$2" || _tst_ret=1 + elif [ "$1" == "-l" ]; then + echo "Try run testcases with level '$2'" + rm -rf "$TST_TS_SYSDIR/level.list" + for l in $(echo "$2" | tr ',' ' '); do + grep -r "@用例级别:[[:blank:]]*$l" $_tst_case_dir | awk -F : '{print $1}' | + sort | uniq >>"$TST_TS_SYSDIR/level.list" + done + tsuite_run_some "$TST_TS_SYSDIR/level.list" || _tst_ret=1 + else + tsuite_run_one "$@" || _tst_ret=1 + fi + + sed -i "/^suite-end-time:/c suite-end-time: $(get_timestamp_ms)" "$TST_RESULT_FILE" + + return $_tst_ret +} + +tsuite_teardown() { + local _tst_ret=0 + + mkdir -p "$TST_TS_TOPDIR/logs" + echo "tsuite try execute ts_teardown" + if [ -f "$TST_TS_TOPDIR/tst_common/lib/tst_ts_teardown" ]; then + "$TST_TS_TOPDIR/tst_common/lib/tst_ts_teardown" || _tst_ret=1 + elif [ -f "$TST_TS_TOPDIR/lib/tst_ts_teardown" ]; then + # 只是tst_suite_common使用 + "$TST_TS_TOPDIR/lib/tst_ts_teardown" || _tst_ret=1 + else + echo "the tst_ts_setup not found" + _tst_ret=1 + fi + + return $_tst_ret +} + +tsuite_clean() { + local _tst_ret=0 + + make -C "$TST_TS_TOPDIR" clean || _tst_ret=1 + + return $_tst_ret +} + +tsuite_cleanall() { + local _tst_ret=0 + + make -C "$TST_TS_TOPDIR" cleanall || _tst_ret=1 + rm -rfv "$TST_TS_TOPDIR/logs" "$TST_TS_TOPDIR/compile_commands.json" + + return $_tst_ret +} + +# 新建用例模板 +# $1 -- 用例代码类型:sh/c/py +# $2 -- 用例名 +# $3 -- 可选参数,用例模板 +tsuite_new_case() { + local _tst_tc_type="$1" + local _tst_tc_name="$2" + local _tst_input_template="$3" + local _tst_tc_id + _tst_tc_id=$(date '+%Y%m%d-%H%M%S-%N') + local _tst_tc_file="testcase/${2}.${1}" + local _tst_template_path="$TST_TS_TOPDIR/tst_common/testcase" + # 为了适配tst_suite_common + [ -d "$_tst_template_path" ] || _tst_template_path="$TST_TS_TOPDIR/testcase" + if [ ! -d "$_tst_template_path" ]; then + echo "the template path is $_tst_template_path, not dir" + return 1 + fi + + if [ -z "$_tst_tc_name" ]; then + echo "the testcase name not set" + return 1 + fi + + if [ -z "$_tst_input_template" ]; then + case "$_tst_tc_type" in + sh) + cp -v "$_tst_template_path/test_shell_testcase.sh" "$TST_TS_TOPDIR/$_tst_tc_file" + sed -i "s|}/lib/common|}/tst_common/lib/common|g" "$TST_TS_TOPDIR/$_tst_tc_file" + ;; + c) + cp -v "$_tst_template_path/test_c_testcase.c" "$TST_TS_TOPDIR/$_tst_tc_file" + ;; + py) + cp -v "$_tst_template_path/test_python_testcase.py" "$TST_TS_TOPDIR/$_tst_tc_file" + sed -i "/from lib.common import TestCase/c from tst_lib.ts_common import MyTestCase" \ + "$TST_TS_TOPDIR/$_tst_tc_file" + sed -i "/class PythonTestCase(TestCase):/c class PythonTestCase(MyTestCase):" \ + "$TST_TS_TOPDIR/$_tst_tc_file" + ;; + *) + echo "unsupported testcase type" + return 1 + ;; + esac + else + if [ ! -f "$_tst_input_template" ]; then + echo "the template file $_tst_input_template not exist" + return 1 + fi + if ! echo "$_tst_input_template" | grep "\.$_tst_tc_type$" >/dev/null; then + echo "the template file $_tst_input_template not match the testcase type $_tst_tc_type" + return 1 + fi + cp -v "$_tst_input_template" "$TST_TS_TOPDIR/$_tst_tc_file" + fi + + sed -i "s|@用例ID:.*|@用例ID: $_tst_tc_id|g" "$TST_TS_TOPDIR/$_tst_tc_file" + sed -i "s|@用例名称:.*|@用例名称: $_tst_tc_name|g" "$TST_TS_TOPDIR/$_tst_tc_file" + echo "" + echo "the new testcase info:" + echo " name: $_tst_tc_name" + echo " type: $_tst_tc_type" + echo " id: $_tst_tc_id" + echo " file: $_tst_tc_file" + echo "" + return 0 +} + +# 新建测试套 +# $1 -- 测试套git路径 +tsuite_new_suite() { + local _tst_git_url="$1" + local _tst_suite_name + _tst_suite_name=$(basename "$_tst_git_url" | sed "s|\.git$||g") + + if ! echo "$_tst_git_url" | grep "\.git$" >/dev/null; then + echo "the git url unusable" + return 1 + fi + if [ -z "$_tst_suite_name" ]; then + echo "get suite name fail" + return 1 + fi + if [ -d "./$_tst_suite_name" ]; then + echo "the ./$_tst_suite_name existed" + return 1 + fi + + echo "git clone $_tst_git_url ./$_tst_suite_name" + if ! git clone "$_tst_git_url" "./$_tst_suite_name"; then + echo "clone $_tst_suite_name fail" + return 1 + fi + if [ -d "./$_tst_suite_name/tst_common" ]; then + echo "the suite $_tst_suite_name initialization has been completed yet" + return 1 + fi + + echo "get suite_example: git clone https://gitee.com/opencloudos-stream/test-suite-example.git" + rm -rf "$TST_TS_SYSDIR/suite_example" + if ! git clone https://gitee.com/opencloudos-stream/test-suite-example.git "$TST_TS_SYSDIR/suite_example"; then + echo "clone suite_example fail" + rm -rf "./$_tst_suite_name" + return 1 + fi + cp -rv "$TST_TS_SYSDIR/suite_example"/* "./$_tst_suite_name" + cp -rv "$TST_TS_SYSDIR/suite_example/.gitignore" "./$_tst_suite_name" + rm -rf "$TST_TS_SYSDIR/suite_example" + + cd "./$_tst_suite_name" || return 1 + rm -rf ./tst_common + echo "add submodule to common for $_tst_suite_name" + if ! git submodule add https://gitee.com/opencloudos-stream/test-suite-base.git ./common; then + echo "add submodule fail" + cd .. + rm -rf "./$_tst_suite_name" + return 1 + fi + + echo "remove the sample testcase" + rm -fv ./testcase/test_* + + return 0 +} + +tsuite_new() { + local _tst_ret=0 + + case $1 in + case) + shift + tsuite_new_case "$@" || _tst_ret=1 + ;; + suite) + shift + tsuite_new_suite "$@" || _tst_ret=1 + ;; + *) + echo "unknown new type: $*" + _tst_ret=1 + ;; + esac + + return $_tst_ret +} + +tsuite_main() { + local _tst_ret=0 + local _tst_cmd="$0 $*" + local _tst_suite_time_start + _tst_suite_time_start=$(get_up_time_ms) + local _tst_suite_time_end + + echo "TST_TS_TOPDIR=$TST_TS_TOPDIR" + cd "$TST_TS_TOPDIR" || return 1 + mkdir -p "$TST_TS_SYSDIR" || return 1 + + case "$1" in + help) + tsuite_usage + return 0 + ;; + new) + shift + tsuite_new "$@" || _tst_ret=1 + ;; + list) + tsuite_list || _tst_ret=1 + ;; + compile) + tsuite_compile || _tst_ret=1 + ;; + setup) + tsuite_setup || _tst_ret=1 + ;; + run) + shift + tsuite_run "$@" || _tst_ret=1 + ;; + teardown) + tsuite_teardown || _tst_ret=1 + ;; + clean) + tsuite_clean || _tst_ret=1 + ;; + cleanall) + tsuite_cleanall || _tst_ret=1 + ;; + *) + echo "$0 $*" + tsuite_usage + return 1 + ;; + esac + + _tst_suite_time_end=$(get_up_time_ms) + if [ $_tst_ret -eq 0 ]; then + echo "execute $_tst_cmd success, cost $(diff_time_ms2sec "$_tst_suite_time_start" "$_tst_suite_time_end")" + else + echo "execute $_tst_cmd fail, cost $(diff_time_ms2sec "$_tst_suite_time_start" "$_tst_suite_time_end")" + fi + return $_tst_ret +} diff --git a/coreutils/tst_common/testcase/Makefile b/coreutils/tst_common/testcase/Makefile new file mode 100644 index 0000000..1cb97df --- /dev/null +++ b/coreutils/tst_common/testcase/Makefile @@ -0,0 +1,20 @@ +export TST_COMMON_TOPDIR ?= $(shell pwd)/.. +include $(TST_COMMON_TOPDIR)/Makefile.common +ALL_SRC := $(wildcard *.c) +ALL_OBJ := $(patsubst %.c,%.o,$(ALL_SRC)) +ALL_BIN := $(patsubst %.o,%.test,$(ALL_OBJ)) +CFLAGS += +LDFLAGS += + +all: $(ALL_BIN) + +$(ALL_BIN):%.test:%.o + $(CC) $^ -o $@ $(LDFLAGS) + +$(ALL_OBJ):%.o:%.c + $(CC) $(CFLAGS) -c $^ -o $@ + +clean: + rm -rfv $(ALL_OBJ) $(ALL_BIN) + +cleanall: clean diff --git a/coreutils/tst_common/testcase/test_c_testcase.c b/coreutils/tst_common/testcase/test_c_testcase.c new file mode 100644 index 0000000..6624689 --- /dev/null +++ b/coreutils/tst_common/testcase/test_c_testcase.c @@ -0,0 +1,35 @@ +/* **************************************************************************** + * @用例ID: 20220418-230037-838974137 + * @用例名称: test_c_testcase + * @用例级别: 3 + * @用例标签: + * @用例类型: 功能 + * ***************************************************************************/ + +#include "main.h" + +int tc_setup(int argc, char **argv) { + msg("this is tc_setup"); + // @预置条件: + // @预置条件: + return 0; +} + +int do_test(int argc, char **argv) { + msg("this is do_test"); + + // @测试步骤:1: + + // @测试步骤:2: + + // @测试步骤:3: + // @预期结果:3: + assert_true(1 + 1 == 2); + + return 0; +} + +int tc_teardown(int argc, char **argv) { + msg("this is tc_teardown"); + return 0; +} diff --git a/coreutils/tst_common/testcase/test_perf_tools.py b/coreutils/tst_common/testcase/test_perf_tools.py new file mode 100755 index 0000000..b09c3b0 --- /dev/null +++ b/coreutils/tst_common/testcase/test_perf_tools.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +# coding: utf-8 +import os.path +import subprocess +import sys + +sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) +from lib.common import TestCase +from lib.benchmark import PerfSysBench + + +def prepare(): + subprocess.run(["which", "sysbench"]) + + +def cleanup(): + pass + + +class PythonTestCase(TestCase): + """ + @用例ID: 20220721-001631-159391306 + @用例名称: test_perf_tools + @用例级别: 3 + @用例标签: + @用例类型: 功能 + """ + + def tc_setup(self, *args): + # @预置条件: + self.msg("this is tc_setup") + + def do_test(self, *args): + # @测试步骤:1: + perf = PerfSysBench(name='cpu', sysbench='sysbench', testname='cpu') + perf.prepare = prepare + perf.cleanup = cleanup + perf.run() + perf.report() + # @测试步骤:2: + + # @测试步骤:3: + # @预期结果:3: + self.assert_true(1 == 1) + + def tc_teardown(self, *args): + self.msg("this is tc_teardown") + + +if __name__ == '__main__': + PythonTestCase().tst_main(sys.argv) diff --git a/coreutils/tst_common/testcase/test_python_testcase.py b/coreutils/tst_common/testcase/test_python_testcase.py new file mode 100755 index 0000000..ea86f3d --- /dev/null +++ b/coreutils/tst_common/testcase/test_python_testcase.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 +# coding: utf-8 + +import os.path +import sys + +sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) +from lib.common import TestCase + + +class PythonTestCase(TestCase): + """ + @用例ID: 20220420-234008-893237761 + @用例名称: test_python_testcase + @用例级别: 3 + @用例标签: + @用例类型: 功能 + """ + + def tc_setup(self, *args): + # @预置条件: + self.msg("this is tc_setup") + + def do_test(self, *args): + # @测试步骤:1: + + # @测试步骤:2: + + # @测试步骤:3: + # @预期结果:3: + self.assert_true(1 == 1) + + def tc_teardown(self, *args): + self.msg("this is tc_teardown") + + +if __name__ == '__main__': + PythonTestCase().tst_main(sys.argv) diff --git a/coreutils/tst_common/testcase/test_shell_testcase.sh b/coreutils/tst_common/testcase/test_shell_testcase.sh new file mode 100755 index 0000000..5f5f5ba --- /dev/null +++ b/coreutils/tst_common/testcase/test_shell_testcase.sh @@ -0,0 +1,47 @@ +#!/bin/bash +############################################################################### +# @用例ID: 20220410-152859-724647329 +# @用例名称: test_shell_testcase +# @用例级别: 3 +# @用例标签: +# @用例类型: 功能 +############################################################################### +[ -z "$TST_TS_TOPDIR" ] && { + TST_TS_TOPDIR="$(realpath "$(dirname "$0")/..")" + export TST_TS_TOPDIR +} +source "${TST_TS_TOPDIR}/lib/common.sh" || exit 1 +############################################################################### + +g_tmpdir="$(mktemp -d)" + +tc_setup() { + msg "this is tc_setup" + # @预置条件: + # @预置条件: + return 0 +} + +do_test() { + msg "this is do_test" + + # @测试步骤:1: + + # @测试步骤:2: + + # @测试步骤:3: + # @预期结果:3: + assert_true [ 1 -eq 1 ] + + return 0 +} + +tc_teardown() { + msg "this is tc_teardown" + rm -rfv "$g_tmpdir" || return 1 + return 0 +} + +############################################################################### +tst_main "$@" +############################################################################### diff --git a/coreutils/tst_common/tsuite b/coreutils/tst_common/tsuite new file mode 100755 index 0000000..ee4170c --- /dev/null +++ b/coreutils/tst_common/tsuite @@ -0,0 +1,17 @@ +#!/bin/bash +# 测试套管理工具 + +TST_TS_TOPDIR=$(realpath "$(dirname "$0")") +export TST_TS_TOPDIR +TST_TS_ORI_CWD="$(pwd)" +export TST_TS_ORI_CWD +if [ -f "$TST_TS_TOPDIR/tst_common/lib/tsuite_func.sh" ]; then + source "$TST_TS_TOPDIR/tst_common/lib/tsuite_func.sh" +elif [ -f "$TST_TS_TOPDIR/lib/tsuite_func.sh" ]; then + source "$TST_TS_TOPDIR/lib/tsuite_func.sh" +else + echo "can't find the tsuite_func.sh file" + exit 1 +fi + +tsuite_main "$@" -- Gitee From 45693423d08ecb4908db255845df5f368886ed25 Mon Sep 17 00:00:00 2001 From: hougit1 Date: Thu, 25 May 2023 13:37:33 +0800 Subject: [PATCH 09/20] =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hougit1 --- coreutils/testcase/mysql-test.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/coreutils/testcase/mysql-test.sh b/coreutils/testcase/mysql-test.sh index b2b38ff..36ca572 100755 --- a/coreutils/testcase/mysql-test.sh +++ b/coreutils/testcase/mysql-test.sh @@ -25,7 +25,7 @@ tc_setup() { return 1 else mysql_version=$(mysql -V |awk '{print $3}' | awk -F, '{print $1}') - echo “MySQL version: $mysql_version” + echo "MySQL version: $mysql_version" fi # 启动MySQL @@ -82,7 +82,7 @@ tc_teardown() { #检查MySQL是否关闭成功 status=$(sudo service mysql status) - if echo "status" | grep -q "MySQL running";then + if echo "$status" | grep -q "MySQL running";then echo "Failed to stop the mysql." else echo "The mysql has been successfully stopped." -- Gitee From bbfa298e14bc85202cb0c8276706d22606f12164 Mon Sep 17 00:00:00 2001 From: hou Date: Thu, 25 May 2023 05:38:25 +0000 Subject: [PATCH 10/20] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=96=87=E4=BB=B6=20co?= =?UTF-8?q?reutils/tst=5Fcommon/.gitignore?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- coreutils/tst_common/.gitignore | 33 --------------------------------- 1 file changed, 33 deletions(-) delete mode 100644 coreutils/tst_common/.gitignore diff --git a/coreutils/tst_common/.gitignore b/coreutils/tst_common/.gitignore deleted file mode 100644 index 8e67438..0000000 --- a/coreutils/tst_common/.gitignore +++ /dev/null @@ -1,33 +0,0 @@ -# Build and Release Folders -bin-debug/ -bin-release/ -[Oo]bj/ -[Bb]in/ - -# Other files and folders -.settings/ - -# Executables -*.swf -*.air -*.ipa -*.apk - -# Project files, i.e. `.project`, `.actionScriptProperties` and `.flexProperties` -# should NOT be excluded as they contain compiler settings and other important -# information for Eclipse / Flash Builder. -.idea/ -logs/ -__pycache__/ -*.o -*.a -*.d -*.cmd -*.test -*.log -*.ko -*.mod -*.mod.c -Module.symvers -modules.order -compile_commands.json -- Gitee From 82a9091ddb018116e317b69d1ad29071a2588559 Mon Sep 17 00:00:00 2001 From: hou Date: Thu, 25 May 2023 05:39:31 +0000 Subject: [PATCH 11/20] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=96=87=E4=BB=B6=20co?= =?UTF-8?q?reutils/tst=5Fcommon?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- coreutils/tst_common/LICENSE | 824 ------------------ coreutils/tst_common/Makefile | 27 - coreutils/tst_common/Makefile.common | 2 - coreutils/tst_common/README.md | 21 - coreutils/tst_common/cmd/Makefile | 20 - coreutils/tst_common/cmd/tsuite.c | 6 - coreutils/tst_common/docs/API-C.md | 24 - coreutils/tst_common/docs/API-Python.md | 62 -- coreutils/tst_common/docs/API-Shell.md | 68 -- coreutils/tst_common/kmod/Makefile | 28 - coreutils/tst_common/kmod/kmod_common.c | 14 - coreutils/tst_common/lib/Makefile | 20 - coreutils/tst_common/lib/benchmark.c | 389 --------- coreutils/tst_common/lib/benchmark.h | 81 -- coreutils/tst_common/lib/benchmark.py | 304 ------- coreutils/tst_common/lib/common.c | 597 ------------- coreutils/tst_common/lib/common.h | 139 --- coreutils/tst_common/lib/common.py | 755 ---------------- coreutils/tst_common/lib/common.sh | 734 ---------------- coreutils/tst_common/lib/common_func.sh | 88 -- coreutils/tst_common/lib/main.h | 12 - coreutils/tst_common/lib/sched.py | 129 --- coreutils/tst_common/lib/tst_ts_setup | 55 -- coreutils/tst_common/lib/tst_ts_teardown | 47 - .../tst_common/lib/tsuite-completion.bash | 51 -- coreutils/tst_common/lib/tsuite_func.sh | 497 ----------- coreutils/tst_common/testcase/Makefile | 20 - .../tst_common/testcase/test_c_testcase.c | 35 - .../tst_common/testcase/test_perf_tools.py | 51 -- .../testcase/test_python_testcase.py | 38 - .../testcase/test_shell_testcase.sh | 47 - coreutils/tst_common/tsuite | 17 - 32 files changed, 5202 deletions(-) delete mode 100644 coreutils/tst_common/LICENSE delete mode 100644 coreutils/tst_common/Makefile delete mode 100644 coreutils/tst_common/Makefile.common delete mode 100644 coreutils/tst_common/README.md delete mode 100644 coreutils/tst_common/cmd/Makefile delete mode 100644 coreutils/tst_common/cmd/tsuite.c delete mode 100644 coreutils/tst_common/docs/API-C.md delete mode 100644 coreutils/tst_common/docs/API-Python.md delete mode 100644 coreutils/tst_common/docs/API-Shell.md delete mode 100644 coreutils/tst_common/kmod/Makefile delete mode 100644 coreutils/tst_common/kmod/kmod_common.c delete mode 100644 coreutils/tst_common/lib/Makefile delete mode 100644 coreutils/tst_common/lib/benchmark.c delete mode 100644 coreutils/tst_common/lib/benchmark.h delete mode 100644 coreutils/tst_common/lib/benchmark.py delete mode 100644 coreutils/tst_common/lib/common.c delete mode 100644 coreutils/tst_common/lib/common.h delete mode 100644 coreutils/tst_common/lib/common.py delete mode 100644 coreutils/tst_common/lib/common.sh delete mode 100644 coreutils/tst_common/lib/common_func.sh delete mode 100644 coreutils/tst_common/lib/main.h delete mode 100644 coreutils/tst_common/lib/sched.py delete mode 100755 coreutils/tst_common/lib/tst_ts_setup delete mode 100755 coreutils/tst_common/lib/tst_ts_teardown delete mode 100644 coreutils/tst_common/lib/tsuite-completion.bash delete mode 100644 coreutils/tst_common/lib/tsuite_func.sh delete mode 100644 coreutils/tst_common/testcase/Makefile delete mode 100644 coreutils/tst_common/testcase/test_c_testcase.c delete mode 100755 coreutils/tst_common/testcase/test_perf_tools.py delete mode 100755 coreutils/tst_common/testcase/test_python_testcase.py delete mode 100755 coreutils/tst_common/testcase/test_shell_testcase.sh delete mode 100755 coreutils/tst_common/tsuite diff --git a/coreutils/tst_common/LICENSE b/coreutils/tst_common/LICENSE deleted file mode 100644 index d06cc9f..0000000 --- a/coreutils/tst_common/LICENSE +++ /dev/null @@ -1,824 +0,0 @@ -Tencent is pleased to support the open source community by making OpenCloudOS Kernel Stream available. - -Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. The below software in this distribution may have been modified by THL A29 Limited ("Tencent Modifications"). All Tencent Modifications are Copyright (C) THL A29 Limited. - -OpenCloudOS Kernel Stream is licensed under the the Mulan Permissive Software License 2.0 except for the third-party components listed below. - - -Terms of the Mulan Permissive Software License 2.0: --------------------------------------------------------------------- - 木兰宽松许可证, 第2版 - -2020年1月 http://license.coscl.org.cn/MulanPSL2 - -您对“软件”的复制、使用、修改及分发受木兰宽松许可证,第2版(“本许可证”)的如下条款的约束: - -0. 定义 - -“软件”是指由“贡献”构成的许可在“本许可证”下的程序和相关文档的集合。 - -“贡献”是指由任一“贡献者”许可在“本许可证”下的受版权法保护的作品。 - -“贡献者”是指将受版权法保护的作品许可在“本许可证”下的自然人或“法人实体”。 - -“法人实体”是指提交贡献的机构及其“关联实体”。 - -“关联实体”是指,对“本许可证”下的行为方而言,控制、受控制或与其共同受控制的机构,此处的控制是指有受控方或共同受控方至少50%直接或间接的投票权、资金或其他有价证券。 - -1. 授予版权许可 - -每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的版权许可,您可以复制、使用、修改、分发其“贡献”,不论修改与否。 - -2. 授予专利许可 - -每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的(根据本条规定撤销除外)专利许可,供您制造、委托制造、使用、许诺销售、销售、进口其“贡献”或以其他方式转移其“贡献”。前述专利许可仅限于“贡献者”现在或将来拥有或控制的其“贡献”本身或其“贡献”与许可“贡献”时的“软件”结合而将必然会侵犯的专利权利要求,不包括对“贡献”的修改或包含“贡献”的其他结合。如果您或您的“关联实体”直接或间接地,就“软件”或其中的“贡献”对任何人发起专利侵权诉讼(包括反诉或交叉诉讼)或其他专利维权行动,指控其侵犯专利权,则“本许可证”授予您对“软件”的专利许可自您提起诉讼或发起维权行动之日终止。 - -3. 无商标许可 - -“本许可证”不提供对“贡献者”的商品名称、商标、服务标志或产品名称的商标许可,但您为满足第4条规定的声明义务而必须使用除外。 - -4. 分发限制 - -您可以在任何媒介中将“软件”以源程序形式或可执行形式重新分发,不论修改与否,但您必须向接收者提供“本许可证”的副本,并保留“软件”中的版权、商标、专利及免责声明。 - -5. 免责声明与责任限制 - -“软件”及其中的“贡献”在提供时不带任何明示或默示的担保。在任何情况下,“贡献者”或版权所有者不对任何人因使用“软件”或其中的“贡献”而引发的任何直接或间接损失承担责任,不论因何种原因导致或者基于何种法律理论,即使其曾被建议有此种损失的可能性。 - -6. 语言 - -“本许可证”以中英文双语表述,中英文版本具有同等法律效力。如果中英文版本存在任何冲突不一致,以中文版为准。 - -条款结束 - -如何将木兰宽松许可证,第2版,应用到您的软件 - -如果您希望将木兰宽松许可证,第2版,应用到您的新软件,为了方便接收者查阅,建议您完成如下三步: - -1,请您补充如下声明中的空白,包括软件名、软件的首次发表年份以及您作为版权人的名字; - -2,请您在软件包的一级目录下创建以“LICENSE”为名的文件,将整个许可证文本放入该文件中; - -3,请将如下声明文本放入每个源文件的头部注释中。 - -Copyright (c) [Year] [name of copyright holder] [Software Name] is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. - -January 2020 http://license.coscl.org.cn/MulanPSL2 - -Your reproduction, use, modification and distribution of the Software shall be subject to Mulan PSL v2 (this License) with the following terms and conditions: - -0. Definition - -Software means the program and related documents which are licensed under this License and comprise all Contribution(s). - -Contribution means the copyrightable work licensed by a particular Contributor under this License. - -Contributor means the Individual or Legal Entity who licenses its copyrightable work under this License. - -Legal Entity means the entity making a Contribution and all its Affiliates. - -Affiliates means entities that control, are controlled by, or are under common control with the acting entity under this License, ‘control’ means direct or indirect ownership of at least fifty percent (50%) of the voting power, capital or other securities of controlled or commonly controlled entity. - -1. Grant of Copyright License - -Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable copyright license to reproduce, use, modify, or distribute its Contribution, with modification or not. - -2. Grant of Patent License - -Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable (except for revocation under this Section) patent license to make, have made, use, offer for sale, sell, import or otherwise transfer its Contribution, where such patent license is only limited to the patent claims owned or controlled by such Contributor now or in future which will be necessarily infringed by its Contribution alone, or by combination of the Contribution with the Software to which the Contribution was contributed. The patent license shall not apply to any modification of the Contribution, and any other combination which includes the Contribution. If you or your Affiliates directly or indirectly institute patent litigation (including a cross claim or counterclaim in a litigation) or other patent enforcement activities against any individual or entity by alleging that the Software or any Contribution in it infringes patents, then any patent license granted to you under this License for the Software shall terminate as of the date such litigation or activity is filed or taken. - -3. No Trademark License - -No trademark license is granted to use the trade names, trademarks, service marks, or product names of Contributor, except as required to fulfill notice requirements in Section 4. - -4. Distribution Restriction - -You may distribute the Software in any medium with or without modification, whether in source or executable forms, provided that you provide recipients with a copy of this License and retain copyright, patent, trademark and disclaimer statements in the Software. - -5. Disclaimer of Warranty and Limitation of Liability - -THE SOFTWARE AND CONTRIBUTION IN IT ARE PROVIDED WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED. IN NO EVENT SHALL ANY CONTRIBUTOR OR COPYRIGHT HOLDER BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO ANY DIRECT, OR INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING FROM YOUR USE OR INABILITY TO USE THE SOFTWARE OR THE CONTRIBUTION IN IT, NO MATTER HOW IT’S CAUSED OR BASED ON WHICH LEGAL THEORY, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -6. Language - -THIS LICENSE IS WRITTEN IN BOTH CHINESE AND ENGLISH, AND THE CHINESE VERSION AND ENGLISH VERSION SHALL HAVE THE SAME LEGAL EFFECT. IN THE CASE OF DIVERGENCE BETWEEN THE CHINESE AND ENGLISH VERSIONS, THE CHINESE VERSION SHALL PREVAIL. - -END OF THE TERMS AND CONDITIONS - - - -Other dependencies and licenses: - - -Open Source Software Licensed under the GPL v2.0 with Linux-syscall-note, and Other Licenses of the Third-Party Components therein: -The below software in this distribution may have been modified by THL A29 Limited ("Tencent Modifications"). All Tencent Modifications are Copyright (C) 2021 THL A29 Limited. --------------------------------------------------------------------- -1. kernel -Copyright © kernel original author and authors - - -The Linux Kernel is provided under: - - SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note - -Being under the terms of the GNU General Public License version 2 only, -according with: - - LICENSES/preferred/GPL-2.0 - -With an explicit syscall exception, as stated at: - - LICENSES/exceptions/Linux-syscall-note - -In addition, other licenses may also apply. Please see: - - Documentation/process/license-rules.rst - -for more details. - -All contributions to the Linux Kernel are subject to this COPYING file. - -Valid-License-Identifier: GPL-2.0 -Valid-License-Identifier: GPL-2.0-only -Valid-License-Identifier: GPL-2.0+ -Valid-License-Identifier: GPL-2.0-or-later -SPDX-URL: https://spdx.org/licenses/GPL-2.0.html -Usage-Guide: - To use this license in source code, put one of the following SPDX - tag/value pairs into a comment according to the placement - guidelines in the licensing rules documentation. - For 'GNU General Public License (GPL) version 2 only' use: - SPDX-License-Identifier: GPL-2.0 - or - SPDX-License-Identifier: GPL-2.0-only - For 'GNU General Public License (GPL) version 2 or any later version' use: - SPDX-License-Identifier: GPL-2.0+ - or - SPDX-License-Identifier: GPL-2.0-or-later -License-Text: - - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Library General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Library General -Public License instead of this License. - -SPDX-Exception-Identifier: Linux-syscall-note -SPDX-URL: https://spdx.org/licenses/Linux-syscall-note.html -SPDX-Licenses: GPL-2.0, GPL-2.0+, GPL-1.0+, LGPL-2.0, LGPL-2.0+, LGPL-2.1, LGPL-2.1+, GPL-2.0-only, GPL-2.0-or-later -Usage-Guide: - This exception is used together with one of the above SPDX-Licenses - to mark user space API (uapi) header files so they can be included - into non GPL compliant user space application code. - To use this exception add it with the keyword WITH to one of the - identifiers in the SPDX-Licenses tag: - SPDX-License-Identifier: WITH Linux-syscall-note -License-Text: - - NOTE! This copyright does *not* cover user programs that use kernel - services by normal system calls - this is merely considered normal use - of the kernel, and does *not* fall under the heading of "derived work". - Also note that the GPL below is copyrighted by the Free Software - Foundation, but the instance of code that it refers to (the Linux - kernel) is copyrighted by me and others who actually wrote it. - - Also note that the only valid version of the GPL as far as the kernel - is concerned is _this_ particular version of the license (ie v2, not - v2.2 or v3.x or whatever), unless explicitly otherwise stated. - - Linus Torvalds - -For the licenses of other third parties, please refer to the following URL: -https://github.com/torvalds/linux/tree/v5.18-rc5/LICENSES - -Linux kernel licensing rules -The Linux Kernel is provided under the terms of the GNU General Public License version 2 only (GPL-2.0), as provided in LICENSES/preferred/GPL-2.0, with an explicit syscall exception described in LICENSES/exceptions/Linux-syscall-note, as described in the COPYING file. - -This documentation file provides a description of how each source file should be annotated to make its license clear and unambiguous. It doesn't replace the Kernel's license. - -The license described in the COPYING file applies to the kernel source as a whole, though individual source files can have a different license which is required to be compatible with the GPL-2.0: - -GPL-1.0+ : GNU General Public License v1.0 or later -GPL-2.0+ : GNU General Public License v2.0 or later -LGPL-2.0 : GNU Library General Public License v2 only -LGPL-2.0+ : GNU Library General Public License v2 or later -LGPL-2.1 : GNU Lesser General Public License v2.1 only -LGPL-2.1+ : GNU Lesser General Public License v2.1 or later -Aside from that, individual files can be provided under a dual license, e.g. one of the compatible GPL variants and alternatively under a permissive license like BSD, MIT etc. - -The User-space API (UAPI) header files, which describe the interface of user-space programs to the kernel are a special case. According to the note in the kernel COPYING file, the syscall interface is a clear boundary, which does not extend the GPL requirements to any software which uses it to communicate with the kernel. Because the UAPI headers must be includable into any source files which create an executable running on the Linux kernel, the exception must be documented by a special license expression. - -The common way of expressing the license of a source file is to add the matching boilerplate text into the top comment of the file. Due to formatting, typos etc. these "boilerplates" are hard to validate for tools which are used in the context of license compliance. - -An alternative to boilerplate text is the use of Software Package Data Exchange (SPDX) license identifiers in each source file. SPDX license identifiers are machine parsable and precise shorthands for the license under which the content of the file is contributed. SPDX license identifiers are managed by the SPDX Workgroup at the Linux Foundation and have been agreed on by partners throughout the industry, tool vendors, and legal teams. For further information see https://spdx.org/ - -The Linux kernel requires the precise SPDX identifier in all source files. The valid identifiers used in the kernel are explained in the section License identifiers and have been retrieved from the official SPDX license list at https://spdx.org/licenses/ along with the license texts. - -License identifier syntax -Placement: - -The SPDX license identifier in kernel files shall be added at the first possible line in a file which can contain a comment. For the majority of files this is the first line, except for scripts which require the '#!PATH_TO_INTERPRETER' in the first line. For those scripts the SPDX identifier goes into the second line. - - -Style: - -The SPDX license identifier is added in form of a comment. The comment style depends on the file type: - -C source: // SPDX-License-Identifier: -C header: /* SPDX-License-Identifier: */ -ASM: /* SPDX-License-Identifier: */ -scripts: # SPDX-License-Identifier: -.rst: .. SPDX-License-Identifier: -.dts{i}: // SPDX-License-Identifier: -If a specific tool cannot handle the standard comment style, then the appropriate comment mechanism which the tool accepts shall be used. This is the reason for having the "/* */" style comment in C header files. There was build breakage observed with generated .lds files where 'ld' failed to parse the C++ comment. This has been fixed by now, but there are still older assembler tools which cannot handle C++ style comments. - - -Syntax: - -A is either an SPDX short form license identifier found on the SPDX License List, or the combination of two SPDX short form license identifiers separated by "WITH" when a license exception applies. When multiple licenses apply, an expression consists of keywords "AND", "OR" separating sub-expressions and surrounded by "(", ")" . - -License identifiers for licenses like [L]GPL with the 'or later' option are constructed by using a "+" for indicating the 'or later' option.: - -// SPDX-License-Identifier: GPL-2.0+ -// SPDX-License-Identifier: LGPL-2.1+ -WITH should be used when there is a modifier to a license needed. For example, the linux kernel UAPI files use the expression: - -// SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note -// SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note -Other examples using WITH exceptions found in the kernel are: - -// SPDX-License-Identifier: GPL-2.0 WITH mif-exception -// SPDX-License-Identifier: GPL-2.0+ WITH GCC-exception-2.0 -Exceptions can only be used with particular License identifiers. The valid License identifiers are listed in the tags of the exception text file. For details see the point Exceptions in the chapter License identifiers. - -OR should be used if the file is dual licensed and only one license is to be selected. For example, some dtsi files are available under dual licenses: - -// SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause -Examples from the kernel for license expressions in dual licensed files: - -// SPDX-License-Identifier: GPL-2.0 OR MIT -// SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause -// SPDX-License-Identifier: GPL-2.0 OR Apache-2.0 -// SPDX-License-Identifier: GPL-2.0 OR MPL-1.1 -// SPDX-License-Identifier: (GPL-2.0 WITH Linux-syscall-note) OR MIT -// SPDX-License-Identifier: GPL-1.0+ OR BSD-3-Clause OR OpenSSL -AND should be used if the file has multiple licenses whose terms all apply to use the file. For example, if code is inherited from another project and permission has been given to put it in the kernel, but the original license terms need to remain in effect: - -// SPDX-License-Identifier: (GPL-2.0 WITH Linux-syscall-note) AND MIT -Another other example where both sets of license terms need to be adhered to is: - -// SPDX-License-Identifier: GPL-1.0+ AND LGPL-2.1+ -License identifiers -The licenses currently used, as well as the licenses for code added to the kernel, can be broken down into: - -Preferred licenses: - -Whenever possible these licenses should be used as they are known to be fully compatible and widely used. These licenses are available from the directory: - -LICENSES/preferred/ -in the kernel source tree. - -The files in this directory contain the full license text and Metatags. The file names are identical to the SPDX license identifier which shall be used for the license in source files. - -Examples: - -LICENSES/preferred/GPL-2.0 -Contains the GPL version 2 license text and the required metatags: - -LICENSES/preferred/MIT -Contains the MIT license text and the required metatags - -Metatags: - -The following meta tags must be available in a license file: - -Valid-License-Identifier: - -One or more lines which declare which License Identifiers are valid inside the project to reference this particular license text. Usually this is a single valid identifier, but e.g. for licenses with the 'or later' options two identifiers are valid. - -SPDX-URL: - -The URL of the SPDX page which contains additional information related to the license. - -Usage-Guidance: - -Freeform text for usage advice. The text must include correct examples for the SPDX license identifiers as they should be put into source files according to the License identifier syntax guidelines. - -License-Text: - -All text after this tag is treated as the original license text - -File format examples: - -Valid-License-Identifier: GPL-2.0 -Valid-License-Identifier: GPL-2.0+ -SPDX-URL: https://spdx.org/licenses/GPL-2.0.html -Usage-Guide: - To use this license in source code, put one of the following SPDX - tag/value pairs into a comment according to the placement - guidelines in the licensing rules documentation. - For 'GNU General Public License (GPL) version 2 only' use: - SPDX-License-Identifier: GPL-2.0 - For 'GNU General Public License (GPL) version 2 or any later version' use: - SPDX-License-Identifier: GPL-2.0+ -License-Text: - Full license text -SPDX-License-Identifier: MIT -SPDX-URL: https://spdx.org/licenses/MIT.html -Usage-Guide: - To use this license in source code, put the following SPDX - tag/value pair into a comment according to the placement - guidelines in the licensing rules documentation. - SPDX-License-Identifier: MIT -License-Text: - Full license text - -Deprecated licenses: - -These licenses should only be used for existing code or for importing code from a different project. These licenses are available from the directory: - -LICENSES/deprecated/ -in the kernel source tree. - -The files in this directory contain the full license text and Metatags. The file names are identical to the SPDX license identifier which shall be used for the license in source files. - -Examples: - -LICENSES/deprecated/ISC -Contains the Internet Systems Consortium license text and the required metatags: - -LICENSES/deprecated/GPL-1.0 -Contains the GPL version 1 license text and the required metatags. - -Metatags: - -The metatag requirements for 'other' licenses are identical to the requirements of the Preferred licenses. - -File format example: - -Valid-License-Identifier: ISC -SPDX-URL: https://spdx.org/licenses/ISC.html -Usage-Guide: - Usage of this license in the kernel for new code is discouraged - and it should solely be used for importing code from an already - existing project. - To use this license in source code, put the following SPDX - tag/value pair into a comment according to the placement - guidelines in the licensing rules documentation. - SPDX-License-Identifier: ISC -License-Text: - Full license text - -Dual Licensing Only - -These licenses should only be used to dual license code with another license in addition to a preferred license. These licenses are available from the directory: - -LICENSES/dual/ -in the kernel source tree. - -The files in this directory contain the full license text and Metatags. The file names are identical to the SPDX license identifier which shall be used for the license in source files. - -Examples: - -LICENSES/dual/MPL-1.1 -Contains the Mozilla Public License version 1.1 license text and the required metatags: - -LICENSES/dual/Apache-2.0 -Contains the Apache License version 2.0 license text and the required metatags. - -Metatags: - -The metatag requirements for 'other' licenses are identical to the requirements of the Preferred licenses. - -File format example: - -Valid-License-Identifier: MPL-1.1 -SPDX-URL: https://spdx.org/licenses/MPL-1.1.html -Usage-Guide: - Do NOT use. The MPL-1.1 is not GPL2 compatible. It may only be used for - dual-licensed files where the other license is GPL2 compatible. - If you end up using this it MUST be used together with a GPL2 compatible - license using "OR". - To use the Mozilla Public License version 1.1 put the following SPDX - tag/value pair into a comment according to the placement guidelines in - the licensing rules documentation: -SPDX-License-Identifier: MPL-1.1 -License-Text: - Full license text - -Exceptions: - -Some licenses can be amended with exceptions which grant certain rights which the original license does not. These exceptions are available from the directory: - -LICENSES/exceptions/ -in the kernel source tree. The files in this directory contain the full exception text and the required Exception Metatags. - -Examples: - -LICENSES/exceptions/Linux-syscall-note -Contains the Linux syscall exception as documented in the COPYING file of the Linux kernel, which is used for UAPI header files. e.g. /* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */: - -LICENSES/exceptions/GCC-exception-2.0 -Contains the GCC 'linking exception' which allows to link any binary independent of its license against the compiled version of a file marked with this exception. This is required for creating runnable executables from source code which is not compatible with the GPL. - -Exception Metatags: - -The following meta tags must be available in an exception file: - -SPDX-Exception-Identifier: - -One exception identifier which can be used with SPDX license identifiers. - -SPDX-URL: - -The URL of the SPDX page which contains additional information related to the exception. - -SPDX-Licenses: - -A comma separated list of SPDX license identifiers for which the exception can be used. - -Usage-Guidance: - -Freeform text for usage advice. The text must be followed by correct examples for the SPDX license identifiers as they should be put into source files according to the License identifier syntax guidelines. - -Exception-Text: - -All text after this tag is treated as the original exception text - -File format examples: - -SPDX-Exception-Identifier: Linux-syscall-note -SPDX-URL: https://spdx.org/licenses/Linux-syscall-note.html -SPDX-Licenses: GPL-2.0, GPL-2.0+, GPL-1.0+, LGPL-2.0, LGPL-2.0+, LGPL-2.1, LGPL-2.1+ -Usage-Guidance: - This exception is used together with one of the above SPDX-Licenses - to mark user-space API (uapi) header files so they can be included - into non GPL compliant user-space application code. - To use this exception add it with the keyword WITH to one of the - identifiers in the SPDX-Licenses tag: - SPDX-License-Identifier: WITH Linux-syscall-note -Exception-Text: - Full exception text -SPDX-Exception-Identifier: GCC-exception-2.0 -SPDX-URL: https://spdx.org/licenses/GCC-exception-2.0.html -SPDX-Licenses: GPL-2.0, GPL-2.0+ -Usage-Guidance: - The "GCC Runtime Library exception 2.0" is used together with one - of the above SPDX-Licenses for code imported from the GCC runtime - library. - To use this exception add it with the keyword WITH to one of the - identifiers in the SPDX-Licenses tag: - SPDX-License-Identifier: WITH GCC-exception-2.0 -Exception-Text: - Full exception text -All SPDX license identifiers and exceptions must have a corresponding file in the LICENSES subdirectories. This is required to allow tool verification (e.g. checkpatch.pl) and to have the licenses ready to read and extract right from the source, which is recommended by various FOSS organizations, e.g. the FSFE REUSE initiative. - -MODULE_LICENSE -Loadable kernel modules also require a MODULE_LICENSE() tag. This tag is neither a replacement for proper source code license information (SPDX-License-Identifier) nor in any way relevant for expressing or determining the exact license under which the source code of the module is provided. - -The sole purpose of this tag is to provide sufficient information whether the module is free software or proprietary for the kernel module loader and for user space tools. - -The valid license strings for MODULE_LICENSE() are: - -"GPL" Module is licensed under GPL version 2. This does not express any distinction between GPL-2.0-only or GPL-2.0-or-later. The exact license information can only be determined via the license information in the corresponding source files. -"GPL v2" Same as "GPL". It exists for historic reasons. -"GPL and additional rights" Historical variant of expressing that the module source is dual licensed under a GPL v2 variant and MIT license. Please do not use in new code. -"Dual MIT/GPL" The correct way of expressing that the module is dual licensed under a GPL v2 variant or MIT license choice. -"Dual BSD/GPL" The module is dual licensed under a GPL v2 variant or BSD license choice. The exact variant of the BSD license can only be determined via the license information in the corresponding source files. -"Dual MPL/GPL" The module is dual licensed under a GPL v2 variant or Mozilla Public License (MPL) choice. The exact variant of the MPL license can only be determined via the license information in the corresponding source files. -"Proprietary" The module is under a proprietary license. This string is solely for proprietary third party modules and cannot be used for modules which have their source code in the kernel tree. Modules tagged that way are tainting the kernel with the 'P' flag when loaded and the kernel module loader refuses to link such modules against symbols which are exported with EXPORT_SYMBOL_GPL(). \ No newline at end of file diff --git a/coreutils/tst_common/Makefile b/coreutils/tst_common/Makefile deleted file mode 100644 index 617a017..0000000 --- a/coreutils/tst_common/Makefile +++ /dev/null @@ -1,27 +0,0 @@ -export TST_COMMON_TOPDIR := $(shell pwd) -DIRS := cmd testcase kmod -LIBS := lib - -all: libs - @for d in $(DIRS); do \ - echo try make common $$d; \ - make -C $$d all; \ - done - -libs: - @for d in $(LIBS); do \ - echo try make common $$d; \ - make -C $$d all; \ - done - -clean: - @for d in $(DIRS) $(LIBS); do \ - echo try clean common $$d; \ - make -C $$d clean; \ - done - -cleanall: - @for d in $(DIRS) $(LIBS); do \ - echo try cleanall common $$d; \ - make -C $$d cleanall; \ - done diff --git a/coreutils/tst_common/Makefile.common b/coreutils/tst_common/Makefile.common deleted file mode 100644 index 80b47be..0000000 --- a/coreutils/tst_common/Makefile.common +++ /dev/null @@ -1,2 +0,0 @@ -CFLAGS += -Wall -g -I$(TST_COMMON_TOPDIR)/lib -LDFLAGS += -lm -lrt -lpthread -lcommon -L$(TST_COMMON_TOPDIR)/lib diff --git a/coreutils/tst_common/README.md b/coreutils/tst_common/README.md deleted file mode 100644 index 315b9f9..0000000 --- a/coreutils/tst_common/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# 概述 -本项目为自动化测试用例的公共代码库和框架代码,公共库接口函数见`docs/API-*.md`部分内容 -测试套应用请参考:https://gitee.com/opencloudos-stream/test-suite-example - -# 用法 -```shell -tsuite options sub_command sub_options - help: 显示帮助信息 - new case sh|c|py case_name [template]: 新增测试用例 - sh|c|py: 【必选】三选一,sh表示Shell脚本用例,c表示C用例,py表示Python脚本用例 - case_name: 【必选】要创建的用例名,同时用作文件名 - template: 【可选】不使用默认用例模板时,可以指定一个文件用作新用例模板 - list: 列出本测试套的测试用例 - compile: 编译测试套 - setup: 执行测试套setup - run [case_path|case_name]: 执行测试用例 - case_path|case_name: 【可选】不指定此参数时执行测试套所有用例,指定时执行指定用例 - teardown: 执行测试套teardown - clean: 执行make clean - cleanall: 执行make cleanall,在clean基础上删除所有临时文件等 -``` \ No newline at end of file diff --git a/coreutils/tst_common/cmd/Makefile b/coreutils/tst_common/cmd/Makefile deleted file mode 100644 index 7eec895..0000000 --- a/coreutils/tst_common/cmd/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -export TST_COMMON_TOPDIR ?= $(shell pwd)/.. -include $(TST_COMMON_TOPDIR)/Makefile.common -ALL_SRC := $(wildcard *.c) -ALL_OBJ := $(patsubst %.c,%.o,$(ALL_SRC)) -ALL_BIN := $(patsubst %.o,%.cmd,$(ALL_OBJ)) -CFLAGS += -LDFLAGS += - -all: $(ALL_BIN) - -$(ALL_BIN):%.cmd:%.o - $(CC) $^ -o $@ $(LDFLAGS) - -$(ALL_OBJ):%.o:%.c - $(CC) $(CFLAGS) -c $^ -o $@ - -clean: - rm -rfv $(ALL_OBJ) $(ALL_BIN) - -cleanall: clean diff --git a/coreutils/tst_common/cmd/tsuite.c b/coreutils/tst_common/cmd/tsuite.c deleted file mode 100644 index 006dcf3..0000000 --- a/coreutils/tst_common/cmd/tsuite.c +++ /dev/null @@ -1,6 +0,0 @@ -#include "common.h" - -int main(void) { - dbg("hello world"); - return 0; -} diff --git a/coreutils/tst_common/docs/API-C.md b/coreutils/tst_common/docs/API-C.md deleted file mode 100644 index 988a482..0000000 --- a/coreutils/tst_common/docs/API-C.md +++ /dev/null @@ -1,24 +0,0 @@ -# 断言 -## assert_true -```C -// 原型:assert_true(expr) -// 功能:断言表达式返回真 -// 参数: -// expr -- 表达式 -// 返回值:无 -// 示例: -assert_true(1 == 2); -assert_true(a >= b); -``` - -## assert_false -```C -// 原型:assert_false(expr) -// 功能:断言表达式返回假 -// 参数: -// expr -- 表达式 -// 返回值:无 -// 示例: -assert_false(1 == 2); -assert_false(a >= b); -``` diff --git a/coreutils/tst_common/docs/API-Python.md b/coreutils/tst_common/docs/API-Python.md deleted file mode 100644 index 033c9f5..0000000 --- a/coreutils/tst_common/docs/API-Python.md +++ /dev/null @@ -1,62 +0,0 @@ -# 断言 -## assert_true -```Python -def assert_true(self, expr, message=None): - """ - 断言表达式返回真 - :param expr: 要断言的表达式 - :param message: 断言要输出的信息 - :return: None - 示例: - assert_true(1 == 2) - assert_true(a >= b) - """ - pass -``` - -## assert_false -```Python -def assert_false(self, expr, message=None): - """ - 断言表达式返回假 - :param expr: 要断言的表达式 - :param message: 断言要输出的信息 - :return: None - 示例: - assert_false(1 == 2) - assert_false(a >= b) - """ - pass -``` - -## skip_test、skip_if_true和skip_if_false -```Python -def skip_test(self, message=None): - """ - 标记用例为SKIP状态(当用例不需要测试时) - :param message: 要输出的信息 - :return: None - 示例: - skip_test(message='内核CONFIG_XXX未开,系统不支持此测试') - """ - -def skip_if_true(self, expr, message=None): - """ - 当表达式返回真或命令执行成功时,用例不满足测试条件,终止测试 - :param expr: 要判断的表达式 - :param message: 要输出的信息 - :return: None - 示例: - skip_if_true(1 == 2) - """ - -def skip_if_false(self, expr, message=None): - """ - 当表达式返回假或命令执行失败,用例不满足测试条件,终止测试 - :param expr: 要判断的表达式 - :param message: 要输出的信息 - :return: None - 示例: - skip_if_false(1 == 2) - """ -``` diff --git a/coreutils/tst_common/docs/API-Shell.md b/coreutils/tst_common/docs/API-Shell.md deleted file mode 100644 index 3aa1ab0..0000000 --- a/coreutils/tst_common/docs/API-Shell.md +++ /dev/null @@ -1,68 +0,0 @@ -# 断言 -## assert_true和assert_true_cont -```Shell -# 功能:断言表达式返回真或命令执行成功,'_cont'后缀的断言函数在断言失败后用例继续执行,不终止 -# 参数: -# $* -- 需要断言的表达式 -# 返回值: -# 0 -- 断言成功 -# 1 -- 断言失败 -# 示例: -assert_true [ $? -eq 0 ] -assert_true_cont grep "abc" /tmp/file -``` - -## assert_false和assert_false_cont -```Shell -# 功能:断言表达式返回假或命令执行失败,'_cont'后缀的断言函数在断言失败后用例继续执行,不终止 -# 参数: -# $* -- 需要断言的表达式 -# 返回值: -# 0 -- 断言成功 -# 1 -- 断言失败 -# 示例: -assert_false test -d /tmp/dir -assert_false_cont rmmod mykmod -``` - -## skip_test、skip_if_true和skip_if_false -```Shell -# skip_test -# 功能:标记用例为SKIP状态(当用例不需要测试时) -# 参数: -# $1 -- 对SKIP状态标记的描述 -# 返回值:无 -# 示例: -skip_test "内核CONFIG_XXXX未打开,系统不支持xxx功能" - -# skip_if_true -# 功能:当表达式返回真或命令执行成功时,用例不满足测试条件,终止测试 -# 参数: -# $* -- 需要断言的表达式 -# 返回值:无 -# 示例: -skip_if_true test -f /etc/xxx.conf - -# skip_if_false -# 功能:当表达式返回假或命令执行失败,用例不满足测试条件,终止测试 -# 参数: -# $* -- 需要断言的表达式 -# 返回值:无 -# 示例: -skip_if_false which ps -``` -# 工具 -## conv_unit -```Shell -# 功能:将K/M/G/T等单位互相转换 -# 参数:conv_unit [-i k|m|g|t] [-o k|m|g|t] value[_with_unit] -# -i k|m|g|t 【可选参数】输入数据的单位,可选参数,若不指定单位,则默认为1,或者输入的值后面带参数 -# -o k|m|g|t 【可选参数】输出数据的单位,若不指定单位,则默认为1 -# value[_with_unit] 【必选参数】需要转换的数据值,可以跟单位(只取单位第一个字母用于判断k|m|g|t) -# 返回值:标准输出转换后的结果 -# 0 -- 转换成功 -# 1 -- 转换失败 -# 示例: -conv_unit -o M 3G -conv_unit -o M -i G 3 -``` diff --git a/coreutils/tst_common/kmod/Makefile b/coreutils/tst_common/kmod/Makefile deleted file mode 100644 index 01632ef..0000000 --- a/coreutils/tst_common/kmod/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -# General Purpose Makefile for Linux Kernel module -# 以下编译适合于在内核代码树之外编译内核模块。 -# 整个过程会导致本Makefile文件被加载执行两遍。 -# 第一遍执行时,由于`KERNELRELEASE`没有被定义,所以先执行`else`下的逻辑。 -# `-C $(KERNEL_DIR)`指明跳转到内核源码目录下读取那里的Makefile; -# `M=$(CURDIR)`表明然后返回到当前目录继续读入当前的Makefile并执行之。此为第二遍执行。 -# 第二遍执行时,此时从内核源码目录返回时,KERNELRELEASE已被被定义, -# kbuild也被启动去解析kbuild语法的语句,make将继续读取else之前的内容。 -# else之前的内容为kbuild语法的语句, 指明模块源码中各文件的依赖关系,以及要生成的目标模块名。 - -CURDIR ?= $(shell pwd) -KERNEL_VER := $(shell uname -r) -KERNEL_DIR ?= /lib/modules/$(KERNEL_VER)/build -export ALL_SRC ?= $(filter-out %.mod.c, $(wildcard *.c)) -export ALL_OBJ ?= $(patsubst %.c,%.o,$(ALL_SRC)) -export ALL_MOD ?= $(patsubst %.o,%.ko,$(ALL_OBJ)) - -ifneq ($(KERNELRELEASE),) - obj-m += $(ALL_OBJ) -else -all: - $(MAKE) -C $(KERNEL_DIR) M=$(CURDIR) modules -endif - -clean: - $(MAKE) -C $(KERNEL_DIR) M=$(CURDIR) clean - -cleanall: clean diff --git a/coreutils/tst_common/kmod/kmod_common.c b/coreutils/tst_common/kmod/kmod_common.c deleted file mode 100644 index 41a779a..0000000 --- a/coreutils/tst_common/kmod/kmod_common.c +++ /dev/null @@ -1,14 +0,0 @@ -#include - -static int __init kmod_common_init(void) { - printk("Hello, World!\n"); - return 0; -} -static void __exit kmod_common_exit(void) { - printk("Goodbye, World!\n"); -} - -module_init(kmod_common_init); -module_exit(kmod_common_exit); - -MODULE_LICENSE("GPL"); diff --git a/coreutils/tst_common/lib/Makefile b/coreutils/tst_common/lib/Makefile deleted file mode 100644 index aaab40e..0000000 --- a/coreutils/tst_common/lib/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -export TST_COMMON_TOPDIR ?= $(shell pwd)/.. -include $(TST_COMMON_TOPDIR)/Makefile.common -ALL_SRC := $(wildcard *.c) -ALL_OBJ := $(patsubst %.c,%.o,$(ALL_SRC)) -LIB_STATIC := libcommon.a -CFLAGS += -Wformat=0 - -all: $(LIB_STATIC) - -$(LIB_STATIC): $(ALL_OBJ) - ar -rc $(LIB_STATIC) $(ALL_OBJ) - -$(ALL_OBJ):%.o:%.c - $(CC) $(CFLAGS) -c $^ -o $@ - -clean: - rm -rfv $(LIB_STATIC) $(ALL_OBJ) - -cleanall: clean - rm -rfv __pycache__ diff --git a/coreutils/tst_common/lib/benchmark.c b/coreutils/tst_common/lib/benchmark.c deleted file mode 100644 index 5ff07e0..0000000 --- a/coreutils/tst_common/lib/benchmark.c +++ /dev/null @@ -1,389 +0,0 @@ -// Time: 2022-06-30 11:10:49 -// Desc: 性能测试框架 - -#include -#include -#include -#include -#include - -#include "benchmark.h" - -long long tst_time_diff(struct tst_time *s, struct tst_time *e) { - return (long long) (e->ts.tv_sec - s->ts.tv_sec) * NS_PER_SEC + (e->ts.tv_nsec - s->ts.tv_nsec); -} - -int tst_get_time(struct tst_time *t) { - if (clock_gettime(CLOCK_MONOTONIC, &(t->ts)) != 0) { - return 1; - } - return 0; -} - -long long tst_time_since_now(struct tst_time *t) { - struct tst_time now; - (void) tst_get_time(&now); - return tst_time_diff(t, &now); -} - -struct tst_perf_ctrl *tst_alloc_ctrl(const char *name, tst_perf_func_t setup, tst_perf_func_t do_test, - tst_perf_func_t teardown, void *args, int warmup, int loop, enum value_type type, - enum key_item key) { - struct tst_perf_ctrl *c = NULL; - - if (name == NULL) { - printf("the name can't be NULL\n"); - return NULL; - } - if (do_test == NULL) { - printf("the do_test function can't be NULL\n"); - return NULL; - } - if (warmup < 0) { - printf("the warmup can't less then 0"); - return NULL; - } - if (loop <= 0) { - printf("the loop must greater then 0"); - return NULL; - } - if (type < LIB || type > HIB) { - printf("the type must in enum value_type"); - return NULL; - } - if (key < key_max || key > key_standard_deviation) { - printf("the key must in enum key_item"); - return NULL; - } - - c = (struct tst_perf_ctrl *) malloc(sizeof(struct tst_perf_ctrl)); - if (c == NULL) { - printf("malloc tst_perf_ctrl fail\n"); - return NULL; - } - (void) memset(c, 0, sizeof(struct tst_perf_ctrl)); - c->name = name; - c->perf_setup = setup; - c->perf_do_test = do_test; - c->perf_teardown = teardown; - c->args = args; - c->nr_warmup = warmup; - c->nr_loop = loop; - c->value_type = type; - c->key_item = key; - c->data = (long long *) calloc(c->nr_loop, sizeof(long long)); - if (c->data == NULL) { - printf("alloc memory for time data fail\n"); - free(c); - return NULL; - } - - return c; -} - -void tst_destroy_ctrl(struct tst_perf_ctrl **c) { - if (c == NULL || *c == NULL) { - return; - } - if ((*c)->data != NULL) { - free((*c)->data); - (*c)->data = NULL; - } - free(*c); - *c = NULL; -} - -int tst_perf_run(struct tst_perf_ctrl *c) { - int ret = 0; - int i; - struct tst_time t; - - if (c == NULL) { - return 1; - } - // 预热 - fprintf(stderr, "%s : start warmup %d\n", c->name, c->nr_warmup); - while (c->nr_warmup > 0) { - c->nr_warmup--; - - if (c->perf_setup) { - ret = c->perf_setup(c->args); - if (ret != 0) { - printf("the perf_setup return %d\n", ret); - return 1; - } - } - - ret = c->perf_do_test(c->args); - if (ret != 0) { - printf("the perf_do_test return %d\n", ret); - return 1; - } - - if (c->perf_teardown) { - ret = c->perf_teardown(c->args); - if (ret != 0) { - printf("the perf_teardown return %d\n", ret); - return 1; - } - } - } - - // 执行性能测试 - fprintf(stderr, "%s : start perf test loop %d\n", c->name, c->nr_loop); - for (i = 0; i < c->nr_loop; i++) { - if (c->perf_setup) { - ret = c->perf_setup(c->args); - if (ret != 0) { - printf("the perf_setup return %d\n", ret); - return 1; - } - } - - (void) tst_get_time(&t); - ret = c->perf_do_test(c->args); - if (ret != 0) { - printf("the perf_do_test return %d\n", ret); - return 1; - } - c->data[i] = tst_time_since_now(&t); - - if (c->perf_teardown) { - ret = c->perf_teardown(c->args); - if (ret != 0) { - printf("the perf_teardown return %d\n", ret); - return 1; - } - } - } - - return 0; -} - -int compare_time(const void *a, const void *b) { - return (int) (*(long long *) a - *(long long *) b); -} - -int statistic_data_base(long long *data, int len, struct tst_statistics_base *result) { - long double sum = 0; - long double step_20, step_100; - long double variance = 0; - int i; - - if (data == NULL || result == NULL || len <= 0) { - return 1; - } - - result->max = data[len - 1]; - result->min = data[0]; - result->median = data[(int) (len / 2)]; - step_20 = (long double) (result->max - result->min) / 20; - step_100 = (long double) (result->max - result->min) / 100; - - for (i = 0; i < len; i++) { - sum += data[i]; - if (step_20 > 0) { - result->dist_20[(int) ((data[i] - result->min) / step_20)]++; - } - if (step_100 > 0) { - result->dist_100[(int) ((data[i] - result->min) / step_100)]++; - } - } - - result->mean = sum / len; - - // 计算方差和 - for (i = 0; i < len; i++) { - variance += powl(data[i] - result->mean, 2); - } - // 计算标准差 - result->standard_deviation = sqrtl(variance / len); - - return 0; -} - -int statistic_data(struct tst_perf_ctrl *c) { - if (c == NULL) { - return 1; - } - int percent_5_start = (int) (c->nr_loop * 0.05); - int percent_5_len = (int) (c->nr_loop * 0.9); - - if (c->data == NULL) { - printf("the data is NULL\n"); - return 1; - } - - // 将时间数据排序 - qsort(c->data, c->nr_loop, sizeof(long long), compare_time); - (void) statistic_data_base(c->data, c->nr_loop, &(c->result.all)); - (void) statistic_data_base(&(c->data[percent_5_start]), percent_5_len, &(c->result.mid_90)); - - return 0; -} - -int show_result_json(struct tst_perf_ctrl *c) { - int i; - - if (statistic_data(c) != 0) { - return 1; - } - - printf("{"); - - printf("'name': '%s',", c->name); - printf("'type': '%s',", "LIB"); - printf("'unit': '%s',", "ns"); - printf("'key': '%s',", "mean"); - - printf("'data': {"); - - printf("100: {"); - printf("'max': %lld,", c->result.all.max); - printf("'min': %lld,", c->result.all.min); - printf("'mean': %Lf,", c->result.all.mean); - printf("'median': %lld,", c->result.all.median); - printf("'standard_deviation': %Lf,", c->result.all.standard_deviation); - printf("'dist_20': ["); - for (i = 0; i < NUM_20; i++) { - printf("%d,", c->result.all.dist_20[i]); - } - printf("],"); - printf("'dist_100': ["); - for (i = 0; i < NUM_100; i++) { - printf("%d,", c->result.all.dist_100[i]); - } - printf("],"); - printf("},"); - - printf("90: {"); - printf("'max': %lld,", c->result.mid_90.max); - printf("'min': %lld,", c->result.mid_90.min); - printf("'mean': %Lf,", c->result.mid_90.mean); - printf("'median': %lld,", c->result.mid_90.median); - printf("'standard_deviation': %Lf,", c->result.mid_90.standard_deviation); - printf("'dist_20': ["); - for (i = 0; i < NUM_20; i++) { - printf("%d,", c->result.mid_90.dist_20[i]); - } - printf("],"); - printf("'dist_100': ["); - for (i = 0; i < NUM_100; i++) { - printf("%d,", c->result.mid_90.dist_100[i]); - } - printf("],"); - printf("},"); - - // end of data - printf("},"); - - printf("}"); - - return 0; -} - - -int tst_test(const char *name, tst_perf_func_t setup, tst_perf_func_t do_test, tst_perf_func_t teardown, - void *args, int warmup, int loop, enum value_type type, enum key_item key) { - - struct tst_perf_ctrl *c = tst_alloc_ctrl(name, setup, do_test, teardown, args, warmup, loop, type, key); - if (c == NULL) { - return 1; - } - tst_perf_run(c); - show_result_json(c); - tst_destroy_ctrl(&c); - return 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/* 下面的代码是示例 */ -#if 0 - -#define NR_LOOP_OPEN 100 -#define OPEN_PATH_LEN 128 -struct open_args { - int nr_opened; - char path[NR_LOOP_OPEN][OPEN_PATH_LEN]; - int fds[NR_LOOP_OPEN]; -}; - -int open_setup(void *args) { - int i; - struct rlimit r; - struct open_args *a = (struct open_args *) (args); - - r.rlim_cur = NR_LOOP_OPEN + 1024; - r.rlim_max = r.rlim_cur; - setrlimit(RLIMIT_NOFILE, &r); - memset(a, 0, sizeof(struct open_args)); - - system("rm -rf ./file.ops"); - system("mkdir ./file.ops"); - - for (i = 0; i < NR_LOOP_OPEN; ++i) { - snprintf(a->path[i], OPEN_PATH_LEN, "./file.ops/open.%08d.test", i); - } - return 0; -} - -int open_do_test(void *args) { - int i; - struct open_args *a = (struct open_args *) (args); - for (i = 0; i < NR_LOOP_OPEN; ++i) { - a->fds[i] = open(a->path[i], O_RDWR | O_CREAT | O_EXCL, 0600); - if (a->fds[i] < 0) { - printf("open the %s file fail\n", a->path[i]); - a->nr_opened = i; - return 1; - } - } - a->nr_opened = i; - return 0; -} - -int open_teardown(void *args) { - int i; - struct open_args *a = (struct open_args *) (args); - for (i = 0; i < a->nr_opened; ++i) { - if (a->fds[i] > 0) { - close(a->fds[i]); - a->fds[i] = 0; - } - } - system("rm -rf ./file.ops"); - return 0; -} - -int exec_do_test(void *args) { - pid_t pid = fork(); - pid_t wait; - if (pid == 0) { - execl("./simple.test", "./simple.test", NULL); - } else if (pid > 0) { - wait = waitpid(pid, NULL, 0); - if (wait == pid) { - return 0; - } - printf("waitpid(%d) return %d not as expect\n", pid, wait); - } else { - printf("fork fail\n"); - } - return 1; -} - - -int main(int argc, char **argv) { - struct open_args a; - printf("{"); - printf("'open': "); - tst_test("open.100", open_setup, open_do_test, open_teardown, &a, 100, 2000, LIB, key_mean); - printf(","); - printf("'exec': "); - tst_test("exec", NULL, exec_do_test, NULL, NULL, 100, 5000, LIB, key_mean); - printf(","); - printf("}\n"); - return 0; -} - -#endif \ No newline at end of file diff --git a/coreutils/tst_common/lib/benchmark.h b/coreutils/tst_common/lib/benchmark.h deleted file mode 100644 index 738eddb..0000000 --- a/coreutils/tst_common/lib/benchmark.h +++ /dev/null @@ -1,81 +0,0 @@ -#ifndef TST_SUITE_COMMON_BENCHMARK_H -#define TST_SUITE_COMMON_BENCHMARK_H - - -#define NS_PER_SEC 1000000000 -#define NUM_20 20 -#define NUM_100 100 - -typedef int (*tst_perf_func_t)(void *); - -enum value_type { - // 越小越好(value_type.LIB) - LIB, - // 越大越好(value_type.HIB) - HIB -}; - -enum key_item { - // 最大值 - key_max, - // 最小值 - key_min, - // 平均值 - key_mean, - // 中位数 - key_median, - // 标准差 - key_standard_deviation -}; - -struct tst_time { - struct timespec ts; -}; - -struct tst_statistics_base { - // 时间单位都是ns - long long max; - long long min; - long double mean; - long long median; - long double standard_deviation; - int dist_20[NUM_20]; - int dist_100[NUM_100]; -}; - -struct tst_statistics_result { - struct tst_statistics_base all; - struct tst_statistics_base mid_90; -}; - -struct tst_perf_ctrl { - // 测试项名称 - const char *name; - // 初始化函数 - tst_perf_func_t perf_setup; - // 性能测试的对象函数 - tst_perf_func_t perf_do_test; - // 清理函数 - tst_perf_func_t perf_teardown; - // 性能测试函数的参数 - void *args; - // 预热循环次数 - int nr_warmup; - // 性能测试循环次数 - int nr_loop; - // 性能数据类型, - int value_type; - // 本性能指标最重要的统计数据项,例如最大值(key_item.max)、平均值(key_item.mean) - int key_item; - - // 性能测试数据 - long long *data; - // 性能数据统计结果 - struct tst_statistics_result result; -}; - -extern int tst_get_time(struct tst_time *t); - -extern long long tst_time_since_now(struct tst_time *t); - -#endif //TST_SUITE_COMMON_BENCHMARK_H diff --git a/coreutils/tst_common/lib/benchmark.py b/coreutils/tst_common/lib/benchmark.py deleted file mode 100644 index 22f9abb..0000000 --- a/coreutils/tst_common/lib/benchmark.py +++ /dev/null @@ -1,304 +0,0 @@ -#!/usr/bin/env python3 -# coding: utf-8 -import abc -import json -import re -import subprocess -from _ctypes import PyObj_FromPtr -from enum import Enum - - -class ValueType(Enum): - # 越小越好(value_type.LIB) - LIB = 'LIB' - # 越大越好(value_type.HIB) - HIB = 'HIB' - - -class KeyItem(Enum): - # 最大值 - key_max = 'max' - # 最小值 - key_min = 'min' - # 平均值 - key_mean = 'mean' - # 中位数 - key_median = 'median' - # 标准差 - key_standard_deviation = 'standard_deviation' - - -class PerfResult: - def __init__(self, name: str, value_type: ValueType, key_item: KeyItem, unit: str): - self._result = { - "name": f'{name}', - "type": f'{value_type}', - "key": f'{key_item}', - "unit": f'{unit}', - "data": { - "100": { - "max": 0, - "min": 0, - "mean": 0, - "median": 0, - "standard_deviation": 0, - "dist_20": [0] * 20, - "dist_100": [0] * 100 - } - } - } - - @property - def result(self): - return self._result - - -class TSTPerf: - def __init__(self): - self._result = dict() - - @abc.abstractmethod - def run(self): - pass - - def add_result(self, result: PerfResult): - if result.result['name'] in self._result: - raise KeyError(f'the result with name {result.result["name"]} has existed') - self._result[result.result['name']] = result.result - - @property - def results(self): - return self._result - - def report(self): - print(json.dumps(self.results, indent=4, ensure_ascii=False)) - - -class PerfSysBench(TSTPerf): - def __init__(self, name: str, sysbench: str, testname: str, general_opt: str = None, test_opt: str = None): - super(PerfSysBench, self).__init__() - self.name = name - self.sysbench = sysbench - self.prepare = None - self.cleanup = None - self.testname = testname - self.general_opt = general_opt - self.test_opt = test_opt - self.command = f'{sysbench} {self.general_opt if self.general_opt else ""} {testname} ' \ - f'{self.test_opt if self.test_opt else ""} run' - self.outs = None - self.errs = None - - def run(self, timeout=None): - if self.prepare is not None and callable(self.prepare): - self.prepare() - proc = subprocess.Popen(self.command, shell=True, encoding='utf-8', stdout=subprocess.PIPE, - stderr=subprocess.PIPE) - self.outs, self.errs = proc.communicate(timeout=timeout) - if self.cleanup is not None and callable(self.cleanup): - self.cleanup() - print(f'execute command [{self.command}] get exit code {proc.returncode}, output:') - print(self.outs) - if self.errs: - print('errors:') - print(self.errs) - self.parse_add_result() - - def get_cpu_result(self): - result = PerfResult(name=self.name, value_type=ValueType.LIB, key_item=KeyItem.key_mean, - unit='ms') - for line in self.outs.splitlines(): - if 'avg:' in line: - mean = float(line.split(':')[1].strip()) - result.result['data']['100']['mean'] = mean - return result - - def get_fileio_result(self, data_type): - result = PerfResult(name=f'{self.name}-{data_type}', value_type=ValueType.HIB, key_item=KeyItem.key_mean, - unit='MiB/s') - for line in self.outs.splitlines(): - if f'{data_type}:' in line: - mean = float((line.split('IOPS')[1]).split(' ')[1].strip()) - result.result['data']['100']['mean'] = mean - return result - - def get_memory_result(self): - result = PerfResult(name=self.name, value_type=ValueType.LIB, key_item=KeyItem.key_mean, - unit='MiB/s') - for line in self.outs.splitlines(): - if 'MiB/sec' in line: - mean = float((line.split('(')[1]).split('MiB')[0].strip()) - result.result['data']['100']['mean'] = mean - return result - def get_threads_result(self): - result = PerfResult(name=self.name, value_type=ValueType.LIB, key_item=KeyItem.key_mean, - unit='ms') - for line in self.outs.splitlines(): - if 'avg:' in line: - mean = float(line.split(':')[1].strip()) - result.result['data']['100']['mean'] = mean - return result - def get_mutex_result(self): - result = PerfResult(name=self.name, value_type=ValueType.LIB, key_item=KeyItem.key_mean, - unit='ms') - for line in self.outs.splitlines(): - if 'avg:' in line: - mean = float(line.split(':')[1].strip()) - result.result['data']['100']['mean'] = mean - return result - def parse_add_result(self): - if self.outs is None: - raise Exception('test output is None') - if self.testname == 'cpu': - self.add_result(self.get_cpu_result()) - elif self.testname == 'fileio': - if re.match(r'read:\s+IOPS=0.0', self.outs): - self.add_result(self.get_fileio_result('write')) - elif re.match(r'write:\s+IOPS=0.0', self.outs): - self.add_result(self.get_fileio_result('read')) - else: - self.add_result(self.get_fileio_result('read')) - self.add_result(self.get_fileio_result('write')) - elif self.testname == 'memory': - self.add_result(self.get_memory_result()) - elif self.testname == 'threads': - self.add_result(self.get_threads_result()) - elif self.testname == 'mutex': - self.add_result(self.get_mutex_result()) - else: - raise Exception(f'unknown test name {self.testname}') - -class PerfStream(TSTPerf): - def __init__(self, name: str, stream: str, general_opt: str = None): - super(PerfStream, self).__init__() - self.name = name - self.stream = stream - self.general_opt = general_opt - self.prepare = None - self.cleanup = None - self.command = f'{stream} {self.general_opt if self.general_opt else ""}' - self.outs = None - self.errs = None - - def run(self, timeout=None): - if self.prepare is not None and callable(self.prepare): - self.prepare() - proc = subprocess.Popen(self.command, shell=True, encoding='utf-8', stdout=subprocess.PIPE, - stderr=subprocess.PIPE) - self.outs, self.errs = proc.communicate(timeout=timeout) - if self.cleanup is not None and callable(self.cleanup): - self.cleanup() - print(f'execute command [{self.command}] get exit code {proc.returncode}, output:') - print(self.outs) - if self.errs: - print('errors:') - print(self.errs) - self.parse_add_result() - - def get_stream_result(self, data_type): - result = PerfResult(name=f'{self.name}-{data_type}', value_type=ValueType.HIB, key_item=KeyItem.key_mean, - unit='MiB/s') - for line in self.outs.splitlines(): - if f'{data_type}:' in line: - mean = float((line.split(':')[1].strip()).split(' ')[0].strip()) - result.result['data']['100']['mean'] = mean - return result - def parse_add_result(self): - if self.outs is None: - raise Exception('test output is None') - if self.stream is not None: - self.add_result(self.get_stream_result('Copy')) - self.add_result(self.get_stream_result('Scale')) - self.add_result(self.get_stream_result('Add')) - self.add_result(self.get_stream_result('Triad')) - else: - raise Exception(f'unknown test item {self.stream}') - -class PerfHackbench(TSTPerf): - def __init__(self, name: str, hackbench: str, general_opt: str = None): - super(PerfHackbench, self).__init__() - self.name = name - self.hackbench = hackbench - self.general_opt = general_opt - self.prepare = None - self.cleanup = None - self.command = f'{hackbench} {self.general_opt if self.general_opt else ""}' - self.outs = None - self.errs = None - - def run(self, timeout=None): - if self.prepare is not None and callable(self.prepare): - self.prepare() - proc = subprocess.Popen(self.command, shell=True, encoding='utf-8', stdout=subprocess.PIPE, - stderr=subprocess.PIPE) - self.outs, self.errs = proc.communicate(timeout=timeout) - if self.cleanup is not None and callable(self.cleanup): - self.cleanup() - print(f'execute command [{self.command}] get exit code {proc.returncode}, output:') - print(self.outs) - if self.errs: - print('errors:') - print(self.errs) - self.parse_add_result() - - def get_hackbench_result(self): - result = PerfResult(name=self.name, value_type=ValueType.LIB, key_item=KeyItem.key_mean, - unit='s') - for line in self.outs.splitlines(): - if 'Time:' in line: - mean = float(line.split(':')[1].strip()) - result.result['data']['100']['mean'] = mean - return result - def parse_add_result(self): - if self.outs is None: - raise Exception('test output is None') - if self.hackbench is not None: - self.add_result(self.get_hackbench_result()) - else: - raise Exception(f'unknown test item {self.hackbench}') - -class PerfLibMicro(TSTPerf): - def __init__(self, name: str, libmicro: str, general_opt: str = None, test_opt: str = None): - super(PerfLibMicro, self).__init__() - self.name = name - self.libmicro = libmicro - self.prepare = None - self.cleanup = None - self.general_opt = general_opt - self.test_opt = test_opt - self.command = f'{libmicro} {self.general_opt if self.general_opt else ""} ' \ - f'{self.test_opt if self.test_opt else ""}' - self.outs = None - self.errs = None - - def run(self, timeout=None): - if self.prepare is not None and callable(self.prepare): - self.prepare() - proc = subprocess.Popen(self.command, shell=True, encoding='utf-8', stdout=subprocess.PIPE, - stderr=subprocess.PIPE) - self.outs, self.errs = proc.communicate(timeout=timeout) - if self.cleanup is not None and callable(self.cleanup): - self.cleanup() - print(f'execute command [{self.command}] get exit code {proc.returncode}, output:') - print(self.outs) - if self.errs: - print('errors:') - print(self.errs) - self.parse_add_result() - - def get_libmicro_result(self): - result = PerfResult(name=self.name, value_type=ValueType.LIB, key_item=KeyItem.key_mean, - unit='us') - for line in self.outs.splitlines(): - if 'mean' in line: - mean = float((line.split('mean')[1].strip()).split(' ')[0].strip()) - result.result['data']['100']['mean'] = mean - return result - def parse_add_result(self): - if self.outs is None: - raise Exception('test output is None') - if self.libmicro is not None: - self.add_result(self.get_libmicro_result()) - else: - raise Exception(f'unknown test item {self.libmicro} ') - diff --git a/coreutils/tst_common/lib/common.c b/coreutils/tst_common/lib/common.c deleted file mode 100644 index 9bb4f28..0000000 --- a/coreutils/tst_common/lib/common.c +++ /dev/null @@ -1,597 +0,0 @@ -// Time: 2022-04-18 14:07:49 -// Desc: C用例基础公共函数库 - -#include "common.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -struct tst_tc_control { - // 用例名 - char tc_name[PATH_MAX]; - // 用例参数 - int tc_argc; - char **tc_argv; - // 用例源文件路径 - char tc_source_path[PATH_MAX]; - // 用例可执行文件路径 - char tc_exec_path[PATH_MAX]; - // 执行用例文件时的目录 - char exec_cwd[PATH_MAX]; - // TST_TC_CWD 测试用例CWD - char tst_tc_cwd[PATH_MAX]; - // 用例开始执行的时间 - struct tst_time time_start; - // TST_TC_PID 测试用例主进程pid - pid_t tst_tc_pid; - // 标记tc_setup是否被调用 - int tc_setup_called; - // 用例执行状态 - int tc_stat; - // TST_TS_TOPDIR 测试套顶层目录 - char tst_ts_topdir[PATH_MAX]; - // TST_COMMON_TOPDIR common顶层目录 - char tst_common_topdir[PATH_MAX]; - // TST_TS_SYSDIR 测试套公共运行目录 - char tst_ts_sysdir[PATH_MAX]; - // TST_TC_SYSDIR 测试用例管理用临时目录 - char tst_tc_sysdir[PATH_MAX]; - // 测试套执行状态标记文件 - char tst_ts_setup_stat[PATH_MAX]; -}; - -struct tst_tc_control *g_tst_tc_control; - -void show_tc_control(void) { - dbg("tc_name: %s", g_tst_tc_control->tc_name); - dbg("tc_source_path: %s", g_tst_tc_control->tc_source_path); - dbg("tc_exec_path: %s", g_tst_tc_control->tc_exec_path); - dbg("exec_cwd: %s", g_tst_tc_control->exec_cwd); - dbg("tst_tc_cwd: %s", g_tst_tc_control->tst_tc_cwd); - dbg("tst_tc_pid: %d", g_tst_tc_control->tst_tc_pid); - dbg("tc_stat: %d", g_tst_tc_control->tc_stat); - dbg("tst_ts_topdir: %s", g_tst_tc_control->tst_ts_topdir); - dbg("tst_ts_sysdir: %s", g_tst_tc_control->tst_ts_sysdir); - dbg("tst_tc_sysdir: %s", g_tst_tc_control->tst_tc_sysdir); - dbg("tst_ts_setup_stat: %s", g_tst_tc_control->tst_ts_setup_stat); -} - -int _print(const char *format, ...) { - va_list ap; - int ret; - char buff[MAX_LOG_LEN] = {0}; - - va_start(ap, format); - ret = vsnprintf(buff, MAX_LOG_LEN - 1, format, ap); - va_end(ap); - - if (buff[ret - 1] != '\n') { - buff[ret] = '\n'; - buff[ret + 1] = '\0'; - } - fprintf(stderr, "%s", buff); - - return ret; -} - -static int _is_main_process(void) { - if (g_tst_tc_control->tst_tc_pid == getpid()) { - return 1; - } - return 0; -} - -static void _set_tcstat(int stat) { - g_tst_tc_control->tc_stat = stat; -} - -static int _get_tcstat(void) { - return g_tst_tc_control->tc_stat; -} - -void _tc_pass(void) { - // 只有初始状态的用例才能置为PASS,其他异常状态的用例不能从异常变为PASS - if (_get_tcstat() == TST_INIT) { - _set_tcstat(TST_PASS); - } -} - -void _tc_fail(void) { - if (_get_tcstat() != TST_FAIL) { - msg("the testcase first fail here"); - } - _set_tcstat(TST_FAIL); -} - -static char *_tcstat_to_str(int tcstat) { - switch (tcstat) { - case TST_PASS: - return "TST_PASS"; - case TST_FAIL: - return "TST_FAIL"; - case TST_INIT: - return "TST_INIT"; - case TST_SKIP: - return "TST_SKIP"; - default: - return "TST_UNKNOWN"; - } -} - -static int _tc_teardown(int argc, char **argv) { - int ret = 0; - - // 只有用例的主进程才能执行此函数 - if (!_is_main_process()) { - return 0; - } - if (tc_teardown) { - if (tc_teardown(argc, argv) == 0) { - msg("call tc_teardown success"); - } else { - err("call tc_teardown fail"); - ret = 1; - } - } else { - msg("tc_teardown not define"); - } - - return ret; -} - -static int _tc_teardown_common(int argc, char **argv) { - int ret = 0; - - // 只有用例的主进程才能执行此函数 - if (!_is_main_process()) { - return 0; - } - if (tc_teardown_common) { - if (tc_teardown_common(argc, argv) == 0) { - msg("call tc_teardown_common success"); - } else { - err("call tc_teardown_common fail"); - ret = 1; - } - } else { - msg("tc_teardown_common not define"); - } - - return ret; -} - -static void _tc_run_complete(int argc, char **argv) { - int ret = 0; - - // 只有用例的主进程才能执行此函数 - if (!_is_main_process()) { - return; - } - // tc_setup有调用时tc_teardown才会被调用 - if (g_tst_tc_control->tc_setup_called) { - if (_tc_teardown(argc, argv) == 0) { - msg("call _tc_teardown success"); - } else { - msg("call _tc_teardown fail"); - ret = 1; - } - } else { - msg("the tc_setup not called, so tc_teardown ignore"); - } - if (_tc_teardown_common(argc, argv) == 0) { - msg("call _tc_teardown_common success"); - } else { - msg("call _tc_teardown_common fail"); - ret = 1; - } - - // TCase自动化执行框架需要用这个输出判断用例是否支持完 - msg("Global test environment tear-down"); - switch (_get_tcstat()) { - case TST_PASS: - msg("RESULT : %s ==> [ PASSED ]", g_tst_tc_control->tc_name); - break; - case TST_FAIL: - msg("RESULT : %s ==> [ FAILED ]", g_tst_tc_control->tc_name); - ret = 1; - break; - case TST_INIT: - msg("RESULT : %s ==> [ NOTEST ]", g_tst_tc_control->tc_name); - ret = 1; - break; - case TST_SKIP: - msg("RESULT : %s ==> [ SKIP ]", g_tst_tc_control->tc_name); - ret = 0; - break; - default: - msg("RESULT : %s ==> [ UNKNOWN ]", g_tst_tc_control->tc_name); - ret = 1; - break; - } - msg("cost %.9Lf", (long double) tst_time_since_now(&(g_tst_tc_control->time_start)) / NS_PER_SEC); - - exit(ret); -} - -void _tst_assert(const char *expr, const char *file, int line, const char *func) { - msg("%s:%d %s assert '%s' fail", file, line, func, expr); - _tc_run_complete(g_tst_tc_control->tc_argc, g_tst_tc_control->tc_argv); -} - -void _skip_test(const char *message, const char *file, int line, const char *func) { - int tc_stat = _get_tcstat(); - - if ((tc_stat == TST_PASS) || (tc_stat == TST_INIT) || (tc_stat == TST_SKIP)) { - _set_tcstat(TST_SKIP); - msg("%s:%d %s: set testcase SKIP: %s", file, line, func, message); - } else { - msg("%s:%d %s: set testcase SKIP fail: %s", file, line, func, message); - err("the testcase stat is %s, can't set to SKIP", _tcstat_to_str(tc_stat)); - } - _tc_run_complete(g_tst_tc_control->tc_argc, g_tst_tc_control->tc_argv); -} - -static int _tc_setup_common(int argc, char **argv) { - int ret = 0; - - if (tc_setup_common) { - if (tc_setup_common(argc, argv) == 0) { - msg("call tc_setup_common success"); - } else { - err("call tc_setup_common fail"); - ret = 1; - } - } else { - msg("tc_setup_common not define"); - } - - return ret; -} - -static int _tc_setup(int argc, char **argv) { - int ret = 0; - - // 只有用例的主进程才能执行此函数 - if (!_is_main_process()) { - return 0; - } - g_tst_tc_control->tc_setup_called = 1; - if (tc_setup) { - if (tc_setup(argc, argv) == 0) { - msg("call tc_setup success"); - } else { - err("call tc_setup fail"); - ret = 1; - } - } else { - msg("tc_setup not define"); - } - - return ret; -} - -static int _do_test(int argc, char **argv) { - int ret = 0; - - // 只有用例的主进程才能执行此函数 - if (!_is_main_process()) { - return 0; - } - if (do_test) { - if (do_test(argc, argv) == 0) { - msg("call do_test success"); - } else { - err("call do_test fail"); - ret = 1; - } - } else { - err("do_test not define"); - ret = 1; - } - - return ret; -} - -static int _is_ts_setup_called(void) { - if (is_file(g_tst_tc_control->tst_ts_setup_stat)) { - return 1; - } - return 0; -} - -static int _get_ts_setup_stat(void) { - char buff[PAGE_SIZE]; - int read_size = read_line(g_tst_tc_control->tst_ts_setup_stat, 1, buff, PAGE_SIZE); - if (read_size <= 0) { - return TST_INIT; - } - return (int) strtol(buff, NULL, 0); -} - -// 功能:判断路径是否为文件并且存在 -// 参数: -// path -- 文件路径 -// 返回值: -// 0 -- 文件不存在 -// 1 -- 文件存在 -int is_file(const char *path) { - struct stat sb; - - if (stat(path, &sb) != 0) { - return 0; - } - if (S_ISDIR(sb.st_mode)) { - return 0; - } - return 1; -} - -// 功能:判断路径是否为目录并且存在 -// 参数: -// path -- 文件路径 -// 返回值: -// 0 -- 文件不存在 -// 1 -- 文件存在 -int is_dir(const char *path) { - struct stat sb; - - if (stat(path, &sb) != 0) { - return 0; - } - if (S_ISDIR(sb.st_mode)) { - return 1; - } - return 0; -} - -// 功能:判断路径是否存在 -// 参数: -// path -- 文件路径 -// 返回值: -// 0 -- 文件不存在 -// 1 -- 文件存在 -int is_exist(const char *path) { - if (access(path, F_OK) == 0) { - return 1; - } else { - return 0; - } -} - -// 功能:读文件内容到buff中 -// 参数: -// path -- 文件路径 -// buff -- 接收文件内容 -// size -- buff大小 -// 返回值: -// -1 -- 文件读取失败 -// 其他 -- 读取到的文件内容长度 -size_t read_file(const char *path, char *buff, size_t size) { - int fd = open(path, O_RDONLY); - if (fd < 0) { - return -1; - } - int ret = read(fd, buff, size) < 0; - if (ret < 0) { - close(fd); - return -1; - } - close(fd); - return ret; -} - -// 功能:读文本文件指定行的内容到buff中 -// 参数: -// path -- 文件路径 -// line -- 要读取内容的行号(从1开始) -// buff -- 接收文件内容 -// size -- buff大小 -// 返回值: -// -1 -- 文件读取失败 -// 其他 -- 读取到的文件内容长度 -size_t read_line(const char *path, int line, char *buff, size_t size) { - int i = 0; - FILE *file = NULL; - if (line <= 0) { - dbg("the line less then 0: %d", line); - return -1; - } - file = fopen(path, "r"); - if (file == NULL) { - dbg("open file %s fail, errno %d, error: %s", path, errno, strerror(errno)); - return -1; - } - while (i < line) { - i++; - if (fgets(buff, size, file) == NULL) { - if (i == line) { - // 刚好读到指定行的时候文件结束 - break; - } - // 文件读完了,但是行号还没有读到 - dbg("get line %d fail, buff: %s, errno %d, error: %s", i, buff, errno, strerror(errno)); - fclose(file); - return -1; - } - } - fclose(file); - return strlen(buff); -} - -// 功能:创建多层目录 -// 参数: -// dir -- 目录 -// mode -- 目录权限 -// 返回值: -// -1 -- 创建失败 -// 0 -- 创建成功 -int mkdirs(const char *dir, mode_t mode) { - int i; - char now_path[PATH_MAX]; - - for (i = 0; i < min(strlen(dir), PATH_MAX - 1); i++) { - if (dir[i] != '/') { - continue; - } - strncpy(now_path, dir, i + 1); - if (is_exist(now_path)) { - if (is_dir(now_path)) { - continue; - } else { - dbg("the path %s exist but not dir", now_path); - return -1; - } - } - if (mkdir(now_path, mode) != 0) { - dbg("mkdir %s fail, errno %d, error: %s", now_path, errno, strerror(errno)); - return -1; - } - } - if (mkdir(dir, mode) != 0) { - dbg("mkdir %s fail, errno %d, error: %s", dir, errno, strerror(errno)); - return -1; - } - if (!is_dir(dir)) { - dbg("mkdirs %s fail", dir); - return -1; - } - return 0; -} - -// 功能:执行命令 -// 参数: -// command_format -- 命令内容 -// 返回值:同system函数 -int command(const char *command_format, ...) { - va_list ap; - char cmd[MAX_CMD_LEN] = {0}; - - va_start(ap, command_format); - (void) vsnprintf(cmd, MAX_CMD_LEN, command_format, ap); - va_end(ap); - - return system(cmd); -} - -static int _tc_init(int argc, char **argv) { - size_t control_size = ((sizeof(struct tst_tc_control) / PAGE_SIZE) + 1) * PAGE_SIZE; - g_tst_tc_control = (struct tst_tc_control *) mmap(NULL, control_size, PROT_READ | PROT_WRITE, - MAP_SHARED | MAP_ANONYMOUS, -1, 0); - if (g_tst_tc_control == NULL) { - msg("mmap g_tst_tc_control fail, errno: %d, %s", errno, strerror(errno)); - return 1; - } - memset(g_tst_tc_control, 0, control_size); - if (tst_get_time(&(g_tst_tc_control->time_start)) != 0) { - msg("tst_get_time fail, errno: %d, %s", errno, strerror(errno)); - return 1; - } - strncpy(g_tst_tc_control->tc_name, basename(argv[0]), PATH_MAX); - g_tst_tc_control->tc_argc = argc; - g_tst_tc_control->tc_argv = argv; - - if (realpath(argv[0], g_tst_tc_control->tc_exec_path) == NULL) { - msg("get the realpath fail, errno: %d, %s", errno, strerror(errno)); - return 1; - } - - strncpy(g_tst_tc_control->tc_source_path, g_tst_tc_control->tc_exec_path, PATH_MAX); - strncat(g_tst_tc_control->tc_source_path, ".c", PATH_MAX); - - if (getcwd(g_tst_tc_control->exec_cwd, PATH_MAX) == NULL) { - msg("get cwd fail, errno: %d, %s", errno, strerror(errno)); - return 1; - } - - strncpy(g_tst_tc_control->tst_tc_cwd, g_tst_tc_control->tc_exec_path, PATH_MAX); - dirname(g_tst_tc_control->tst_tc_cwd); - - g_tst_tc_control->tst_tc_pid = getpid(); - g_tst_tc_control->tc_stat = TST_INIT; - - // 尝试获取TST_TS_TOPDIR - strncpy(g_tst_tc_control->tst_ts_topdir, g_tst_tc_control->tc_exec_path, PATH_MAX); - char path_tst_common[PATH_MAX]; - char path_cmd[PATH_MAX]; - char path_testcase[PATH_MAX]; - char path_tsuite[PATH_MAX]; - while (g_tst_tc_control->tst_ts_topdir[1] != '\0') { - snprintf(path_tst_common, PATH_MAX, "%s/tst_common", g_tst_tc_control->tst_ts_topdir); - snprintf(path_cmd, PATH_MAX, "%s/cmd", g_tst_tc_control->tst_ts_topdir); - snprintf(path_testcase, PATH_MAX, "%s/testcase", g_tst_tc_control->tst_ts_topdir); - snprintf(path_tsuite, PATH_MAX, "%s/tsuite", g_tst_tc_control->tst_ts_topdir); - if (is_dir(path_cmd) && is_dir(path_testcase) && is_file(path_tsuite)) { - if (is_dir(path_tst_common)) { - strncpy(g_tst_tc_control->tst_common_topdir, path_tst_common, PATH_MAX); - } else { - strncpy(g_tst_tc_control->tst_common_topdir, g_tst_tc_control->tst_ts_topdir, PATH_MAX); - } - break; - } - if (g_tst_tc_control->tst_ts_topdir[1] == '\0') { - memset(g_tst_tc_control->tst_ts_topdir, 0, PATH_MAX); - memset(g_tst_tc_control->tst_common_topdir, 0, PATH_MAX); - break; - } - dirname(g_tst_tc_control->tst_ts_topdir); - } - // TST_TS_TOPDIR成功获取后,TST_TS_SYSDIR和TST_TC_SYSDIR可以生成了 - if (g_tst_tc_control->tst_ts_topdir[0] != '\0') { - snprintf(g_tst_tc_control->tst_ts_sysdir, PATH_MAX, "%s/logs/.ts.sysdir", g_tst_tc_control->tst_ts_topdir); - snprintf(g_tst_tc_control->tst_tc_sysdir, PATH_MAX, "%s/logs/testcase/.tc.%d.sysdir", - g_tst_tc_control->tst_ts_topdir, g_tst_tc_control->tst_tc_pid); - snprintf(g_tst_tc_control->tst_ts_setup_stat, PATH_MAX, "%s/ts.setup.stat", g_tst_tc_control->tst_ts_sysdir); - } - - return 0; -} - -int tst_main(int argc, char **argv) { - int ret = 0; - - if (_tc_init(argc, argv) != 0) { - return 1; - } - if (chdir(g_tst_tc_control->tst_tc_cwd) != 0) { - msg("chdir to %s fail, errno: %d, %s", g_tst_tc_control->tst_tc_cwd, errno, strerror(errno)); - return 1; - } - - if (_is_ts_setup_called()) { - msg("tsuite setup executed, stat is %d", _get_ts_setup_stat()); - } else { - msg("tsuite setup may not executed"); - } - - _set_tcstat(TST_INIT); - - if (_tc_setup_common(argc, argv) == 0) { - if (_tc_setup(argc, argv) == 0) { - msg("call _tc_setup success"); - if (_do_test(argc, argv) == 0) { - msg("call _do_test success"); - } else { - err("call _do_test fail"); - ret = 1; - } - } else { - err("call _tc_setup success"); - ret = 1; - } - } else { - err("call _tc_setup_common success"); - ret = 1; - } - - _tc_run_complete(argc, argv); - - return ret; -} diff --git a/coreutils/tst_common/lib/common.h b/coreutils/tst_common/lib/common.h deleted file mode 100644 index c9d6264..0000000 --- a/coreutils/tst_common/lib/common.h +++ /dev/null @@ -1,139 +0,0 @@ -#ifndef __COMMON_H__ -#define __COMMON_H__ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "benchmark.h" - -#define TST_PASS 0 -#define TST_FAIL 1 -#define TST_INIT 2 -#define TST_SKIP 3 - -#ifndef MAX_LOG_LEN -#define MAX_LOG_LEN 4096 -#endif /* MAX_LOG_LEN */ -#ifndef MAX_CMD_LEN -#define MAX_CMD_LEN 4096 -#endif /* MAX_CMD_LEN */ - -#ifndef PAGE_SHIFT -#define PAGE_SHIFT 12 -#endif /* PAGE_SHIFT */ -#ifndef PAGE_SIZE -#define PAGE_SIZE (1UL << PAGE_SHIFT) -#endif /* PAGE_SIZE */ -#ifndef PAGE_MASK -#define PAGE_MASK (~(PAGE_SIZE-1)) -#endif /* PAGE_MASK */ - -#define KB (1024) -#define MB (KB * KB) -#define GB (MB * KB) - -extern int _print(const char *format, ...); - -#define min(a, b) ((a) > (b) ? (b) : (a)) -#define max(a, b) ((a) < (b) ? (b) : (a)) - -#define dbg(format, ...) _print(format, ##__VA_ARGS__) -#define msg(format, ...) _print(format, ##__VA_ARGS__) -#define err(format, ...) \ - do{ \ - _tc_fail(); \ - _print("%s:%d %s: " format, __FILE__, __LINE__, __FUNCTION__, ##__VA_ARGS__); \ - }while(0) - -extern void _skip_test(const char *message, const char *file, int line, const char *func); - -#define skip_test(message) _skip_test(message, __FILE__, __LINE__, __FUNCTION__) - -#define skip_if_true(expr) \ - do{ \ - if(expr){ \ - skip_test("skip_if_true " #expr); \ - } \ - }while(0) - -#define skip_if_false(expr) \ - do{ \ - if(!(expr)){ \ - skip_test("skip_if_false " #expr); \ - } \ - }while(0) - -extern void _tc_pass(void); - -extern void _tc_fail(void); - -extern void _tst_assert(const char *expr, const char *file, int line, const char *func); - -// 功能:断言表达式返回真 -// 参数: -// expr -- 表达式 -// 返回值:无 -#define assert_true(expr) \ - do{ \ - if(expr){ \ - _tc_pass(); \ - }else{ \ - _tc_fail(); \ - _tst_assert(#expr, __FILE__, __LINE__, __FUNCTION__); \ - } \ - }while(0) - -// 功能:断言表达式返回假 -// 参数: -// expr -- 表达式 -// 返回值:无 -#define assert_false(expr) \ - do{ \ - if(!(expr)){ \ - _tc_pass(); \ - }else{ \ - _tc_fail(); \ - _tst_assert(#expr, __FILE__, __LINE__, __FUNCTION__); \ - } \ - }while(0) - - -extern void show_tc_control(void); - -extern int is_file(const char *path); - -extern int is_dir(const char *path); - -extern int is_exist(const char *path); - -extern size_t read_line(const char *path, int line, char *buff, size_t size); - -extern size_t read_file(const char *path, char *buff, size_t size); - -extern int mkdirs(const char *dir, mode_t mode); - -extern int command(const char *command_format, ...); - -extern int tc_setup_common(int argc, char **argv) __attribute__((weak)); - -extern int tc_setup(int argc, char **argv) __attribute__((weak)); - -extern int do_test(int argc, char **argv) __attribute__((weak)); - -extern int tc_teardown(int argc, char **argv) __attribute__((weak)); - -extern int tc_teardown_common(int argc, char **argv) __attribute__((weak)); - -#endif // __COMMON_H__ diff --git a/coreutils/tst_common/lib/common.py b/coreutils/tst_common/lib/common.py deleted file mode 100644 index d9a1b97..0000000 --- a/coreutils/tst_common/lib/common.py +++ /dev/null @@ -1,755 +0,0 @@ -#!/usr/bin/env python3 -# coding: utf-8 -# Time: 2022-04-19 22:26:42 -# Desc: Python用例公共模块 - -import abc -import getpass -import os -import platform -import re -import shutil -import socket -import subprocess -import sys -import tempfile -import time -import traceback -import __main__ as main - -TST_PASS = 0 -TST_FAIL = 1 -TST_INIT = 2 -TST_SKIP = 3 -tst_tc_stat_dict = { - TST_PASS: 'TST_PASS', - TST_FAIL: 'TST_FAIL', - TST_INIT: 'TST_INIT', - TST_SKIP: 'TST_SKIP', -} - - -def command(cmd, timeout=20): - proc = subprocess.Popen(cmd, shell=True, encoding='utf-8') - try: - proc.communicate(timeout=timeout) - except subprocess.TimeoutExpired: - proc.kill() - return proc.wait() - - -def command_output(cmd, timeout=20): - proc = subprocess.Popen(cmd, shell=True, encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.PIPE) - outs = "" - errs = "" - try: - outs, errs = proc.communicate(timeout=timeout) - except subprocess.TimeoutExpired: - proc.kill() - code = proc.wait() - return outs, errs, code - - -def command_quiet(cmd, timeout=20): - proc = subprocess.Popen(cmd, shell=True, encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.PIPE) - try: - proc.communicate(timeout=timeout) - except subprocess.TimeoutExpired: - proc.kill() - code = proc.wait() - return code - - -def get_yum_provide(filename): - outs, errs, code = command_output(f'yum provides {filename}') - print(f'stdout:\n{outs}') - print(f'stderr:\n{errs}') - print(f'status: {code}') - if code != 0 or outs is None: - return None - for line in outs.splitlines(): - match = re.match(r'^([-\w.]+)-\d(\.\d+)+-.* : ', line) - if match: - package = match.groups()[0] - print(f'get file {filename} provide: {package}') - return package - return None - - -def try_install_command(cmd, package=None): - if command_quiet(f'which {cmd}') == 0: - return True - if package is None: - package = get_yum_provide(cmd) - if package is not None: - command(f'yum install -y {package}') - if command(f'which {cmd}') == 0: - return True - return False - - -def get_kernel_release(): - return platform.release() - - -def get_system_boot_time(): - with open('/proc/uptime', 'r') as f: - uptime = float(f.readline().split()[0]) - now_time = time.time() - boot_time = now_time - uptime - result = boot_time - - tsuite_tmpdir = os.path.join('/tmp', f'.tsuite-{getpass.getuser()}') - if not os.path.exists(tsuite_tmpdir): - os.makedirs(tsuite_tmpdir, mode=0o755, exist_ok=True) - boot_time_file = os.path.join(tsuite_tmpdir, 'boot-time') - if os.path.exists(boot_time_file): - # 如果系统启动的时间已经有记录,那么看看是否同一次启动 - with open(boot_time_file, 'r') as f: - old_boot_time = float(f.readline()) - # 如果记录的时间和当前计算的时间差别不大,那么就认为是同一次启动 - if abs(old_boot_time - boot_time) <= 10: - result = old_boot_time - else: - with open(boot_time_file, 'w') as f: - f.write(f'{boot_time}') - else: - with open(boot_time_file, 'w') as f: - f.write(f'{boot_time}') - return 'boot-time.' + time.strftime('%Y%m%d-%H%M%S', time.localtime(result)) - - -def get_os_release(): - release = None - if os.path.isfile('/etc/os-release'): - with open('/etc/os-release', 'r') as f: - for line in f.readlines(): - if re.match(r'PRETTY_NAME=', line, re.IGNORECASE): - release = re.sub(r'[^\w.]+', '-', line.split('=')[1].strip()) - if os.path.isfile('/etc/tencentos-release'): - with open('/etc/tencentos-release', 'r') as f: - for line in f.readlines(): - if re.match(r'TencentOS', line, re.IGNORECASE): - release = re.sub(r'[^\w.]+', '-', line.strip()) - if os.path.isfile('/etc/motd'): - with open('/etc/motd', 'r') as f: - for line in f.readlines(): - if re.match(r'version', line, re.IGNORECASE): - release = re.sub(r'[^\w.]+', '-', line.strip()) - if re.match(r'tlinux', line, re.IGNORECASE): - release = re.sub(r'[^\w.]+', '-', line.strip()) - if release is None: - return 'Unknown-Linux' - return release.strip('-') - - -def get_tst_test_env_ip(): - outs, _, _ = command_output('ifconfig eth1') - eth1_ip = get_ip_of_ifconfig(outs) - # 测试环境的eth1都是192.168.x.x - if (eth1_ip is None) or (not eth1_ip.startswith('192.168.')): - return None - env_main_ip_1 = re.sub(r'\.\d{1,3}$', '.11', eth1_ip) - # 获取测试环境主环境的IP - outs, _, _ = command_output(f'ssh root@{env_main_ip_1} ifconfig eth0', timeout=3) - env_main_ip_0 = get_ip_of_ifconfig(outs) - if env_main_ip_0 is None: - return None - return [env_main_ip_0, eth1_ip] - - -def get_ip_of_ifconfig(ifconfig_outs: str): - if ifconfig_outs is None: - return None - if not isinstance(ifconfig_outs, str): - return None - for line in ifconfig_outs.splitlines(): - if 'netmask' not in line: - continue - return re.search(r'\b(?:\d{1,3}\.){3}\d{1,3}\b', line).group() - return None - - -def get_host_ip(): - """ - 这个方法是目前见过最优雅获取本机服务器的IP方法了。没有任何的依赖,也没有去猜测机器上的网络设备信息。 - 而且是利用 UDP 协议来实现的,生成一个UDP包,把自己的 IP 放如到 UDP 协议头中,然后从UDP包中获取本机的IP。 - 这个方法并不会真实的向外部发包,所以用抓包工具是看不到的。但是会申请一个 UDP 的端口,所以如果经常调用也会比较耗时的, - 这里如果需要可以将查询到的IP给缓存起来,性能可以获得很大提升。 - - 作者:钟翦 - 链接:https://www.zhihu.com/question/49036683/answer/1243217025 - 来源:知乎 - 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 - - :return: - """ - _local_ip = None - s = None - try: - if not _local_ip: - s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - s.connect(('8.8.8.8', 80)) - _local_ip = s.getsockname()[0] - return _local_ip - finally: - if s: - s.close() - - -def command_to_filename(cmd: str): - return re.sub(r'\W+', '.', cmd) + '.txt' - - -def get_commands_logs(cmd_list, logs_dir, timeout=60): - start_time = time.time() - exec_list = list() - index = 1 - for cmd in cmd_list: - # print(f'{index} execute command: {cmd}') - cmd_dict = { - 'index': index, - 'command': cmd, - 'timeout': timeout, - 'start_time': time.time(), - 'proc': subprocess.Popen(cmd, shell=True, encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.PIPE), - 'log_file': os.path.join(os.path.realpath(logs_dir), command_to_filename(cmd)), - 'end_time': None, - 'cost': None, - 'stdout': None, - 'stderr': None, - 'status': None - } - exec_list.append(cmd_dict) - index += 1 - - # 检查命令是否执行完 - while True: - all_command_ok = True - if time.time() - start_time > timeout: - break - for proc_dict in exec_list: - if proc_dict['status'] is not None: - continue - try: - proc_dict['stdout'], proc_dict['stderr'] = proc_dict['proc'].communicate(timeout=1) - except subprocess.TimeoutExpired: - all_command_ok = False - continue - proc_dict['status'] = proc_dict['proc'].returncode - proc_dict['end_time'] = time.time() - proc_dict['cost'] = proc_dict['end_time'] - proc_dict['start_time'] - # print(f'{proc_dict["index"]} command {proc_dict["command"]} end, status {proc_dict["status"]}') - if all_command_ok: - break - - # 记录命令执行结果,还没有结束的命令直接终止 - for proc_dict in exec_list: - if proc_dict['status'] is None: - proc_dict['proc'].kill() - proc_dict['stdout'], proc_dict['stderr'] = proc_dict['proc'].communicate(timeout=1) - proc_dict['status'] = proc_dict['proc'].returncode - proc_dict['end_time'] = time.time() - proc_dict['cost'] = proc_dict['end_time'] - proc_dict['start_time'] - print(f'{proc_dict["index"]} command {proc_dict["command"]} killed, status {proc_dict["status"]}') - with open(file=proc_dict['log_file'], mode='a', buffering=1, encoding='utf-8') as f: - f.write('=' * 60 + '\n') - f.write(f'### command: {proc_dict["command"]}\n') - f.write(f'### timeout: {proc_dict["timeout"]}\n') - f.write(f'### start_time: ' - f'{time.strftime("%Y-%m-%d %H:%M:%S %z", time.localtime(proc_dict["start_time"]))}\n') - f.write(f'### end_time: ' - f'{time.strftime("%Y-%m-%d %H:%M:%S %z", time.localtime(proc_dict["end_time"]))}\n') - f.write(f'### cost: {proc_dict["cost"]}\n') - f.write(f'### log_file: {proc_dict["log_file"]}\n') - f.write(f'### status: {proc_dict["status"]}\n') - f.write('=' * 60 + '\n') - f.write('### stdout:\n') - f.write(proc_dict["stdout"]) - f.write('=' * 60 + '\n') - f.write('### stderr:\n') - f.write(proc_dict["stderr"]) - f.write('=' * 60 + '\n') - print(f'### all command cost {time.time() - start_time}') - - -def sysinfo(log_dir, install_command=False, merge_files=True): - command_list = [ - "uname -a", - "ulimit -a", - "lscpu", - "lspci", - "lspci -k", - "lspci -vv", - "lspci -t -vv -nn", - "lsscsi", - "lsscsi --list --verbose --long", - "lsusb", - "lsusb --tree", - "lshw -short", - "lsmod", - "route -n", - "ifconfig -a", - "dmidecode", - "udevadm info --export-db", - "ipmitool sdr", - "ipmitool fru", - "ipmitool sensor", - "ipmitool sel", - "fdisk -l", - "mount", - "df -P", - "lsblk", - "lsblk -O", - "smartctl --scan" - "free", - "numastat -v", - "numastat -v -m", - "cpupower --cpu all frequency-info", - "cpupower --cpu all idle-info", - "sysctl -a", - "cat /etc/os-release", - "cat /etc/system-release", - "cat /etc/centos-release", - "cat /etc/redhat-release", - "cat /etc/system-release", - "cat /etc/tencentos-release", - "cat /etc/tlinux-release", - "cat /proc/cpuinfo", - "cat /proc/meminfo", - "cat /proc/buddyinfo", - "cat /proc/devices", - "cat /proc/interrupts", - "cat /proc/iomem", - "cat /proc/ioports", - "cat /proc/modules", - "cat /proc/module_md5_list", - "zcat /proc/config.gz", - "zcat /proc/bt_stat", - "zcat /proc/cgroups", - "zcat /proc/cmdline", - "zcat /proc/consoles", - "zcat /proc/crypto", - "zcat /proc/devices", - "zcat /proc/diskstats", - "zcat /proc/dma", - "zcat /proc/execdomains", - "zcat /proc/filesystems", - "zcat /proc/kallsyms", - "zcat /proc/loadavg", - "zcat /proc/loadavg_bt", - "zcat /proc/locks", - "zcat /proc/mdstat", - "zcat /proc/misc", - "zcat /proc/mtrr", - "zcat /proc/partitions", - "zcat /proc/sched_debug", - "zcat /proc/schedstat", - "zcat /proc/slabinfo", - "zcat /proc/softirqs", - "zcat /proc/stat", - "zcat /proc/swaps", - "zcat /proc/timer_list", - "zcat /proc/uptime", - "zcat /proc/version", - "zcat /proc/vmallocinfo", - "zcat /proc/vmstat", - "zcat /proc/zoneinfo", - "dmesg" - ] - if os.path.isfile('/proc/net/dev'): - with open(file='/proc/net/dev', mode='r') as f: - for line in f.readlines(): - if ':' not in line: - continue - dev = line.split(':')[0].strip() - command_list.append(f'ethtool {dev}') - command_list.append(f'ethtool -i {dev}') - if os.path.isfile('/proc/modules'): - with open(file='/proc/modules', mode='r') as f: - for line in f.readlines(): - module = line.split()[0].strip() - command_list.append(f'modinfo {module}') - outs, _, _ = command_output('smartctl --scan') - if outs: - for line in outs.splitlines(): - dev = line.split()[0].strip() - command_list.append(f'smartctl --xall {dev}') - command_list.append(f'hdparm {dev}') - - # 尝试安装命令 - if install_command: - for cmd in set([c.split()[0] for c in command_list]): - try_install_command(cmd) - - if not os.path.exists(log_dir): - os.makedirs(log_dir, mode=0o755, exist_ok=True) - get_commands_logs(command_list, log_dir) - # 将多个日志文本文件合并成一个文件 - if merge_files: - tmp_file = tempfile.mkstemp()[1] - with open(tmp_file, 'w') as f: - for txt_file in os.listdir(log_dir): - txt_path = os.path.join(log_dir, txt_file) - with open(txt_path, 'r') as tf: - f.write(tf.read()) - os.remove(txt_path) - shutil.move(tmp_file, os.path.join(log_dir, 'sysinfo.txt')) - - -def get_crash_path(): - result = None - if not os.path.exists('/etc/kdump.conf'): - return result - with open('/etc/kdump.conf', 'r') as f: - for line in f.readlines(): - if line.startswith('path '): - result = line.split()[1] - return result - - -def safe_repr(obj, short=False): - max_len = 120 - try: - result = repr(obj) - except Exception: - result = object.__repr__(obj) - if not short or len(result) < max_len: - return result - return result[:max_len] + ' [truncated]...' - - -def set_env(env, value): - if os.environ.get(env): - print(f"the env {env} has value {os.environ.get(env)}, don't set to {value}") - return - os.environ[env] = f"{value}" - - -def set_env_force(env, value): - if os.environ.get(env): - print(f"the env {env} has value {os.environ.get(env)}, now set to {value}") - os.environ[env] = value - - -def get_env(env): - return os.environ.get(env) - - -def get_env_default(env, default): - return os.environ.get(env, default) - - -def _is_main_process(): - return int(get_env_default('TST_TC_PID', '0')) == os.getpid() - - -class ExceptionSkip(Exception): - def __init__(self, message=""): - super(ExceptionSkip, self).__init__(self) - self.message = f'{message}' - - def __str__(self): - return self.message - - -def tcstat_to_str(tcstat): - tst_tc_stat_dict.get(tcstat, 'UNKNOWN') - - -class TestCase: - def __init__(self, *args): - # 用例文件路径 - self.tc_path = os.path.realpath(main.__file__) - # 用例名 - self.tc_name = self._get_tc_attr('用例名称') - # 执行用例文件时的目录 - self.exec_cwd = os.getcwd() - # TST_TC_CWD 测试用例CWD - self.tst_tc_cwd = os.path.dirname(self.tc_path) - set_env('TST_TC_CWD', self.tst_tc_cwd) - # TST_TC_PID 测试用例主进程pid - self.tst_tc_pid = os.getpid() - set_env('TST_TC_PID', self.tst_tc_pid) - # 用例执行状态 - self._tcstat = TST_INIT - # 用例退出码,0表示用例PASS或SKIP,其他表示异常 - self._exit_code = 0 - # TST_TS_TOPDIR 测试套顶层目录 - self.tst_ts_topdir = self._get_ts_topdir() - set_env('TST_TS_TOPDIR', self.tst_ts_topdir) - # TST_COMMON_TOPDIR common顶层目录 - self.tst_common_topdir = self._get_common_topdir() - set_env('TST_COMMON_TOPDIR', self.tst_common_topdir) - # 标记tc_setup是否被调用 - self._tc_setup_called = False - # TST_TS_SYSDIR 测试套公共运行目录 - self.tst_ts_sysdir = None if self.tst_ts_topdir is None \ - else os.path.join(self.tst_ts_topdir, 'logs', '.ts.sysdir') - set_env('TST_TS_SYSDIR', self.tst_ts_sysdir) - # TST_TC_SYSDIR 测试用例管理用临时目录 - self.tst_tc_sysdir = None if self.tst_ts_topdir is None \ - else os.path.join(self.tst_ts_topdir, 'logs', 'testcase', f'.tc.{self.tst_tc_pid}.sysdir') - set_env('TST_TC_SYSDIR', self.tst_tc_sysdir) - - def dbg(self, message): - print(message, file=sys.stderr) - - def msg(self, message): - print(message, file=sys.stderr) - - def err(self, message): - print(message, file=sys.stderr) - self._fail(message) - - def _get_tc_attr(self, attr): - with open(file=self.tc_path, mode='r', encoding='utf-8') as f: - for line in f.readlines(): - if f"@{attr}:" not in line: - continue - return re.sub(f'.*@{attr}:', '', line).strip() - return None - - def _get_ts_topdir(self): - result = self.tst_tc_cwd - while True: - if os.path.isdir(os.path.join(result, 'cmd')) and os.path.isdir(os.path.join(result, 'testcase')) and \ - os.path.isfile(os.path.join(result, 'tsuite')): - if os.path.isdir(os.path.join(result, '..', 'tst_common')): - return os.path.dirname(result) - return result - next_path = os.path.dirname(result) - if next_path == result: - return None - result = next_path - - def _get_common_topdir(self): - if self.tst_ts_topdir is None: - return None - if os.path.isdir(os.path.join(self.tst_ts_topdir, 'tst_common')): - return os.path.join(self.tst_ts_topdir, 'tst_common') - return self.tst_ts_topdir - - def _set_tcstat(self, stat): - self._tcstat = stat - - def _get_tcstat(self): - return self._tcstat - - def _get_tcstat_str(self): - return tcstat_to_str(self._tcstat) - - def _fail(self, message=None): - if self._tcstat != TST_FAIL: - self.msg("the testcase first fail here") - self._set_tcstat(TST_FAIL) - raise AssertionError(message) - - def _pass(self): - if self._get_tcstat() == TST_INIT: - self._set_tcstat(TST_PASS) - - def skip_test(self, message=None): - """ - 标记用例为SKIP状态(当用例不需要测试时) - :param message: 要输出的信息 - :return: None - 示例: - skip_test(message='内核CONFIG_XXX未开,系统不支持此测试') - """ - if self._get_tcstat() in (TST_PASS, TST_INIT, TST_SKIP): - self._set_tcstat(TST_SKIP) - raise ExceptionSkip(f'set testcase SKIP: {message}') - else: - self.msg(f'set testcase SKIP fail: {message}') - self._fail(f'the testcase stat is {self._get_tcstat_str()}, can\'t set to SKIP') - - def skip_if_true(self, expr, message=None): - """ - 当表达式返回真或命令执行成功时,用例不满足测试条件,终止测试 - :param expr: 要判断的表达式 - :param message: 要输出的信息 - :return: None - 示例: - skip_if_true(1 == 2) - """ - if expr: - self.skip_test(f'skip_if_true -> {safe_repr(expr)}: {message}') - - def skip_if_false(self, expr, message=None): - """ - 当表达式返回假或命令执行失败,用例不满足测试条件,终止测试 - :param expr: 要判断的表达式 - :param message: 要输出的信息 - :return: None - 示例: - skip_if_false(1 == 2) - """ - if not expr: - self.skip_test(f'skip_if_false -> {safe_repr(expr)}: {message}') - - def assert_true(self, expr, message=None): - """ - 断言表达式返回真 - :param expr: 要断言的表达式 - :param message: 断言要输出的信息 - :return: None - 示例: - assert_true(1 == 2) - assert_true(a >= b) - """ - if not expr: - self.msg(f"{safe_repr(expr)} is not true: {message}") - self._fail(message) - else: - self._pass() - - def assert_false(self, expr, message=None): - """ - 断言表达式返回假 - :param expr: 要断言的表达式 - :param message: 断言要输出的信息 - :return: None - 示例: - assert_false(1 == 2) - assert_false(a >= b) - """ - if expr: - self.msg(f"{safe_repr(expr)} is not false: {message}") - self._fail(message) - else: - self._pass() - - def _tc_setup_common(self, *args): - # 只有用例的主进程才能执行此函数 - if not _is_main_process(): - return None - try: - self.tc_setup_common(*args) - except Exception: - raise - - def tc_setup_common(self, *args): - self.msg("this is TestCase.tc_setup_common") - - def _tc_setup(self, *args): - # 只有用例的主进程才能执行此函数 - if not _is_main_process(): - return None - try: - self._tc_setup_called = True - self.tc_setup(*args) - except Exception: - raise - - def tc_setup(self, *args): - self.msg("this is TestCase.tc_setup") - - def _do_test(self, *args): - # 只有用例的主进程才能执行此函数 - if not _is_main_process(): - return None - try: - self.do_test(*args) - except Exception: - raise - - @abc.abstractmethod - def do_test(self, *args): - self.msg("this is TestCase.do_test") - - def _tc_teardown(self, *args): - # 只有用例的主进程才能执行此函数 - if not _is_main_process(): - return None - try: - self.tc_teardown(*args) - except Exception: - raise - - def tc_teardown(self, *args): - self.msg("this is TestCase.tc_teardown") - - def _tc_teardown_common(self, *args): - # 只有用例的主进程才能执行此函数 - if not _is_main_process(): - return None - try: - self.tc_teardown_common(*args) - except Exception: - raise - - def tc_teardown_common(self, *args): - self.msg("this is TestCase.tc_teardown_common") - - def _is_ts_setup_called(self): - if self.tst_ts_sysdir: - return os.path.isfile(os.path.join(self.tst_ts_sysdir, 'ts.setup.stat')) - else: - return False - - def _get_ts_setup_stat(self): - if self.tst_ts_sysdir: - ts_stat_file = os.path.join(self.tst_ts_sysdir, 'ts.setup.stat') - if not os.path.isfile(ts_stat_file): - return None - with open(file=ts_stat_file, mode='r', encoding='utf-8') as f: - line = f.readline() - return int(line) - else: - return None - - def tst_main(self, *args): - time_start = int(time.monotonic() * 1000000000) - if self._is_ts_setup_called(): - self.msg(f"tsuite setup executed, stat is {self._get_ts_setup_stat()}") - else: - self.msg("tsuite setup may not executed") - - try: - self._tc_setup_common(*args) - self.msg("call _tc_setup_common success") - self._tc_setup(*args) - self.msg("call _tc_setup success") - self._do_test(*args) - self.msg("call _do_test success") - except ExceptionSkip as e: - self._set_tcstat(TST_SKIP) - self.msg(e.message) - except Exception: - self._set_tcstat(TST_FAIL) - self.msg(traceback.format_exc()) - finally: - try: - if self._tc_setup_called: - self._tc_teardown(*args) - else: - self.msg("the tc_setup not called, so tc_teardown ignore") - self._tc_teardown_common(*args) - except ExceptionSkip as e: - self._set_tcstat(TST_SKIP) - self.msg(e.message) - except Exception: - self._set_tcstat(TST_FAIL) - self.msg(traceback.format_exc()) - - # TCase自动化执行框架需要用这个输出判断用例是否支持完 - self.msg("Global test environment tear-down") - if self._get_tcstat() == TST_PASS: - self.msg(f"RESULT : {self.tc_name} ==> [ PASSED ]") - self._exit_code = 0 - elif self._get_tcstat() == TST_FAIL: - self.msg(f"RESULT : {self.tc_name} ==> [ FAILED ]") - self._exit_code = 1 - elif self._get_tcstat() == TST_INIT: - self.msg(f"RESULT : {self.tc_name} ==> [ NOTEST ]") - self._exit_code = 1 - elif self._get_tcstat() == TST_SKIP: - self.msg(f"RESULT : {self.tc_name} ==> [ SKIP ]") - self._exit_code = 0 - else: - self.msg(f"RESULT : {self.tc_name} ==> [ UNKNOWN ]") - self._exit_code = 1 - time_end = int(time.monotonic() * 1000000000) - self.msg(f'cost {(time_end - time_start) / 1000000000:.9f}') - exit(self._exit_code) diff --git a/coreutils/tst_common/lib/common.sh b/coreutils/tst_common/lib/common.sh deleted file mode 100644 index 3c6baaa..0000000 --- a/coreutils/tst_common/lib/common.sh +++ /dev/null @@ -1,734 +0,0 @@ -#!/bin/bash -# 所有shell脚本的测试用例都应该source此文件 -# 约定: -# 1、以下划线"_"开头的函数和变量用例不能直接调用 -# 2、环境变量全大写,全局变量加上"g_"前置,局部变量统一加"local"修饰 - -export LANG="en_US.UTF-8" -export LANGUAGE="en_US:en" - -if [ -d "$TST_TS_TOPDIR/tst_common" ]; then - export TST_COMMON_TOPDIR="$TST_TS_TOPDIR/tst_common" - # 先source测试用例自定义的公共文件 - source "$TST_TS_TOPDIR/tst_lib/ts_common.sh" || exit 1 - # 再source全局公共文件 - source "$TST_COMMON_TOPDIR/lib/common_func.sh" || exit 1 -elif [ -d "$TST_TS_TOPDIR/lib" ]; then - export TST_COMMON_TOPDIR="$TST_TS_TOPDIR" - # 只是tst_suite_common使用 - source "$TST_TS_TOPDIR/lib/common_func.sh" || exit 1 -else - echo "can't find the tsuite common file" - exit 1 -fi - -# 环境变量 -# TST_TS_TOPDIR 测试套顶层目录 -# TST_TS_SYSDIR 测试套公共运行目录 -[ -z "$TST_TS_SYSDIR" ] && export TST_TS_SYSDIR="$TST_TS_TOPDIR/logs/.ts.sysdir" -# TST_TC_SYSDIR 测试用例管理用临时目录 -# TST_TC_CWD 测试用例CWD -# TST_TC_PID 测试用例主进程pid -# 下面几个为用例结果状态 -export TST_PASS=0 -export TST_FAIL=1 -export TST_INIT=2 -export TST_SKIP=3 -# TST_TC_NAME 用例名称 -# TST_TC_FILE 用例文件 -# TST_VM_SUBNET 虚拟机子网 -if [ -z "$TST_VM_SUBNET" ]; then - TST_VM_SUBNET=$(ifconfig eth0 2>/dev/null | grep "netmask .* broadcast 192\.168\." | awk '{print $2}') - [ -z "$TST_VM_SUBNET" ] && TST_VM_SUBNET=$(ifconfig eth1 2>/dev/null | grep "netmask .* broadcast 192\.168\." | awk '{print $2}') - [ -z "$TST_VM_SUBNET" ] && TST_VM_SUBNET=$(ifconfig eth2 2>/dev/null | grep "netmask .* broadcast 192\.168\." | awk '{print $2}') - TST_VM_SUBNET=${TST_VM_SUBNET%.*} -fi -export TST_VM_SUBNET - -g_tst_case_start=$(get_up_time_ms) -g_tst_trap_signal=12 - -_tcstat_to_str() { - case "$1" in - "TST_PASS" | "$TST_PASS") - echo "TST_PASS" - ;; - "TST_FAIL" | "$TST_FAIL") - echo "TST_FAIL" - ;; - "TST_INIT" | "$TST_INIT") - echo "TST_INIT" - ;; - "TST_SKIP" | "$TST_SKIP") - echo "TST_SKIP" - ;; - *) - echo "TST_UNKNOWN" - ;; - esac -} - -# 获取用例属性 -# $1 -- 用例属性名称,例如:用例ID、用例名称 -_get_case_attr() { - grep "@${1}:" "$TST_TC_FILE_FULL" | head -n 1 | sed "s|.*@${1}:\s*||g" | sed "s|\s*$||g" -} -_get_case_preconditions() { - grep "@预置条件:" "$TST_TC_FILE_FULL" -} -_get_case_steps() { - grep "@测试步骤:" "$TST_TC_FILE_FULL" -} -_get_case_expect() { - grep "@预期结果:" "$TST_TC_FILE_FULL" -} - -# 功能:设置环境变量 -# 参数: -# $1 -- 环境变量名 -# $2 -- 环境变量值 -# 返回值: -# 0 -- 环境变量设置成功 -# 1 -- 环境变量设置失败 -setup_env_var() { - local _tst_var_name="$1" - local _tst_old_value - eval _tst_old_value=\"\$"${1}"\" - local _tst_new_value="$2" - - if ! echo "$_tst_var_name" | grep "^[A-Z_]\+$" >/dev/null; then - msg "the var name must be upper and '_'" - return 1 - fi - [ -n "$_tst_old_value" ] && msg "the environment variable $_tst_var_name has old value: $_tst_old_value" - eval export "$_tst_var_name"=\""$_tst_new_value"\" - echo "export $_tst_var_name=\"$_tst_new_value\"" >>"$TST_TS_SYSDIR/environment_variable" - return 0 -} - -# 功能:将K/M/G/T等单位互相转换 -# 参数:wait_proc_exit -p pid [-t timeout] [-s signal] -# -p pid 【必选参数】进程pid -# -t timeout 【可选参数】等待超时时间(单位:秒,不指定时默认等待60秒),如果等待超时进程仍未退出则返回失败 -# -s signal 【可选参数】必须配合-t参数使用,超时时间到期后发送-s指定信号到进程 -# 返回值: -# 0 -- 进程退出 -# 1 -- 等待失败 -wait_proc_exit() { - local _tst_all_args="$*" - local _tst_pid - local _tst_timeout - local _tst_signal - while [ $# -gt 0 ]; do - case "$1" in - "-p") - shift - _tst_pid="$1" - shift - ;; - "-t") - shift - _tst_timeout="$1" - shift - ;; - "-s") - shift - _tst_signal="$1" - shift - ;; - *) - msg "unknown args $1 in $_tst_all_args" - return 1 - ;; - esac - done - if [ -z "$_tst_pid" ]; then - msg "pid not set" - return 1 - fi - [ -z "$_tst_timeout" ] && _tst_timeout=60 - - local _tst_time_start - _tst_time_start="$(get_uptime)" - local _tst_time_now - _tst_time_now="$(get_uptime)" - while [ $((_tst_time_start + _tst_timeout)) -gt "$_tst_time_now" ]; do - [ -d "/proc/$_tst_pid" ] || return 0 - sleep 1 - _tst_time_now="$(get_uptime)" - done - [ -n "$_tst_signal" ] && kill -s "$_tst_signal" "$_tst_pid" - sleep 1 - [ -d "/proc/$_tst_pid" ] || return 0 - return 1 -} - -# 功能:获取系统启动后到现在的时间,单位:秒 -# 参数:无 -# 返回值:标准输出时间 -get_uptime() { - awk -F . '{print $1}' /proc/uptime -} - -# 功能:将K/M/G/T等单位互相转换 -# 参数:conv_unit [-i k|m|g|t] [-o k|m|g|t] value[_with_unit] -# -i k|m|g|t 【可选参数】输入数据的单位,可选参数,若不指定单位,则默认为1,或者输入的值后面带参数 -# -o k|m|g|t 【可选参数】输出数据的单位,若不指定单位,则默认为1 -# value[_with_unit] 【必选参数】需要转换的数据值,可以跟单位(只取单位第一个字母用于判断k|m|g|t) -# 返回值:标准输出转换后的结果 -# 0 -- 转换成功 -# 1 -- 转换失败 -conv_unit() { - local _tst_input_all - local _tst_input_value - local _tst_input_unit - local _tst_output_value - local _tst_output_unit - while [ $# -gt 0 ]; do - case "$1" in - "-i") - shift - _tst_input_unit="$1" - shift - ;; - "-o") - shift - _tst_output_unit="$1" - shift - ;; - *) - _tst_input_all="$_tst_input_all $1" - shift - ;; - esac - done - # shellcheck disable=SC2001 - _tst_input_value=$(echo "$_tst_input_all" | sed "s|^[[:blank:]]*\([0-9]\+\)[[:blank:]]*\(.*\)|\1|g") - # shellcheck disable=SC2001 - [ -z "$_tst_input_unit" ] && _tst_input_unit=$(echo "$_tst_input_all" | sed "s|^[[:blank:]]*\([0-9]\+\)[[:blank:]]*\(.*\)|\2|g" | head -c 1) - [ -z "$_tst_input_unit" ] && _tst_input_unit="b" - [ -z "$_tst_output_unit" ] && _tst_output_unit="b" - if [ -z "$_tst_input_value" ]; then - msg "no input value" - return 1 - fi - case "$_tst_input_unit" in - b | B) ;; - k | K) - _tst_input_value=$((_tst_input_value * 1024)) - ;; - m | M) - _tst_input_value=$((_tst_input_value * 1024 * 1024)) - ;; - g | G) - _tst_input_value=$((_tst_input_value * 1024 * 1024 * 1024)) - ;; - t | T) - _tst_input_value=$((_tst_input_value * 1024 * 1024 * 1024 * 1024)) - ;; - *) - msg "unknown input unit $_tst_input_unit" - return 1 - ;; - esac - case "$_tst_output_unit" in - b | B) - _tst_output_value=$_tst_input_value - ;; - k | K) - _tst_output_value=$((_tst_input_value / 1024)) - ;; - m | M) - _tst_output_value=$((_tst_input_value / 1024 / 1024)) - ;; - g | G) - _tst_output_value=$((_tst_input_value / 1024 / 1024 / 1024)) - ;; - t | T) - _tst_output_value=$((_tst_input_value / 1024 / 1024 / 1024 / 1024)) - ;; - *) - msg "unknown output unit $_tst_output_unit" - return 1 - ;; - esac - echo $_tst_output_value - return 0 -} - -# 功能:ssh到环境子网中指定机器上 -# 参数: -# $1 -- 需要登录的机器IP编号 -# $* -- 要远程执行的命令及参数 -# 返回值:同ssh -env_ssh() { - local _tst_ip="${TST_VM_SUBNET}.$1" - shift - msg "try ssh to $_tst_ip execute: $*" - timeout -s SIGTERM 60 ssh -q -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@"$_tst_ip" "$@" -} - -# 功能:scp本机的文件到到环境子网中指定机器的指定路径 -# 参数: -# $1 -- scp目标机器IP编号 -# $2 -- 远程机器的目标文件夹 -# $* -- 需要从本机拷贝到远端机器的文件,可以拷贝多个文件 -# 返回值:同scp -env_scpt() { - local _tst_ip="${TST_VM_SUBNET}.$1" - shift - local _tst_target="$1" - shift - msg "try scp $* to ${_tst_ip}:$_tst_target" - timeout -s SIGTERM 120 scp -rvq -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null "$@" root@"$_tst_ip":"$_tst_target" -} - -# 功能:scp指定机器的文件到本机路径 -# 参数: -# $1 -- scp目标机器IP编号 -# $2 -- 本机目标文件夹 -# $* -- 需要从远端机器拷贝到本机的文件,可以拷贝多个文件 -# 返回值:同scp -env_scpf() { - local _tst_ret=0 - local _tst_ip="${TST_VM_SUBNET}.$1" - shift - local _tst_target="$1" - shift - while [ -n "$1" ]; do - msg "try scp ${_tst_ip}:$1 to local $_tst_target" - timeout -s SIGTERM 120 scp -rvq -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@"$_tst_ip":"$1" "$_tst_target" || _tst_ret=1 - shift - done - return $_tst_ret -} - -# 功能:等待指定机器就绪,默认超时时间60秒 -# 参数: -# $1 -- 目标机器IP编号 -# $2 -- 【可选】等待的超时时间,默认等待60秒 -# 返回值: -# 0 -- 机器在超时前就绪 -# 1 -- 机器启动异常 -env_wait() { - local _tst_start_time - _tst_start_time=$(get_uptime) - local _tst_end_time - _tst_end_time=$(get_uptime) - local _tst_timeout - if [ -z "$2" ]; then - _tst_timeout=60 - else - _tst_timeout=$2 - fi - - local _tst_ip="${TST_VM_SUBNET}.$1" - msg "wait env $_tst_ip standby" - while [ $((_tst_start_time + _tst_timeout)) -ge "$_tst_end_time" ]; do - echo -n "." - sleep 3 - _tst_end_time=$(get_uptime) - ping -w 1 -W 1 -c 1 "$_tst_ip" >/dev/null 2>&1 || continue - if env_ssh "$1" test -d /proc; then - msg "the env with IP $_tst_ip ssh success, wait total $((_tst_end_time - _tst_start_time)) seconds" - return 0 - else - continue - fi - done - _tst_end_time=$(get_uptime) - msg "wait the env $_tst_ip timeout, wait total $((_tst_end_time - _tst_start_time)) seconds" - return 1 -} - -_assert_trap_exit() { - kill -s "$g_tst_trap_signal" "$TST_TC_PID" -} - -# 功能:标记用例为SKIP状态(当用例不需要测试时) -# 参数: -# $* -- 对SKIP状态标记的描述 -# 返回值:无 -skip_test() { - local _tst_tc_stat - _tst_tc_stat="$(_get_tcstat)" - - case "$_tst_tc_stat" in - "$TST_PASS" | "$TST_INIT" | "$TST_SKIP") - _set_tcstat "$TST_SKIP" - msg "set testcase SKIP: $*" - _assert_trap_exit - ;; - *) - msg "set testcase SKIP fail: $*" - err "the testcase stat is $(_tcstat_to_str "$_tst_tc_stat"), can't set to SKIP" - ;; - esac -} - -# 功能:当表达式返回真或命令执行成功时,用例不满足测试条件,终止测试 -# 参数: -# $* -- 需要断言的表达式 -# 返回值:无 -skip_if_true() { - local _tst_ret - "$@" - _tst_ret=$? - if [ $_tst_ret -eq 0 ]; then - skip_test "skip_if_true get (_tst_ret:$_tst_ret) ->" "$@" - fi -} - -# 功能:当表达式返回假或命令执行失败,用例不满足测试条件,终止测试 -# 参数: -# $* -- 需要断言的表达式 -# 返回值:无 -skip_if_false() { - local _tst_ret - "$@" - _tst_ret=$? - if [ $_tst_ret -ne 0 ]; then - skip_test "skip_if_false get (_tst_ret:$_tst_ret) ->" "$@" - fi -} - -# 功能:断言表达式返回真或命令执行成功,'_cont'后缀的断言函数在断言失败后用例继续执行,不终止 -# 参数: -# $* -- 需要断言的表达式 -# 返回值:无 -assert_true_cont() { - local _tst_ret - "$@" - _tst_ret=$? - if [ $_tst_ret -eq 0 ]; then - _tc_pass - return 0 - else - err "assert_true, but return ${_tst_ret}: $*" - return 1 - fi -} -assert_true() { - assert_true_cont "$@" || _assert_trap_exit -} - -# 功能:断言表达式返回假或命令执行失败,'_cont'后缀的断言函数在断言失败后用例继续执行,不终止 -# 参数: -# $* -- 需要断言的表达式 -# 返回值:无 -assert_false_cont() { - local _tst_ret - "$@" - _tst_ret=$? - if [ $_tst_ret -ne 0 ]; then - _tc_pass - return 0 - else - err "assert_false, but return ${_tst_ret}: $*" - return 1 - fi -} -assert_false_skip() { - assert_false_cont "$@" || _skip "expect false but true ->" "$@" -} -assert_false() { - assert_false_cont "$@" || _assert_trap_exit -} - -_set_tcstat() { - echo "$1" >"$TST_TC_SYSDIR/tcstat" -} - -_get_tcstat() { - cat "$TST_TC_SYSDIR/tcstat" 2>/dev/null -} - -_tc_pass() { - # 只有初始状态的用例才能置为PASS,其他异常状态的用例不能从异常变为PASS - if [ "$(cat "$TST_TC_SYSDIR/tcstat" 2>/dev/null)" == "$TST_INIT" ]; then - _set_tcstat $TST_PASS - fi -} - -_tc_fail() { - if [ "$(_get_tcstat)" != "$TST_FAIL" ]; then - echo "the testcase first fail here" - fi - _set_tcstat $TST_FAIL -} - -_tc_setup_common() { - local _tst_ret=0 - - # 只有用例的主进程才能执行此函数 - [ "$TST_TC_PID" != "$$" ] && return 0 - - # 对用例执行环境进行初始化设置 - mkdir -p "${TST_TC_SYSDIR}/core" - ulimit -c >"$TST_TC_SYSDIR/old.ulimit.c" - ulimit -c unlimited - cat /proc/sys/kernel/core_pattern >"$TST_TC_SYSDIR/old.proc.core_pattern" - is_root && echo "${TST_TC_SYSDIR}/core/core-e%e-p%p-i%i-s%s-g%g-u%u-t%t.dump" >/proc/sys/kernel/core_pattern - - if is_function tc_setup_common; then - msg "try call tc_setup_common" - if tc_setup_common "$@"; then - msg "call tc_setup_common success" - else - err "call tc_setup_common fail" - _tst_ret=1 - fi - else - msg "tc_setup_common not define" - fi - - return $_tst_ret -} - -_tc_setup() { - local _tst_ret=0 - - # 只有用例的主进程才能执行此函数 - [ "$TST_TC_PID" != "$$" ] && return 0 - touch "$TST_TC_SYSDIR/tc_setup_called" - if is_function tc_setup; then - msg "try call tc_setup" - if tc_setup "$@"; then - msg "call tc_setup success" - else - err "call tc_setup fail" - _tst_ret=1 - fi - else - msg "tc_setup not define" - fi - - return $_tst_ret -} - -_do_test() { - local _tst_ret=0 - - # 只有用例的主进程才能执行此函数 - [ "$TST_TC_PID" != "$$" ] && return 0 - if is_function do_test; then - msg "try call do_test" - if do_test "$@"; then - msg "call do_test success" - else - err "call do_test fail" - _tst_ret=1 - fi - else - err "do_test not define" - _tst_ret=1 - fi - - return $_tst_ret -} - -_tc_teardown() { - local _tst_ret=0 - - # 只有用例的主进程才能执行此函数 - [ "$TST_TC_PID" != "$$" ] && return 0 - if is_function tc_teardown; then - msg "try call tc_teardown" - if tc_teardown "$@"; then - msg "call tc_teardown success" - else - err "call tc_teardown fail" - _tst_ret=1 - fi - else - msg "tc_teardown not define" - fi - - return $_tst_ret -} - -_tc_teardown_common() { - local _tst_ret=0 - - # 只有用例的主进程才能执行此函数 - [ "$TST_TC_PID" != "$$" ] && return 0 - if is_function tc_teardown_common; then - msg "try call tc_teardown_common" - if tc_teardown_common "$@"; then - msg "call tc_teardown_common success" - else - err "call tc_teardown_common fail" - _tst_ret=1 - fi - else - msg "tc_teardown_common not define" - fi - - # 恢复用例执行前做的初始化设置 - ulimit -c "$(cat "$TST_TC_SYSDIR/old.ulimit.c")" - is_root && cat "$TST_TC_SYSDIR/old.proc.core_pattern" >/proc/sys/kernel/core_pattern - - return $_tst_ret -} - -_tc_trap_call() { - _tc_run_complete || exit 1 - exit 0 -} - -_tc_run_complete() { - local _tst_ret=0 - - # 只有用例的主进程才能执行此函数 - [ "$TST_TC_PID" != "$$" ] && return 0 - if [ -e "$TST_TC_SYSDIR/tc_setup_called" ]; then - if _tc_teardown "$@"; then - msg "call _tc_teardown success" - else - err "call _tc_teardown fail" - _tst_ret=1 - fi - else - msg "the tc_setup not called, so tc_teardown ignore" - fi - if _tc_teardown_common "$@"; then - msg "call _tc_teardown_common success" - else - err "call _tc_teardown_common fail" - _tst_ret=1 - fi - - # TCase自动化执行框架需要用这个输出判断用例是否执行完 - echo "Global test environment tear-down" - # 用例失败则收集系统日志上传到TCase用于定位 - case "$(_get_tcstat)" in - "$TST_PASS") - msg "RESULT : $TST_TC_NAME ==> [ PASSED ]" - rm -rf "$TST_TC_SYSDIR" - echo "case-result: PASS" >>"$TST_RESULT_FILE" - ;; - "$TST_FAIL") - msg "RESULT : $TST_TC_NAME ==> [ FAILED ]" - _tst_ret=1 - echo "case-result: FAIL" >>"$TST_RESULT_FILE" - ;; - "$TST_INIT") - msg "RESULT : $TST_TC_NAME ==> [ NOTEST ]" - _tst_ret=1 - echo "case-result: ABORT" >>"$TST_RESULT_FILE" - ;; - "$TST_SKIP") - msg "RESULT : $TST_TC_NAME ==> [ SKIP ]" - rm -rf "$TST_TC_SYSDIR" - _tst_ret=0 - echo "case-result: SKIP" >>"$TST_RESULT_FILE" - ;; - *) - msg "RESULT : $TST_TC_NAME ==> [ UNKNOWN ]" - _tst_ret=1 - echo "case-result: ABORT" >>"$TST_RESULT_FILE" - ;; - esac - local _tst_case_end - _tst_case_end=$(get_up_time_ms) - msg "cost $(diff_time_ms2sec "$g_tst_case_start" "$_tst_case_end")" - - { - echo "case-end-time: $(get_timestamp_ms)" - echo "" - } >>"$TST_RESULT_FILE" - - return $_tst_ret -} - -_set_ts_setup_stat() { - echo "$1" >"$TST_TS_SYSDIR/ts.setup.stat" -} - -_get_ts_setup_stat() { - cat "$TST_TS_SYSDIR/ts.setup.stat" 2>/dev/null -} - -_is_ts_setup_called() { - test -f "$TST_TS_SYSDIR/ts.setup.stat" -} - -_clean_ts_setup_stat() { - rm -rf "$TST_TS_SYSDIR/ts.setup.stat" -} - -tst_main() { - local _tst_ret=0 - - if [ -z "$TST_TS_TOPDIR" ]; then - msg "the TST_TS_TOPDIR not set" - return 1 - fi - if [ ! -d "$TST_TS_TOPDIR" ]; then - msg "the TST_TS_TOPDIR=$TST_TS_TOPDIR not dir" - return 1 - fi - - [ -f "$TST_TS_SYSDIR/environment_variable" ] && source "$TST_TS_SYSDIR/environment_variable" - export TST_TC_PID=$$ - TST_TC_CWD="$(realpath "$(dirname "$0")")" - export TST_TC_CWD - TST_TC_FILE_FULL="$(realpath "$0")" - export TST_TC_FILE_FULL - # shellcheck disable=SC2001 - TST_TC_FILE="$(echo "$TST_TC_FILE_FULL" | sed "s|^${TST_TS_TOPDIR}/*||g")" - export TST_TC_FILE - TST_TC_NAME="$(_get_case_attr "用例名称")" - export TST_TC_NAME - export TST_TC_SYSDIR="$TST_TS_TOPDIR/logs/testcase/.tc.${TST_TC_PID}.sysdir" - - # 用于断言,有的断言会终止测试活动 - trap _tc_trap_call "$g_tst_trap_signal" - - # 生成结果记录文件 - _get_tst_result_file - - { - echo "TESTCASE" - echo "case-name: $TST_TC_NAME" - echo "case-id: $(_get_case_attr "用例ID")" - echo "case-type: case-type" - echo "case-level: $(_get_case_attr "用例级别")" - echo "case-label: $(_get_case_attr "用例标签")" - echo "case-steps: $(_get_case_steps)" - echo "case-result-id: ${TST_TC_NAME}-result-${TST_RESULT_ID}" - echo "case-start-time: $(get_timestamp_ms)" - } >>"$TST_RESULT_FILE" - - if _is_ts_setup_called; then - msg "tsuite setup executed, stat is $(_get_ts_setup_stat)" - else - msg "tsuite setup may not executed" - fi - - cd "$TST_TC_CWD" || return 1 - mkdir -p "$TST_TC_SYSDIR" - _set_tcstat $TST_INIT - - if _tc_setup_common "$@"; then - if _tc_setup "$@"; then - msg "call _tc_setup success" - if _do_test "$@"; then - msg "call _do_test success" - else - err "call _do_test fail" - _tst_ret=1 - fi - else - err "call _tc_setup fail" - _tst_ret=1 - fi - else - err "call _tc_setup_common fail" - _tst_ret=1 - fi - - _tc_run_complete "$@" || _tst_ret=1 - - return $_tst_ret -} diff --git a/coreutils/tst_common/lib/common_func.sh b/coreutils/tst_common/lib/common_func.sh deleted file mode 100644 index 9217202..0000000 --- a/coreutils/tst_common/lib/common_func.sh +++ /dev/null @@ -1,88 +0,0 @@ -#!/bin/bash -# 所有shell脚本的测试用例都应该source此文件 -# 约定: -# 1、以下划线"_"开头的函数和变量用例不能直接调用 -# 2、环境变量全大写,全局变量加上"g_"前置,局部变量统一加"local"修饰 - -# Func: 输出调试级别用例日志 -dbg() { - echo "$@" 1>&2 -} - -# Func: 输出普通级别用例日志 -msg() { - echo "$@" 1>&2 -} - -# Func: 输出错误级别用例日志,如果是用例上下文,则标记用例为失败状态 -err() { - echo "$@" 1>&2 - # 只有用例上下文才设置用例状态 - is_function _tc_fail && _tc_fail -} - -is_function() { - type "$1" 2>&1 | head -n 1 | grep "$1 is a function" >/dev/null 2>&1 - return $? -} - -is_root() { - [ "$(id -u)" == "0" ] && return 0 - return 1 -} - -get_up_time_sec() { - awk -F . '{print $1}' /proc/uptime -} - -get_up_time_ms() { - local _tst_uptime - _tst_uptime=$(awk '{print $1}' /proc/uptime | tr -d '.') - echo -n "${_tst_uptime}0" -} - -# 获取时间戳 -get_timestamp_sec() { - date +%s -} -get_timestamp_ms() { - date +%s%N | sed "s|......$||g" -} - -# 输出时间差,并将ms转换为sec -# $1 -- start time: ms -# $2 -- end time: ms -diff_time_ms2sec() { - local _tst_diff_time=$(($2 - $1)) - local _tst_time_sec=$((_tst_diff_time / 1000)) - local _tst_time_ms=$((_tst_diff_time % 1000)) - printf "%d.%03d" $_tst_time_sec $_tst_time_ms -} - -# 获取测试套名 -get_suite_name() { - basename "$TST_TS_TOPDIR" -} - -# 获取测试结果文件 -_get_tst_result_file() { - if [ -z "$TST_RESULT_FILE" ]; then - local test_index=0 - while [ $test_index -lt 10000 ]; do - test_index=$((test_index + 1)) - [ -f "$TST_TS_TOPDIR/logs/${test_index}.result" ] && continue - break - done - export TST_RESULT_ID="$test_index" - TST_RESULT_FILE="$TST_TS_TOPDIR/logs/${test_index}.result" - export TST_RESULT_FILE - { - echo "TESTSUITE" - echo "suite-name: $(get_suite_name)" - echo "suite-start-time: $(get_timestamp_ms)" - echo "suite-end-time:" - echo "" - } >>"$TST_RESULT_FILE" - fi - echo "$TST_RESULT_FILE" -} diff --git a/coreutils/tst_common/lib/main.h b/coreutils/tst_common/lib/main.h deleted file mode 100644 index 7a2ca85..0000000 --- a/coreutils/tst_common/lib/main.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef __MAIN_H__ -#define __MAIN_H__ - -#include "common.h" - -extern int tst_main(int argc, char **argv); - -int main(int argc, char **argv) { - return tst_main(argc, argv); -} - -#endif // __MAIN_H__ diff --git a/coreutils/tst_common/lib/sched.py b/coreutils/tst_common/lib/sched.py deleted file mode 100644 index 09e3972..0000000 --- a/coreutils/tst_common/lib/sched.py +++ /dev/null @@ -1,129 +0,0 @@ -#!/usr/bin/env python3 -# coding: utf-8 -# Time: 2022-08-24 12:22:09 -# Desc: 系统调度 - -import os, time -from multiprocessing import Process, cpu_count - - -def exec_cpu(cpu: int, rate: float, interval: int, timeout: int) -> None: - t_start = time.time() - while time.time() - t_start < timeout: - if ((time.time() - t_start) / interval) % 1 < rate: - pass - else: - time.sleep((1 - rate) * interval) - print(f'cpu {cpu} execute terminated') - - -def set_cpu_rate_of_system(rate: float, interval: int = 1, timeout: int = 10) -> None: - """ - 设置系统CPU使用率到指定值 - :param rate: 系统CPU使用率百分比, [0, cpu_num] - :param interval: 设置使用率的采样间隔时间 - :param timeout: 设置使用率的时间 - :return: None - """ - cpu_num = cpu_count() - if (rate < 0 or rate > cpu_num): - print(f'Input usage rate is {rate}, which must be a float value between 0 and {cpu_num}!') - return - if (interval <= 0): - print(f'Input interval is {interval}, which must be a positive number!') - return - if (timeout <= 0): - print(f'Input timeout is {timeout}, which must be a positive number!') - return - - ps_list = [] - cpu_rate = rate / cpu_num - for i in range(0, cpu_num): - ps_list.append(Process(target = exec_cpu, args = (i, cpu_rate, interval, timeout))) - for p in ps_list: - p.start() - for p in ps_list: - p.join() - print("all cpus execute over") - - -def exec_on_specific_cpu(cpu: int, rate: float, interval: int, timeout: int) -> None: - pid = os.getpid() - os.sched_setaffinity(pid, {cpu}) - t_start = time.time() - while time.time() - t_start < timeout: - if ((time.time() - t_start) / interval) % 1 < rate: - pass - else: - time.sleep((1 - rate) * interval) - print(f'cpu {cpu} execute terminated') - - -def set_cpu_rate_of_cpu(cpu_index: int, rate: float, interval: int = 1, timeout : int = 10) -> Process: - """ - 设置某个CPU的使用率到指定值 - :param cpu_index: cpu编号 - :param rate: CPU使用率百分比, [0, 1] - :param interval: 设置使用率的采样间隔时间 - :param timeout: 设置使用率的时间 - :return: None - """ - if (rate < 0 or rate > 1): - print(f'Input usage rate is {rate}, which must be a float value between 0 and 1!') - return - if (interval <= 0): - print(f'Input interval is {interval}, which must be a positive number!') - return - if (timeout <= 0): - print(f'Input timeout is {timeout}, which must be a positive number!') - return - pid = os.getpid() - eligible_cpu_set = os.sched_getaffinity(pid) - if (cpu_index not in eligible_cpu_set): - print(f'Input cpu index is {cpu_index}, which is not valid! ' + - f'The eligible cpu set is {eligible_cpu_set}') - return - - print(f'Set cpu usage of cpu{cpu_index} to {rate}') - - p = Process(target = exec_on_specific_cpu, args = (cpu_index, rate, interval, timeout)) - p.start() - return p - - -def set_cpu_rate_of_task(rate: float, interval: int = 1, timeout : int = 10) -> None: - """ - 设置进程的使用率到指定值 - :param rate: 进程CPU使用率百分比, [0, 1] - :param interval: 设置使用率的采样间隔时间 - :param timeout: 设置使用率的时间 - :return: None - """ - if (rate < 0 or rate > 1): - print(f'Input usage rate is {rate}, which must be a float value between 0 and 1!') - return - if (interval <= 0): - print(f'Input interval is {interval}, which must be a positive number!') - return - if (timeout <= 0): - print(f'Input timeout is {timeout}, which must be a positive number!') - return - - pid = os.getpid() - print(f'set cpu usage of pid {pid} to {rate}') - t_start = time.time() - - while time.time() - t_start < timeout: - if ((time.time() - t_start) / interval) % 1 < rate: - pass - else: - time.sleep((1 - rate) * interval) - -if __name__ == '__main__': - # set_cpu_rate_of_system(4, 1, 60) - p = set_cpu_rate_of_cpu(1, 0.3, 1, 30) - print('joining') - p.join() - print('cpu test finished') - # set_cpu_rate_of_task(1.5, 1, 20) - diff --git a/coreutils/tst_common/lib/tst_ts_setup b/coreutils/tst_common/lib/tst_ts_setup deleted file mode 100755 index 17bd646..0000000 --- a/coreutils/tst_common/lib/tst_ts_setup +++ /dev/null @@ -1,55 +0,0 @@ -#!/bin/bash -# Time: 2022-04-19 22:44:25 -# Desc: 测试套公共ts_setup - -if [ -d "$TST_TS_TOPDIR/tst_common" ]; then - # 先source测试用例自定义的公共文件 - source "$TST_TS_TOPDIR/tst_lib/ts_common.sh" || exit 1 - # 再source全局公共文件 - source "$TST_TS_TOPDIR/tst_common/lib/common.sh" || exit 1 -elif [ -d "$TST_TS_TOPDIR/lib" ]; then - # 只是tst_suite_common使用 - source "$TST_TS_TOPDIR/lib/common.sh" || exit 1 -else - echo "can't find the tsuite common file" - exit 1 -fi - -_ts_setup() { - if _is_ts_setup_called; then - if [ "$(_get_ts_setup_stat)" == "$TST_PASS" ]; then - echo "the ts_setup executed passed yet" - return 0 - else - echo "the ts_setup executed yet, but fail" - return 1 - fi - fi - - local _tst_ret=0 - - if [ -f "$TST_TS_TOPDIR/tst_lib/ts_setup" ]; then - if [ -x "$TST_TS_TOPDIR/tst_lib/ts_setup" ]; then - msg "try execute $TST_TS_TOPDIR/tst_lib/ts_setup" - if "$TST_TS_TOPDIR/tst_lib/ts_setup"; then - msg "execute ts_setup success" - _set_ts_setup_stat "$TST_PASS" - else - msg "execute ts_setup fail" - _set_ts_setup_stat "$TST_FAIL" - _tst_ret=1 - fi - else - msg "the $TST_TS_TOPDIR/tst_lib/ts_setup can't execute" - _set_ts_setup_stat "$TST_FAIL" - _tst_ret=1 - fi - else - msg "ts_setup not exist" - _set_ts_setup_stat "$TST_PASS" - fi - - return $_tst_ret -} - -_ts_setup diff --git a/coreutils/tst_common/lib/tst_ts_teardown b/coreutils/tst_common/lib/tst_ts_teardown deleted file mode 100755 index c3ae1ba..0000000 --- a/coreutils/tst_common/lib/tst_ts_teardown +++ /dev/null @@ -1,47 +0,0 @@ -#!/bin/bash -# Time: 2022-04-19 22:44:25 -# Desc: 测试套公共ts_teardown - -if [ -d "$TST_TS_TOPDIR/tst_common" ]; then - # 先source测试用例自定义的公共文件 - source "$TST_TS_TOPDIR/tst_lib/ts_common.sh" || exit 1 - # 再source全局公共文件 - source "$TST_TS_TOPDIR/tst_common/lib/common.sh" || exit 1 -elif [ -d "$TST_TS_TOPDIR/lib" ]; then - # 只是tst_suite_common使用 - source "$TST_TS_TOPDIR/lib/common.sh" || exit 1 -else - echo "can't find the tsuite common file" - exit 1 -fi - -_ts_teardown() { - local _tst_ret=0 - - if ! _is_ts_setup_called; then - msg "the ts_setup may not execute, we'll not execute the ts_teardown" - return 1 - fi - - if [ -f "$TST_TS_TOPDIR/tst_lib/ts_teardown" ]; then - if [ -x "$TST_TS_TOPDIR/tst_lib/ts_teardown" ]; then - msg "try execute $TST_TS_TOPDIR/tst_lib/ts_teardown" - if ts_teardown; then - msg "execute ts_teardown success" - else - msg "execute ts_teardown fail" - _tst_ret=1 - fi - else - msg "the $TST_TS_TOPDIR/tst_lib/ts_teardown exist, but can't execute" - _tst_ret=1 - fi - else - msg "ts_teardown not exist" - fi - _clean_ts_setup_stat - - return $_tst_ret -} - -_ts_teardown diff --git a/coreutils/tst_common/lib/tsuite-completion.bash b/coreutils/tst_common/lib/tsuite-completion.bash deleted file mode 100644 index e1d3e4c..0000000 --- a/coreutils/tst_common/lib/tsuite-completion.bash +++ /dev/null @@ -1,51 +0,0 @@ -# bash/zsh completion support for tsuite. - -# To use these routines: -# -# 1) Copy this file to somewhere (e.g. ~/.tsuite-completion.bash). -# 2) Add the following line to your .bashrc/.zshrc: -# source ~/.tsuite-completion.bash - -_tsuite_completion() { - local cur prev - - cur=${COMP_WORDS[COMP_CWORD]} - prev=${COMP_WORDS[COMP_CWORD - 1]} - - case ${COMP_CWORD} in - 1) - COMPREPLY=($(compgen -W "help new list compile setup run teardown clean cleanall" -- ${cur})) - ;; - 2) - case ${prev} in - new) - COMPREPLY=($(compgen -W "case" -- ${cur})) - ;; - run) - local arr i file - arr=($(grep --include \*.c --include \*.sh --include \*.py -Ril "@用例名称:" testcase/)) - COMPREPLY=() - for ((i = 0; i < ${#arr[@]}; ++i)); do - file=${arr[i]} - if [[ -d $MEMO_DIR/$file ]]; then - file=$file/ - fi - COMPREPLY[i]=$file - done - ;; - esac - ;; - 3) - case ${prev} in - case) - COMPREPLY=($(compgen -W "sh c py" -- ${cur})) - ;; - esac - ;; - *) - COMPREPLY=() - ;; - esac -} - -complete -F _tsuite_completion tsuite diff --git a/coreutils/tst_common/lib/tsuite_func.sh b/coreutils/tst_common/lib/tsuite_func.sh deleted file mode 100644 index 054cc21..0000000 --- a/coreutils/tst_common/lib/tsuite_func.sh +++ /dev/null @@ -1,497 +0,0 @@ -#!/bin/bash -# 测试套管理工具 - -export LANG=en_US.UTF-8 - -if [ -d "$TST_TS_TOPDIR/tst_common" ]; then - source "$TST_TS_TOPDIR/tst_common/lib/common.sh" || exit 1 -elif [ -d "$TST_TS_TOPDIR/lib" ]; then - # 只是tst_suite_common使用 - source "$TST_TS_TOPDIR/lib/common.sh" || exit 1 -else - echo "can't find the tsuite common file" - exit 1 -fi - -[ -z "$TST_TS_SYSDIR" ] && export TST_TS_SYSDIR="$TST_TS_TOPDIR/logs/.ts.sysdir" - -tsuite_usage() { - echo -e "" - echo -e "./tsuite options sub_command sub_options" - echo -e " help: 显示帮助信息" - echo -e " new case sh|c|py case_name [template]: 新增测试用例" - echo -e " sh|c|py: 【必选】三选一,sh表示Shell脚本用例,c表示C用例,py表示Python脚本用例" - echo -e " case_name: 【必选】要创建的用例名,同时用作文件名" - echo -e " template: 【可选】不使用默认用例模板时,可以指定一个文件用作新用例模板" - echo -e " list: 列出本测试套的测试用例" - echo -e " compile: 编译测试套" - echo -e " setup: 执行测试套setup" - echo -e " run options: 执行测试用例,options可选参数如下:" - echo -e " null: 不指定时默认执行所有用例" - echo -e " case_path: 执行指定用例" - echo -e " -l level: 执行指定级别的用例,例如:0,1,2" - echo -e " -f case_list: 执行指定列表文件的用例" - echo -e " teardown: 执行测试套teardown" - echo -e " clean: 执行make clean" - echo -e " cleanall: 执行make cleanall,在clean基础上删除所有临时文件等" - echo -e "" -} - -get_all_testcase() { - local _tst_case_dir=./testcase - if [ ! -d "$_tst_case_dir" ]; then - echo "no testcase dir" - return 1 - fi - touch "$TST_TS_SYSDIR/all_testcase.list" - grep -r "@用例名称:" $_tst_case_dir | awk -F : '{print $1}' | sort | uniq >"$TST_TS_SYSDIR/all_testcase.list" -} - -# 获取用例属性 -# $1 -- 属性名称 -# $2 -- 用例文件 -get_case_attr() { - grep "@${1}:" "$2" 2>/dev/null | head -n 1 | sed "s|.*@${1}:\s*||g" | sed "s|\s*$||g" -} - -tsuite_list() { - local _tst_index=1 - - get_all_testcase - local _tst_nr_all_case - _tst_nr_all_case=$(wc -l <"$TST_TS_SYSDIR/all_testcase.list") - - echo "" - for i in $(seq "$_tst_nr_all_case"); do - local _tst_case_file - local _tst_case_name - _tst_case_file="$(sed -n "${i}p" "$TST_TS_SYSDIR/all_testcase.list")" - _tst_case_name=$(get_case_attr "用例名称" "$_tst_case_file") - printf "%4d : %-30s : %s\n" $_tst_index "$_tst_case_name" "$_tst_case_file" - _tst_index=$((_tst_index + 1)) - done - echo "" - echo "total $_tst_nr_all_case testcase" - echo "" -} - -# 执行单个用例 -# $1 -- 用例文件,Shell和Python用例直接执行脚本文件,C可以是源码文件,也可以是二进制文件(两个文件要同名,后缀不同) -tsuite_run_one() { - local _tst_input_file="$1" - shift - - local _tst_ret=0 - local _tst_log_dir="$TST_TS_TOPDIR/logs/testcase" - - local _tst_exec_file - local _tst_case_file - # C用例 - if file "$_tst_input_file" | grep -w "ELF" >/dev/null; then - _tst_exec_file="$_tst_input_file" - _tst_case_file="${_tst_exec_file%.test}" - _tst_case_file="${_tst_case_file}.c" - elif file "$_tst_input_file" | grep -w "C source" >/dev/null; then - _tst_exec_file="${_tst_input_file%.c}" - _tst_exec_file="${_tst_exec_file}.test" - _tst_case_file="${_tst_input_file}" - else - _tst_exec_file="${_tst_input_file}" - _tst_case_file="${_tst_input_file}" - fi - local _tst_case_name - _tst_case_name=$(get_case_attr "用例名称" "$_tst_case_file") - - mkdir -p "$_tst_log_dir" - - echo "execute $_tst_case_name: $_tst_exec_file $*" - "$_tst_exec_file" "$@" || _tst_ret=1 - - return $_tst_ret -} - -# 执行指定列表文件的用例 -# $1 -- 要执行的用例列表文件,每行一个用例,井号'#'表示忽略对应用例 -tsuite_run_some() { - if [ ! -f "$1" ]; then - echo "testcase list file '$1' not exist" - fi - local _tst_run_list="$TST_TS_SYSDIR/run.list" - local _tst_run_result="$TST_TS_SYSDIR/run.result" - rm -rf "$_tst_run_list" "$_tst_run_result" - # 去掉注释行和空行,删掉行前的空格 - grep -v "^[[:blank:]]*#" "$1" | grep -v "^[[:blank:]]*$" | sed "s|^[[:blank:]]\+||g" >"$_tst_run_list" - - local _tst_ret=0 - local _tst_nr_pass=0 - local _tst_nr_skip=0 - local _tst_nr_fail=0 - local _tst_index=1 - local _tst_nr_all_case - _tst_nr_all_case=$(wc -l <"$_tst_run_list") - local _tst_case_time_start - local _tst_case_time_end - local _tst_case_cost - - printf "\n %-30s ==>" "ts_setup" - if tsuite_setup >"$TST_TS_TOPDIR/logs/ts_setup.log" 2>&1; then - echo " PASS" - else - echo " FAIL" - fi - mkdir -p "$TST_TS_TOPDIR/logs/testcase" - for i in $(seq "$_tst_nr_all_case"); do - local _tst_case_file - local _tst_case_name - local _tst_case_result - _tst_case_file="$(sed -n "${i}p" "$_tst_run_list")" - _tst_case_name=$(get_case_attr "用例名称" "$_tst_case_file") - local _tst_case_log="$TST_TS_TOPDIR/logs/testcase/${_tst_case_name}.log" - printf "%4d/%-4d : %-30s ==>" $_tst_index "$_tst_nr_all_case" "$_tst_case_name" - _tst_case_time_start=$(get_up_time_ms) - tsuite_run_one "$_tst_case_file" >"$_tst_case_log" 2>&1 - _tst_case_time_end=$(get_up_time_ms) - _tst_case_cost=$(diff_time_ms2sec "$_tst_case_time_start" "$_tst_case_time_end") - _tst_case_result=$(grep "RESULT : .* ==> \[ [A-Z]\+ \]" "$_tst_case_log" | - tail -n 1 | sed "s|.* ==> \[ \([A-Z]\+\) \].*|\1|g") - case "$_tst_case_result" in - "PASSED") - _tst_nr_pass=$((_tst_nr_pass + 1)) - echo "$_tst_index/$_tst_nr_all_case $_tst_case_name PASS cost:$_tst_case_cost" >>"$_tst_run_result" - echo " PASS (cost $_tst_case_cost)" - ;; - "SKIP") - _tst_nr_skip=$((_tst_nr_skip + 1)) - echo "$_tst_index/$_tst_nr_all_case $_tst_case_name SKIP cost:$_tst_case_cost" >>"$_tst_run_result" - echo " SKIP (cost $_tst_case_cost)" - ;; - *) - _tst_nr_fail=$((_tst_nr_fail + 1)) - echo "$_tst_index/$_tst_nr_all_case $_tst_case_name FAIL cost:$_tst_case_cost" >>"$_tst_run_result" - echo " FAIL (cost $_tst_case_cost)" - _tst_ret=1 - ;; - esac - _tst_index=$((_tst_index + 1)) - done - printf " %-30s ==>" "ts_teardown" - if tsuite_teardown >"$TST_TS_TOPDIR/logs/ts_teardown.log" 2>&1; then - echo " PASS" - else - echo " FAIL" - fi - - echo "" - echo "total: $_tst_nr_all_case" - echo " pass: $_tst_nr_pass" - echo " skip: $_tst_nr_skip" - echo " fail: $_tst_nr_fail" - echo "" - - return $_tst_ret -} - -tsuite_run_all() { - get_all_testcase - tsuite_run_some "$TST_TS_SYSDIR/all_testcase.list" -} - -tsuite_compile() { - local _tst_ret=0 - - echo "try cleanall before compile" - make -C "$TST_TS_TOPDIR" cleanall || _tst_ret=1 - echo "compile the testsuite" - if which bear; then - bear -- make -C "$TST_TS_TOPDIR" all || _tst_ret=1 - else - make -C "$TST_TS_TOPDIR" all || _tst_ret=1 - fi - - return $_tst_ret -} - -tsuite_setup() { - local _tst_ret=0 - - echo "tsuite try execute ts_setup" - if [ -f "$TST_TS_TOPDIR/tst_common/lib/tst_ts_setup" ]; then - "$TST_TS_TOPDIR/tst_common/lib/tst_ts_setup" || _tst_ret=1 - elif [ -f "$TST_TS_TOPDIR/lib/tst_ts_setup" ]; then - # 只是tst_suite_common使用 - "$TST_TS_TOPDIR/lib/tst_ts_setup" || _tst_ret=1 - else - echo "the tst_ts_setup not found" - _tst_ret=1 - fi - - return $_tst_ret -} - -tsuite_run() { - local _tst_ret=0 - - # 生成结果记录文件 - _get_tst_result_file - - if [ -z "$1" ]; then - tsuite_run_all || _tst_ret=1 - elif [ "$1" == "-f" ]; then - echo "Try run testcases in list file '$2'" - tsuite_run_some "$2" || _tst_ret=1 - elif [ "$1" == "-l" ]; then - echo "Try run testcases with level '$2'" - rm -rf "$TST_TS_SYSDIR/level.list" - for l in $(echo "$2" | tr ',' ' '); do - grep -r "@用例级别:[[:blank:]]*$l" $_tst_case_dir | awk -F : '{print $1}' | - sort | uniq >>"$TST_TS_SYSDIR/level.list" - done - tsuite_run_some "$TST_TS_SYSDIR/level.list" || _tst_ret=1 - else - tsuite_run_one "$@" || _tst_ret=1 - fi - - sed -i "/^suite-end-time:/c suite-end-time: $(get_timestamp_ms)" "$TST_RESULT_FILE" - - return $_tst_ret -} - -tsuite_teardown() { - local _tst_ret=0 - - mkdir -p "$TST_TS_TOPDIR/logs" - echo "tsuite try execute ts_teardown" - if [ -f "$TST_TS_TOPDIR/tst_common/lib/tst_ts_teardown" ]; then - "$TST_TS_TOPDIR/tst_common/lib/tst_ts_teardown" || _tst_ret=1 - elif [ -f "$TST_TS_TOPDIR/lib/tst_ts_teardown" ]; then - # 只是tst_suite_common使用 - "$TST_TS_TOPDIR/lib/tst_ts_teardown" || _tst_ret=1 - else - echo "the tst_ts_setup not found" - _tst_ret=1 - fi - - return $_tst_ret -} - -tsuite_clean() { - local _tst_ret=0 - - make -C "$TST_TS_TOPDIR" clean || _tst_ret=1 - - return $_tst_ret -} - -tsuite_cleanall() { - local _tst_ret=0 - - make -C "$TST_TS_TOPDIR" cleanall || _tst_ret=1 - rm -rfv "$TST_TS_TOPDIR/logs" "$TST_TS_TOPDIR/compile_commands.json" - - return $_tst_ret -} - -# 新建用例模板 -# $1 -- 用例代码类型:sh/c/py -# $2 -- 用例名 -# $3 -- 可选参数,用例模板 -tsuite_new_case() { - local _tst_tc_type="$1" - local _tst_tc_name="$2" - local _tst_input_template="$3" - local _tst_tc_id - _tst_tc_id=$(date '+%Y%m%d-%H%M%S-%N') - local _tst_tc_file="testcase/${2}.${1}" - local _tst_template_path="$TST_TS_TOPDIR/tst_common/testcase" - # 为了适配tst_suite_common - [ -d "$_tst_template_path" ] || _tst_template_path="$TST_TS_TOPDIR/testcase" - if [ ! -d "$_tst_template_path" ]; then - echo "the template path is $_tst_template_path, not dir" - return 1 - fi - - if [ -z "$_tst_tc_name" ]; then - echo "the testcase name not set" - return 1 - fi - - if [ -z "$_tst_input_template" ]; then - case "$_tst_tc_type" in - sh) - cp -v "$_tst_template_path/test_shell_testcase.sh" "$TST_TS_TOPDIR/$_tst_tc_file" - sed -i "s|}/lib/common|}/tst_common/lib/common|g" "$TST_TS_TOPDIR/$_tst_tc_file" - ;; - c) - cp -v "$_tst_template_path/test_c_testcase.c" "$TST_TS_TOPDIR/$_tst_tc_file" - ;; - py) - cp -v "$_tst_template_path/test_python_testcase.py" "$TST_TS_TOPDIR/$_tst_tc_file" - sed -i "/from lib.common import TestCase/c from tst_lib.ts_common import MyTestCase" \ - "$TST_TS_TOPDIR/$_tst_tc_file" - sed -i "/class PythonTestCase(TestCase):/c class PythonTestCase(MyTestCase):" \ - "$TST_TS_TOPDIR/$_tst_tc_file" - ;; - *) - echo "unsupported testcase type" - return 1 - ;; - esac - else - if [ ! -f "$_tst_input_template" ]; then - echo "the template file $_tst_input_template not exist" - return 1 - fi - if ! echo "$_tst_input_template" | grep "\.$_tst_tc_type$" >/dev/null; then - echo "the template file $_tst_input_template not match the testcase type $_tst_tc_type" - return 1 - fi - cp -v "$_tst_input_template" "$TST_TS_TOPDIR/$_tst_tc_file" - fi - - sed -i "s|@用例ID:.*|@用例ID: $_tst_tc_id|g" "$TST_TS_TOPDIR/$_tst_tc_file" - sed -i "s|@用例名称:.*|@用例名称: $_tst_tc_name|g" "$TST_TS_TOPDIR/$_tst_tc_file" - echo "" - echo "the new testcase info:" - echo " name: $_tst_tc_name" - echo " type: $_tst_tc_type" - echo " id: $_tst_tc_id" - echo " file: $_tst_tc_file" - echo "" - return 0 -} - -# 新建测试套 -# $1 -- 测试套git路径 -tsuite_new_suite() { - local _tst_git_url="$1" - local _tst_suite_name - _tst_suite_name=$(basename "$_tst_git_url" | sed "s|\.git$||g") - - if ! echo "$_tst_git_url" | grep "\.git$" >/dev/null; then - echo "the git url unusable" - return 1 - fi - if [ -z "$_tst_suite_name" ]; then - echo "get suite name fail" - return 1 - fi - if [ -d "./$_tst_suite_name" ]; then - echo "the ./$_tst_suite_name existed" - return 1 - fi - - echo "git clone $_tst_git_url ./$_tst_suite_name" - if ! git clone "$_tst_git_url" "./$_tst_suite_name"; then - echo "clone $_tst_suite_name fail" - return 1 - fi - if [ -d "./$_tst_suite_name/tst_common" ]; then - echo "the suite $_tst_suite_name initialization has been completed yet" - return 1 - fi - - echo "get suite_example: git clone https://gitee.com/opencloudos-stream/test-suite-example.git" - rm -rf "$TST_TS_SYSDIR/suite_example" - if ! git clone https://gitee.com/opencloudos-stream/test-suite-example.git "$TST_TS_SYSDIR/suite_example"; then - echo "clone suite_example fail" - rm -rf "./$_tst_suite_name" - return 1 - fi - cp -rv "$TST_TS_SYSDIR/suite_example"/* "./$_tst_suite_name" - cp -rv "$TST_TS_SYSDIR/suite_example/.gitignore" "./$_tst_suite_name" - rm -rf "$TST_TS_SYSDIR/suite_example" - - cd "./$_tst_suite_name" || return 1 - rm -rf ./tst_common - echo "add submodule to common for $_tst_suite_name" - if ! git submodule add https://gitee.com/opencloudos-stream/test-suite-base.git ./common; then - echo "add submodule fail" - cd .. - rm -rf "./$_tst_suite_name" - return 1 - fi - - echo "remove the sample testcase" - rm -fv ./testcase/test_* - - return 0 -} - -tsuite_new() { - local _tst_ret=0 - - case $1 in - case) - shift - tsuite_new_case "$@" || _tst_ret=1 - ;; - suite) - shift - tsuite_new_suite "$@" || _tst_ret=1 - ;; - *) - echo "unknown new type: $*" - _tst_ret=1 - ;; - esac - - return $_tst_ret -} - -tsuite_main() { - local _tst_ret=0 - local _tst_cmd="$0 $*" - local _tst_suite_time_start - _tst_suite_time_start=$(get_up_time_ms) - local _tst_suite_time_end - - echo "TST_TS_TOPDIR=$TST_TS_TOPDIR" - cd "$TST_TS_TOPDIR" || return 1 - mkdir -p "$TST_TS_SYSDIR" || return 1 - - case "$1" in - help) - tsuite_usage - return 0 - ;; - new) - shift - tsuite_new "$@" || _tst_ret=1 - ;; - list) - tsuite_list || _tst_ret=1 - ;; - compile) - tsuite_compile || _tst_ret=1 - ;; - setup) - tsuite_setup || _tst_ret=1 - ;; - run) - shift - tsuite_run "$@" || _tst_ret=1 - ;; - teardown) - tsuite_teardown || _tst_ret=1 - ;; - clean) - tsuite_clean || _tst_ret=1 - ;; - cleanall) - tsuite_cleanall || _tst_ret=1 - ;; - *) - echo "$0 $*" - tsuite_usage - return 1 - ;; - esac - - _tst_suite_time_end=$(get_up_time_ms) - if [ $_tst_ret -eq 0 ]; then - echo "execute $_tst_cmd success, cost $(diff_time_ms2sec "$_tst_suite_time_start" "$_tst_suite_time_end")" - else - echo "execute $_tst_cmd fail, cost $(diff_time_ms2sec "$_tst_suite_time_start" "$_tst_suite_time_end")" - fi - return $_tst_ret -} diff --git a/coreutils/tst_common/testcase/Makefile b/coreutils/tst_common/testcase/Makefile deleted file mode 100644 index 1cb97df..0000000 --- a/coreutils/tst_common/testcase/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -export TST_COMMON_TOPDIR ?= $(shell pwd)/.. -include $(TST_COMMON_TOPDIR)/Makefile.common -ALL_SRC := $(wildcard *.c) -ALL_OBJ := $(patsubst %.c,%.o,$(ALL_SRC)) -ALL_BIN := $(patsubst %.o,%.test,$(ALL_OBJ)) -CFLAGS += -LDFLAGS += - -all: $(ALL_BIN) - -$(ALL_BIN):%.test:%.o - $(CC) $^ -o $@ $(LDFLAGS) - -$(ALL_OBJ):%.o:%.c - $(CC) $(CFLAGS) -c $^ -o $@ - -clean: - rm -rfv $(ALL_OBJ) $(ALL_BIN) - -cleanall: clean diff --git a/coreutils/tst_common/testcase/test_c_testcase.c b/coreutils/tst_common/testcase/test_c_testcase.c deleted file mode 100644 index 6624689..0000000 --- a/coreutils/tst_common/testcase/test_c_testcase.c +++ /dev/null @@ -1,35 +0,0 @@ -/* **************************************************************************** - * @用例ID: 20220418-230037-838974137 - * @用例名称: test_c_testcase - * @用例级别: 3 - * @用例标签: - * @用例类型: 功能 - * ***************************************************************************/ - -#include "main.h" - -int tc_setup(int argc, char **argv) { - msg("this is tc_setup"); - // @预置条件: - // @预置条件: - return 0; -} - -int do_test(int argc, char **argv) { - msg("this is do_test"); - - // @测试步骤:1: - - // @测试步骤:2: - - // @测试步骤:3: - // @预期结果:3: - assert_true(1 + 1 == 2); - - return 0; -} - -int tc_teardown(int argc, char **argv) { - msg("this is tc_teardown"); - return 0; -} diff --git a/coreutils/tst_common/testcase/test_perf_tools.py b/coreutils/tst_common/testcase/test_perf_tools.py deleted file mode 100755 index b09c3b0..0000000 --- a/coreutils/tst_common/testcase/test_perf_tools.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python3 -# coding: utf-8 -import os.path -import subprocess -import sys - -sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) -from lib.common import TestCase -from lib.benchmark import PerfSysBench - - -def prepare(): - subprocess.run(["which", "sysbench"]) - - -def cleanup(): - pass - - -class PythonTestCase(TestCase): - """ - @用例ID: 20220721-001631-159391306 - @用例名称: test_perf_tools - @用例级别: 3 - @用例标签: - @用例类型: 功能 - """ - - def tc_setup(self, *args): - # @预置条件: - self.msg("this is tc_setup") - - def do_test(self, *args): - # @测试步骤:1: - perf = PerfSysBench(name='cpu', sysbench='sysbench', testname='cpu') - perf.prepare = prepare - perf.cleanup = cleanup - perf.run() - perf.report() - # @测试步骤:2: - - # @测试步骤:3: - # @预期结果:3: - self.assert_true(1 == 1) - - def tc_teardown(self, *args): - self.msg("this is tc_teardown") - - -if __name__ == '__main__': - PythonTestCase().tst_main(sys.argv) diff --git a/coreutils/tst_common/testcase/test_python_testcase.py b/coreutils/tst_common/testcase/test_python_testcase.py deleted file mode 100755 index ea86f3d..0000000 --- a/coreutils/tst_common/testcase/test_python_testcase.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env python3 -# coding: utf-8 - -import os.path -import sys - -sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) -from lib.common import TestCase - - -class PythonTestCase(TestCase): - """ - @用例ID: 20220420-234008-893237761 - @用例名称: test_python_testcase - @用例级别: 3 - @用例标签: - @用例类型: 功能 - """ - - def tc_setup(self, *args): - # @预置条件: - self.msg("this is tc_setup") - - def do_test(self, *args): - # @测试步骤:1: - - # @测试步骤:2: - - # @测试步骤:3: - # @预期结果:3: - self.assert_true(1 == 1) - - def tc_teardown(self, *args): - self.msg("this is tc_teardown") - - -if __name__ == '__main__': - PythonTestCase().tst_main(sys.argv) diff --git a/coreutils/tst_common/testcase/test_shell_testcase.sh b/coreutils/tst_common/testcase/test_shell_testcase.sh deleted file mode 100755 index 5f5f5ba..0000000 --- a/coreutils/tst_common/testcase/test_shell_testcase.sh +++ /dev/null @@ -1,47 +0,0 @@ -#!/bin/bash -############################################################################### -# @用例ID: 20220410-152859-724647329 -# @用例名称: test_shell_testcase -# @用例级别: 3 -# @用例标签: -# @用例类型: 功能 -############################################################################### -[ -z "$TST_TS_TOPDIR" ] && { - TST_TS_TOPDIR="$(realpath "$(dirname "$0")/..")" - export TST_TS_TOPDIR -} -source "${TST_TS_TOPDIR}/lib/common.sh" || exit 1 -############################################################################### - -g_tmpdir="$(mktemp -d)" - -tc_setup() { - msg "this is tc_setup" - # @预置条件: - # @预置条件: - return 0 -} - -do_test() { - msg "this is do_test" - - # @测试步骤:1: - - # @测试步骤:2: - - # @测试步骤:3: - # @预期结果:3: - assert_true [ 1 -eq 1 ] - - return 0 -} - -tc_teardown() { - msg "this is tc_teardown" - rm -rfv "$g_tmpdir" || return 1 - return 0 -} - -############################################################################### -tst_main "$@" -############################################################################### diff --git a/coreutils/tst_common/tsuite b/coreutils/tst_common/tsuite deleted file mode 100755 index ee4170c..0000000 --- a/coreutils/tst_common/tsuite +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/bash -# 测试套管理工具 - -TST_TS_TOPDIR=$(realpath "$(dirname "$0")") -export TST_TS_TOPDIR -TST_TS_ORI_CWD="$(pwd)" -export TST_TS_ORI_CWD -if [ -f "$TST_TS_TOPDIR/tst_common/lib/tsuite_func.sh" ]; then - source "$TST_TS_TOPDIR/tst_common/lib/tsuite_func.sh" -elif [ -f "$TST_TS_TOPDIR/lib/tsuite_func.sh" ]; then - source "$TST_TS_TOPDIR/lib/tsuite_func.sh" -else - echo "can't find the tsuite_func.sh file" - exit 1 -fi - -tsuite_main "$@" -- Gitee From a737c9aafaa888341e56785fecb314f9055557bf Mon Sep 17 00:00:00 2001 From: hou Date: Thu, 25 May 2023 05:46:43 +0000 Subject: [PATCH 12/20] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=96=87=E4=BB=B6=20co?= =?UTF-8?q?reutils?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- coreutils/.gitignore | 15 - coreutils/LICENSE | 824 ------------------------------ coreutils/Makefile | 27 - coreutils/Makefile.common | 3 - coreutils/cmd/Makefile | 20 - coreutils/cmd/hello.c | 6 - coreutils/kmod/Makefile | 28 - coreutils/kmod/ts_kcommon.c | 14 - coreutils/testcase/Makefile | 21 - coreutils/testcase/mysql-test.sh | 98 ---- coreutils/testcase/tc-mkdir-01.sh | 48 -- coreutils/tst_lib/Makefile | 20 - coreutils/tst_lib/other_common.sh | 5 - coreutils/tst_lib/ts_common.c | 23 - coreutils/tst_lib/ts_common.h | 6 - coreutils/tst_lib/ts_common.py | 35 -- coreutils/tst_lib/ts_common.sh | 28 - coreutils/tst_lib/ts_setup | 14 - coreutils/tst_lib/ts_teardown | 13 - coreutils/tsuite | 1 - 20 files changed, 1249 deletions(-) delete mode 100644 coreutils/.gitignore delete mode 100644 coreutils/LICENSE delete mode 100644 coreutils/Makefile delete mode 100644 coreutils/Makefile.common delete mode 100644 coreutils/cmd/Makefile delete mode 100644 coreutils/cmd/hello.c delete mode 100644 coreutils/kmod/Makefile delete mode 100644 coreutils/kmod/ts_kcommon.c delete mode 100644 coreutils/testcase/Makefile delete mode 100755 coreutils/testcase/mysql-test.sh delete mode 100755 coreutils/testcase/tc-mkdir-01.sh delete mode 100644 coreutils/tst_lib/Makefile delete mode 100644 coreutils/tst_lib/other_common.sh delete mode 100644 coreutils/tst_lib/ts_common.c delete mode 100644 coreutils/tst_lib/ts_common.h delete mode 100644 coreutils/tst_lib/ts_common.py delete mode 100644 coreutils/tst_lib/ts_common.sh delete mode 100755 coreutils/tst_lib/ts_setup delete mode 100755 coreutils/tst_lib/ts_teardown delete mode 120000 coreutils/tsuite diff --git a/coreutils/.gitignore b/coreutils/.gitignore deleted file mode 100644 index d9510fe..0000000 --- a/coreutils/.gitignore +++ /dev/null @@ -1,15 +0,0 @@ -.idea/ -logs/ -__pycache__/ -*.o -*.a -*.d -*.cmd -*.test -*.ko -*.mod -*.mod.c -Module.symvers -modules.order -compile_commands.json - diff --git a/coreutils/LICENSE b/coreutils/LICENSE deleted file mode 100644 index d06cc9f..0000000 --- a/coreutils/LICENSE +++ /dev/null @@ -1,824 +0,0 @@ -Tencent is pleased to support the open source community by making OpenCloudOS Kernel Stream available. - -Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. The below software in this distribution may have been modified by THL A29 Limited ("Tencent Modifications"). All Tencent Modifications are Copyright (C) THL A29 Limited. - -OpenCloudOS Kernel Stream is licensed under the the Mulan Permissive Software License 2.0 except for the third-party components listed below. - - -Terms of the Mulan Permissive Software License 2.0: --------------------------------------------------------------------- - 木兰宽松许可证, 第2版 - -2020年1月 http://license.coscl.org.cn/MulanPSL2 - -您对“软件”的复制、使用、修改及分发受木兰宽松许可证,第2版(“本许可证”)的如下条款的约束: - -0. 定义 - -“软件”是指由“贡献”构成的许可在“本许可证”下的程序和相关文档的集合。 - -“贡献”是指由任一“贡献者”许可在“本许可证”下的受版权法保护的作品。 - -“贡献者”是指将受版权法保护的作品许可在“本许可证”下的自然人或“法人实体”。 - -“法人实体”是指提交贡献的机构及其“关联实体”。 - -“关联实体”是指,对“本许可证”下的行为方而言,控制、受控制或与其共同受控制的机构,此处的控制是指有受控方或共同受控方至少50%直接或间接的投票权、资金或其他有价证券。 - -1. 授予版权许可 - -每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的版权许可,您可以复制、使用、修改、分发其“贡献”,不论修改与否。 - -2. 授予专利许可 - -每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的(根据本条规定撤销除外)专利许可,供您制造、委托制造、使用、许诺销售、销售、进口其“贡献”或以其他方式转移其“贡献”。前述专利许可仅限于“贡献者”现在或将来拥有或控制的其“贡献”本身或其“贡献”与许可“贡献”时的“软件”结合而将必然会侵犯的专利权利要求,不包括对“贡献”的修改或包含“贡献”的其他结合。如果您或您的“关联实体”直接或间接地,就“软件”或其中的“贡献”对任何人发起专利侵权诉讼(包括反诉或交叉诉讼)或其他专利维权行动,指控其侵犯专利权,则“本许可证”授予您对“软件”的专利许可自您提起诉讼或发起维权行动之日终止。 - -3. 无商标许可 - -“本许可证”不提供对“贡献者”的商品名称、商标、服务标志或产品名称的商标许可,但您为满足第4条规定的声明义务而必须使用除外。 - -4. 分发限制 - -您可以在任何媒介中将“软件”以源程序形式或可执行形式重新分发,不论修改与否,但您必须向接收者提供“本许可证”的副本,并保留“软件”中的版权、商标、专利及免责声明。 - -5. 免责声明与责任限制 - -“软件”及其中的“贡献”在提供时不带任何明示或默示的担保。在任何情况下,“贡献者”或版权所有者不对任何人因使用“软件”或其中的“贡献”而引发的任何直接或间接损失承担责任,不论因何种原因导致或者基于何种法律理论,即使其曾被建议有此种损失的可能性。 - -6. 语言 - -“本许可证”以中英文双语表述,中英文版本具有同等法律效力。如果中英文版本存在任何冲突不一致,以中文版为准。 - -条款结束 - -如何将木兰宽松许可证,第2版,应用到您的软件 - -如果您希望将木兰宽松许可证,第2版,应用到您的新软件,为了方便接收者查阅,建议您完成如下三步: - -1,请您补充如下声明中的空白,包括软件名、软件的首次发表年份以及您作为版权人的名字; - -2,请您在软件包的一级目录下创建以“LICENSE”为名的文件,将整个许可证文本放入该文件中; - -3,请将如下声明文本放入每个源文件的头部注释中。 - -Copyright (c) [Year] [name of copyright holder] [Software Name] is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. - -January 2020 http://license.coscl.org.cn/MulanPSL2 - -Your reproduction, use, modification and distribution of the Software shall be subject to Mulan PSL v2 (this License) with the following terms and conditions: - -0. Definition - -Software means the program and related documents which are licensed under this License and comprise all Contribution(s). - -Contribution means the copyrightable work licensed by a particular Contributor under this License. - -Contributor means the Individual or Legal Entity who licenses its copyrightable work under this License. - -Legal Entity means the entity making a Contribution and all its Affiliates. - -Affiliates means entities that control, are controlled by, or are under common control with the acting entity under this License, ‘control’ means direct or indirect ownership of at least fifty percent (50%) of the voting power, capital or other securities of controlled or commonly controlled entity. - -1. Grant of Copyright License - -Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable copyright license to reproduce, use, modify, or distribute its Contribution, with modification or not. - -2. Grant of Patent License - -Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable (except for revocation under this Section) patent license to make, have made, use, offer for sale, sell, import or otherwise transfer its Contribution, where such patent license is only limited to the patent claims owned or controlled by such Contributor now or in future which will be necessarily infringed by its Contribution alone, or by combination of the Contribution with the Software to which the Contribution was contributed. The patent license shall not apply to any modification of the Contribution, and any other combination which includes the Contribution. If you or your Affiliates directly or indirectly institute patent litigation (including a cross claim or counterclaim in a litigation) or other patent enforcement activities against any individual or entity by alleging that the Software or any Contribution in it infringes patents, then any patent license granted to you under this License for the Software shall terminate as of the date such litigation or activity is filed or taken. - -3. No Trademark License - -No trademark license is granted to use the trade names, trademarks, service marks, or product names of Contributor, except as required to fulfill notice requirements in Section 4. - -4. Distribution Restriction - -You may distribute the Software in any medium with or without modification, whether in source or executable forms, provided that you provide recipients with a copy of this License and retain copyright, patent, trademark and disclaimer statements in the Software. - -5. Disclaimer of Warranty and Limitation of Liability - -THE SOFTWARE AND CONTRIBUTION IN IT ARE PROVIDED WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED. IN NO EVENT SHALL ANY CONTRIBUTOR OR COPYRIGHT HOLDER BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO ANY DIRECT, OR INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING FROM YOUR USE OR INABILITY TO USE THE SOFTWARE OR THE CONTRIBUTION IN IT, NO MATTER HOW IT’S CAUSED OR BASED ON WHICH LEGAL THEORY, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -6. Language - -THIS LICENSE IS WRITTEN IN BOTH CHINESE AND ENGLISH, AND THE CHINESE VERSION AND ENGLISH VERSION SHALL HAVE THE SAME LEGAL EFFECT. IN THE CASE OF DIVERGENCE BETWEEN THE CHINESE AND ENGLISH VERSIONS, THE CHINESE VERSION SHALL PREVAIL. - -END OF THE TERMS AND CONDITIONS - - - -Other dependencies and licenses: - - -Open Source Software Licensed under the GPL v2.0 with Linux-syscall-note, and Other Licenses of the Third-Party Components therein: -The below software in this distribution may have been modified by THL A29 Limited ("Tencent Modifications"). All Tencent Modifications are Copyright (C) 2021 THL A29 Limited. --------------------------------------------------------------------- -1. kernel -Copyright © kernel original author and authors - - -The Linux Kernel is provided under: - - SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note - -Being under the terms of the GNU General Public License version 2 only, -according with: - - LICENSES/preferred/GPL-2.0 - -With an explicit syscall exception, as stated at: - - LICENSES/exceptions/Linux-syscall-note - -In addition, other licenses may also apply. Please see: - - Documentation/process/license-rules.rst - -for more details. - -All contributions to the Linux Kernel are subject to this COPYING file. - -Valid-License-Identifier: GPL-2.0 -Valid-License-Identifier: GPL-2.0-only -Valid-License-Identifier: GPL-2.0+ -Valid-License-Identifier: GPL-2.0-or-later -SPDX-URL: https://spdx.org/licenses/GPL-2.0.html -Usage-Guide: - To use this license in source code, put one of the following SPDX - tag/value pairs into a comment according to the placement - guidelines in the licensing rules documentation. - For 'GNU General Public License (GPL) version 2 only' use: - SPDX-License-Identifier: GPL-2.0 - or - SPDX-License-Identifier: GPL-2.0-only - For 'GNU General Public License (GPL) version 2 or any later version' use: - SPDX-License-Identifier: GPL-2.0+ - or - SPDX-License-Identifier: GPL-2.0-or-later -License-Text: - - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Library General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Library General -Public License instead of this License. - -SPDX-Exception-Identifier: Linux-syscall-note -SPDX-URL: https://spdx.org/licenses/Linux-syscall-note.html -SPDX-Licenses: GPL-2.0, GPL-2.0+, GPL-1.0+, LGPL-2.0, LGPL-2.0+, LGPL-2.1, LGPL-2.1+, GPL-2.0-only, GPL-2.0-or-later -Usage-Guide: - This exception is used together with one of the above SPDX-Licenses - to mark user space API (uapi) header files so they can be included - into non GPL compliant user space application code. - To use this exception add it with the keyword WITH to one of the - identifiers in the SPDX-Licenses tag: - SPDX-License-Identifier: WITH Linux-syscall-note -License-Text: - - NOTE! This copyright does *not* cover user programs that use kernel - services by normal system calls - this is merely considered normal use - of the kernel, and does *not* fall under the heading of "derived work". - Also note that the GPL below is copyrighted by the Free Software - Foundation, but the instance of code that it refers to (the Linux - kernel) is copyrighted by me and others who actually wrote it. - - Also note that the only valid version of the GPL as far as the kernel - is concerned is _this_ particular version of the license (ie v2, not - v2.2 or v3.x or whatever), unless explicitly otherwise stated. - - Linus Torvalds - -For the licenses of other third parties, please refer to the following URL: -https://github.com/torvalds/linux/tree/v5.18-rc5/LICENSES - -Linux kernel licensing rules -The Linux Kernel is provided under the terms of the GNU General Public License version 2 only (GPL-2.0), as provided in LICENSES/preferred/GPL-2.0, with an explicit syscall exception described in LICENSES/exceptions/Linux-syscall-note, as described in the COPYING file. - -This documentation file provides a description of how each source file should be annotated to make its license clear and unambiguous. It doesn't replace the Kernel's license. - -The license described in the COPYING file applies to the kernel source as a whole, though individual source files can have a different license which is required to be compatible with the GPL-2.0: - -GPL-1.0+ : GNU General Public License v1.0 or later -GPL-2.0+ : GNU General Public License v2.0 or later -LGPL-2.0 : GNU Library General Public License v2 only -LGPL-2.0+ : GNU Library General Public License v2 or later -LGPL-2.1 : GNU Lesser General Public License v2.1 only -LGPL-2.1+ : GNU Lesser General Public License v2.1 or later -Aside from that, individual files can be provided under a dual license, e.g. one of the compatible GPL variants and alternatively under a permissive license like BSD, MIT etc. - -The User-space API (UAPI) header files, which describe the interface of user-space programs to the kernel are a special case. According to the note in the kernel COPYING file, the syscall interface is a clear boundary, which does not extend the GPL requirements to any software which uses it to communicate with the kernel. Because the UAPI headers must be includable into any source files which create an executable running on the Linux kernel, the exception must be documented by a special license expression. - -The common way of expressing the license of a source file is to add the matching boilerplate text into the top comment of the file. Due to formatting, typos etc. these "boilerplates" are hard to validate for tools which are used in the context of license compliance. - -An alternative to boilerplate text is the use of Software Package Data Exchange (SPDX) license identifiers in each source file. SPDX license identifiers are machine parsable and precise shorthands for the license under which the content of the file is contributed. SPDX license identifiers are managed by the SPDX Workgroup at the Linux Foundation and have been agreed on by partners throughout the industry, tool vendors, and legal teams. For further information see https://spdx.org/ - -The Linux kernel requires the precise SPDX identifier in all source files. The valid identifiers used in the kernel are explained in the section License identifiers and have been retrieved from the official SPDX license list at https://spdx.org/licenses/ along with the license texts. - -License identifier syntax -Placement: - -The SPDX license identifier in kernel files shall be added at the first possible line in a file which can contain a comment. For the majority of files this is the first line, except for scripts which require the '#!PATH_TO_INTERPRETER' in the first line. For those scripts the SPDX identifier goes into the second line. - - -Style: - -The SPDX license identifier is added in form of a comment. The comment style depends on the file type: - -C source: // SPDX-License-Identifier: -C header: /* SPDX-License-Identifier: */ -ASM: /* SPDX-License-Identifier: */ -scripts: # SPDX-License-Identifier: -.rst: .. SPDX-License-Identifier: -.dts{i}: // SPDX-License-Identifier: -If a specific tool cannot handle the standard comment style, then the appropriate comment mechanism which the tool accepts shall be used. This is the reason for having the "/* */" style comment in C header files. There was build breakage observed with generated .lds files where 'ld' failed to parse the C++ comment. This has been fixed by now, but there are still older assembler tools which cannot handle C++ style comments. - - -Syntax: - -A is either an SPDX short form license identifier found on the SPDX License List, or the combination of two SPDX short form license identifiers separated by "WITH" when a license exception applies. When multiple licenses apply, an expression consists of keywords "AND", "OR" separating sub-expressions and surrounded by "(", ")" . - -License identifiers for licenses like [L]GPL with the 'or later' option are constructed by using a "+" for indicating the 'or later' option.: - -// SPDX-License-Identifier: GPL-2.0+ -// SPDX-License-Identifier: LGPL-2.1+ -WITH should be used when there is a modifier to a license needed. For example, the linux kernel UAPI files use the expression: - -// SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note -// SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note -Other examples using WITH exceptions found in the kernel are: - -// SPDX-License-Identifier: GPL-2.0 WITH mif-exception -// SPDX-License-Identifier: GPL-2.0+ WITH GCC-exception-2.0 -Exceptions can only be used with particular License identifiers. The valid License identifiers are listed in the tags of the exception text file. For details see the point Exceptions in the chapter License identifiers. - -OR should be used if the file is dual licensed and only one license is to be selected. For example, some dtsi files are available under dual licenses: - -// SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause -Examples from the kernel for license expressions in dual licensed files: - -// SPDX-License-Identifier: GPL-2.0 OR MIT -// SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause -// SPDX-License-Identifier: GPL-2.0 OR Apache-2.0 -// SPDX-License-Identifier: GPL-2.0 OR MPL-1.1 -// SPDX-License-Identifier: (GPL-2.0 WITH Linux-syscall-note) OR MIT -// SPDX-License-Identifier: GPL-1.0+ OR BSD-3-Clause OR OpenSSL -AND should be used if the file has multiple licenses whose terms all apply to use the file. For example, if code is inherited from another project and permission has been given to put it in the kernel, but the original license terms need to remain in effect: - -// SPDX-License-Identifier: (GPL-2.0 WITH Linux-syscall-note) AND MIT -Another other example where both sets of license terms need to be adhered to is: - -// SPDX-License-Identifier: GPL-1.0+ AND LGPL-2.1+ -License identifiers -The licenses currently used, as well as the licenses for code added to the kernel, can be broken down into: - -Preferred licenses: - -Whenever possible these licenses should be used as they are known to be fully compatible and widely used. These licenses are available from the directory: - -LICENSES/preferred/ -in the kernel source tree. - -The files in this directory contain the full license text and Metatags. The file names are identical to the SPDX license identifier which shall be used for the license in source files. - -Examples: - -LICENSES/preferred/GPL-2.0 -Contains the GPL version 2 license text and the required metatags: - -LICENSES/preferred/MIT -Contains the MIT license text and the required metatags - -Metatags: - -The following meta tags must be available in a license file: - -Valid-License-Identifier: - -One or more lines which declare which License Identifiers are valid inside the project to reference this particular license text. Usually this is a single valid identifier, but e.g. for licenses with the 'or later' options two identifiers are valid. - -SPDX-URL: - -The URL of the SPDX page which contains additional information related to the license. - -Usage-Guidance: - -Freeform text for usage advice. The text must include correct examples for the SPDX license identifiers as they should be put into source files according to the License identifier syntax guidelines. - -License-Text: - -All text after this tag is treated as the original license text - -File format examples: - -Valid-License-Identifier: GPL-2.0 -Valid-License-Identifier: GPL-2.0+ -SPDX-URL: https://spdx.org/licenses/GPL-2.0.html -Usage-Guide: - To use this license in source code, put one of the following SPDX - tag/value pairs into a comment according to the placement - guidelines in the licensing rules documentation. - For 'GNU General Public License (GPL) version 2 only' use: - SPDX-License-Identifier: GPL-2.0 - For 'GNU General Public License (GPL) version 2 or any later version' use: - SPDX-License-Identifier: GPL-2.0+ -License-Text: - Full license text -SPDX-License-Identifier: MIT -SPDX-URL: https://spdx.org/licenses/MIT.html -Usage-Guide: - To use this license in source code, put the following SPDX - tag/value pair into a comment according to the placement - guidelines in the licensing rules documentation. - SPDX-License-Identifier: MIT -License-Text: - Full license text - -Deprecated licenses: - -These licenses should only be used for existing code or for importing code from a different project. These licenses are available from the directory: - -LICENSES/deprecated/ -in the kernel source tree. - -The files in this directory contain the full license text and Metatags. The file names are identical to the SPDX license identifier which shall be used for the license in source files. - -Examples: - -LICENSES/deprecated/ISC -Contains the Internet Systems Consortium license text and the required metatags: - -LICENSES/deprecated/GPL-1.0 -Contains the GPL version 1 license text and the required metatags. - -Metatags: - -The metatag requirements for 'other' licenses are identical to the requirements of the Preferred licenses. - -File format example: - -Valid-License-Identifier: ISC -SPDX-URL: https://spdx.org/licenses/ISC.html -Usage-Guide: - Usage of this license in the kernel for new code is discouraged - and it should solely be used for importing code from an already - existing project. - To use this license in source code, put the following SPDX - tag/value pair into a comment according to the placement - guidelines in the licensing rules documentation. - SPDX-License-Identifier: ISC -License-Text: - Full license text - -Dual Licensing Only - -These licenses should only be used to dual license code with another license in addition to a preferred license. These licenses are available from the directory: - -LICENSES/dual/ -in the kernel source tree. - -The files in this directory contain the full license text and Metatags. The file names are identical to the SPDX license identifier which shall be used for the license in source files. - -Examples: - -LICENSES/dual/MPL-1.1 -Contains the Mozilla Public License version 1.1 license text and the required metatags: - -LICENSES/dual/Apache-2.0 -Contains the Apache License version 2.0 license text and the required metatags. - -Metatags: - -The metatag requirements for 'other' licenses are identical to the requirements of the Preferred licenses. - -File format example: - -Valid-License-Identifier: MPL-1.1 -SPDX-URL: https://spdx.org/licenses/MPL-1.1.html -Usage-Guide: - Do NOT use. The MPL-1.1 is not GPL2 compatible. It may only be used for - dual-licensed files where the other license is GPL2 compatible. - If you end up using this it MUST be used together with a GPL2 compatible - license using "OR". - To use the Mozilla Public License version 1.1 put the following SPDX - tag/value pair into a comment according to the placement guidelines in - the licensing rules documentation: -SPDX-License-Identifier: MPL-1.1 -License-Text: - Full license text - -Exceptions: - -Some licenses can be amended with exceptions which grant certain rights which the original license does not. These exceptions are available from the directory: - -LICENSES/exceptions/ -in the kernel source tree. The files in this directory contain the full exception text and the required Exception Metatags. - -Examples: - -LICENSES/exceptions/Linux-syscall-note -Contains the Linux syscall exception as documented in the COPYING file of the Linux kernel, which is used for UAPI header files. e.g. /* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */: - -LICENSES/exceptions/GCC-exception-2.0 -Contains the GCC 'linking exception' which allows to link any binary independent of its license against the compiled version of a file marked with this exception. This is required for creating runnable executables from source code which is not compatible with the GPL. - -Exception Metatags: - -The following meta tags must be available in an exception file: - -SPDX-Exception-Identifier: - -One exception identifier which can be used with SPDX license identifiers. - -SPDX-URL: - -The URL of the SPDX page which contains additional information related to the exception. - -SPDX-Licenses: - -A comma separated list of SPDX license identifiers for which the exception can be used. - -Usage-Guidance: - -Freeform text for usage advice. The text must be followed by correct examples for the SPDX license identifiers as they should be put into source files according to the License identifier syntax guidelines. - -Exception-Text: - -All text after this tag is treated as the original exception text - -File format examples: - -SPDX-Exception-Identifier: Linux-syscall-note -SPDX-URL: https://spdx.org/licenses/Linux-syscall-note.html -SPDX-Licenses: GPL-2.0, GPL-2.0+, GPL-1.0+, LGPL-2.0, LGPL-2.0+, LGPL-2.1, LGPL-2.1+ -Usage-Guidance: - This exception is used together with one of the above SPDX-Licenses - to mark user-space API (uapi) header files so they can be included - into non GPL compliant user-space application code. - To use this exception add it with the keyword WITH to one of the - identifiers in the SPDX-Licenses tag: - SPDX-License-Identifier: WITH Linux-syscall-note -Exception-Text: - Full exception text -SPDX-Exception-Identifier: GCC-exception-2.0 -SPDX-URL: https://spdx.org/licenses/GCC-exception-2.0.html -SPDX-Licenses: GPL-2.0, GPL-2.0+ -Usage-Guidance: - The "GCC Runtime Library exception 2.0" is used together with one - of the above SPDX-Licenses for code imported from the GCC runtime - library. - To use this exception add it with the keyword WITH to one of the - identifiers in the SPDX-Licenses tag: - SPDX-License-Identifier: WITH GCC-exception-2.0 -Exception-Text: - Full exception text -All SPDX license identifiers and exceptions must have a corresponding file in the LICENSES subdirectories. This is required to allow tool verification (e.g. checkpatch.pl) and to have the licenses ready to read and extract right from the source, which is recommended by various FOSS organizations, e.g. the FSFE REUSE initiative. - -MODULE_LICENSE -Loadable kernel modules also require a MODULE_LICENSE() tag. This tag is neither a replacement for proper source code license information (SPDX-License-Identifier) nor in any way relevant for expressing or determining the exact license under which the source code of the module is provided. - -The sole purpose of this tag is to provide sufficient information whether the module is free software or proprietary for the kernel module loader and for user space tools. - -The valid license strings for MODULE_LICENSE() are: - -"GPL" Module is licensed under GPL version 2. This does not express any distinction between GPL-2.0-only or GPL-2.0-or-later. The exact license information can only be determined via the license information in the corresponding source files. -"GPL v2" Same as "GPL". It exists for historic reasons. -"GPL and additional rights" Historical variant of expressing that the module source is dual licensed under a GPL v2 variant and MIT license. Please do not use in new code. -"Dual MIT/GPL" The correct way of expressing that the module is dual licensed under a GPL v2 variant or MIT license choice. -"Dual BSD/GPL" The module is dual licensed under a GPL v2 variant or BSD license choice. The exact variant of the BSD license can only be determined via the license information in the corresponding source files. -"Dual MPL/GPL" The module is dual licensed under a GPL v2 variant or Mozilla Public License (MPL) choice. The exact variant of the MPL license can only be determined via the license information in the corresponding source files. -"Proprietary" The module is under a proprietary license. This string is solely for proprietary third party modules and cannot be used for modules which have their source code in the kernel tree. Modules tagged that way are tainting the kernel with the 'P' flag when loaded and the kernel module loader refuses to link such modules against symbols which are exported with EXPORT_SYMBOL_GPL(). \ No newline at end of file diff --git a/coreutils/Makefile b/coreutils/Makefile deleted file mode 100644 index 0ae2951..0000000 --- a/coreutils/Makefile +++ /dev/null @@ -1,27 +0,0 @@ -export TST_TS_TOPDIR := $(shell pwd) -DIRS := cmd testcase kmod -LIBS := tst_common tst_lib - -all: libs - @for d in $(DIRS); do \ - echo try make $$d; \ - make -C $$d all; \ - done - -libs: - @for d in $(LIBS); do \ - echo try make $$d; \ - make -C $$d all; \ - done - -clean: - @for d in $(DIRS) $(LIBS); do \ - echo try clean $$d; \ - make -C $$d clean; \ - done - -cleanall: - @for d in $(DIRS) $(LIBS); do \ - echo try cleanall $$d; \ - make -C $$d cleanall; \ - done diff --git a/coreutils/Makefile.common b/coreutils/Makefile.common deleted file mode 100644 index 1d9d2da..0000000 --- a/coreutils/Makefile.common +++ /dev/null @@ -1,3 +0,0 @@ -CFLAGS += -Wall -g -I$(TST_TS_TOPDIR)/tst_common/lib -I$(TST_TS_TOPDIR)/tst_lib -LDFLAGS += -L$(TST_TS_TOPDIR)/tst_common/lib -L$(TST_TS_TOPDIR)/tst_lib -LDFLAGS += -lm -lrt -lpthread -Wl,--whole-archive -lcommon -ltscommon -Wl,--no-whole-archive diff --git a/coreutils/cmd/Makefile b/coreutils/cmd/Makefile deleted file mode 100644 index 133158c..0000000 --- a/coreutils/cmd/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -export TST_TS_TOPDIR ?= $(shell pwd)/.. -include $(TST_TS_TOPDIR)/Makefile.common -ALL_SRC := $(wildcard *.c) -ALL_OBJ := $(patsubst %.c,%.o,$(ALL_SRC)) -ALL_BIN := $(patsubst %.o,%.cmd,$(ALL_OBJ)) -CFLAGS += -LDFLAGS += - -all: $(ALL_BIN) - -$(ALL_BIN):%.cmd:%.o - $(CC) $^ -o $@ $(LDFLAGS) - -$(ALL_OBJ):%.o:%.c - $(CC) $(CFLAGS) -c $^ -o $@ - -clean: - rm -rfv $(ALL_OBJ) $(ALL_BIN) - -cleanall: clean diff --git a/coreutils/cmd/hello.c b/coreutils/cmd/hello.c deleted file mode 100644 index c70b442..0000000 --- a/coreutils/cmd/hello.c +++ /dev/null @@ -1,6 +0,0 @@ -#include - -int main(void) { - printf("hello world\n"); - return 0; -} diff --git a/coreutils/kmod/Makefile b/coreutils/kmod/Makefile deleted file mode 100644 index 01632ef..0000000 --- a/coreutils/kmod/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -# General Purpose Makefile for Linux Kernel module -# 以下编译适合于在内核代码树之外编译内核模块。 -# 整个过程会导致本Makefile文件被加载执行两遍。 -# 第一遍执行时,由于`KERNELRELEASE`没有被定义,所以先执行`else`下的逻辑。 -# `-C $(KERNEL_DIR)`指明跳转到内核源码目录下读取那里的Makefile; -# `M=$(CURDIR)`表明然后返回到当前目录继续读入当前的Makefile并执行之。此为第二遍执行。 -# 第二遍执行时,此时从内核源码目录返回时,KERNELRELEASE已被被定义, -# kbuild也被启动去解析kbuild语法的语句,make将继续读取else之前的内容。 -# else之前的内容为kbuild语法的语句, 指明模块源码中各文件的依赖关系,以及要生成的目标模块名。 - -CURDIR ?= $(shell pwd) -KERNEL_VER := $(shell uname -r) -KERNEL_DIR ?= /lib/modules/$(KERNEL_VER)/build -export ALL_SRC ?= $(filter-out %.mod.c, $(wildcard *.c)) -export ALL_OBJ ?= $(patsubst %.c,%.o,$(ALL_SRC)) -export ALL_MOD ?= $(patsubst %.o,%.ko,$(ALL_OBJ)) - -ifneq ($(KERNELRELEASE),) - obj-m += $(ALL_OBJ) -else -all: - $(MAKE) -C $(KERNEL_DIR) M=$(CURDIR) modules -endif - -clean: - $(MAKE) -C $(KERNEL_DIR) M=$(CURDIR) clean - -cleanall: clean diff --git a/coreutils/kmod/ts_kcommon.c b/coreutils/kmod/ts_kcommon.c deleted file mode 100644 index 41a779a..0000000 --- a/coreutils/kmod/ts_kcommon.c +++ /dev/null @@ -1,14 +0,0 @@ -#include - -static int __init kmod_common_init(void) { - printk("Hello, World!\n"); - return 0; -} -static void __exit kmod_common_exit(void) { - printk("Goodbye, World!\n"); -} - -module_init(kmod_common_init); -module_exit(kmod_common_exit); - -MODULE_LICENSE("GPL"); diff --git a/coreutils/testcase/Makefile b/coreutils/testcase/Makefile deleted file mode 100644 index 1b4db5b..0000000 --- a/coreutils/testcase/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -export TST_TS_TOPDIR ?= $(shell pwd)/.. -include $(TST_TS_TOPDIR)/Makefile.common -ALL_SRC := $(filter-out %.mod.c, $(wildcard *.c)) -ALL_OBJ := $(patsubst %.c,%.o,$(ALL_SRC)) -ALL_BIN := $(patsubst %.o,%.test,$(ALL_OBJ)) -CFLAGS += -LDFLAGS += -LDFLAGS += - -all: $(ALL_BIN) - -$(ALL_BIN):%.test:%.o - $(CC) $^ -o $@ $(LDFLAGS) - -$(ALL_OBJ):%.o:%.c - $(CC) $(CFLAGS) -c $^ -o $@ - -clean: - rm -rfv $(ALL_OBJ) $(ALL_BIN) - -cleanall: clean diff --git a/coreutils/testcase/mysql-test.sh b/coreutils/testcase/mysql-test.sh deleted file mode 100755 index 36ca572..0000000 --- a/coreutils/testcase/mysql-test.sh +++ /dev/null @@ -1,98 +0,0 @@ -#!/bin/bash -############################################################################### -# @用例ID: 20230525-101210-083410876 -# @用例名称: mysql-test -# @用例级别: 3 -# @用例标签: -# @用例类型: 功能 -############################################################################### -[ -z "$TST_TS_TOPDIR" ] && { - TST_TS_TOPDIR="$(realpath "$(dirname "$0")/..")" - export TST_TS_TOPDIR -} -source "${TST_TS_TOPDIR}/tst_common/lib/common.sh" || exit 1 -############################################################################### - -g_tmpdir="$(mktemp -d)" - -tc_setup() { - msg "this is tc_setup" - - #检查是否安装了MySQL - - if ! command -v mysql >/dev/null 2>&1; then - echo "MySQL not installed." - return 1 - else - mysql_version=$(mysql -V |awk '{print $3}' | awk -F, '{print $1}') - echo "MySQL version: $mysql_version" - fi - - # 启动MySQL - sudo service mysql start - - #检查MySQL是否成功启动 - status=$(service mysql status) - - if echo "$status" | grep -q "MySQL running";then - echo "MySQL started successfully." - return 0 - else - echo "Failed to start MySQL." - return 1 - fi -} - -do_test() { - msg "this is do_test" - - # 运行MySQL测试 - - #查找安装路径 - mysql_install_path=$(which mysql) - cd $(dirname $(which mysql)) - cd .. - cd mysql-test - ./mysql-test-run 2>&1 | tee test_output.txt - - #检查测试结果 - - if grep -q "All tests" "test_output.txt"; then - echo "All tests passed" - elif grep -q "Not all tests completed" "test_output.txt";then - echo "Some tests failed" - else - echo "Test failed!" - return 1 - fi - - assert_true [ 1 -eq 1 ] - - return 0 -} - - -tc_teardown() { - msg "this is tc_teardown" - #关闭MySQL - sudo service mysql stop - - #等待MySQL关闭 - sleep 10 - - #检查MySQL是否关闭成功 - status=$(sudo service mysql status) - if echo "$status" | grep -q "MySQL running";then - echo "Failed to stop the mysql." - else - echo "The mysql has been successfully stopped." - return 1 - fi - rm -rfv "$g_tmpdir" || return 1 - return 0 -} - - -############################################################################### -tst_main "$@" -############################################################################### diff --git a/coreutils/testcase/tc-mkdir-01.sh b/coreutils/testcase/tc-mkdir-01.sh deleted file mode 100755 index 0875eb7..0000000 --- a/coreutils/testcase/tc-mkdir-01.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/bin/bash -############################################################################### -# @用例ID: 20230106-200139-207891169 -# @用例名称: tc-mkdir-01 -# @用例级别: 3 -# @用例标签: -# @用例类型: 功能 -############################################################################### -[ -z "$TST_TS_TOPDIR" ] && { - TST_TS_TOPDIR="$(realpath "$(dirname "$0")/..")" - export TST_TS_TOPDIR -} -source "${TST_TS_TOPDIR}/tst_common/lib/common.sh" || exit 1 -############################################################################### - -g_tmpdir="$(mktemp -d)" - -tc_setup() { - msg "this is tc_setup" - # @预置条件: 系统已安装coreutils软件包 - return 0 -} - -do_test() { - msg "this is do_test" - - # @测试步骤:1: 创建目录验证mkdir命令基础功能 - # @预期结果:1: 目录创建成功,符合参数设置预期 - assert_true mkdir "$g_tmpdir/mkdir.test" - assert_true test -d "$g_tmpdir/mkdir.test" - assert_true rm -rv "$g_tmpdir/mkdir.test" - - assert_true mkdir -p "$g_tmpdir/mkdir.test/child" - assert_true test -d "$g_tmpdir/mkdir.test/child" - assert_true rm -rv "$g_tmpdir/mkdir.test" - - return 0 -} - -tc_teardown() { - msg "this is tc_teardown" - rm -rfv "$g_tmpdir" || return 1 - return 0 -} - -############################################################################### -tst_main "$@" -############################################################################### diff --git a/coreutils/tst_lib/Makefile b/coreutils/tst_lib/Makefile deleted file mode 100644 index 171b10b..0000000 --- a/coreutils/tst_lib/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -export TST_TS_TOPDIR ?= $(shell pwd)/.. -include $(TST_TS_TOPDIR)/Makefile.common -ALL_SRC := $(wildcard *.c) -ALL_OBJ := $(patsubst %.c,%.o,$(ALL_SRC)) -LIB_STATIC := libtscommon.a -CFLAGS += - -all: $(LIB_STATIC) - -$(LIB_STATIC): $(ALL_OBJ) - ar -rc $(LIB_STATIC) $(ALL_OBJ) - -$(ALL_OBJ):%.o:%.c - $(CC) $(CFLAGS) -c $^ -o $@ - -clean: - rm -rfv $(LIB_STATIC) $(ALL_OBJ) - -cleanall: clean - rm -rfv __pycache__ diff --git a/coreutils/tst_lib/other_common.sh b/coreutils/tst_lib/other_common.sh deleted file mode 100644 index e63ac90..0000000 --- a/coreutils/tst_lib/other_common.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/bash - -my_func() { - return 0 -} diff --git a/coreutils/tst_lib/ts_common.c b/coreutils/tst_lib/ts_common.c deleted file mode 100644 index b65caf6..0000000 --- a/coreutils/tst_lib/ts_common.c +++ /dev/null @@ -1,23 +0,0 @@ -// 测试套自定义公共函数库 -#include "common.h" -#include "ts_common.h" - -int ts_setup(void) { - msg("this is ts_setup"); - return 0; -} - -int tc_setup_common(int argc, char **argv) { - msg("this is tc_setup_common"); - return 0; -} - -int tc_teardown_common(int argc, char **argv) { - msg("this is tc_teardown_common"); - return 0; -} - -int ts_teardown(void) { - msg("this is ts_teardown"); - return 0; -} diff --git a/coreutils/tst_lib/ts_common.h b/coreutils/tst_lib/ts_common.h deleted file mode 100644 index 9ed2c5f..0000000 --- a/coreutils/tst_lib/ts_common.h +++ /dev/null @@ -1,6 +0,0 @@ -#ifndef __TS_COMMON_H__ -#define __TS_COMMON_H__ - -// 测试套自定义头文件内容 - -#endif // __TS_COMMON_H__ diff --git a/coreutils/tst_lib/ts_common.py b/coreutils/tst_lib/ts_common.py deleted file mode 100644 index 5b60299..0000000 --- a/coreutils/tst_lib/ts_common.py +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env python3 -# coding: utf-8 -# Desc: 测试套公共模块 -import abc -import os.path -import sys - -sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) -from tst_common.lib.common import TestCase - - -class MyTestCase(TestCase): - """ - 本测试套内的Python用例需要继承此类 - """ - - def tc_setup_common(self, *args): - """ - 所有Python用例执行tc_setup函数前会先执行本函数 - :param args: - :return: - """ - self.msg("this is tc_setup_common") - - @abc.abstractmethod - def do_test(self, *args): - pass - - def tc_teardown_common(self, *args): - """ - 所有Python用例执行tc_teardown函数后会执行本函数 - :param args: - :return: - """ - self.msg("this is tc_teardown_common") diff --git a/coreutils/tst_lib/ts_common.sh b/coreutils/tst_lib/ts_common.sh deleted file mode 100644 index 0516a9e..0000000 --- a/coreutils/tst_lib/ts_common.sh +++ /dev/null @@ -1,28 +0,0 @@ -#!/bin/bash -# 测试套公共函数 -# 约定: -# 1、以下划线"_"开头的函数和变量用例不能直接调用 -# 2、环境变量全大写,全局变量加上"g_"前置,局部变量统一加"local"修饰 - -# source自己定义的其他公共函数 -source "${TST_TS_TOPDIR}/tst_lib/other_common.sh" || exit 1 - -ts_setup() { - msg "this is ts_setup" - return 0 -} - -tc_setup_common() { - msg "this is tc_setup_common" - return 0 -} - -tc_teardown_common() { - msg "this is tc_teardown_common" - return 0 -} - -ts_teardown() { - msg "this is ts_teardown" - return 0 -} diff --git a/coreutils/tst_lib/ts_setup b/coreutils/tst_lib/ts_setup deleted file mode 100755 index 4e65f5a..0000000 --- a/coreutils/tst_lib/ts_setup +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/bash -# Time: 2022-04-19 22:44:25 -# Desc: ts_setup -[ -z "$TST_TS_TOPDIR" ] && export TST_TS_TOPDIR="$(realpath "$(dirname "$0")/..")" -source "${TST_TS_TOPDIR}/tst_common/lib/common.sh" - -ts_setup() { - # 测试套setup脚本,在这里增加setup操作 - msg "this is ts_setup" - yum install -y coreutils - return 0 -} - -ts_setup diff --git a/coreutils/tst_lib/ts_teardown b/coreutils/tst_lib/ts_teardown deleted file mode 100755 index 324080f..0000000 --- a/coreutils/tst_lib/ts_teardown +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash -# Time: 2022-04-19 22:44:25 -# Desc: ts_teardown -[ -z "$TST_TS_TOPDIR" ] && export TST_TS_TOPDIR="$(realpath "$(dirname "$0")/..")" -source "${TST_TS_TOPDIR}/tst_common/lib/common.sh" - -ts_teardown() { - # 测试套teardown脚本,在这里增加teardown操作 - msg "this is ts_teardown" - return 0 -} - -ts_teardown diff --git a/coreutils/tsuite b/coreutils/tsuite deleted file mode 120000 index d7009e5..0000000 --- a/coreutils/tsuite +++ /dev/null @@ -1 +0,0 @@ -tst_common/tsuite \ No newline at end of file -- Gitee From f43656f7e3e576ca1104eb662e918b4d9acbadc1 Mon Sep 17 00:00:00 2001 From: hou Date: Thu, 25 May 2023 05:46:49 +0000 Subject: [PATCH 13/20] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=96=87=E4=BB=B6=20.g?= =?UTF-8?q?itmodules?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitmodules | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 .gitmodules diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 26e658d..0000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "coreutils/tst_common"] - path = coreutils/tst_common - url = https://gitee.com/opencloudos-stream/test-suite-base.git -- Gitee From edc67dfa1562dbc055dd2a1d2f5076a6bf9c3b38 Mon Sep 17 00:00:00 2001 From: hou Date: Thu, 25 May 2023 05:46:55 +0000 Subject: [PATCH 14/20] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=96=87=E4=BB=B6=20RE?= =?UTF-8?q?ADME.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 30 ------------------------------ 1 file changed, 30 deletions(-) delete mode 100644 README.md diff --git a/README.md b/README.md deleted file mode 100644 index 2a3f718..0000000 --- a/README.md +++ /dev/null @@ -1,30 +0,0 @@ -# packages-testing - - -#### 介绍 -OpenCloudOS软件测试项目 - - -#### 软件架构 -本项目集成OpenCloudOS软件包测试套,项目下每个目录对应一个软件包的测试套。 -本项目测试套要求在测试套的setup中完成软件包的安装动作,测试套中的用例要求完全独立,互相之间不能有耦合。 - - -#### 使用说明 -下载项目代码到本地:`git clone --recurse-submodules https://gitee.com/OpenCloudOS/packages-testing.git` -按需使用项目中的测试套对软件包进行测试,用法参考:https://gitee.com/opencloudos-stream/test-suite-base - - -#### 使用说明 -测试套用法:https://gitee.com/opencloudos-stream/test-suite-base - - -#### 参与贡献 - -1. Fork 本仓库`git clone --recurse-submodules https://gitee.com/OpenCloudOS/packages-testing.git` -2. 新建软件包测试套`cd ./packages-testing && ./tstManager new my_test_suite` -3. 开发软件测试用例 -4. 提交代码 -5. 新建 Pull Request - -测试套和用例开发参考:https://gitee.com/opencloudos-stream/test-suite-example -- Gitee From 254dab0c8c14cbf5316566b117d64592cd034c16 Mon Sep 17 00:00:00 2001 From: hou Date: Thu, 25 May 2023 05:47:01 +0000 Subject: [PATCH 15/20] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=96=87=E4=BB=B6=20ts?= =?UTF-8?q?tManager?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tstManager | 114 ----------------------------------------------------- 1 file changed, 114 deletions(-) delete mode 100755 tstManager diff --git a/tstManager b/tstManager deleted file mode 100755 index 860427f..0000000 --- a/tstManager +++ /dev/null @@ -1,114 +0,0 @@ -#!/bin/bash -# 本工具用于对测试套的管理 - -g_topdir="$(realpath "$(dirname "$0")")" - -# 新建测试套 -# $1 -- 测试套名称 -new_suite(){ - local suite_name="$1" - if [ -z "$suite_name" ]; then - echo "the suite name not set" - return 1 - fi - if [ -e ./$suite_name ]; then - echo "the suite name $suite_name existed" - return 1 - fi - if ! echo $suite_name | grep -q "^[-_.a-zA-Z0-9]\+$"; then - echo "the suite name can only [-_.a-zA-Z0-9]" - return 1 - fi - - echo try git clone https://gitee.com/opencloudos-stream/test-suite-example.git ./$suite_name - if ! git clone https://gitee.com/opencloudos-stream/test-suite-example.git ./$suite_name; then - echo "clone the test-suite-example fail" - rm -rf ./$suite_name - return 1 - fi - mv ./$suite_name/.gitignore ./$suite_name/gitignore - rm -rf ./$suite_name/.git* ./$suite_name/tst_common - mv ./$suite_name/gitignore ./$suite_name/.gitignore - - echo try git submodule add https://gitee.com/opencloudos-stream/test-suite-base.git ./$suite_name/tst_common - if ! git submodule add https://gitee.com/opencloudos-stream/test-suite-base.git ./$suite_name/tst_common; then - echo "set the suite $suite_name submodule fail" - rm -rf ./$suite_name - return 1 - fi - rm -f ./$suite_name/testcase/test_* - - return 0 -} - -# 编译测试套 -# $* -- 要编译的测试套 -compile_suite(){ - local tst_cwd="$(pwd)" - local tst_ret=0 - local suite_list="$*" - - if [ -z "$suite_list" ]; then - echo "suite not set, compile all" - for f in */tsuite; do - suite_list="$suite_list $(dirname $f)" - done - fi - - for suite in $suite_list; do - cd "$tst_cwd" || return 1 - if [ ! -f ./$suite/tsuite ]; then - echo "the suite $suite has no tsuite, ignore" - continue - fi - cd ./$suite || return 1 - if ./tsuite compile; then - echo "compile $suite success" - else - echo "compile $suite fail" - tst_ret=1 - fi - done - - cd "$tst_cwd" || return 1 - return $tst_ret -} - -usage(){ - echo "" - echo "Usage: $0 command" - echo "command:" - echo " new suite_name: 新建测试套" - echo " suite_name: 【必选】新测试套名称" - echo " compile [suite_name...]: 编译测试套" - echo " suite_name: 【可选】要编译的测试套名称,不指定则编译所有测试套" - echo "" -} - -main(){ - local ret=0 - - echo "g_topdir=$g_topdir" - echo "change the CWD to $g_topdir" - cd "$g_topdir" - - case "$1" in - new) - shift - new_suite "$@" || ret=1 - ;; - compile) - shift - compile_suite "$@" || ret=1 - ;; - *) - echo "unknow command: $*" - usage - return 1 - ;; - esac - - return $ret -} - -main "$@" -- Gitee From e034b0a28df0333e2b6be2cd59906ba9712505e5 Mon Sep 17 00:00:00 2001 From: hou Date: Thu, 25 May 2023 05:49:04 +0000 Subject: [PATCH 16/20] =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hou --- .gitmodules | 3 ++ README.md | 30 ++++++++++++++ tstManager | 114 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 147 insertions(+) create mode 100644 .gitmodules create mode 100644 README.md create mode 100644 tstManager diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..26e658d --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "coreutils/tst_common"] + path = coreutils/tst_common + url = https://gitee.com/opencloudos-stream/test-suite-base.git diff --git a/README.md b/README.md new file mode 100644 index 0000000..2a3f718 --- /dev/null +++ b/README.md @@ -0,0 +1,30 @@ +# packages-testing + + +#### 介绍 +OpenCloudOS软件测试项目 + + +#### 软件架构 +本项目集成OpenCloudOS软件包测试套,项目下每个目录对应一个软件包的测试套。 +本项目测试套要求在测试套的setup中完成软件包的安装动作,测试套中的用例要求完全独立,互相之间不能有耦合。 + + +#### 使用说明 +下载项目代码到本地:`git clone --recurse-submodules https://gitee.com/OpenCloudOS/packages-testing.git` +按需使用项目中的测试套对软件包进行测试,用法参考:https://gitee.com/opencloudos-stream/test-suite-base + + +#### 使用说明 +测试套用法:https://gitee.com/opencloudos-stream/test-suite-base + + +#### 参与贡献 + +1. Fork 本仓库`git clone --recurse-submodules https://gitee.com/OpenCloudOS/packages-testing.git` +2. 新建软件包测试套`cd ./packages-testing && ./tstManager new my_test_suite` +3. 开发软件测试用例 +4. 提交代码 +5. 新建 Pull Request + +测试套和用例开发参考:https://gitee.com/opencloudos-stream/test-suite-example diff --git a/tstManager b/tstManager new file mode 100644 index 0000000..860427f --- /dev/null +++ b/tstManager @@ -0,0 +1,114 @@ +#!/bin/bash +# 本工具用于对测试套的管理 + +g_topdir="$(realpath "$(dirname "$0")")" + +# 新建测试套 +# $1 -- 测试套名称 +new_suite(){ + local suite_name="$1" + if [ -z "$suite_name" ]; then + echo "the suite name not set" + return 1 + fi + if [ -e ./$suite_name ]; then + echo "the suite name $suite_name existed" + return 1 + fi + if ! echo $suite_name | grep -q "^[-_.a-zA-Z0-9]\+$"; then + echo "the suite name can only [-_.a-zA-Z0-9]" + return 1 + fi + + echo try git clone https://gitee.com/opencloudos-stream/test-suite-example.git ./$suite_name + if ! git clone https://gitee.com/opencloudos-stream/test-suite-example.git ./$suite_name; then + echo "clone the test-suite-example fail" + rm -rf ./$suite_name + return 1 + fi + mv ./$suite_name/.gitignore ./$suite_name/gitignore + rm -rf ./$suite_name/.git* ./$suite_name/tst_common + mv ./$suite_name/gitignore ./$suite_name/.gitignore + + echo try git submodule add https://gitee.com/opencloudos-stream/test-suite-base.git ./$suite_name/tst_common + if ! git submodule add https://gitee.com/opencloudos-stream/test-suite-base.git ./$suite_name/tst_common; then + echo "set the suite $suite_name submodule fail" + rm -rf ./$suite_name + return 1 + fi + rm -f ./$suite_name/testcase/test_* + + return 0 +} + +# 编译测试套 +# $* -- 要编译的测试套 +compile_suite(){ + local tst_cwd="$(pwd)" + local tst_ret=0 + local suite_list="$*" + + if [ -z "$suite_list" ]; then + echo "suite not set, compile all" + for f in */tsuite; do + suite_list="$suite_list $(dirname $f)" + done + fi + + for suite in $suite_list; do + cd "$tst_cwd" || return 1 + if [ ! -f ./$suite/tsuite ]; then + echo "the suite $suite has no tsuite, ignore" + continue + fi + cd ./$suite || return 1 + if ./tsuite compile; then + echo "compile $suite success" + else + echo "compile $suite fail" + tst_ret=1 + fi + done + + cd "$tst_cwd" || return 1 + return $tst_ret +} + +usage(){ + echo "" + echo "Usage: $0 command" + echo "command:" + echo " new suite_name: 新建测试套" + echo " suite_name: 【必选】新测试套名称" + echo " compile [suite_name...]: 编译测试套" + echo " suite_name: 【可选】要编译的测试套名称,不指定则编译所有测试套" + echo "" +} + +main(){ + local ret=0 + + echo "g_topdir=$g_topdir" + echo "change the CWD to $g_topdir" + cd "$g_topdir" + + case "$1" in + new) + shift + new_suite "$@" || ret=1 + ;; + compile) + shift + compile_suite "$@" || ret=1 + ;; + *) + echo "unknow command: $*" + usage + return 1 + ;; + esac + + return $ret +} + +main "$@" -- Gitee From fa3160b3bdc8002a863811975d64386f3973d61e Mon Sep 17 00:00:00 2001 From: hou Date: Thu, 25 May 2023 05:59:05 +0000 Subject: [PATCH 17/20] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=96=87=E4=BB=B6=20.g?= =?UTF-8?q?itmodules?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitmodules | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 .gitmodules diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 26e658d..0000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "coreutils/tst_common"] - path = coreutils/tst_common - url = https://gitee.com/opencloudos-stream/test-suite-base.git -- Gitee From b9a63430f10c4ad2947ec3cf0978a0b35c421fb8 Mon Sep 17 00:00:00 2001 From: hou Date: Thu, 25 May 2023 05:59:12 +0000 Subject: [PATCH 18/20] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=96=87=E4=BB=B6=20RE?= =?UTF-8?q?ADME.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 30 ------------------------------ 1 file changed, 30 deletions(-) delete mode 100644 README.md diff --git a/README.md b/README.md deleted file mode 100644 index 2a3f718..0000000 --- a/README.md +++ /dev/null @@ -1,30 +0,0 @@ -# packages-testing - - -#### 介绍 -OpenCloudOS软件测试项目 - - -#### 软件架构 -本项目集成OpenCloudOS软件包测试套,项目下每个目录对应一个软件包的测试套。 -本项目测试套要求在测试套的setup中完成软件包的安装动作,测试套中的用例要求完全独立,互相之间不能有耦合。 - - -#### 使用说明 -下载项目代码到本地:`git clone --recurse-submodules https://gitee.com/OpenCloudOS/packages-testing.git` -按需使用项目中的测试套对软件包进行测试,用法参考:https://gitee.com/opencloudos-stream/test-suite-base - - -#### 使用说明 -测试套用法:https://gitee.com/opencloudos-stream/test-suite-base - - -#### 参与贡献 - -1. Fork 本仓库`git clone --recurse-submodules https://gitee.com/OpenCloudOS/packages-testing.git` -2. 新建软件包测试套`cd ./packages-testing && ./tstManager new my_test_suite` -3. 开发软件测试用例 -4. 提交代码 -5. 新建 Pull Request - -测试套和用例开发参考:https://gitee.com/opencloudos-stream/test-suite-example -- Gitee From 3b49f538ced9be901f627dd57b9faaca398a3f9f Mon Sep 17 00:00:00 2001 From: hou Date: Thu, 25 May 2023 05:59:17 +0000 Subject: [PATCH 19/20] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=96=87=E4=BB=B6=20ts?= =?UTF-8?q?tManager?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tstManager | 114 ----------------------------------------------------- 1 file changed, 114 deletions(-) delete mode 100644 tstManager diff --git a/tstManager b/tstManager deleted file mode 100644 index 860427f..0000000 --- a/tstManager +++ /dev/null @@ -1,114 +0,0 @@ -#!/bin/bash -# 本工具用于对测试套的管理 - -g_topdir="$(realpath "$(dirname "$0")")" - -# 新建测试套 -# $1 -- 测试套名称 -new_suite(){ - local suite_name="$1" - if [ -z "$suite_name" ]; then - echo "the suite name not set" - return 1 - fi - if [ -e ./$suite_name ]; then - echo "the suite name $suite_name existed" - return 1 - fi - if ! echo $suite_name | grep -q "^[-_.a-zA-Z0-9]\+$"; then - echo "the suite name can only [-_.a-zA-Z0-9]" - return 1 - fi - - echo try git clone https://gitee.com/opencloudos-stream/test-suite-example.git ./$suite_name - if ! git clone https://gitee.com/opencloudos-stream/test-suite-example.git ./$suite_name; then - echo "clone the test-suite-example fail" - rm -rf ./$suite_name - return 1 - fi - mv ./$suite_name/.gitignore ./$suite_name/gitignore - rm -rf ./$suite_name/.git* ./$suite_name/tst_common - mv ./$suite_name/gitignore ./$suite_name/.gitignore - - echo try git submodule add https://gitee.com/opencloudos-stream/test-suite-base.git ./$suite_name/tst_common - if ! git submodule add https://gitee.com/opencloudos-stream/test-suite-base.git ./$suite_name/tst_common; then - echo "set the suite $suite_name submodule fail" - rm -rf ./$suite_name - return 1 - fi - rm -f ./$suite_name/testcase/test_* - - return 0 -} - -# 编译测试套 -# $* -- 要编译的测试套 -compile_suite(){ - local tst_cwd="$(pwd)" - local tst_ret=0 - local suite_list="$*" - - if [ -z "$suite_list" ]; then - echo "suite not set, compile all" - for f in */tsuite; do - suite_list="$suite_list $(dirname $f)" - done - fi - - for suite in $suite_list; do - cd "$tst_cwd" || return 1 - if [ ! -f ./$suite/tsuite ]; then - echo "the suite $suite has no tsuite, ignore" - continue - fi - cd ./$suite || return 1 - if ./tsuite compile; then - echo "compile $suite success" - else - echo "compile $suite fail" - tst_ret=1 - fi - done - - cd "$tst_cwd" || return 1 - return $tst_ret -} - -usage(){ - echo "" - echo "Usage: $0 command" - echo "command:" - echo " new suite_name: 新建测试套" - echo " suite_name: 【必选】新测试套名称" - echo " compile [suite_name...]: 编译测试套" - echo " suite_name: 【可选】要编译的测试套名称,不指定则编译所有测试套" - echo "" -} - -main(){ - local ret=0 - - echo "g_topdir=$g_topdir" - echo "change the CWD to $g_topdir" - cd "$g_topdir" - - case "$1" in - new) - shift - new_suite "$@" || ret=1 - ;; - compile) - shift - compile_suite "$@" || ret=1 - ;; - *) - echo "unknow command: $*" - usage - return 1 - ;; - esac - - return $ret -} - -main "$@" -- Gitee From c5920b5337d02ebb4f5aaa436e9fc7e15142d050 Mon Sep 17 00:00:00 2001 From: hou Date: Thu, 25 May 2023 05:59:34 +0000 Subject: [PATCH 20/20] =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hou --- mysql-test.sh | 98 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 mysql-test.sh diff --git a/mysql-test.sh b/mysql-test.sh new file mode 100644 index 0000000..36ca572 --- /dev/null +++ b/mysql-test.sh @@ -0,0 +1,98 @@ +#!/bin/bash +############################################################################### +# @用例ID: 20230525-101210-083410876 +# @用例名称: mysql-test +# @用例级别: 3 +# @用例标签: +# @用例类型: 功能 +############################################################################### +[ -z "$TST_TS_TOPDIR" ] && { + TST_TS_TOPDIR="$(realpath "$(dirname "$0")/..")" + export TST_TS_TOPDIR +} +source "${TST_TS_TOPDIR}/tst_common/lib/common.sh" || exit 1 +############################################################################### + +g_tmpdir="$(mktemp -d)" + +tc_setup() { + msg "this is tc_setup" + + #检查是否安装了MySQL + + if ! command -v mysql >/dev/null 2>&1; then + echo "MySQL not installed." + return 1 + else + mysql_version=$(mysql -V |awk '{print $3}' | awk -F, '{print $1}') + echo "MySQL version: $mysql_version" + fi + + # 启动MySQL + sudo service mysql start + + #检查MySQL是否成功启动 + status=$(service mysql status) + + if echo "$status" | grep -q "MySQL running";then + echo "MySQL started successfully." + return 0 + else + echo "Failed to start MySQL." + return 1 + fi +} + +do_test() { + msg "this is do_test" + + # 运行MySQL测试 + + #查找安装路径 + mysql_install_path=$(which mysql) + cd $(dirname $(which mysql)) + cd .. + cd mysql-test + ./mysql-test-run 2>&1 | tee test_output.txt + + #检查测试结果 + + if grep -q "All tests" "test_output.txt"; then + echo "All tests passed" + elif grep -q "Not all tests completed" "test_output.txt";then + echo "Some tests failed" + else + echo "Test failed!" + return 1 + fi + + assert_true [ 1 -eq 1 ] + + return 0 +} + + +tc_teardown() { + msg "this is tc_teardown" + #关闭MySQL + sudo service mysql stop + + #等待MySQL关闭 + sleep 10 + + #检查MySQL是否关闭成功 + status=$(sudo service mysql status) + if echo "$status" | grep -q "MySQL running";then + echo "Failed to stop the mysql." + else + echo "The mysql has been successfully stopped." + return 1 + fi + rm -rfv "$g_tmpdir" || return 1 + return 0 +} + + +############################################################################### +tst_main "$@" +############################################################################### -- Gitee