PIE模型
Fault:靜態存在於軟件中的缺陷;如代碼存在錯誤
int numbers[] = {3, 5, 6};
int lenth = numbers.length;
double mean,sum;
sum = 0.0;
// 計算數組所有元素的平均值
for (int i = 1; i < lenth; i++) { // 這裏i應該爲0,但是i卻爲1,代碼存在一個靜態缺陷
sum += numbers[i];
}
mean = sum / (double) lenth;
System.out.print("Mean:" + mean);
Error: 軟件運行中,運行到fault,觸發產生的錯誤;
Failure: Error傳播到軟件外部,使用戶用結果與專業文檔對比,觀測到失效的行爲。
要觀測到Failure需要三個必要的條件:
1、執行必須通過錯誤的代碼(Execution-執行);
2、在執行錯誤代碼的時候必須觸發出一個錯誤的中間狀態(Infection-感染);
3、錯誤的中間狀態必須傳播到最後輸出,使得觀測到輸出結果與預期結果不一致(Propagation-傳播)。
一個測試執行到包含fault的代碼,不一定會產生錯誤的中間狀態error;產生了錯誤的中間狀態,不一定會有失效failure。
在上述代碼段中,如 for (int i = 1; i < lenth; i++) 就是一個fault,在正確代碼中,i的初值應該爲0,應該從數組的0號元素開始計算,這種錯誤就是Fault。
當有Fault的代碼,在運行過程中就會導致相應的Error。
如下代碼,若將i = 0,打成 i = 1,則會導致 sum=5+6(正常情況:i = 0,則sum = 3+5+6),Fault導致的sum表現出計算錯誤,這種 sum的計算錯誤爲Error。代碼繼續運行會導致 平均數mean的結果錯誤,mean的計算錯誤表現在輸出,即爲Failure。
如果數組爲(0,1,1,3) 時,雖然導致了error,但是輸出中並沒有體現出計算錯誤,這時Failure就不存在。
PIE模型相關的題目
Please construct a simple program P (with a fault) and 3 tests (t1, t2, t3), s.t.
t1 executes the fault, but no error
t2 (executes the fault and) produces an error, but no failure
t3 produces a failure
*/
public class test {
public static int[] P(int[] array) { //冒泡排序
if (array.length == 0)
return array;
for (int i = 1; i < array.length; i++) // for (int i = 0; i < array.length; i++)
for (int j = 1; j < array.length - 1 - i; j++) //for (int j = 0; j < array.length - 1 - i; j++)
if (array[j + 1] < array[j]) {
int temp = array[j + 1];
array[j + 1] = array[j];
array[j] = temp;
}
return array;
}
public static void print(int[] array) { //輸出數組元素
System.out.print(" 排序後:" );
for(int i=0;i<array.length;i++) {
System.out.print( " " + array[i] );
}
}
public static void main(String[] args) {
int array1[] = {1, 2, 8, 11, 58}; //t1 t1 executes the fault, but no error
int array2[] = {2, 6, 5, 11, 8, 26}; //t2 t2 (executes the fault and) produces an error, but no failure
int array3[] = {24, 8, 5, 11, 2, 9}; //t3 t3 produces a failure
System.out.println("t1排序前:1 2 8 11 58 " );
P(array1);
print(array1);
System.out.println('\n');
System.out.println("t2排序前:2 6 5 11 8 26 " );
P(array2);
print(array2);
System.out.println('\n');
System.out.println("t3排序前:24 8 5 11 2 9 " );
P(array3);
print(array3);
}
}