Example 1: python hangman
import random
word_list = ["insert", "your", "words", "in", "this", "python", "list"]
def get_word(word_list):
word = random.choice(word_list)
return word.upper()
def play(word):
word_completion = "_" * len(word)
guessed = False
guessed_letters = []
guessed_words = []
tries = 6
print("Let's play Hangman")
print(display_hangman(tries))
print(word_completion)
print("\n")
while not guessed and tries > 0:
guess = input("guess a letter or word: ").upper()
if len(guess) == 1 and guess.isalpha():
if guess in guessed_letters:
print("you already tried", guess, "!")
elif guess not in word:
print(guess, "isn't in the word :(")
tries -= 1
guessed_letters.append(guess)
else:
print("Nice one,", guess, "is in the word!")
guessed_letters.append(guess)
word_as_list = list(word_completion)
indices = [i for i, letter in enumerate(word) if letter == guess]
for index in indices:
word_as_list[index] = guess
word_completion = "".join(word_as_list)
if "_" not in word_completion:
guessed = True
elif len(guess) == len(word) and guess.isalpha():
if guess in guessed_words:
print("You already tried ", guess, "!")
elif guess != word:
print(guess, " ist nicht das Wort :(")
tries -= 1
guessed_words.append(guess)
else:
guessed = True
word_completion = word
else:
print("invalid input")
print(display_hangman(tries))
print(word_completion)
print("\n")
if guessed:
print("Good Job, you guessed the word!")
else:
print("I'm sorry, but you ran out of tries. The word was " + word + ". Maybe next time!")
def display_hangman(tries):
stages = [ """
--------
| |
| O
| \\|/
| |
| / \\
-
""",
"""
--------
| |
| O
| \\|/
| |
| /
-
""",
"""
--------
| |
| O
| \\|/
| |
|
-
""",
"""
--------
| |
| O
| \\|
| |
|
-
""",
"""
--------
| |
| O
| |
| |
|
-
""",
"""
--------
| |
| O
|
|
|
-
""",
"""
--------
| |
|
|
|
|
-
"""
]
return stages[tries]
def main():
word = get_word(word_list)
play(word)
while input("Again? (Y/N) ").upper() == "Y":
word = get_word(word_list)
play(word)
if __name__ == "__main__":
main()
Example 2: python rsa
import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
random_generator = Random.new().read
key = RSA.generate(1024, random_generator)
publickey = key.publickey
encrypted = publickey.encrypt('encrypt this message', 32)
print 'encrypted message:', encrypted
f = open ('encryption.txt', 'w'w)
f.write(str(encrypted))
f.close()
f = open ('encryption.txt', 'r')
message = f.read()
decrypted = key.decrypt(message)
print 'decrypted', decrypted
f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()
Example 3: python mock input
from io import StringIO
def enter_name():
name = input('Please enter name: ')
return 'Hello ' + name
mock_input = StringIO('John\n')
def test_enter_name(monkeypatch):
monkeypatch.setattr('sys.stdin', mock_input)
assert enter_name() == 'Hello John'
Example 4: format for unit test python
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
with self.assertRaises(TypeError):
s.split(2)
if __name__ == '__main__':
unittest.main()
Example 5: python unittest setUpClass
class MyUnitTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
do_something_expensive_for_all_sets_of_tests()
class MyFirstSetOfTests(MyUnitTest):
@classmethod
def setUpClass(cls):
super(MyFirstSetOfTests, cls).setUpClass()
do_something_expensive_for_just_these_first_tests()
Example 6: self.assertequal python
'''
In other words, assertEquals is a function to check if two variables are equal, for purposes of automated testing:
'''
def assertEquals(var1, var2):
if var1 == var2:
return True
else:
return False