Test et Validation - Cedric
Transcription
Test et Validation - Cedric
Test et Validation Tristan Crolard Laboratoire CEDRIC Equipe CPR [email protected] cedric.cnam.fr/cpr/crolard 1 Organisation du cours Cours/ED : 5 séances de 3h ¡ ¡ Langages de programmations : Java et Ada Exemples et démonstrations d'outils TP : 4 séances de 3h ¡ ¡ Langage de programmation : Java Plateforme de test : jUnit et autres plugins Eclipse 2 Organisation du cours 1. 2. 3. 4. 5. 6. 7. Séances de cours Fondamentaux des tests 1 Tester pendant le cycle de vie logiciel Techniques de test Techniques statiques et revues de code Techniques boites noires 2 Techniques boites blanches Critères de couverture 3 Gestion des tests Tester à partir de modèles Modéliser les spécications 4 Génération automatique de tests Outils de support aux tests Méthodes formelles (survol) 5 3 TP X X X X X X Bibliographie Pratique des tests logiciels (Dunod, 2009) J. Printz, J.-F. Peyre. Le test des logiciels (Hermès, 2000) S. Xanthakis, P. Régnier, C. Karapoulios. The art of software testing (Wiley, 1979. Second edition 2004) G. J. Meyers. Glossaire des termes utilisés en tests de logiciels. (CFTL/ISTQB, 2007) Comité Français des Tests Logiciels/International Software Testing Qualications Board. 4 Test, vérication et validation Terminologie Validation. The assurance that a product, service, or system meets the needs of the customer and other identied stakeholders. It often involves acceptance and suitability with external customers. Verification. The evaluation of whether or not a product, service, or system complies with a regulation, requirement, specication, or imposed condition. It is often an internal process. The PMBOK guide (norme IEEE) 5 Test, vérication et validation Citation Verication is building the product right, and Validation is building the right product. B. W. Boehm Verifying and Validating Software Requirements and Design Specications Software Risk Management, pp. 205 - 218, IEEE Computer Society Press, 1989. 6 Terminologie Extraite des normes IEEE STD 982 et 1044 : ERROR (Erreur) : Human action that results in software containing a fault. E.g. omission or misinterpretation of user requirements in a software specification, and incorrect translation or omission of a requirement in the design specication. DEFECT (Défaut) : A product anomaly; e.g. (1) omissions and imperfections found during early life cycle phases and (2) faults contained in software suciently mature for test or operation. FAULT (Défaillance) : (1) An accidental condition that causes a functional unit to fail to perform its required function. (2) A manifestation of an error in software. A fault if encountered may cause a failure. FAILURE (Panne) : The termination of the ability of a functional unit to perform its required function. A failure may be produced when a fault is encountered. 7 Méthodes de vérication et validation Revue de code et de documentation (relecture) Analyse statique (typage, analyse de ot information/contrôle, ...) Test (dynamique) Execution symbolique (génération de tests, ...) Vérication formelle (model-checking , preuve de programme, ...) 8 Analyse statique Principalement réalisée par le compilateur ¡ vérication de la syntaxe ¡ vérication du ot d'information (variables initialisées) ¡ vérication du typage ¡ vérication du ot de contrôle (code mort) Certains outils existent souvent pour les langages dynamiques (comme python, javascript, php, ...) Certains outils permettent de faire des analyses plus nes que celles des compilateurs (par exemple par interprétation abstraite) 9 Analyse statique (exemple) Closure : Compilateur javascript de Google https://developers.google.com/closure/compiler/docs/js-for-compiler Extraits de la documentation : The Closure Compiler provides warnings for illegal JavaScript and warnings for potentially dangerous operations, helping you to produce JavaScript that is less buggy and easier to maintain. The Closure Compiler can use data type information about JavaScript variables to provide enhanced optimization and warnings. The Closure Compiler's type language derives from the annotations used by the JSDoc document-generation tool. 10 Analyse statique de source JavaScript /** * @param {number} x * @return {number} */ function foo(x) { return x+2; } /** * @param {number} x some value * @return {number} some result */ function bar(x) { return x+"bar"; } Line 14: WARNING - inconsistent return type found : string required: number return x+"bar"; ^ 0 error(s), 1 warning(s), 100.0% typed 11 Analyse statique (autre exemple) Phantm : PHP ANALYZER FOR TYPE MISMATCH http://lara.ep.ch/w/phantm Extraits de la documentation : Phantm analyzes PHP code statically (with optional help from dynamic instrumention). It has found many errors in real PHP applications. Phantm is a tool written in Scala that can be used to detect potential programming errors inside PHP applications. It will both work for small isolated script as well as full-blown applications. Phantm does multiple things: it first parses your php files, then try to resolve both constants and included les, from that point it will do name analysis, ensuring basic language restrictions. From that stage, it will perform data-ow analysis for every scopes in your applications. This dataow analysis will be focused on checking whether the types of the values are used in a sound way. 12 Analyse statique de source PHP <?php /** * @param int $x * @return int */ function foo($x) { return ($x + 2); } /** * @param int $b */ function bar($b) { return $x+"bar"; } Line 14 Notice: Type mismatch: expected: Numeric, found: Top return $x+"bar"; 1 notice and 0 error occured. 13 Autres exemples récents Facebook Hack: Statically Typed PHP Perl 6 Mypy : experimental optional static type checker for Python Apple Swift Microsoft TypeScript (javascript) 14 Test : dénition et citations Testing is the process of analyzing a software item to detect the dierences between existing and required conditions, (that is, bugs) and to evaluate the features of the software items IEEE (Standard Glossary of Software Engineering Terminology). Testing is the process of executing a program with the intent of nding errors. Glenford J. Myers. The Art of Software testing. Wiley, 1979. Second edition 2004. Testing can reveal the presence of errors but never their absence Edsgar W. Dijkstra. Notes on structured programming. Academic Press, 1972. 15 Terminologie [CFTL] Processus de test : processus consistant en toutes les activités du cycle de vie, statiques et dynamiques, concernant la planication et l'évaluation de produits logiciels, pour déterminer s'ils satisfont aux exigences, pour démontrer qu'ils sont aptes aux objectifs et pour en détecter des anomalies. Test : un ensemble d'un ou plusieurs cas de tests [IEEE 829]. Cas de test : un ensemble de valeurs d'entrée (données de tests), de pré conditions d'exécution, de résultats attendus et de post conditions d'exécution, développées pour un objectif particulier, tel qu'exécuter un chemin donné d'un programme ou vérifier le respect d'une exigence spécifique [IEEE 610]. Objectif de test : une raison ou un but pour la conception et l'exécution d'un test. Scénario de test : un document spécifiant la séquence d'actions pour l'exécution d'un cas de test. Stratégie de test : un document de haut niveau dénissant, pour un programme, les tests à exécuter (pour un ou plusieurs projets). 16 Cycle de vie du logiciel modèle en V Tests de conformité Spécifications Tests d’intégration Conception générale Tests unitaires Conception détaillée Implémentation 17 Diérents types de tests En fonction de la granularité Tests unitaires Tests d'intégration Tests de conformité En fonction des caractéristiques En fonction de l'accessibilité Tests fonctionnels boites noires Tests structurels boites blanches 18 Tests de non-régression Tests de performance ... Tests de robustesse Tests de sécurité Test fonctionnel boites noires Dénition [CFTL] Technique de test où les cas de tests sont élaborés à partir d'une analyse des spécifications des fonctionnalités d'un composant ou système sans référence à sa structure interne. Méthodes du test fonctionnel Test aléatoire Analyse partitionnelle des domaines des données d'entrée (et test aux limites) Test combinatoire Algorithmes Pairwise Génération automatique de tests à partir de spécications 19 Test structurel boites blanches Dénition [CFTL] Technique de test où les cas de tests sont basés sur une analyse de la structure interne d'un composant ou système (en général, le code source). Méthodes du test structurel Basés sur le graphe de ot de contrôle (toutes les instructions, toutes les branches, tous les chemins, ...) Basés sur la couverture du flot de données (toutes les définitions de variable, toutes les utilisations, ...) Remarque. Le test structurel complète le test fonctionnel, il ne peut pas le remplacer (il permet de couvrir le code source existant mais il ne dit rien sur le code source qui peut manquer). 20 Le test dans le cadre des logiciels critiques Norme DO-178 : Software Considerations in Airborne Systems and Equipment Certication (Règlementation pour le développement de logiciels dans le secteur aéronautique). Norme EN 50128 : Railway applications Software for railway control and protection systems Communication, signalling and processing systems (Domaine ferroviaire Logiciels pour les systèmes de contrôle et de protection ferroviaires Systèmes de signalisation électroniques reliés à la sécurité) 21 Norme DO-178 (aéronautique) 6.4 Software Testing Process ::: 6.4.4 Test Coverage Analysis Test coverage analysis is a two step process, involving requirements-based coverage analysis and structural coverage analysis. The first step analyzes the test cases in relation to the software requirements to conrm that the selected test cases satisfy the specified criteria. The second step confirms that the requirements-based test procedures exercised the code structure. 22 Norme DO-178 (aéronautique) Software Criticality Level Failure Denition Associated Structural Coverage Level Level A Catastrophic: prevents continued safe ight or landing, many fatal injuries MC/DC & Statement Coverage Level B Hazardous/Severe: potential fatal injuries to a small number of occupants Decision Coverage & Statement Coverage Level C Major : impairs crew eciency, discomfort or possible injuries to occupants Statement Coverage Level D Minor : reduced aircraft safety margins but well within crew capabilities None required Level E No Eect: does not eect the safety of the aircraft at all None required 23 Norme EN 50128 (ferroviaire) Test Coverage Criterion SIL 0 SIL 1 SIL 2 SIL 3 SIL 4 Statement R HR HR HR HR Branch - R R HR HR Compound Condition - R R HR HR Data ow - R R HR HR Path - R R HR HR R : Recommended HR : Highly Recommended 24 Why is structural testing not a DO-178B/ED12B requirement? (RTCA/DO-248A 1,FAQ #44) There is a distinction between structural coverage analysis and structural testing. The purpose of structural coverage analysis is to determine which code structure was not exercised by the requirements-based test procedures (reference DO-178B/ED-12B Section 6.4.4.2). Structural testing is the process of exercising software with test scenarios written from the source code, not from the requirements. Structural testing does not meet the DO-178B/ED-12B objective that all code structure is exercised by the requirements-based test procedures. The correct approach when structural coverage analysis identies untested code is to consider the possible causes in accordance with DO-178B/ED-12B Section 6.4.4.3. If any additional testing is required, it should be requirements-based testing, using high-level, low-level, or derived requirements, as appropriate. 25 Structured testing cannot find errors such as the non-implementation of some of the requirements. Since the starting point for developing structural test cases is the code itself, there is no way of nding requirements (highlevel, low-level, or derived) not implemented in the code through structural tests. It is a natural tendency to consider outputs of the actual code (which is de facto the reference for structural testing) as the expected results. This bias cannot occur when expected outputs of a tested piece of code are determined by analysis of the requirements. Since the code itself is used as the basis of the test cases, structural testing may fail to nd simple coding errors. 1. RTCA/DO-248A, Second Annual Report for Clarification of DO-178B "Software Considerations in Airborne Systems and Equipment Certification". RTCA, Inc., Washington, D. C., September 13, 2000. 26 Exercice 1 On suppose donné en java une fonction de tri dont le prototype est le suivant : public static void sort( int[] num ) L'exigence de test est la suivante : après un appel à sort le tableau num contient toujours les mêmes éléments, mais classés dans l'ordre décroissant. 1. Proposer des cas de tests pour cette fonction de tri. 2. Compléter les tests en supposant que la fonction est écrite comme suit. 27 BubbleSort public static void sort( int[] num ) { int j ; boolean ag = true ; // set ag to true to begin rst pass int temp; // holding variable } while ( ag ) { ag = false ; // set ag to false awaiting a possible swap for( j =0; j < num.length -1; j ++ ) { if ( num[ j ] < num[j +1] ) // change to > for ascending sort { temp = num[ j ]; // swap elements num[ j ] = num[ j +1 ]; num[ j +1 ] = temp; ag = true; // shows a swap occurred } } } 28 Exercice 2 Même question pour l'implantation suivante des piles : class SimpleStack { private Object[] elems ; private int top, max ; public SimpleStack (int sz ) { max = sz ; elems = new Object[sz ]; } public void push(Object obj ) { elems[top++] = obj ; } public Object pop() { return elems [- -top]; } public boolean isFull () { return top == max ; } public boolean isEmpty () { return top == 0; } } 29 Exigences pour les piles Vérier que top est toujours compris entre 0 et max Vérier qu'une pile est correctement créée si sz est supérieur à 0. Vérier que si on empile un objet sur une pile non pleine, la pile contient alors un élément de plus et son sommet est l'objet empilé. Vérier que si on dépile un objet d'une pile non vide, la pile contient alors un élément de moins et on retourne bien l'ancien sommet de la pile. Vérier que isFull détermine bien si la pile est pleine. ::: Vérier que isEmpty détermine bien si la pile est vide. 30 CleanStack Spécication des piles utilisant invariant et pre/post-conditions : /** @inv (top >= 0 && top <= max ) */ class CleanStack { private Object[] elems ; private int top, max ; 31 /** @pre (sz > 0) @post (max == sz && elems != null ) */ public CleanStack (int sz ) { max = sz ; top = 0; elems = new Object[sz ]; } /** @pre !isFull () @post (top == $pre (int, top) + 1) && elems[top-1] == obj */ public void push(Object obj ) { elems[top++] = obj ; } /** @pre !isEmpty () @post (top == $pre (int, top) - 1) && $ret == elems [top] */ public Object pop() { return elems [- -top]; } 32 /** @post ($ret == (top == max )) */ public boolean isFull () { return top == max ; } /** @post ($ret == (top == 0)) */ public boolean isEmpty () { return top == 0; } } // End MyStack 33