5/23/2020

Python - Full-Featured Web App Part 1 - Getting Started

** Full-Featured Web App Part 1 - Getting Started


==========================================

C:\Users\purunet>pip install flask
Collecting flask
  Downloading Flask-1.1.2-py2.py3-none-any.whl (94 kB)
     |████████████████████████████████| 94 kB 154 kB/s
Collecting Jinja2>=2.10.1
  Downloading Jinja2-2.11.2-py2.py3-none-any.whl (125 kB)
     |████████████████████████████████| 125 kB 656 kB/s
Collecting Werkzeug>=0.15
  Downloading Werkzeug-1.0.1-py2.py3-none-any.whl (298 kB)
     |████████████████████████████████| 298 kB 2.2 MB/s
Collecting itsdangerous>=0.24
  Downloading itsdangerous-1.1.0-py2.py3-none-any.whl (16 kB)
Collecting click>=5.1
  Downloading click-7.1.2-py2.py3-none-any.whl (82 kB)
     |████████████████████████████████| 82 kB 188 kB/s
Collecting MarkupSafe>=0.23
  Downloading MarkupSafe-1.1.1-cp38-cp38-win32.whl (16 kB)
Installing collected packages: MarkupSafe, Jinja2, Werkzeug, itsdangerous, click
, flask
Successfully installed Jinja2-2.11.2 MarkupSafe-1.1.1 Werkzeug-1.0.1 click-7.1.2
 flask-1.1.2 itsdangerous-1.1.0

==========================================

C:\Users\purunet>python
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import flask
>>> exit()

==========================================

C:\Users\purunet\Documents\Flask_Blog>set FLASK_APP = flaskblog.py

==========================================

C:\Users\purunet\Documents\Flask_Blog>python flaskblog.py
 * Serving Flask app "flaskblog" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployme
nt.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 234-451-768
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [23/May/2020 12:48:56] " [37mGET / HTTP/1.1 [0m" 200 -
127.0.0.1 - - [23/May/2020 12:48:56] " [33mGET /favicon.ico HTTP/1.1 [0m" 404 -
 * Detected change in 'C:\\Users\\purunet\\Documents\\Flask_Blog\\flaskblog.py',
 reloading
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 234-451-768
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [23/May/2020 12:49:33] " [37mGET / HTTP/1.1 [0m" 200 -

==========================================

from flask import Flask

app = Flask(__name__)



@app.route('/')

def hello_world():

return 'Hello World!'



if __name__ == '__main__':

app.run()

---------------------------------





---------------------------------

==========================================

C:\Users\purunet\Documents\Flask_Blog>set FLASK_DEBUG=1

C:\Users\purunet\Documents\Flask_Blog>flask run
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployme
nt.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 556-684-567
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [23/May/2020 14:14:14] " [35m [1mGET / HTTP/1.1 [0m" 500 -
Traceback (most recent call last):
  File "C:\Users\purunet\AppData\Local\Programs\Python\Python38-32\Lib\site-pack
ages\flask\cli.py", line 338, in __call__
    self._flush_bg_loading_exception()
  File "C:\Users\purunet\AppData\Local\Programs\Python\Python38-32\Lib\site-pack
ages\flask\cli.py", line 326, in _flush_bg_loading_exception
    reraise(*exc_info)
  File "C:\Users\purunet\AppData\Local\Programs\Python\Python38-32\Lib\site-pack
ages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\Users\purunet\AppData\Local\Programs\Python\Python38-32\Lib\site-pack
ages\flask\cli.py", line 314, in _load_app
    self._load_unlocked()
  File "C:\Users\purunet\AppData\Local\Programs\Python\Python38-32\Lib\site-pack
ages\flask\cli.py", line 330, in _load_unlocked
    self._app = rv = self.loader()
  File "C:\Users\purunet\AppData\Local\Programs\Python\Python38-32\Lib\site-pack
