"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Les critères de divisibilité : application à la structure set de Python"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Vous avez un ensemble de fonctions qui permettent de tester des critères de divisibilité d'un nombre entier.\n",
"Le but est de déterminer la liste des diviseurs d'un nombre.\n",
"Dans ce TP vous avez à organiser les tests unitaires des différentes fonctions proposées.\n",
"\n",
"Vous pouvez prolonger ce TP en écrivant les fonctions et les tests pour tester si des nombres sont : \n",
"\n",
"- premiers\n",
"- parfaits\n",
"- aimables\n",
"- abondants"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"# -*- coding: utf-8 -*-\n",
"from math import *\n",
"from random import *\n"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"n=1E99+1\n",
"import sys\n",
"max = sys.maxsize\n",
"\n",
"ensemble2={'0','2','4','6','8'}\n",
"ensemble5={'0','5'}\n",
"\n",
"\n",
"\n",
"def estPair(n):\n",
" assert (float(n)).is_integer()\n",
" if str(n)[-1] in ensemble2 :return True\n",
" else : return False\n",
" \n",
"\n",
"def transforme(n):\n",
" return [int(lettre) for lettre in str(n)]\n",
"\n",
"\n",
"def estDivisiblePar3(n):\n",
" assert (float(n)).is_integer()\n",
" if sum(transforme(n))%3==0 : return True\n",
" else : return False\n",
" \n",
"def estDiviblePar5(n):\n",
" assert (float(n)).is_integer()\n",
" if str(n)[-1] in ensemble5 : return True\n",
" else :return False \n",
" \n",
"\n",
"def diviseurs(n):\n",
" assert (float(n)).is_integer()\n",
" return [x for x in range(1,n+1) if n % x == 0]\n",
" "
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120]"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"diviseurs(120)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
Des tests avec unittest de python
"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Ce modul contient des éléments pour faire vos tests unitaires.\n",
"https://openclassrooms.com/fr/courses/235344-apprenez-a-programmer-en-python/2235416-creez-des-tests-unitaires-avec-unittest\n"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Help on package unittest:\n",
"\n",
"NAME\n",
" unittest\n",
"\n",
"DESCRIPTION\n",
" Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's\n",
" Smalltalk testing framework (used with permission).\n",
" \n",
" This module contains the core framework classes that form the basis of\n",
" specific test cases and suites (TestCase, TestSuite etc.), and also a\n",
" text-based utility class for running the tests and reporting the results\n",
" (TextTestRunner).\n",
" \n",
" Simple usage:\n",
" \n",
" import unittest\n",
" \n",
" class IntegerArithmeticTestCase(unittest.TestCase):\n",
" def testAdd(self): # test method names begin with 'test'\n",
" self.assertEqual((1 + 2), 3)\n",
" self.assertEqual(0 + 1, 1)\n",
" def testMultiply(self):\n",
" self.assertEqual((0 * 10), 0)\n",
" self.assertEqual((5 * 8), 40)\n",
" \n",
" if __name__ == '__main__':\n",
" unittest.main()\n",
" \n",
" Further information is available in the bundled documentation, and from\n",
" \n",
" http://docs.python.org/library/unittest.html\n",
" \n",
" Copyright (c) 1999-2003 Steve Purcell\n",
" Copyright (c) 2003-2010 Python Software Foundation\n",
" This module is free software, and you may redistribute it and/or modify\n",
" it under the same terms as Python itself, so long as this copyright message\n",
" and disclaimer are retained in their original form.\n",
" \n",
" IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n",
" SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF\n",
" THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH\n",
" DAMAGE.\n",
" \n",
" THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT\n",
" LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n",
" PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS,\n",
" AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,\n",
" SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n",
"\n",
"PACKAGE CONTENTS\n",
" __main__\n",
" case\n",
" loader\n",
" main\n",
" mock\n",
" result\n",
" runner\n",
" signals\n",
" suite\n",
" test (package)\n",
" util\n",
"\n",
"CLASSES\n",
" builtins.Exception(builtins.BaseException)\n",
" unittest.case.SkipTest\n",
" builtins.object\n",
" unittest.case.TestCase\n",
" unittest.case.FunctionTestCase\n",
" unittest.loader.TestLoader\n",
" unittest.main.TestProgram\n",
" unittest.result.TestResult\n",
" unittest.runner.TextTestResult\n",
" unittest.runner.TextTestRunner\n",
" unittest.suite.BaseTestSuite(builtins.object)\n",
" unittest.suite.TestSuite\n",
" \n",
" class FunctionTestCase(TestCase)\n",
" | FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)\n",
" | \n",
" | A test case that wraps a test function.\n",
" | \n",
" | This is useful for slipping pre-existing test functions into the\n",
" | unittest framework. Optionally, set-up and tidy-up functions can be\n",
" | supplied. As with TestCase, the tidy-up ('tearDown') function will\n",
" | always be called if the set-up ('setUp') function ran successfully.\n",
" | \n",
" | Method resolution order:\n",
" | FunctionTestCase\n",
" | TestCase\n",
" | builtins.object\n",
" | \n",
" | Methods defined here:\n",
" | \n",
" | __eq__(self, other)\n",
" | Return self==value.\n",
" | \n",
" | __hash__(self)\n",
" | Return hash(self).\n",
" | \n",
" | __init__(self, testFunc, setUp=None, tearDown=None, description=None)\n",
" | Create an instance of the class that will use the named test\n",
" | method when executed. Raises a ValueError if the instance does\n",
" | not have a method with the specified name.\n",
" | \n",
" | __repr__(self)\n",
" | Return repr(self).\n",
" | \n",
" | __str__(self)\n",
" | Return str(self).\n",
" | \n",
" | id(self)\n",
" | \n",
" | runTest(self)\n",
" | \n",
" | setUp(self)\n",
" | Hook method for setting up the test fixture before exercising it.\n",
" | \n",
" | shortDescription(self)\n",
" | Returns a one-line description of the test, or None if no\n",
" | description has been provided.\n",
" | \n",
" | The default implementation of this method returns the first line of\n",
" | the specified test method's docstring.\n",
" | \n",
" | tearDown(self)\n",
" | Hook method for deconstructing the test fixture after testing it.\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Methods inherited from TestCase:\n",
" | \n",
" | __call__(self, *args, **kwds)\n",
" | Call self as a function.\n",
" | \n",
" | addCleanup(self, function, *args, **kwargs)\n",
" | Add a function, with arguments, to be called when the test is\n",
" | completed. Functions added are called on a LIFO basis and are\n",
" | called after tearDown on test failure or success.\n",
" | \n",
" | Cleanup items are called even if setUp fails (unlike tearDown).\n",
" | \n",
" | addTypeEqualityFunc(self, typeobj, function)\n",
" | Add a type specific assertEqual style function to compare a type.\n",
" | \n",
" | This method is for use by TestCase subclasses that need to register\n",
" | their own type equality functions to provide nicer error messages.\n",
" | \n",
" | Args:\n",
" | typeobj: The data type to call this function on when both values\n",
" | are of the same type in assertEqual().\n",
" | function: The callable taking two arguments and an optional\n",
" | msg= argument that raises self.failureException with a\n",
" | useful error message when the two arguments are not equal.\n",
" | \n",
" | assertAlmostEqual(self, first, second, places=None, msg=None, delta=None)\n",
" | Fail if the two objects are unequal as determined by their\n",
" | difference rounded to the given number of decimal places\n",
" | (default 7) and comparing to zero, or by comparing that the\n",
" | difference between the two objects is more than the given\n",
" | delta.\n",
" | \n",
" | Note that decimal places (from zero) are usually not the same\n",
" | as significant digits (measured from the most significant digit).\n",
" | \n",
" | If the two objects compare equal then they will automatically\n",
" | compare almost equal.\n",
" | \n",
" | assertAlmostEquals = deprecated_func(*args, **kwargs)\n",
" | \n",
" | assertCountEqual(self, first, second, msg=None)\n",
" | An unordered sequence comparison asserting that the same elements,\n",
" | regardless of order. If the same element occurs more than once,\n",
" | it verifies that the elements occur the same number of times.\n",
" | \n",
" | self.assertEqual(Counter(list(first)),\n",
" | Counter(list(second)))\n",
" | \n",
" | Example:\n",
" | - [0, 1, 1] and [1, 0, 1] compare equal.\n",
" | - [0, 0, 1] and [0, 1] compare unequal.\n",
" | \n",
" | assertDictContainsSubset(self, subset, dictionary, msg=None)\n",
" | Checks whether dictionary is a superset of subset.\n",
" | \n",
" | assertDictEqual(self, d1, d2, msg=None)\n",
" | \n",
" | assertEqual(self, first, second, msg=None)\n",
" | Fail if the two objects are unequal as determined by the '=='\n",
" | operator.\n",
" | \n",
" | assertEquals = deprecated_func(*args, **kwargs)\n",
" | \n",
" | assertFalse(self, expr, msg=None)\n",
" | Check that the expression is false.\n",
" | \n",
" | assertGreater(self, a, b, msg=None)\n",
" | Just like self.assertTrue(a > b), but with a nicer default message.\n",
" | \n",
" | assertGreaterEqual(self, a, b, msg=None)\n",
" | Just like self.assertTrue(a >= b), but with a nicer default message.\n",
" | \n",
" | assertIn(self, member, container, msg=None)\n",
" | Just like self.assertTrue(a in b), but with a nicer default message.\n",
" | \n",
" | assertIs(self, expr1, expr2, msg=None)\n",
" | Just like self.assertTrue(a is b), but with a nicer default message.\n",
" | \n",
" | assertIsInstance(self, obj, cls, msg=None)\n",
" | Same as self.assertTrue(isinstance(obj, cls)), with a nicer\n",
" | default message.\n",
" | \n",
" | assertIsNone(self, obj, msg=None)\n",
" | Same as self.assertTrue(obj is None), with a nicer default message.\n",
" | \n",
" | assertIsNot(self, expr1, expr2, msg=None)\n",
" | Just like self.assertTrue(a is not b), but with a nicer default message.\n",
" | \n",
" | assertIsNotNone(self, obj, msg=None)\n",
" | Included for symmetry with assertIsNone.\n",
" | \n",
" | assertLess(self, a, b, msg=None)\n",
" | Just like self.assertTrue(a < b), but with a nicer default message.\n",
" | \n",
" | assertLessEqual(self, a, b, msg=None)\n",
" | Just like self.assertTrue(a <= b), but with a nicer default message.\n",
" | \n",
" | assertListEqual(self, list1, list2, msg=None)\n",
" | A list-specific equality assertion.\n",
" | \n",
" | Args:\n",
" | list1: The first list to compare.\n",
" | list2: The second list to compare.\n",
" | msg: Optional message to use on failure instead of a list of\n",
" | differences.\n",
" | \n",
" | assertLogs(self, logger=None, level=None)\n",
" | Fail unless a log message of level *level* or higher is emitted\n",
" | on *logger_name* or its children. If omitted, *level* defaults to\n",
" | INFO and *logger* defaults to the root logger.\n",
" | \n",
" | This method must be used as a context manager, and will yield\n",
" | a recording object with two attributes: `output` and `records`.\n",
" | At the end of the context manager, the `output` attribute will\n",
" | be a list of the matching formatted log messages and the\n",
" | `records` attribute will be a list of the corresponding LogRecord\n",
" | objects.\n",
" | \n",
" | Example::\n",
" | \n",
" | with self.assertLogs('foo', level='INFO') as cm:\n",
" | logging.getLogger('foo').info('first message')\n",
" | logging.getLogger('foo.bar').error('second message')\n",
" | self.assertEqual(cm.output, ['INFO:foo:first message',\n",
" | 'ERROR:foo.bar:second message'])\n",
" | \n",
" | assertMultiLineEqual(self, first, second, msg=None)\n",
" | Assert that two multi-line strings are equal.\n",
" | \n",
" | assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None)\n",
" | Fail if the two objects are equal as determined by their\n",
" | difference rounded to the given number of decimal places\n",
" | (default 7) and comparing to zero, or by comparing that the\n",
" | difference between the two objects is less than the given delta.\n",
" | \n",
" | Note that decimal places (from zero) are usually not the same\n",
" | as significant digits (measured from the most significant digit).\n",
" | \n",
" | Objects that are equal automatically fail.\n",
" | \n",
" | assertNotAlmostEquals = deprecated_func(*args, **kwargs)\n",
" | \n",
" | assertNotEqual(self, first, second, msg=None)\n",
" | Fail if the two objects are equal as determined by the '!='\n",
" | operator.\n",
" | \n",
" | assertNotEquals = deprecated_func(*args, **kwargs)\n",
" | \n",
" | assertNotIn(self, member, container, msg=None)\n",
" | Just like self.assertTrue(a not in b), but with a nicer default message.\n",
" | \n",
" | assertNotIsInstance(self, obj, cls, msg=None)\n",
" | Included for symmetry with assertIsInstance.\n",
" | \n",
" | assertNotRegex(self, text, unexpected_regex, msg=None)\n",
" | Fail the test if the text matches the regular expression.\n",
" | \n",
" | assertNotRegexpMatches = deprecated_func(*args, **kwargs)\n",
" | \n",
" | assertRaises(self, expected_exception, *args, **kwargs)\n",
" | Fail unless an exception of class expected_exception is raised\n",
" | by the callable when invoked with specified positional and\n",
" | keyword arguments. If a different type of exception is\n",
" | raised, it will not be caught, and the test case will be\n",
" | deemed to have suffered an error, exactly as for an\n",
" | unexpected exception.\n",
" | \n",
" | If called with the callable and arguments omitted, will return a\n",
" | context object used like this::\n",
" | \n",
" | with self.assertRaises(SomeException):\n",
" | do_something()\n",
" | \n",
" | An optional keyword argument 'msg' can be provided when assertRaises\n",
" | is used as a context object.\n",
" | \n",
" | The context manager keeps a reference to the exception as\n",
" | the 'exception' attribute. This allows you to inspect the\n",
" | exception after the assertion::\n",
" | \n",
" | with self.assertRaises(SomeException) as cm:\n",
" | do_something()\n",
" | the_exception = cm.exception\n",
" | self.assertEqual(the_exception.error_code, 3)\n",
" | \n",
" | assertRaisesRegex(self, expected_exception, expected_regex, *args, **kwargs)\n",
" | Asserts that the message in a raised exception matches a regex.\n",
" | \n",
" | Args:\n",
" | expected_exception: Exception class expected to be raised.\n",
" | expected_regex: Regex (re.Pattern object or string) expected\n",
" | to be found in error message.\n",
" | args: Function to be called and extra positional args.\n",
" | kwargs: Extra kwargs.\n",
" | msg: Optional message used in case of failure. Can only be used\n",
" | when assertRaisesRegex is used as a context manager.\n",
" | \n",
" | assertRaisesRegexp = deprecated_func(*args, **kwargs)\n",
" | \n",
" | assertRegex(self, text, expected_regex, msg=None)\n",
" | Fail the test unless the text matches the regular expression.\n",
" | \n",
" | assertRegexpMatches = deprecated_func(*args, **kwargs)\n",
" | \n",
" | assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None)\n",
" | An equality assertion for ordered sequences (like lists and tuples).\n",
" | \n",
" | For the purposes of this function, a valid ordered sequence type is one\n",
" | which can be indexed, has a length, and has an equality operator.\n",
" | \n",
" | Args:\n",
" | seq1: The first sequence to compare.\n",
" | seq2: The second sequence to compare.\n",
" | seq_type: The expected datatype of the sequences, or None if no\n",
" | datatype should be enforced.\n",
" | msg: Optional message to use on failure instead of a list of\n",
" | differences.\n",
" | \n",
" | assertSetEqual(self, set1, set2, msg=None)\n",
" | A set-specific equality assertion.\n",
" | \n",
" | Args:\n",
" | set1: The first set to compare.\n",
" | set2: The second set to compare.\n",
" | msg: Optional message to use on failure instead of a list of\n",
" | differences.\n",
" | \n",
" | assertSetEqual uses ducktyping to support different types of sets, and\n",
" | is optimized for sets specifically (parameters must support a\n",
" | difference method).\n",
" | \n",
" | assertTrue(self, expr, msg=None)\n",
" | Check that the expression is true.\n",
" | \n",
" | assertTupleEqual(self, tuple1, tuple2, msg=None)\n",
" | A tuple-specific equality assertion.\n",
" | \n",
" | Args:\n",
" | tuple1: The first tuple to compare.\n",
" | tuple2: The second tuple to compare.\n",
" | msg: Optional message to use on failure instead of a list of\n",
" | differences.\n",
" | \n",
" | assertWarns(self, expected_warning, *args, **kwargs)\n",
" | Fail unless a warning of class warnClass is triggered\n",
" | by the callable when invoked with specified positional and\n",
" | keyword arguments. If a different type of warning is\n",
" | triggered, it will not be handled: depending on the other\n",
" | warning filtering rules in effect, it might be silenced, printed\n",
" | out, or raised as an exception.\n",
" | \n",
" | If called with the callable and arguments omitted, will return a\n",
" | context object used like this::\n",
" | \n",
" | with self.assertWarns(SomeWarning):\n",
" | do_something()\n",
" | \n",
" | An optional keyword argument 'msg' can be provided when assertWarns\n",
" | is used as a context object.\n",
" | \n",
" | The context manager keeps a reference to the first matching\n",
" | warning as the 'warning' attribute; similarly, the 'filename'\n",
" | and 'lineno' attributes give you information about the line\n",
" | of Python code from which the warning was triggered.\n",
" | This allows you to inspect the warning after the assertion::\n",
" | \n",
" | with self.assertWarns(SomeWarning) as cm:\n",
" | do_something()\n",
" | the_warning = cm.warning\n",
" | self.assertEqual(the_warning.some_attribute, 147)\n",
" | \n",
" | assertWarnsRegex(self, expected_warning, expected_regex, *args, **kwargs)\n",
" | Asserts that the message in a triggered warning matches a regexp.\n",
" | Basic functioning is similar to assertWarns() with the addition\n",
" | that only warnings whose messages also match the regular expression\n",
" | are considered successful matches.\n",
" | \n",
" | Args:\n",
" | expected_warning: Warning class expected to be triggered.\n",
" | expected_regex: Regex (re.Pattern object or string) expected\n",
" | to be found in error message.\n",
" | args: Function to be called and extra positional args.\n",
" | kwargs: Extra kwargs.\n",
" | msg: Optional message used in case of failure. Can only be used\n",
" | when assertWarnsRegex is used as a context manager.\n",
" | \n",
" | assert_ = deprecated_func(*args, **kwargs)\n",
" | \n",
" | countTestCases(self)\n",
" | \n",
" | debug(self)\n",
" | Run the test without collecting errors in a TestResult\n",
" | \n",
" | defaultTestResult(self)\n",
" | \n",
" | doCleanups(self)\n",
" | Execute all cleanup functions. Normally called for you after\n",
" | tearDown.\n",
" | \n",
" | fail(self, msg=None)\n",
" | Fail immediately, with the given message.\n",
" | \n",
" | failIf = deprecated_func(*args, **kwargs)\n",
" | \n",
" | failIfAlmostEqual = deprecated_func(*args, **kwargs)\n",
" | \n",
" | failIfEqual = deprecated_func(*args, **kwargs)\n",
" | \n",
" | failUnless = deprecated_func(*args, **kwargs)\n",
" | \n",
" | failUnlessAlmostEqual = deprecated_func(*args, **kwargs)\n",
" | \n",
" | failUnlessEqual = deprecated_func(*args, **kwargs)\n",
" | \n",
" | failUnlessRaises = deprecated_func(*args, **kwargs)\n",
" | \n",
" | run(self, result=None)\n",
" | \n",
" | skipTest(self, reason)\n",
" | Skip this test.\n",
" | \n",
" | subTest(self, msg=