diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..d4a1542 Binary files /dev/null and b/.DS_Store differ diff --git a/.vscode/.ropeproject/config.py b/.vscode/.ropeproject/config.py new file mode 100644 index 0000000..dee2d1a --- /dev/null +++ b/.vscode/.ropeproject/config.py @@ -0,0 +1,114 @@ +# The default ``config.py`` +# flake8: noqa + + +def set_prefs(prefs): + """This function is called before opening the project""" + + # Specify which files and folders to ignore in the project. + # Changes to ignored resources are not added to the history and + # VCSs. Also they are not returned in `Project.get_files()`. + # Note that ``?`` and ``*`` match all characters but slashes. + # '*.pyc': matches 'test.pyc' and 'pkg/test.pyc' + # 'mod*.pyc': matches 'test/mod1.pyc' but not 'mod/1.pyc' + # '.svn': matches 'pkg/.svn' and all of its children + # 'build/*.o': matches 'build/lib.o' but not 'build/sub/lib.o' + # 'build//*.o': matches 'build/lib.o' and 'build/sub/lib.o' + prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject', + '.hg', '.svn', '_svn', '.git', '.tox'] + + # Specifies which files should be considered python files. It is + # useful when you have scripts inside your project. Only files + # ending with ``.py`` are considered to be python files by + # default. + # prefs['python_files'] = ['*.py'] + + # Custom source folders: By default rope searches the project + # for finding source folders (folders that should be searched + # for finding modules). You can add paths to that list. Note + # that rope guesses project source folders correctly most of the + # time; use this if you have any problems. + # The folders should be relative to project root and use '/' for + # separating folders regardless of the platform rope is running on. + # 'src/my_source_folder' for instance. + # prefs.add('source_folders', 'src') + + # You can extend python path for looking up modules + # prefs.add('python_path', '~/python/') + + # Should rope save object information or not. + prefs['save_objectdb'] = True + prefs['compress_objectdb'] = False + + # If `True`, rope analyzes each module when it is being saved. + prefs['automatic_soa'] = True + # The depth of calls to follow in static object analysis + prefs['soa_followed_calls'] = 0 + + # If `False` when running modules or unit tests "dynamic object + # analysis" is turned off. This makes them much faster. + prefs['perform_doa'] = True + + # Rope can check the validity of its object DB when running. + prefs['validate_objectdb'] = True + + # How many undos to hold? + prefs['max_history_items'] = 32 + + # Shows whether to save history across sessions. + prefs['save_history'] = True + prefs['compress_history'] = False + + # Set the number spaces used for indenting. According to + # :PEP:`8`, it is best to use 4 spaces. Since most of rope's + # unit-tests use 4 spaces it is more reliable, too. + prefs['indent_size'] = 4 + + # Builtin and c-extension modules that are allowed to be imported + # and inspected by rope. + prefs['extension_modules'] = [] + + # Add all standard c-extensions to extension_modules list. + prefs['import_dynload_stdmods'] = True + + # If `True` modules with syntax errors are considered to be empty. + # The default value is `False`; When `False` syntax errors raise + # `rope.base.exceptions.ModuleSyntaxError` exception. + prefs['ignore_syntax_errors'] = False + + # If `True`, rope ignores unresolvable imports. Otherwise, they + # appear in the importing namespace. + prefs['ignore_bad_imports'] = False + + # If `True`, rope will insert new module imports as + # `from import ` by default. + prefs['prefer_module_from_imports'] = False + + # If `True`, rope will transform a comma list of imports into + # multiple separate import statements when organizing + # imports. + prefs['split_imports'] = False + + # If `True`, rope will remove all top-level import statements and + # reinsert them at the top of the module when making changes. + prefs['pull_imports_to_top'] = True + + # If `True`, rope will sort imports alphabetically by module name instead + # of alphabetically by import statement, with from imports after normal + # imports. + prefs['sort_imports_alphabetically'] = False + + # Location of implementation of + # rope.base.oi.type_hinting.interfaces.ITypeHintingFactory In general + # case, you don't have to change this value, unless you're an rope expert. + # Change this value to inject you own implementations of interfaces + # listed in module rope.base.oi.type_hinting.providers.interfaces + # For example, you can add you own providers for Django Models, or disable + # the search type-hinting in a class hierarchy, etc. + prefs['type_hinting_factory'] = ( + 'rope.base.oi.type_hinting.factory.default_type_hinting_factory') + + +def project_opened(project): + """This function is called after opening the project""" + # Do whatever you like here! diff --git a/.vscode/.ropeproject/objectdb b/.vscode/.ropeproject/objectdb new file mode 100644 index 0000000..0a47446 Binary files /dev/null and b/.vscode/.ropeproject/objectdb differ diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..17e15f2 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,15 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Python: Current File", + "type": "python", + "request": "launch", + "program": "${file}", + "console": "integratedTerminal" + } + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..d5d660b --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "restructuredtext.confPath": "${workspaceFolder}" +} \ No newline at end of file diff --git a/create-with-arg.py b/create-with-arg.py new file mode 100755 index 0000000..be1d006 --- /dev/null +++ b/create-with-arg.py @@ -0,0 +1,40 @@ +import sys,os + +print(sys.argv) + + +def main(): + l = sys.argv[1].split("/") + alist = [ + [ + l[-1].upper(), + l[-1], + ','+sys.argv[2] if len(sys.argv)>=3 else '' + ] + ] + dirName = '/'.join(l[:-1]) + # Create target directory & all intermediate directories if don't exists + try: + print("Directory " , dirName , " Created ") + os.makedirs(dirName) + except FileExistsError: + print("Directory " , dirName , " already exists") + for item in alist: + f = open(sys.argv[1] + ".py", "w+") + # for i in range(10): + # f.write("This is line %d\r\n" % (i+1)) + content = """ +import unittest{2} +class TDD_{0}(unittest.TestCase): + def test_{1}(self): + +if __name__ == '__main__': + unittest.main() + + """ + f.write(content.format(item[0], item[1],item[2])) + f.close() + + +if __name__ == "__main__": + main() diff --git a/func2.log b/func2.log new file mode 100644 index 0000000..74ffc75 --- /dev/null +++ b/func2.log @@ -0,0 +1,25 @@ +myfunc2 was called +myfunc2 +myfunc2 +myfunc2 +myfunc2 +myfunc2 +myfunc2 +myfunc2 +myfunc2 +myfunc2 +myfunc2 +myfunc2 +myfunc2 +myfunc2 +myfunc2 +myfunc2 +myfunc2 +myfunc2 +myfunc2 +myfunc2 +myfunc2 +myfunc2 +myfunc2 +myfunc2 +myfunc2 diff --git a/out.log b/out.log new file mode 100644 index 0000000..04de490 --- /dev/null +++ b/out.log @@ -0,0 +1,37 @@ +myfunc1 was called +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 +myfunc1 diff --git a/out2.log b/out2.log new file mode 100644 index 0000000..79c6a0b --- /dev/null +++ b/out2.log @@ -0,0 +1,17 @@ +myfunc1 was called +myfunc1 was called +myfunc1 was called +myfunc1 was called +myfunc1 was called +myfunc1 was called +myfunc1 was called +myfunc1 was called +myfunc1 was called +myfunc1 was called +myfunc1 was called +myfunc1 was called +myfunc1 was called +myfunc1 was called +myfunc1 was called +myfunc1 was called +myfunc1 was called diff --git a/some_file b/some_file new file mode 100644 index 0000000..22875c8 --- /dev/null +++ b/some_file @@ -0,0 +1 @@ +Hola! \ No newline at end of file diff --git a/test/Classes.py b/test/Classes.py new file mode 100644 index 0000000..0ec984d --- /dev/null +++ b/test/Classes.py @@ -0,0 +1,83 @@ +import unittest +class TDD_CLASSES(unittest.TestCase): + def test_Classes(self): + class Cal(object): + # pi is a class variable + pi = 3.142 + def __init__(self, radius): + # self.radius is an instance variable + self.radius = radius + def area(self): + return self.pi * (self.radius ** 2) + a = Cal(32) + self.assertEqual(a.area(),Cal.pi*a.radius**2) + self.assertEqual(a.pi,3.142) + a.pi = 43 + self.assertEqual(a.pi,43) + b = Cal(44) + self.assertEqual(b.area(),3.142*44**2) + self.assertEqual(b.pi,3.142) + b.pi = 50 + self.assertEqual(b.pi,50) + def test_mutable_class_var(self): + class SuperClass(object): + superpowers = [] + def __init__(self, name): + self.name = name + def add_superpower(self, power): + self.superpowers.append(power) + foo = SuperClass('foo') + bar = SuperClass('bar') + self.assertEqual(foo.name,'foo') + self.assertEqual(bar.name,'bar') + self.assertEqual(bar.superpowers,[]) + foo.add_superpower('fly') + self.assertEqual(bar.superpowers,['fly']) + self.assertEqual(bar.superpowers,foo.superpowers) + def test_new_style_class(self): + class OldClass(): + def __init__(self): + pass + class NewClass(object): + def __init__(self): + pass + old = OldClass() + new = NewClass() + self.assertIsInstance(old,object) + self.assertIsInstance(new,object) + def test_magic_methods(self): + class GetTest(object): + def __init__(self,i=0): + self.i=i+1 + def another_method(self): + self.i+=1 + a = GetTest() + self.assertEqual(a.i,1) + a.another_method() + self.assertEqual(a.i,2) + class GetTest(object): + def __init__(self, name): + self.greet=('Greetings!! {0}'.format(name)) + def another_method(self): + print('I am another method which is not' + ' automatically called') + a = GetTest('yasoob') + self.assertEqual(a.greet,'Greetings!! yasoob') + # Try creating an instance without the name arguments + self.assertRaises(TypeError, lambda: GetTest()) + self.assertRaises(TypeError,lambda:a['name']) + def test_getitem(self): + class GetTest(object): + def __init__(self): + self.info = { + 'name':'Yasoob', + 'country':'Pakistan', + 'number':12345812 + } + def __getitem__(self,i): + return self.info[i] + foo = GetTest() + self.assertEqual(foo['name'],'Yasoob') + self.assertEqual(foo['number'],12345812) +if __name__ == '__main__': + unittest.main() diff --git a/test/Coroutines.py b/test/Coroutines.py new file mode 100644 index 0000000..b25f312 --- /dev/null +++ b/test/Coroutines.py @@ -0,0 +1,30 @@ + +import unittest +class TDD_COROUTINES(unittest.TestCase): + def test_Coroutines(self): + def fib(n): + a, b = 0, 1 + while a '.join(hi()), + 'hi() function start -> greet() function -> welcome() function -> hi() function end' + ) + # This shows that whenever you call hi(), greet() and welcome() + # are also called. However the greet() and welcome() functions + # are not available outside the hi() function e.g: + self.assertRaises(NameError, lambda: greet) + def test_return_inline_function(self): + def hi(name="yasoob"): + def greet(): + return "now you are in the greet() function" + def welcome(): + return "now you are in the welcome() function" + if name == "yasoob": + return greet + else: + return welcome + a = hi() + self.assertTrue(callable(a)) + # This clearly shows that `a` now points to the greet() function in hi() + # Now try this + self.assertEqual(a(), "now you are in the greet() function") + def test_give_argument(self): + def hi(): + return "hi yasoob!" + def doSomethingBeforeHi(func): + return ("I am doing some boring work before executing hi() ")+(func()) + self.assertEqual(doSomethingBeforeHi( + hi), "I am doing some boring work before executing hi() hi yasoob!") + def test_decorator(self): + def a_new_decorator(a_func): + def wrapTheFunction(): + l = [] + l.append("before executing a_func()") + l.append(a_func()) + l.append("after executing a_func()") + return l + return wrapTheFunction + def a_function_requiring_decoration(): + return ("needs some decoration") + self.assertEqual(a_function_requiring_decoration(), + 'needs some decoration') + a_function_requiring_decoration1 = a_new_decorator( + a_function_requiring_decoration) + s = 'before executing a_func() -> needs some decoration -> after executing a_func()' + self.assertEqual(' -> '.join(a_function_requiring_decoration1()), s) + @a_new_decorator + def a_function_requiring_decoration2(): + """Hey you! Decorate me!""" + return("needs some decoration") + self.assertEqual(' -> '.join(a_function_requiring_decoration2()),s) + # the @a_new_decorator is just a short way of saying: + a_function_requiring_decoration3 = a_new_decorator(a_function_requiring_decoration) + self.assertEqual(' -> '.join(a_function_requiring_decoration3()), s) + self.assertEqual(a_function_requiring_decoration.__name__,'a_function_requiring_decoration') + self.assertEqual(a_function_requiring_decoration3.__name__, 'wrapTheFunction') + def test_wraps(self): + def a_new_decorator(a_func): + @wraps(a_func) + def wrapTheFunction(): + l = [] + l.append("before executing a_func()") + l.append(a_func()) + l.append("after executing a_func()") + return l + return wrapTheFunction + @a_new_decorator + def a_function_requiring_decoration(): + """Hey yo! Decorate me!""" + print("needs some decoration") + self.assertEqual(a_function_requiring_decoration.__name__,'a_function_requiring_decoration') + def test_outer_variable(self): + def decorator_name(f): + @wraps(f) + def decorated(*args, **kwargs): + if not can_run: + return "Function will not run" + return f(*args, **kwargs) + return decorated + @decorator_name + def func(): + return("Function is running") + can_run = True + self.assertEqual(func(),"Function is running") + can_run = False + self.assertEqual(func(),"Function will not run") + def test_authorization(self): + class request(): + class Auth(): + username='' + password = '' + authorization = Auth + def authenticate(): + return 5 + def check_auth(name,pwd): + return False + def requires_auth(f): + @wraps(f) + def decorated(*args, **kwargs): + auth = request.authorization + n=0 + if not auth or not check_auth(auth.username, auth.password): + n=authenticate() + return f(n=n,*args, **kwargs) + return decorated + d = requires_auth(lambda x, y,three,n: n+x + y+three)(1, 2,three=6) + self.assertEqual(d, 5 + 1 + 2 + 6) + def test_logging(self): + def logit(func): + @wraps(func) + def with_logging(*args, **kwargs): + self.assertEqual(func.__name__ , 'addition_func') + return func(5,*args, **kwargs) + return with_logging + @logit + def addition_func(x,y): + """Do some math.""" + return x + y + result = addition_func(4) + self.assertEqual(result,4+5) + def test_nesting_decorator(self): + def logit(logfile='out.log'): + def logging_decorator(func): + @wraps(func) + def wrapped_function(*args, **kwargs): + log_string = func.__name__ + self.assertRegex(log_string,'myfunc1|myfunc2') + # Open the logfile and append + with open(logfile, 'a') as opened_file: + # Now we log to the specified logfile + opened_file.write(log_string + '\n') + return func(logfile,*args, **kwargs) + return wrapped_function + return logging_decorator + + @logit() + def myfunc1(fileName): + return fileName + + self.assertEqual(myfunc1(),'out.log') + # Output: myfunc1 was called + # A file called out.log now exists, with the above string + + @logit(logfile='func2.log') + def myfunc2(fileName): + return fileName + + self.assertEqual(myfunc2(),'func2.log') + def test_decorator_classes(self): + class logit(object): + + _logfile = 'out.log' + + def __init__(self, func): + self.func = func + + def __call__(self, *args): + log_string = self.func.__name__ + " was called" + # Open the logfile and append + with open(self._logfile, 'a') as opened_file: + # Now we log to the specified logfile + opened_file.write(log_string + '\n') + # Now, send a notification + self.notify() + + # return base func + return self.func(log_string,*args) + + + + def notify(self): + # logit only logs, no more + pass + logit._logfile = 'out2.log' # if change log file + @logit + def myfunc1(s): + return s + + self.assertEqual(myfunc1(),'myfunc1 was called') + class email_logit(logit): + ''' + A logit implementation for sending emails to admins + when the function is called. + ''' + def __init__(self, email='admin@myproject.com', *args, **kwargs): + self.email = email + super(email_logit, self).__init__(*args, **kwargs) + + def notify(self): + # Send an email to self.email + # Will not be implemented here + return self.email + self.assertEqual(email_logit(func=lambda x:x).notify(),'admin@myproject.com') +if __name__ == '__main__': + unittest.main() diff --git a/test/demo.txt b/test/demo.txt new file mode 100644 index 0000000..e69de29 diff --git a/test/example.c b/test/example.c new file mode 100644 index 0000000..f2106ea --- /dev/null +++ b/test/example.c @@ -0,0 +1,18 @@ +#include +double My_variable = 3.0; + +int fact(int n) { + if (n <= 1) return 1; + else return n*fact(n-1); +} + +int my_mod(int x, int y) { + return (x%y); +} + +char *get_time() +{ + time_t ltime; + time(<ime); + return ctime(<ime); +} \ No newline at end of file diff --git a/test/example.i b/test/example.i new file mode 100644 index 0000000..d923c4b --- /dev/null +++ b/test/example.i @@ -0,0 +1,14 @@ +/* example.i */ + %module example + %{ + /* Put header files here or function declarations like below */ + extern double My_variable; + extern int fact(int n); + extern int my_mod(int x, int y); + extern char *get_time(); + %} + + extern double My_variable; + extern int fact(int n); + extern int my_mod(int x, int y); + extern char *get_time(); \ No newline at end of file diff --git a/test/file.json b/test/file.json new file mode 100644 index 0000000..217a463 --- /dev/null +++ b/test/file.json @@ -0,0 +1 @@ +{"name":"val"} \ No newline at end of file diff --git a/test/for_else.py b/test/for_else.py new file mode 100644 index 0000000..d79acf4 --- /dev/null +++ b/test/for_else.py @@ -0,0 +1,33 @@ + +import unittest +class TDD_FOR_ELSE(unittest.TestCase): + def test_for_else(self): + fruits = ['apple', 'banana', 'mango'] + l=[] + for fruit in fruits: + l.append(fruit.capitalize()) + self.assertEqual(l,['Apple','Banana','Mango']) + def test_else_clause(self): + container = [] + not_found_in_container=lambda x:self.assertEqual(x,[]) + for item in container: + if search_something(item): + # Found it! + process(item) + break + else: + # Didn't find anything.. + not_found_in_container(container) + prime=[] + for n in range(2, 10): + for x in range(2, n): + if n % x == 0: + break + else: + # loop fell through without finding a factor + prime.append(n) + self.assertEqual(prime,[2,3,5,7]) +if __name__ == '__main__': + unittest.main() + + \ No newline at end of file diff --git a/test/function_caching.py b/test/function_caching.py new file mode 100644 index 0000000..41a87ef --- /dev/null +++ b/test/function_caching.py @@ -0,0 +1,33 @@ +from functools import wraps +import unittest +class TDD_FUNCTION_CACHING(unittest.TestCase): + def test_function_caching(self): + from functools import lru_cache + @lru_cache(maxsize=32) + def fib(n): + if n < 2: + return n + return fib(n-1) + fib(n-2) + l=([fib(n) for n in range(10)]) + self.assertEqual(l, [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]) + fib.cache_clear() + self.assertEqual(l, [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]) + def test_python2_plus(self): + def memoize(function): + memo = {} + @wraps(function) + def wrapper(*args): + try: + return memo[args] + except KeyError: + rv = function(*args) + memo[args] = rv + return rv + return wrapper + @memoize + def fibonacci(n): + if n < 2: return n + return fibonacci(n - 1) + fibonacci(n - 2) + self.assertEqual(fibonacci(25),75025) +if __name__ == '__main__': + unittest.main() diff --git a/test/generators.py b/test/generators.py new file mode 100644 index 0000000..a83a0cc --- /dev/null +++ b/test/generators.py @@ -0,0 +1,46 @@ +import unittest +class TDD_GENERATORS(unittest.TestCase): + def test_generators(self): + def generator_function(): + for i in range(10): + yield i + l=[] + for item in generator_function(): + l.append(item) + self.assertEqual(l, list(range(10))) + def test_large_sets(self): + # generator version + def fibon(n): + a = b = 1 + for i in range(n): + yield a + a, b = b, a + b + g=fibon(1) + self.assertEqual(next(g),1) + self.assertRaises(StopIteration,lambda:next(g)) + g=fibon(4) + self.assertEqual(next(g),1) + self.assertEqual(next(g),1) + self.assertEqual(next(g),2) + self.assertEqual(next(g),3) + self.assertRaises(StopIteration,lambda:next(g)) + def test_next(self): + def generator_function(): + for i in range(3): + yield i + gen = generator_function() + self.assertEqual(next(gen),0) + self.assertEqual(next(gen),1) + self.assertEqual(next(gen),2) + self.assertRaises(StopIteration,lambda:next(gen)) + def test_err(self): + int_var = 1779 + self.assertRaises(TypeError,lambda:next(int_var)) + self.assertRaises(TypeError,lambda:iter(int_var)) + my_string = "Yasoob" + self.assertRaises(TypeError, lambda: next(my_string)) + my_iter = iter(my_string) + self.assertEqual(next(my_iter),'Y') + self.assertEqual(next(my_iter),'a') +if __name__ == '__main__': + unittest.main() diff --git a/test/global_return.py b/test/global_return.py new file mode 100644 index 0000000..acddb09 --- /dev/null +++ b/test/global_return.py @@ -0,0 +1,58 @@ +import unittest +class TDD_GLOBAL_RETURN(unittest.TestCase): + def test_global_return(self): + def add(value1, value2): + result=value1 + value2 + return result + add(3, 5) + self.assertRaises(NameError,lambda:result) + result = add(3, 5) + self.assertEqual(result, 8) + def add(value1,value2): + global result1 + result1 = value1 + value2 + add(3,5) + self.assertEqual(result1,8) + def test_multiple_return(self): + def profile(): + global name + global age + name = "Danny" + age = 30 + profile() + self.assertEqual(name,'Danny') + self.assertEqual(age,30) + def profile(): + name = "Danny" + age = 30 + return (name, age) + profile_data = profile() + self.assertEqual(profile_data[0],'Danny') + self.assertEqual(profile_data[1],30) + def profile(): + name = "Danny" + age = 30 + return name, age + profile_name, profile_age = profile() + self.assertEqual(profile_data[0],'Danny') + self.assertEqual(profile_data[1],30) + def test_namedtuple(self): + from collections import namedtuple + def profile(): + Person = namedtuple('Person', 'name age') + return Person(name="Danny", age=31) + # Use as namedtuple + p = profile() + self.assertIsInstance(p, object) + self.assertEqual(p.name,'Danny') + self.assertEqual(p.age,31) + # Use as plain tuple + p = profile() + self.assertEqual(p[0],'Danny') + self.assertEqual(p[1],31) + # Unpack it immediatly + name, age = profile() + self.assertEqual(name,'Danny') + self.assertEqual(age,31) +if __name__ == '__main__': + unittest.main() diff --git a/test/lambdas.py b/test/lambdas.py new file mode 100644 index 0000000..1f83b7f --- /dev/null +++ b/test/lambdas.py @@ -0,0 +1,17 @@ +import unittest +class TDD_LAMBDAS(unittest.TestCase): + def test_lambdas(self): + add = lambda x, y: x + y + self.assertEqual(add(3, 5),8) + a = [(1, 2), (4, 1), (9, 10), (13, -3)] + a.sort(key=lambda x: x[1]) + self.assertEqual(a, [(13, -3), (4, 1), (1, 2), (9, 10)]) + list1 = [2,1, 3] + list2=[7,5,6,4] + data = zip(list1, list2) + data = sorted(data) + list1, list2 = map(lambda t: list(t), zip(*data)) + self.assertEqual(list1,[1,2,3]) + self.assertEqual(list2,[5,7,6]) +if __name__ == '__main__': + unittest.main() diff --git a/test/map_filter_reduce.py b/test/map_filter_reduce.py new file mode 100644 index 0000000..5dc1e05 --- /dev/null +++ b/test/map_filter_reduce.py @@ -0,0 +1,41 @@ + +import unittest +class TDD_MAP_FILTER_REDUCE(unittest.TestCase): + def test_map_filter_reduce(self): + items = [1, 2, 3, 4, 5] + squared = [] + for i in items: + squared.append(i ** 2) + self.assertEqual(squared,[1,4,9,16,25]) + squared1 = list(map(lambda x: x**2, items)) + self.assertEqual(squared, squared1) + def multiply(x): + return (x*x) + def add(x): + return (x+x) + + funcs = [multiply, add] + value=[] + for i in range(5): + value .append( list(map(lambda x: x(i), funcs))) + self.assertEqual(value,[[0,0],[1,2],[4,4],[9,6],[16,8]]) + def test_filter(self): + number_list = range(-5, 5) + less_than_zero = list(filter(lambda x: x < 0, number_list)) + self.assertEqual(less_than_zero,[-5,-4,-3,-2,-1]) + def test_reduce(self): + product = 1 + list = [1, 2, 3, 4] + for num in list: + product=product * num + self.assertEqual(product, 24) + from functools import reduce + product1 = reduce((lambda x, y: x * y), [1, 2, 3, 4]) + self.assertEqual(product1,24) + product1 = reduce((lambda x, y: x * y), [ 3, 4]) + self.assertEqual(product1,12) + +if __name__ == '__main__': + unittest.main() + + \ No newline at end of file diff --git a/test/mutation.py b/test/mutation.py new file mode 100644 index 0000000..cc382fd --- /dev/null +++ b/test/mutation.py @@ -0,0 +1,26 @@ +import unittest +class TDD_MUTATION(unittest.TestCase): + def test_mutation(self): + foo = ['hi'] + self.assertEqual(foo,['hi']) + bar = foo + bar += ['bye'] + self.assertEqual(foo,['hi','bye']) + def test_never_default_mutable(self): + def add_to(num, target=[]): + target.append(num) + return target + + self.assertEqual(add_to(1),[1]) + self.assertEqual(add_to(2),[1,2]) + self.assertEqual(add_to(3),[1,2,3]) + def add_to(element, target=None): + if target is None: + target = [] + target.append(element) + return target + self.assertEqual(add_to(1),[1]) + self.assertEqual(add_to(2),[2]) + self.assertEqual(add_to(3),[3]) +if __name__ == '__main__': + unittest.main() diff --git a/test/my_script.py b/test/my_script.py new file mode 100644 index 0000000..e69de29 diff --git a/test/one_liners.py b/test/one_liners.py new file mode 100644 index 0000000..dd21e11 --- /dev/null +++ b/test/one_liners.py @@ -0,0 +1,48 @@ +from pprint import pprint +import unittest +import subprocess +import itertools + + +class TDD_ONE_LINERS(unittest.TestCase): + def test_server(self): + pass + # subprocess.run('python3 -m http.server', shell=True) + + def test_json(self): + subprocess.run('cat test/file.json | python -m json.tool', shell=True) + + def test_profiling(self): + subprocess.run('python3 -m cProfile test/my_script.py', shell=True) + + def test_csv_to_json(self): + pass + # subprocess.run('python3 -c "import csv,json;print json.dumps(list(csv.reader(open(\'test/csv_file.csv\'))))"',shell=True) + + def test_one_liners(self): + my_dict = {'name': 'Yasoob', 'age': 'undefined', + 'personality': 'awesome'} + # print(dir(my_dict)) + pprint(dir(my_dict)) + + def test_list_flattening(self): + a_list = [[1, 2], [3, 4], [5, 6]] + self.assertEqual(list(itertools.chain.from_iterable(a_list)), [ + 1, 2, 3, 4, 5, 6]) + self.assertEqual(list(itertools.chain(*a_list)), [1, 2, 3, 4, 5, 6]) + + def test_constructors(self): + class A(object): + def __init__(self, a, b, c, d, e, f): + self.__dict__.update( + {k: v for k, v in locals().items() if k != 'self'}) + ins = A('a', 'b', 'c', 'd', 'e', 'f') + p = ins.__dict__ + self.assertEqual(p, { + 'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd', 'e': 'e', 'f': 'f'}) + self.assertEqual(p['a'], 'a') + self.assertEqual(ins.a,'a') + + +if __name__ == '__main__': + unittest.main() diff --git a/test/open.py b/test/open.py new file mode 100644 index 0000000..17af790 --- /dev/null +++ b/test/open.py @@ -0,0 +1,31 @@ + +import unittest +class TDD_OPEN(unittest.TestCase): + def test_open(self): + with open('test/photo.jpg', 'rb') as f: + jpgdata = f.read() + self.assertIsInstance(jpgdata,bytes) + f.close() + def test_io(self): + import io + + with open('test/photo.jpg', 'rb') as inf: + jpgdata = inf.read() + + if jpgdata.startswith(b'\xff\xd8'): + text = u'This is a JPEG file (%d bytes long)\n' + else: + text = u'This is a random file (%d bytes long)\n' + + with io.open('test/summary.txt', 'w', encoding='utf-8') as outf: + outf.write(text % len(jpgdata)) + inf.close() + outf.close() + f=open('test/summary.txt') + data = f.read() + self.assertEqual(data,'This is a JPEG file (28573 bytes long)\n') + f.close() +if __name__ == '__main__': + unittest.main() + + \ No newline at end of file diff --git a/test/photo.jpg b/test/photo.jpg new file mode 100644 index 0000000..db8ceff Binary files /dev/null and b/test/photo.jpg differ diff --git a/test/set_data_structure.py b/test/set_data_structure.py new file mode 100644 index 0000000..00ad4af --- /dev/null +++ b/test/set_data_structure.py @@ -0,0 +1,31 @@ + +import unittest +class TDD_DATA_STRUCTURE(unittest.TestCase): + def test_set_data_structure(self): + some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n'] + + duplicates = [] + for value in some_list: + if some_list.count(value) > 1: + if value not in duplicates: + duplicates.append(value) + + self.assertEqual(duplicates, ['b', 'n']) + duplicates1 = list(set([x for x in some_list if some_list.count(x) > 1])) + self.assertCountEqual(duplicates1,duplicates) + def test_intersection(self): + valid = set(['yellow', 'red', 'blue', 'green', 'black']) + input_set = set(['red', 'brown']) + self.assertEqual(input_set.intersection(valid),{'red'}) + def test_difference(self): + valid = set(['yellow', 'red', 'blue', 'green', 'black']) + input_set = set(['red', 'brown']) + self.assertEqual(input_set.difference(valid),{'brown'}) + self.assertEqual(valid.difference(input_set),{'yellow','blue','green','black'}) + a_set = {'red', 'blue', 'green'} + self.assertIsInstance(a_set,set) + +if __name__ == '__main__': + unittest.main() + + \ No newline at end of file diff --git a/test/slots.py b/test/slots.py new file mode 100644 index 0000000..6b5c60f --- /dev/null +++ b/test/slots.py @@ -0,0 +1,67 @@ + +import unittest +class TDD_SLOTS(unittest.TestCase): + def test_slots(self): + class MyClass(object): + def __init__(self, name, identifier): + self.name = name + self.identifier = identifier + self.set_up() + def set_up(self): + pass + class MyClass1(object): + # reduce the burden on your RAM + __slots__ = ['name', 'identifier'] + def __init__(self, name, identifier): + self.name = name + self.identifier = identifier + self.set_up() + def set_up(self): + pass + self.assertEqual(MyClass('n','i').identifier,'i') + self.assertEqual(MyClass1('n', 'i').identifier, 'i') + def test_memory_usuage(self): + # Python 3.4.3 (default, Jun 6 2015, 13:32:34) + # Type "copyright", "credits" or "license" for more information. + + # IPython 4.0.0 -- An enhanced Interactive Python. + # ? -> Introduction and overview of IPython's features. + # %quickref -> Quick reference. + # help -> Python's own help system. + # object? -> Details about 'object', use 'object??' for extra details. + + # In [1]: import ipython_memory_usage.ipython_memory_usage as imu + + # In [2]: imu.start_watching_memory() + # In [2] used 0.0000 MiB RAM in 5.31s, peaked 0.00 MiB above current, total RAM usage 15.57 MiB + + # In [3]: %cat slots.py + class MyClass(object): + __slots__ = ['name', 'identifier'] + def __init__(self, name, identifier): + self.name = name + self.identifier = identifier + + num = 1024*256 + x = [MyClass(1,1) for i in range(num)] + # In [3] used 0.2305 MiB RAM in 0.12s, peaked 0.00 MiB above current, total RAM usage 15.80 MiB + + # In [4]: from slots import * + # In [4] used 9.3008 MiB RAM in 0.72s, peaked 0.00 MiB above current, total RAM usage 25.10 MiB + + # In [5]: %cat noslots.py + class MyClass(object): + def __init__(self, name, identifier): + self.name = name + self.identifier = identifier + + num = 1024*256 + x = [MyClass(1,1) for i in range(num)] + # In [5] used 0.1758 MiB RAM in 0.12s, peaked 0.00 MiB above current, total RAM usage 25.28 MiB + + # In [6]: from noslots import * + # In [6] used 22.6680 MiB RAM in 0.80s, peaked 0.00 MiB above current, total RAM usage 47.95 MiB +if __name__ == '__main__': + unittest.main() + + \ No newline at end of file diff --git a/test/some_file b/test/some_file new file mode 100644 index 0000000..0d5acab --- /dev/null +++ b/test/some_file @@ -0,0 +1 @@ +hola! \ No newline at end of file diff --git a/test/summary.txt b/test/summary.txt new file mode 100644 index 0000000..1255b3b --- /dev/null +++ b/test/summary.txt @@ -0,0 +1 @@ +This is a JPEG file (28573 bytes long) diff --git a/test/targeting_python.py b/test/targeting_python.py new file mode 100644 index 0000000..bf9d355 --- /dev/null +++ b/test/targeting_python.py @@ -0,0 +1,19 @@ +from __future__ import print_function +# from future.builtins.disabled import * +import unittest +class TDD_TARGETING_PYTHON(unittest.TestCase): + def test_targeting_python(self): + print + # Output: + self.assertTrue(callable(print)) + def test_compatible(self): + try: + import urllib.request as urllib_request # for Python 3 + print('??') + except ImportError: + import urllib2 as urllib_request # for Python 2 + print(urllib_request) + def test_Obsolete_Python2_builtins(self): + self.assertRaises(NameError,lambda:apply()) +if __name__ == '__main__': + unittest.main() diff --git a/test/ternary_operators.py b/test/ternary_operators.py new file mode 100644 index 0000000..39d3de6 --- /dev/null +++ b/test/ternary_operators.py @@ -0,0 +1,32 @@ + +import unittest +class TDD_TERNARY_OPERATORS(unittest.TestCase): + def test_ternary_operators(self): + is_nice = True + state = "nice" if is_nice else "not nice" + self.assertEqual(state,'nice') + def test_bool(self): + nice = True + personality = ("mean", "nice")[nice] + self.assertEqual(personality,'nice') + personality1 = ( "nice","mean")[nice] + self.assertEqual(personality1, 'mean') + condition = True + self.assertEqual(2 if condition else 1/0,2) + self.assertRaises(ZeroDivisionError,lambda:(1/0, 2)[condition]) + def test_shorthand_ternary(self): + self.assertTrue(True or "Some") + self.assertEqual(False or "Some",'Some') + output = None + msg = output or "No data returned" + self.assertEqual(msg,'No data returned') + def test_default_parameter(self): + def my_function(real_name, optional_display_name=None): + optional_display_name = optional_display_name or real_name + return (optional_display_name) + self.assertEqual(my_function("John"),'John') + self.assertEqual(my_function("Mike", "anonymous123"),'anonymous123') +if __name__ == '__main__': + unittest.main() + + \ No newline at end of file