ages\flask\cli.py", line 398, in load_app
    raise NoAppException(
flask.cli.NoAppException: Could not locate a Flask application. You did not prov
ide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was
 not found in the current directory.
127.0.0.1 - - [23/May/2020 14:14:14] " [37mGET /?__debugger__=yes&cmd=resource&f
=style.css HTTP/1.1 [0m" 200 -
127.0.0.1 - - [23/May/2020 14:14:14] " [37mGET /?__debugger__=yes&cmd=resource&f
=debugger.js HTTP/1.1 [0m" 200 -
127.0.0.1 - - [23/May/2020 14:14:16] " [37mGET /?__debugger__=yes&cmd=resource&f
=jquery.js HTTP/1.1 [0m" 200 -
127.0.0.1 - - [23/May/2020 14:14:17] " [37mGET /?__debugger__=yes&cmd=resource&f
=console.png HTTP/1.1 [0m" 200 -
127.0.0.1 - - [23/May/2020 14:14:18] " [37mGET /?__debugger__=yes&cmd=resource&f
=ubuntu.ttf HTTP/1.1 [0m" 200 -
127.0.0.1 - - [23/May/2020 14:14:18] " [37mGET /?__debugger__=yes&cmd=resource&f
=console.png HTTP/1.1 [0m" 200 -

---------------------------------





---------------------------------

==========================================

from flask import Flask
app = Flask(__name__)


@app.route("/")
def hello():
return "

Hello World!

"


if __name__ == '__main__':
app.run(debug=True)

---------------------------------





---------------------------------

==========================================

from flask import Flask
app = Flask(__name__)


@app.route("/")
@app.route("/home")
def home():
    return "

Home Page

"


@app.route("/about")
def about():
    return "

About Page

"


if __name__ == '__main__':
    app.run(debug=True)

---------------------------------








5/22/2020

Python - Ex Machina Easter Egg - Hidden Message within the Code

** Ex Machina Easter Egg - Hidden Message within the Code


==========================================


# BlueBook code decryption

import sys
def sieve(n):
    x = [1] * n
    x[1] = 0
    for i in range(2,n/2):
            j = 2 * i
            while j < n:
                    x[j]=0
                    j = j+i
    return x

def prime(n,x):
    i = 1
    j = 1
    while j <= n:
            if x[i] == 1:
                    j = j + 1
            i = i + 1
    return i - 1
x=sieve(10000)
code = [1206,301,384,5]
key =[1,1,2,2,]

sys.stdout.write("".join(chr(i) for i in [73,83,66,78,32,61,32]))
for i in range (0,4):
    sys.stdout.write(str(prime(code[i],x)-key[i]))

print

---------------------------------


Traceback (most recent call last):
  File "C:\Users\purunet\Documents\py7\sub1.py", line 23, in
    x=sieve(10000)
  File "C:\Users\purunet\Documents\py7\sub1.py", line 8, in sieve
    for i in range(2,n/2):
TypeError: 'float' object cannot be interpreted as an integer

---------------------------------

<~~ 차후에 해결.

---------------------------------

Python - Image Manipulation with Pillow

** Image Manipulation with Pillow


==========================================

from PIL import Image

image1 = Image.open('girl1.jpg')
image1.show()

---------------------------------




---------------------------------

==========================================

from PIL import Image

image1 = Image.open('apple1.jpg')
image1.save('apple1.png')

---------------------------------





---------------------------------

==========================================

from PIL import Image
import os

for f in os.listdir('.'):
if f.endswith('.jpg'):
print(f)

---------------------------------

apple1.jpg
apple2.jpg
apple3.jpg
apple4.jpg

---------------------------------

==========================================

from PIL import Image
import os

for f in os.listdir('.'):
if f.endswith('.jpg'):
i = Image.open(f)
fn, fext = os.path.splitext(f)
i.save('pngs/{}.png'.format(fn))

---------------------------------




---------------------------------

==========================================

from PIL import Image
import os

size_300 = (300, 300)

for f in os.listdir('.'):
if f.endswith('.jpg'):
i = Image.open(f)
fn, fext = os.path.splitext(f)

i.thumbnail(size_300)
i.save('300/{}_300{}.png'.format(fn, fext))


---------------------------------




---------------------------------

==========================================

from PIL import Image
import os

size_300 = (300, 300)
size_700 = (700, 700)


for f in os.listdir('.'):
if f.endswith('.jpg'):
i = Image.open(f)
fn, fext = os.path.splitext(f)

i.thumbnail(size_700)
i.save('700/{}_700{}.png'.format(fn, fext))

i.thumbnail(size_300)
i.save('300/{}_300{}.png'.format(fn, fext))


---------------------------------




---------------------------------

==========================================

from PIL import Image
import os

image1 = Image.open('apple1.jpg')
image1.rotate(90).save('apple1_mod.jpg')

---------------------------------




---------------------------------

==========================================

from PIL import Image
import os

image1 = Image.open('apple1.jpg')
image1.convert(mode='L').save('apple1_mod.jpg')

---------------------------------




---------------------------------

==========================================

from PIL import Image, ImageFilter
import os

image1 = Image.open('apple1.jpg')
image1.filter(ImageFilter.GaussianBlur()).save('apple1_mod.jpg')

---------------------------------




---------------------------------

==========================================

from PIL import Image, ImageFilter
import os

image1 = Image.open('apple1.jpg')
image1.filter(ImageFilter.GaussianBlur(15)).save('apple1_mod.jpg')

---------------------------------




---------------------------------



Python - Else Clauses on Loops

** Else Clauses on Loops


==========================================

my_list = [1, 2, 3, 4, 5]

for i in my_list:
print(i)

else:
print("Hit the For/Else Statement!")


---------------------------------

1
2
3
4
5
Hit the For/Else Statement!

---------------------------------

==========================================

num = 3

if num < 2 :
print("num is less than 2!")

else:
print("num is not less than 2!")

---------------------------------

num is not less than 2!

---------------------------------

==========================================


my_list = [1, 2, 3, 4, 5]

for i in my_list:
print(i)
if i == 3:
break

else:
print("Hit the For/Else Statement!")

---------------------------------

1
2
3

---------------------------------

==========================================

my_list = [1, 2, 3, 4, 5]

for i in my_list:
print(i)
if i == 6:
break

else:
print("Hit the For/Else Statement!")


---------------------------------

1
2
3
4
5
Hit the For/Else Statement!

---------------------------------

==========================================

i = 1
while i <= 5:
    print(i)
    i += 1
    # if i == 3:
    #     break
else:
    print('Hit the While/Else Statement!')


---------------------------------

1
2
3
4
5
Hit the While/Else Statement!

---------------------------------

==========================================

i = 1
while i <= 5:
    print(i)
    i += 1
    if i == 3:
        break
else:
    print('Hit the While/Else Statement!')

---------------------------------

1
2

---------------------------------

==========================================

def find_index(to_search, target):
  for i, value in enumerate(to_search):
    if value == target:
      break
  else:
    return -1
  return i


my_list = ['HAN', 'Rick', 'John']
index_location = find_index(my_list, 'Steve')

print('Location of target is index: {}'.format(index_location))

---------------------------------

Location of target is index: -1

---------------------------------

==========================================

def find_index(to_search, target):
  for i, value in enumerate(to_search):
    if value == target:
      break
  else:
    return -1
  return i


my_list = ['HAN', 'Rick', 'John']
index_location = find_index(my_list, 'HAN')

print('Location of target is index: {}'.format(index_location))

---------------------------------

Location of target is index: 0

---------------------------------


Python - Preparing for a Python Interview: 10 Things You Should Know

** Preparing for a Python Interview: 10 Things You Should Know


==========================================

#1. Know how to write code on a whiteboard or paper.

#2. Know basic PYTHON control flow.

#3. Be able to discuss how you've used PYTHON.

#4. Know how to solve common interview problems.

#5. Know basic PYTHON data types and when to use them.

#6. Know how to use list comprehensions.

#7. Know how to use generators.

#8. Know the basics of OOP.

#9. Have PYTHON related questions ready to ask your interviewer.

#10. Know the basics of other technologies.

==========================================

==========================================

for i in range(1, 11):
print(i)

---------------------------------

1
2
3
4
5
6
7
8
9
10

---------------------------------

==========================================

i = 1

while i <= 10:
print(i)
i += 1

---------------------------------

1
2
3
4
5
6
7
8
9
10

---------------------------------

==========================================

a = 10
b = 20

if a < b:
print("{} is less than {}".format(a,b))

elif a == 20:
print("{} is equal to {}".format(a,b))

else:
print("{} is greater than {}".format(a,b))

---------------------------------

10 is less than 20

---------------------------------

==========================================

import os, glob

os.chdir("C:\\Users\\purunet\\Desktop\\LinuxerHaN blog")
for file in glob.glob("*.jpg"):
print(file)

---------------------------------

0.jpg
02.jpg
0b9414af9a817942fbf78c5f0d321b0d.jpg
1.jpg
1d080fc32a69dc4e278cbd8da186a043.jpg
2.jpg
2b553978cb8eadf4cf0813e67335bf97_11244249426.jpg
2bb176b1cf90c3dc3565bd48bc7e9ac4.jpg
3.jpg
4.jpg
4a23935e_2i.jpg
5.jpg
5ca203419e9574500442.jpg
6.jpg
6c1ee4b2992f99282927d6e2638eb490.jpg
7.jpg
8.jpg
8ab64f3ab4b6831f1843bd993b73d627.jpg

---------------------------------

==========================================

# fizz Buzz

for num in range(1, 101):
if num % 5 == 0 and num % 3 == 0:
print("FizzBuzz")
elif num %3 == 0:
print("Fizz")
elif num %5 == 0:
print("Buzz")
else:
print(num)

---------------------------------

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
FizzBuzz
46
47
Fizz
49
Buzz
Fizz
52
53
Fizz
Buzz
56
Fizz
58
59
FizzBuzz
61
62
Fizz
64
Buzz
Fizz
67
68
Fizz
Buzz
71
Fizz
73
74
FizzBuzz
76
77
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz

---------------------------------

==========================================

python 3 에서는 range() 가 xrange() 를 대신함.

==========================================

==========================================

# Fibonacci Sequence

a, b = 0, 1

for i in range(0, 10):
print(a)
a, b = b, a + b

---------------------------------

0
1
1
2
3
5
8
13
21
34

---------------------------------

==========================================

# Lists

my_list = [10, 20, 30, 40, 50]

for i in my_list:
print(i)

---------------------------------

10
20
30
40
50

---------------------------------

==========================================

# Set

my_set = {10, 20, 30, 40, 50, 10, 20, 30, 40, 50}

for i in my_set:
print(i)

---------------------------------

40
10
50
20
30

---------------------------------

==========================================

# Tuples

my_tup = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

for i in my_tup:
print(i)

---------------------------------

1
2
3
4
5
6
7
8
9
10

---------------------------------

==========================================

# Dict

my_dict = {'name': 'Bronx', 'age': '2', 'occupation': "LinuxerHAN's Cat"}

for key, val in my_dict.items():
print("My {} is {}".format(key, val))

---------------------------------

My name is Bronx
My age is 2
My occupation is LinuxerHAN's Cat

---------------------------------

==========================================

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Give me each number in a list squared

squares = [num * num for num in my_list]

print(squares)

---------------------------------

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

---------------------------------

==========================================

# Fibonacci Generator

def fib(num):
a,b = 0,1
for i in range(0, num):
yield "{}: {}".format(i+1, a)
a, b = b, a+b

for item in fib(10):
print(item)


---------------------------------

1: 0
2: 1
3: 1
4: 2
5: 3
6: 5
7: 8
8: 13
9: 21
10: 34

---------------------------------

==========================================

class Person(object):
def __init__(self, name):
self.name = name

def reveal_identity(self):
print("My name is {}".format(self.name))


class SuperHero(Person):
def __init__(self, name, hero_name):
super(SuperHero, self).__init__(name)
self.hero_name = hero_name

def reveal_identity(self):
super(SuperHero, self).reveal_identity()
print("...And I am {}".format(self.hero_name))


LinuxerHAN = Person('LinuxerHAN')
LinuxerHAN.reveal_identity()

---------------------------------

My name is LinuxerHAN

---------------------------------

==========================================


class Person(object):
def __init__(self, name):
self.name = name

def reveal_identity(self):
print("My name is {}".format(self.name))


class SuperHero(Person):
def __init__(self, name, hero_name):
super(SuperHero, self).__init__(name)
self.hero_name = hero_name

def reveal_identity(self):
super(SuperHero, self).reveal_identity()
print("...And I am {}".format(self.hero_name))

SeokDu = SuperHero('SeokDu', 'Deadpool')
SeokDu.reveal_identity()

---------------------------------

My name is SeokDu
...And I am Deadpool

---------------------------------



5/21/2020

Python - Pipenv - Easily Manage Packages and Virtual Environments

** Pipenv - Easily Manage Packages and Virtual Environments


==========================================

C:\Users\purunet>pip install pipenv
Collecting pipenv
  Downloading pipenv-2018.11.26-py3-none-any.whl (5.2 MB)
     |████████████████████████████████| 5.2 MB 1.1 MB/s
Requirement already satisfied: certifi in c:\users\purunet\appdata\local\program
s\python\python38-32\lib\site-packages (from pipenv) (2020.4.5.1)
Requirement already satisfied: setuptools>=36.2.1 in c:\users\purunet\appdata\lo
cal\programs\python\python38-32\lib\site-packages (from pipenv) (41.2.0)
Collecting virtualenv-clone>=0.2.5
  Downloading virtualenv_clone-0.5.4-py2.py3-none-any.whl (6.6 kB)
Requirement already satisfied: pip>=9.0.1 in c:\users\purunet\appdata\local\prog
rams\python\python38-32\lib\site-packages (from pipenv) (20.1)
Collecting virtualenv
  Downloading virtualenv-20.0.21-py2.py3-none-any.whl (4.7 MB)
     |████████████████████████████████| 4.7 MB 4.4 kB/s
Collecting appdirs<2>=1.4.3
  Downloading appdirs-1.4.4-py2.py3-none-any.whl (9.6 kB)
Collecting distlib<1>=0.3.0
  Downloading distlib-0.3.0.zip (571 kB)
     |████████████████████████████████| 571 kB 6.4 MB/s
Requirement already satisfied: six<2>=1.9.0 in c:\users\purunet\appdata\roaming
\python\python38\site-packages (from virtualenv->pipenv) (1.14.0)
Collecting filelock<4>=3.0.0
  Downloading filelock-3.0.12-py3-none-any.whl (7.6 kB)
Building wheels for collected packages: distlib
  Building wheel for distlib (setup.py) ... done
  Created wheel for distlib: filename=distlib-0.3.0-py3-none-any.whl size=340432
 sha256=fdea3c822aee056af092de0d42aca1b44c877bd62738907c3de567c5d03aaa94
  Stored in directory: c:\users\purunet\appdata\local\pip\cache\wheels\eb\4e\d2\
a903d4184fb49e4ac06474d65715b129aee13d69f7d227e78e
Successfully built distlib
Installing collected packages: virtualenv-clone, appdirs, distlib, filelock, vir
tualenv, pipenv
Successfully installed appdirs-1.4.4 distlib-0.3.0 filelock-3.0.12 pipenv-2018.1
1.26 virtualenv-20.0.21 virtualenv-clone-0.5.4
WARNING: You are using pip version 20.1; however, version 20.1.1 is available.
You should consider upgrading via the 'c:\users\purunet\appdata\local\programs\p
ython\python38-32\python.exe -m pip install --upgrade pip' command.

C:\Users\purunet>python.exe -m pip install --upgrade pip
Collecting pip
  Downloading pip-20.1.1-py2.py3-none-any.whl (1.5 MB)
     |████████████████████████████████| 1.5 MB 726 kB/s
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 20.1
    Uninstalling pip-20.1:
      Successfully uninstalled pip-20.1
Successfully installed pip-20.1.1

C:\Users\purunet>pip install pipenv
Requirement already satisfied: pipenv in c:\users\purunet\appdata\local\programs
\python\python38-32\lib\site-packages (2018.11.26)
Requirement already satisfied: virtualenv in c:\users\purunet\appdata\local\prog
rams\python\python38-32\lib\site-packages (from pipenv) (20.0.21)
Requirement already satisfied: pip>=9.0.1 in c:\users\purunet\appdata\local\prog
rams\python\python38-32\lib\site-packages (from pipenv) (20.1.1)
Requirement already satisfied: virtualenv-clone>=0.2.5 in c:\users\purunet\appda
ta\local\programs\python\python38-32\lib\site-packages (from pipenv) (0.5.4)
Requirement already satisfied: setuptools>=36.2.1 in c:\users\purunet\appdata\lo
cal\programs\python\python38-32\lib\site-packages (from pipenv) (41.2.0)
Requirement already satisfied: certifi in c:\users\purunet\appdata\local\program
s\python\python38-32\lib\site-packages (from pipenv) (2020.4.5.1)
Requirement already satisfied: distlib<1>=0.3.0 in c:\users\purunet\appdata\loc
al\programs\python\python38-32\lib\site-packages (from virtualenv->pipenv) (0.3.
0)
Requirement already satisfied: appdirs<2>=1.4.3 in c:\users\purunet\appdata\loc
al\programs\python\python38-32\lib\site-packages (from virtualenv->pipenv) (1.4.
4)
Requirement already satisfied: filelock<4>=3.0.0 in c:\users\purunet\appdata\lo
cal\programs\python\python38-32\lib\site-packages (from virtualenv->pipenv) (3.0
.12)
Requirement already satisfied: six<2>=1.9.0 in c:\users\purunet\appdata\roaming
\python\python38\site-packages (from virtualenv->pipenv) (1.14.0)

==========================================

C:\Users\purunet>pipenv install requests
Creating a virtualenv for this project…
Pipfile: C:\Users\purunet\Pipfile
Using c:\users\purunet\appdata\local\programs\python\python38-32\python.exe (3.8
.2) to create virtualenv…
[    ] Creating virtual environment...created virtual environment CPython3.8.2.f
inal.0-32 in 13262ms

  creator CPython3Windows(dest=C:\Users\purunet\.virtualenvs\purunet-gFaNxclQ, c
lear=False, global=False)

  seeder FromAppData(download=False, pip=latest, setuptools=latest, wheel=latest
, via=copy, app_data_dir=C:\Users\purunet\AppData\Local\pypa\virtualenv\seed-app
-data\v1.0.1)

  activators BashActivator,BatchActivator,FishActivator,PowerShellActivator,Pyth
onActivator,XonshActivator

Successfully created virtual environment!
Virtualenv location: C:\Users\purunet\.virtualenvs\purunet-gFaNxclQ
Creating a Pipfile for this project…
Installing requests…
Adding requests to Pipfile's [packages]…
Installation Succeeded
Pipfile.lock not found, creating…
Locking [dev-packages] dependencies…
Locking [packages] dependencies…
Success!
Updated Pipfile.lock (fbd99e)!
Installing dependencies from Pipfile.lock (fbd99e)…
  ================================ 5/5 - 00:00:09
To activate this project's virtualenv, run pipenv shell.
Alternatively, run a command inside the virtualenv with pipenv run.

C:\Users\purunet>mkdir my_project

C:\Users\purunet>cd my_project

C:\Users\purunet\my_project>pipenv install requests
Installing requests…
Adding requests to Pipfile's [packages]…
Installation Succeeded
Installing dependencies from Pipfile.lock (fbd99e)…
  ================================ 5/5 - 00:00:03
To activate this project's virtualenv, run pipenv shell.
Alternatively, run a command inside the virtualenv with pipenv run.


==========================================

C:\Users\purunet\my_project>pipenv shell
Launching subshell in virtual environment…
Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

==========================================

(purunet-gFaNxclQ) C:\Users\purunet>python
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.executable
'C:\\Users\\purunet\\.virtualenvs\\purunet-gFaNxclQ\\Scripts\\python.exe'
>>> import requests
>>> exit()

(purunet-gFaNxclQ) C:\Users\purunet>exit


==========================================

C:\Users\purunet\my_project>pipenv run python
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.executable
'C:\\Users\\purunet\\.virtualenvs\\purunet-gFaNxclQ\\Scripts\\python.exe'
>>> import requests
>>> exit()

==========================================

C:\Users\purunet\my_project>pipenv
Usage: pipenv [OPTIONS] COMMAND [ARGS]...

Options:
  --where             Output project home information.
  --venv              Output virtualenv information.
  --py                Output Python interpreter information.
  --envs              Output Environment Variable options.
  --rm                Remove the virtualenv.
  --bare              Minimal output.
  --completion        Output completion (to be eval'd).
  --man               Display manpage.
  --support           Output diagnostic information for use in GitHub issues.
  --site-packages     Enable site-packages for the virtualenv.  [env var:
                      PIPENV_SITE_PACKAGES]
  --python TEXT       Specify which version of Python virtualenv should use.
  --three / --two     Use Python 3/2 when creating virtualenv.
  --clear             Clears caches (pipenv, pip, and pip-tools).  [env var:
                      PIPENV_CLEAR]
  -v, --verbose       Verbose mode.
  --pypi-mirror TEXT  Specify a PyPI mirror.
  --version           Show the version and exit.
  -h, --help          Show this message and exit.


Usage Examples:
   Create a new project using Python 3.7, specifically:
   $ pipenv --python 3.7

   Remove project virtualenv (inferred from current directory):
   $ pipenv --rm

   Install all dependencies for a project (including dev):
   $ pipenv install --dev

   Create a lockfile containing pre-releases:
   $ pipenv lock --pre

   Show a graph of your installed dependencies:
   $ pipenv graph

   Check your installed dependencies for security vulnerabilities:
   $ pipenv check

   Install a local setup.py into your virtual environment/Pipfile:
   $ pipenv install -e .

   Use a lower-level pip command:
   $ pipenv run pip freeze

Commands:
  check      Checks for security vulnerabilities and against PEP 508 markers
             provided in Pipfile.
  clean      Uninstalls all packages not specified in Pipfile.lock.
  graph      Displays currently-installed dependency graph information.
  install    Installs provided packages and adds them to Pipfile, or (if no
             packages are given), installs all packages from Pipfile.
  lock       Generates Pipfile.lock.
  open       View a given module in your editor.
  run        Spawns a command installed into the virtualenv.
  shell      Spawns a shell within the virtualenv.
  sync       Installs all packages specified in Pipfile.lock.
  uninstall  Un-installs a provided package and removes it from Pipfile.
  update     Runs lock, then sync.

==========================================

C:\Users\purunet\my_project>pip

Usage:
  pip [options]

Commands:
  install                     Install packages.
  download                    Download packages.
  uninstall                   Uninstall packages.
  freeze                      Output installed packages in requirements format.
  list                        List installed packages.
  show                        Show information about installed packages.
  check                       Verify installed packages have compatible dependen
cies.
  config                      Manage local and global configuration.
  search                      Search PyPI for packages.
  cache                       Inspect and manage pip's wheel cache.
  wheel                       Build wheels from your requirements.
  hash                        Compute hashes of package archives.
  completion                  A helper command used for command completion.
  debug                       Show information useful for debugging.
  help                        Show help for commands.

General Options:
  -h, --help                  Show help.
  --isolated                  Run pip in an isolated mode, ignoring
                              environment variables and user configuration.
  -v, --verbose               Give more output. Option is additive, and can be
                              used up to 3 times.
  -V, --version               Show version and exit.
  -q, --quiet                 Give less output. Option is additive, and can be
                              used up to 3 times (corresponding to WARNING,
                              ERROR, and CRITICAL logging levels).
  --log                 Path to a verbose appending log.
  --proxy              Specify a proxy in the form
                              [user:passwd@]proxy.server:port.
  --retries          Maximum number of retries each connection should
                              attempt (default 5 times).
  --timeout              Set the socket timeout (default 15 seconds).
  --exists-action     Default action when a path already exists:
                              (s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.
  --trusted-host    Mark this host or host:port pair as trusted,
                              even though it does not have valid or any HTTPS.
  --cert                Path to alternate CA bundle.
  --client-cert         Path to SSL client certificate, a single file
                              containing the private key and the certificate
                              in PEM format.
  --cache-dir

           Store the cache data in .
  --no-cache-dir              Disable the cache.
  --disable-pip-version-check
                              Don't periodically check PyPI to determine
                              whether a new version of pip is available for
                              download. Implied with --no-index.
  --no-color                  Suppress colored output
  --no-python-version-warning
                              Silence deprecation warnings for upcoming
                              unsupported Pythons.


==========================================

C:\Users\purunet\my_project>pipenv install pytest --dev
Installing pytest…
Adding pytest to Pipfile's [dev-packages]…
Installation Succeeded
Pipfile.lock (9e60ab) out of date, updating to (fbd99e)…
Locking [dev-packages] dependencies…
Success!
Locking [packages] dependencies…
Success!
Updated Pipfile.lock (9e60ab)!
Installing dependencies from Pipfile.lock (9e60ab)…
  ================================ 16/16 - 00:00:14
To activate this project's virtualenv, run pipenv shell.
Alternatively, run a command inside the virtualenv with pipenv run.

==========================================

C:\Users\purunet\my_project>pipenv graph
pytest==5.4.2
  - atomicwrites [required: >=1.0, installed: 1.4.0]
  - attrs [required: >=17.4.0, installed: 19.3.0]
  - colorama [required: Any, installed: 0.4.3]
  - more-itertools [required: >=4.0.0, installed: 8.3.0]
  - packaging [required: Any, installed: 20.4]
    - pyparsing [required: >=2.0.2, installed: 2.4.7]
    - six [required: Any, installed: 1.14.0]
  - pluggy [required: >=0.12,<1 .0="" 0.13.1="" installed:="" p="">  - py [required: >=1.5.0, installed: 1.8.1]
  - wcwidth [required: Any, installed: 0.1.9]
requests==2.23.0
  - certifi [required: >=2017.4.17, installed: 2020.4.5.1]
  - chardet [required: >=3.0.2,<4 3.0.4="" installed:="" p="">  - idna [required: >=2.5,<3 2.9="" installed:="" p="">  - urllib3 [required: >=1.21.1,<1 .26="" 1.25.9="" installed:="" p="">
==========================================


5/20/2020

Python - Unit Testing Your Code with the unittest Module

** Unit Testing Your Code with the unittest Module


==========================================

def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
    return x * y


def divide(x, y):
    """Divide Function"""
    if y == 0:
        raise ValueError('Can not divide by zero!')
    return x / y


print(add(10,5))

---------------------------------

15

---------------------------------

==========================================

import unittest
import calc


class TestCalc(unittest.TestCase):

    def test_add(self):
        result = calc.add(10, 5)
        self.assertEqual(result, 15)

-----------calc.py-----------------

def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
    return x * y


def divide(x, y):
    """Divide Function"""
    if y == 0:
        raise ValueError('Can not divide by zero!')
    return x / y

---------------------------------

C:\Users\purunet\Documents\py6>python -m unittest test_calc.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

---------------------------------

==========================================

import unittest
import calc


class TestCalc(unittest.TestCase):

    def test_add(self):
        result = calc.add(10, 5)
        self.assertEqual(result, 15)


if __name__ == '__main__':
    unittest.main()

-----------calc.py-----------------

def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
    return x * y


def divide(x, y):
    """Divide Function"""
    if y == 0:
        raise ValueError('Can not divide by zero!')
    return x / y

---------------------------------

C:\Users\purunet\Documents\py6>python -m unittest test_calc.py
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

---------------------------------

==========================================

import unittest
import calc


class TestCalc(unittest.TestCase):

    def add_test(self):
        result = calc.add(10, 5)
        self.assertEqual(result, 15)


if __name__ == '__main__':
    unittest.main()

---------------------------------


----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK

---------------------------------
==========================================

import unittest
import calc


class TestCalc(unittest.TestCase):

    def test_add(self):
        result = calc.add(10, 5)
        self.assertEqual(result, 15)


if __name__ == '__main__':
    unittest.main()

---------------------------------

.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

---------------------------------

==========================================

import unittest
import calc


class TestCalc(unittest.TestCase):

    def test_add(self):
        result = calc.add(10, 5)
        self.assertEqual(result, 14)


if __name__ == '__main__':
    unittest.main()

---------------------------------

F
======================================================================
FAIL: test_add (__main__.TestCalc)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\purunet\Documents\py6\test_calc.py", line 9, in test_add
    self.assertEqual(result, 14)
AssertionError: 15 != 14

----------------------------------------------------------------------
Ran 1 test in 0.013s

FAILED (failures=1)
[Finished in 0.5s with exit code 1]

---------------------------------

==========================================

import unittest
import calc


class TestCalc(unittest.TestCase):

    def test_add(self):
        self.assertEqual(calc.add(10, 5), 15)
        self.assertEqual(calc.add(-1, 1), 0)
        self.assertEqual(calc.add(-1, -1), -2)


if __name__ == '__main__':
    unittest.main()


---------------------------------

.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

---------------------------------

==========================================

import unittest
import calc


class TestCalc(unittest.TestCase):

    def test_add(self):
        self.assertEqual(calc.add(10, 5), 15)
        self.assertEqual(calc.add(-1, 1), 0)
        self.assertEqual(calc.add(-1, -1), -2)

    def test_subtract(self):
        self.assertEqual(calc.subtract(10, 5), 5)
        self.assertEqual(calc.subtract(-1, 1), -2)
        self.assertEqual(calc.subtract(-1, -1), 0)

    def test_multiply(self):
        self.assertEqual(calc.multiply(10, 5), 50)
        self.assertEqual(calc.multiply(-1, 1), -1)
        self.assertEqual(calc.multiply(-1, -1), 1)

    def test_divide(self):
        self.assertEqual(calc.divide(10, 5), 2)
        self.assertEqual(calc.divide(-1, 1), -1)
        self.assertEqual(calc.divide(-1, -1), 1)
        self.assertEqual(calc.divide(5, 2), 2.5)


if __name__ == '__main__':
    unittest.main()

---------------------------------

....
----------------------------------------------------------------------
Ran 4 tests in 0.001s

OK

---------------------------------

==========================================

import unittest
import calc


class TestCalc(unittest.TestCase):

    def test_add(self):
        self.assertEqual(calc.add(10, 5), 15)
        self.assertEqual(calc.add(-1, 1), 0)
        self.assertEqual(calc.add(-1, -1), -2)

    def test_subtract(self):
        self.assertEqual(calc.subtract(10, 5), 5)
        self.assertEqual(calc.subtract(-1, 1), -2)
        self.assertEqual(calc.subtract(-1, -1), 0)

    def test_multiply(self):
        self.assertEqual(calc.multiply(10, 5), 50)
        self.assertEqual(calc.multiply(-1, 1), -1)
        self.assertEqual(calc.multiply(-1, -1), 1)

    def test_divide(self):
        self.assertEqual(calc.divide(10, 5), 2)
        self.assertEqual(calc.divide(-1, 1), -1)
        self.assertEqual(calc.divide(-1, -1), 1)
        self.assertEqual(calc.divide(5, 2), 2.5)


if __name__ == '__main__':
    unittest.main()

-----------calc.py-----------------

def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
# error
    return x ** y                             


def divide(x, y):
    """Divide Function"""
    if y == 0:
        raise ValueError('Can not divide by zero!')
    return x / y

---------------------------------

..F.
======================================================================
FAIL: test_multiply (__main__.TestCalc)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\purunet\Documents\py6\test_calc.py", line 18, in test_multiply
    self.assertEqual(calc.multiply(10, 5), 50)
AssertionError: 100000 != 50

----------------------------------------------------------------------
Ran 4 tests in 0.002s

FAILED (failures=1)
[Finished in 0.5s with exit code 1]

---------------------------------

==========================================

import unittest
import calc


class TestCalc(unittest.TestCase):

    def test_add(self):
        self.assertEqual(calc.add(10, 5), 15)
        self.assertEqual(calc.add(-1, 1), 0)
        self.assertEqual(calc.add(-1, -1), -2)

    def test_subtract(self):
        self.assertEqual(calc.subtract(10, 5), 5)
        self.assertEqual(calc.subtract(-1, 1), -2)
        self.assertEqual(calc.subtract(-1, -1), 0)

    def test_multiply(self):
        self.assertEqual(calc.multiply(10, 5), 50)
        self.assertEqual(calc.multiply(-1, 1), -1)
        self.assertEqual(calc.multiply(-1, -1), 1)

    def test_divide(self):
        self.assertEqual(calc.divide(10, 5), 2)
        self.assertEqual(calc.divide(-1, 1), -1)
        self.assertEqual(calc.divide(-1, -1), 1)
        self.assertEqual(calc.divide(5, 2), 2.5)

        self.assertRaises(ValueError, calc.divide, 10, 0)

if __name__ == '__main__':
    unittest.main()

-----------calc.py-----------------

def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
# error
    return x ** y                             


def divide(x, y):
    """Divide Function"""
    if y == 0:
        raise ValueError('Can not divide by zero!')
    return x / y

---------------------------------

....
----------------------------------------------------------------------
Ran 4 tests in 0.001s

OK

---------------------------------

==========================================

import unittest
import calc


class TestCalc(unittest.TestCase):

    def test_add(self):
        self.assertEqual(calc.add(10, 5), 15)
        self.assertEqual(calc.add(-1, 1), 0)
        self.assertEqual(calc.add(-1, -1), -2)

    def test_subtract(self):
        self.assertEqual(calc.subtract(10, 5), 5)
        self.assertEqual(calc.subtract(-1, 1), -2)
        self.assertEqual(calc.subtract(-1, -1), 0)

    def test_multiply(self):
        self.assertEqual(calc.multiply(10, 5), 50)
        self.assertEqual(calc.multiply(-1, 1), -1)
        self.assertEqual(calc.multiply(-1, -1), 1)

    def test_divide(self):
        self.assertEqual(calc.divide(10, 5), 2)
        self.assertEqual(calc.divide(-1, 1), -1)
        self.assertEqual(calc.divide(-1, -1), 1)
        self.assertEqual(calc.divide(5, 2), 2.5)

        self.assertRaises(ValueError, calc.divide, 10, 2)

if __name__ == '__main__':
    unittest.main()

-----------calc.py-----------------

def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
# error
    return x ** y                             


def divide(x, y):
    """Divide Function"""
    if y == 0:
        raise ValueError('Can not divide by zero!')
    return x / y

---------------------------------

.F..
======================================================================
FAIL: test_divide (__main__.TestCalc)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\purunet\Documents\py6\test_calc.py", line 28, in test_divide
    self.assertRaises(ValueError, calc.divide, 10, 2)
AssertionError: ValueError not raised by divide

----------------------------------------------------------------------
Ran 4 tests in 0.002s

FAILED (failures=1)
[Finished in 0.4s with exit code 1]

---------------------------------

==========================================

import unittest
import calc


class TestCalc(unittest.TestCase):

    def test_add(self):
        self.assertEqual(calc.add(10, 5), 15)
        self.assertEqual(calc.add(-1, 1), 0)
        self.assertEqual(calc.add(-1, -1), -2)

    def test_subtract(self):
        self.assertEqual(calc.subtract(10, 5), 5)
        self.assertEqual(calc.subtract(-1, 1), -2)
        self.assertEqual(calc.subtract(-1, -1), 0)

    def test_multiply(self):
        self.assertEqual(calc.multiply(10, 5), 50)
        self.assertEqual(calc.multiply(-1, 1), -1)
        self.assertEqual(calc.multiply(-1, -1), 1)

    def test_divide(self):
        self.assertEqual(calc.divide(10, 5), 2)
        self.assertEqual(calc.divide(-1, 1), -1)
        self.assertEqual(calc.divide(-1, -1), 1)
        self.assertEqual(calc.divide(5, 2), 2.5)

        with self.assertRaises(ValueError):
            calc.divide(10, 0)

if __name__ == '__main__':
    unittest.main()

-----------calc.py-----------------

def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
# error
    return x ** y                             


def divide(x, y):
    """Divide Function"""
    if y == 0:
        raise ValueError('Can not divide by zero!')
    return x / y

---------------------------------

....
----------------------------------------------------------------------
Ran 4 tests in 0.001s

OK

---------------------------------

==========================================

import unittest
from employee import Employee


class TestEmployee(unittest.TestCase):

 
    def test_email(self):
        emp_1 = Employee('Corey', 'Schafer', 50000)
        emp_2 = Employee('Sue', 'Smith', 60000)

        self.assertEqual(emp_1.email, 'Corey.Schafer@email.com')
        self.assertEqual(emp_2.email, 'Sue.Smith@email.com')

        emp_1.first = 'John'
        emp_2.first = 'Jane'

        self.assertEqual(emp_1.email, 'John.Schafer@email.com')
        self.assertEqual(emp_2.email, 'Jane.Smith@email.com')

    def test_fullname(self):
        emp_1 = Employee('Corey', 'Schafer', 50000)
        emp_2 = Employee('Sue', 'Smith', 60000)

        self.assertEqual(emp_1.fullname, 'Corey Schafer')
        self.assertEqual(emp_2.fullname, 'Sue Smith')

        emp_1.first = 'John'
        emp_2.first = 'Jane'

        self.assertEqual(emp_1.fullname, 'John Schafer')
        self.assertEqual(emp_2.fullname, 'Jane Smith')

    def test_apply_raise(self):
        emp_1 = Employee('Corey', 'Schafer', 50000)
        emp_2 = Employee('Sue', 'Smith', 60000)

        emp_1.apply_raise()
        emp_2.apply_raise()

        self.assertEqual(emp_1.pay, 52500)
        self.assertEqual(emp_2.pay, 63000)


if __name__ == '__main__':
    unittest.main()

-----------employee.py--------------

import requests


class Employee:
    """A sample Employee class"""

    raise_amt = 1.05

    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay

    @property
    def email(self):
        return '{}.{}@email.com'.format(self.first, self.last)

    @property
    def fullname(self):
        return '{} {}'.format(self.first, self.last)

    def apply_raise(self):
        self.pay = int(self.pay * self.raise_amt)

    def monthly_schedule(self, month):
        response = requests.get(f'http://company.com/{self.last}/{month}')
        if response.ok:
            return response.text
        else:
            return 'Bad Response!'

---------------------------------

...
----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK

---------------------------------

==========================================

import unittest

from employee import Employee

class TestEmployee(unittest.TestCase):

   def setUp(self):
        self.emp_1 = Employee('Corey', 'Schafer', 50000)
        self.emp_2 = Employee('Sue', 'Smith', 60000)

    def tearDown(self):
        pass
       

    def test_email(self):
        self.assertEqual(self.emp_1.email, 'Corey.Schafer@email.com')
        self.assertEqual(self.emp_2.email, 'Sue.Smith@email.com')

        self.emp_1.first = 'John'
        self.emp_2.first = 'Jane'

        self.assertEqual(self.emp_1.email, 'John.Schafer@email.com')
        self.assertEqual(self.emp_2.email, 'Jane.Smith@email.com')

    def test_fullname(self):
        self.assertEqual(self.emp_1.fullname, 'Corey Schafer')
        self.assertEqual(self.emp_2.fullname, 'Sue Smith')

        self.emp_1.first = 'John'
        self.emp_2.first = 'Jane'

        self.assertEqual(self.emp_1.fullname, 'John Schafer')
        self.assertEqual(self.emp_2.fullname, 'Jane Smith')

    def test_apply_raise(self):
        self.emp_1.apply_raise()
        self.emp_2.apply_raise()

        self.assertEqual(self.emp_1.pay, 52500)
        self.assertEqual(self.emp_2.pay, 63000)

if __name__ == '__main__':
    unittest.main()

-----------employee.py--------------

import requests


class Employee:
    """A sample Employee class"""

    raise_amt = 1.05

    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay

    @property
    def email(self):
        return '{}.{}@email.com'.format(self.first, self.last)

    @property
    def fullname(self):
        return '{} {}'.format(self.first, self.last)

    def apply_raise(self):
        self.pay = int(self.pay * self.raise_amt)

    def monthly_schedule(self, month):
        response = requests.get(f'http://company.com/{self.last}/{month}')
        if response.ok:
            return response.text
        else:
            return 'Bad Response!'

---------------------------------

...
----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK

---------------------------------

==========================================

import unittest

from employee import Employee

class TestEmployee(unittest.TestCase):

    def setUp(self):
        print('setUp')
        self.emp_1 = Employee('Corey', 'Schafer', 50000)
        self.emp_2 = Employee('Sue', 'Smith', 60000)

    def tearDown(self):
        print('tearDown\n')

    def test_email(self):
        print('test_email')
        self.assertEqual(self.emp_1.email, 'Corey.Schafer@email.com')
        self.assertEqual(self.emp_2.email, 'Sue.Smith@email.com')

        self.emp_1.first = 'John'
        self.emp_2.first = 'Jane'

        self.assertEqual(self.emp_1.email, 'John.Schafer@email.com')
        self.assertEqual(self.emp_2.email, 'Jane.Smith@email.com')

    def test_fullname(self):
        print('test_fullname')
        self.assertEqual(self.emp_1.fullname, 'Corey Schafer')
        self.assertEqual(self.emp_2.fullname, 'Sue Smith')

        self.emp_1.first = 'John'
        self.emp_2.first = 'Jane'

        self.assertEqual(self.emp_1.fullname, 'John Schafer')
        self.assertEqual(self.emp_2.fullname, 'Jane Smith')

    def test_apply_raise(self):
        print('test_apply_raise')
        self.emp_1.apply_raise()
        self.emp_2.apply_raise()

        self.assertEqual(self.emp_1.pay, 52500)
        self.assertEqual(self.emp_2.pay, 63000)

if __name__ == '__main__':
    unittest.main()

-----------employee.py--------------

import requests


class Employee:
    """A sample Employee class"""

    raise_amt = 1.05

    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay

    @property
    def email(self):
        return '{}.{}@email.com'.format(self.first, self.last)

    @property
    def fullname(self):
        return '{} {}'.format(self.first, self.last)

    def apply_raise(self):
        self.pay = int(self.pay * self.raise_amt)

    def monthly_schedule(self, month):
        response = requests.get(f'http://company.com/{self.last}/{month}')
        if response.ok:
            return response.text
        else:
            return 'Bad Response!'

---------------------------------

setUp
test_apply_raise
tearDown

.setUp
test_email
tearDown

.setUp.
test_fullname
tearDown


----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK

---------------------------------

==========================================

import unittest

from employee import Employee

class TestEmployee(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        print('setupClass')

    @classmethod
    def tearDownClass(cls):
        print('teardownClass')
    def setUp(self):
        print('setUp')
        self.emp_1 = Employee('Corey', 'Schafer', 50000)
        self.emp_2 = Employee('Sue', 'Smith', 60000)

    def tearDown(self):
        print('tearDown\n')

    def test_email(self):
        print('test_email')
        self.assertEqual(self.emp_1.email, 'Corey.Schafer@email.com')
        self.assertEqual(self.emp_2.email, 'Sue.Smith@email.com')

        self.emp_1.first = 'John'
        self.emp_2.first = 'Jane'

        self.assertEqual(self.emp_1.email, 'John.Schafer@email.com')
        self.assertEqual(self.emp_2.email, 'Jane.Smith@email.com')

    def test_fullname(self):
        print('test_fullname')
        self.assertEqual(self.emp_1.fullname, 'Corey Schafer')
        self.assertEqual(self.emp_2.fullname, 'Sue Smith')

        self.emp_1.first = 'John'
        self.emp_2.first = 'Jane'

        self.assertEqual(self.emp_1.fullname, 'John Schafer')
        self.assertEqual(self.emp_2.fullname, 'Jane Smith')

    def test_apply_raise(self):
        print('test_apply_raise')
        self.emp_1.apply_raise()
        self.emp_2.apply_raise()

        self.assertEqual(self.emp_1.pay, 52500)
        self.assertEqual(self.emp_2.pay, 63000)

if __name__ == '__main__':
    unittest.main()

-----------employee.py--------------

import requests


class Employee:
    """A sample Employee class"""

    raise_amt = 1.05

    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay

    @property
    def email(self):
        return '{}.{}@email.com'.format(self.first, self.last)

    @property
    def fullname(self):
        return '{} {}'.format(self.first, self.last)

    def apply_raise(self):
        self.pay = int(self.pay * self.raise_amt)

    def monthly_schedule(self, month):
        response = requests.get(f'http://company.com/{self.last}/{month}')
        if response.ok:
            return response.text
        else:
            return 'Bad Response!'

---------------------------------

setupClass
setUp
test_apply_raise
tearDown

.setUp
test_email
tearDown

.setUp
test_fullname
tearDown

.teardownClass

----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK

---------------------------------

==========================================

import unittest
from unittest.mock import patch
from employee import Employee


class TestEmployee(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        print('setupClass')

    @classmethod
    def tearDownClass(cls):
        print('teardownClass')

    def setUp(self):
        print('setUp')
        self.emp_1 = Employee('Corey', 'Schafer', 50000)
        self.emp_2 = Employee('Sue', 'Smith', 60000)

    def tearDown(self):
        print('tearDown\n')

    def test_email(self):
        print('test_email')
        self.assertEqual(self.emp_1.email, 'Corey.Schafer@email.com')
        self.assertEqual(self.emp_2.email, 'Sue.Smith@email.com')

        self.emp_1.first = 'John'
        self.emp_2.first = 'Jane'

        self.assertEqual(self.emp_1.email, 'John.Schafer@email.com')
        self.assertEqual(self.emp_2.email, 'Jane.Smith@email.com')

    def test_fullname(self):
        print('test_fullname')
        self.assertEqual(self.emp_1.fullname, 'Corey Schafer')
        self.assertEqual(self.emp_2.fullname, 'Sue Smith')

        self.emp_1.first = 'John'
        self.emp_2.first = 'Jane'

        self.assertEqual(self.emp_1.fullname, 'John Schafer')
        self.assertEqual(self.emp_2.fullname, 'Jane Smith')

    def test_apply_raise(self):
        print('test_apply_raise')
        self.emp_1.apply_raise()
        self.emp_2.apply_raise()

        self.assertEqual(self.emp_1.pay, 52500)
        self.assertEqual(self.emp_2.pay, 63000)

    def test_monthly_schedule(self):
        with patch('employee.requests.get') as mocked_get:
            mocked_get.return_value.ok = True
            mocked_get.return_value.text = 'Success'

            schedule = self.emp_1.monthly_schedule('May')
            mocked_get.assert_called_with('http://company.com/Schafer/May')
            self.assertEqual(schedule, 'Success')

            mocked_get.return_value.ok = False

            schedule = self.emp_2.monthly_schedule('June')
            mocked_get.assert_called_with('http://company.com/Smith/June')
            self.assertEqual(schedule, 'Bad Response!')


if __name__ == '__main__':
    unittest.main()

-----------employee.py--------------

import requests


class Employee:
    """A sample Employee class"""

    raise_amt = 1.05

    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay

    @property
    def email(self):
        return '{}.{}@email.com'.format(self.first, self.last)

    @property
    def fullname(self):
        return '{} {}'.format(self.first, self.last)

    def apply_raise(self):
        self.pay = int(self.pay * self.raise_amt)

    def monthly_schedule(self, month):
        response = requests.get(f'http://company.com/{self.last}/{month}')
        if response.ok:
            return response.text
        else:
            return 'Bad Response!'

---------------------------------

setupClass
setUp
test_apply_raise
tearDown
.
setUp
test_email
tearDown

.setUp
test_fullname
tearDown

.setUp
tearDown
.

teardownClass
----------------------------------------------------------------------
Ran 4 tests in 0.022s

OK

---------------------------------


Python - if __name__ == '__main__'

** if __name__ == '__main__'


==========================================

print(__name__)

---------------------------------

__main__

---------------------------------

==========================================

print("First Module's Name: {}".format(__name__))

---------------------------------

First Module's Name: __main__

---------------------------------

==========================================

import first_module

-------first_module.py---------------

print("First Module's Name: {}".format(__name__))

---------------------------------

First Module's Name: first_module

---------------------------------

==========================================

import first_module

print("Second Module's Name: {}".format(__name__))


-------first_module.py---------------

print("First Module's Name: {}".format(__name__))

---------------------------------

First Module's Name: first_module
Second Module's Name: __main__

---------------------------------

==========================================


def main():
print("First Module's Name: {}".format(__name__))

if __name__ == '__main__':
main()

---------------------------------

First Module's Name: __main__

---------------------------------

==========================================

import first_module

print("Second Module's Name: {}".format(__name__))

-------first_module.py---------------

def main():
print("First Module's Name: {}".format(__name__))

if __name__ == '__main__':
main()

---------------------------------

Second Module's Name: __main__

---------------------------------

==========================================

import first_module

print("Second Module's Name: {}".format(__name__))

-------first_module.py---------------

if __name__ == '__main__':
print("Run Directly")

else:
print("Run From Import")

---------------------------------

Run From Import
Second Module's Name: __main__

---------------------------------

==========================================

print("This will always be run")

def main():
print("First Module's Main Method")

if __name__ == '__main__':
main()

---------------------------------

This will always be run
First Module's Main Method

---------------------------------

==========================================

import first_module

print("Second Module's Name: {}".format(__name__))

-------first_module.py---------------

print("This will always be run")

def main():
print("First Module's Main Method")

if __name__ == '__main__':
main()

---------------------------------

This will always be run
Second Module's Name: __main__

---------------------------------

==========================================

import first_module

first_module.main()

print("Second Module's Name: {}".format(__name__))

-------first_module.py---------------

print("This will always be run")

def main():
print("First Module's Main Method")

if __name__ == '__main__':
main()

---------------------------------

This will always be run
First Module's Main Method
Second Module's Name: __main__

---------------------------------