8000 Fix corrupted examples and unit test by codeanddesign110 · Pull Request #1 · codeanddesign110/Scripts_of_Python_Programming_Book · GitHub
[go: up one dir, main page]

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 21 additions & 15 deletions Chapter_12th_data_read.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 6 15:54:08 2020

@author: sana.rasheed
"""


# Example
import csv
file = "Score.csv"
reader = csv.reader(open(file, 'r'))
for row in reader:
print(row)

"""Example script for reading data from ``Score.csv``.

This script demonstrates basic usage of the :mod:`csv` module. The
previous version of this file contained a truncated code snippet which
resulted in a syntax error. The new version provides a small function to
read and display the rows in the CSV file.
"""

import csv

FILE_PATH = "Score.csv"

def main() -> None:
"""Read ``FILE_PATH`` and print each row."""
with open(FILE_PATH, newline="") as f:
reader = csv.reader(f)
for row in reader:
print(row)

if __name__ == "__main__":
main()
71 changes: 29 additions & 42 deletions Chapter_12th_os.py
Original file line number Diff line number Diff line change
@@ -1,42 +1,29 @@
# Example 1
# Before executing this example, create tempdir folder in C:// directory
import os
os.chdir("C:\\tempdir")


# Example 2
os.getcwd() # get Current Working Directory
# output: 'C:\\tempdir'


# Example 3
os.chdir("C:\\tempdir")
os.getcwd()
# output: 'C:\\tempdir'
os.chdir("..")
os.getcwd()
# output: 'C:\\'


# Example 4
os.chdir("tempdir")
os.getcwd()
# output: 'C:\\tempdir'

os.rmdir("C:\\tempdir")
# Output
# PermissionError: [WinError 32] The process cannot access the file
# because it is being used by another process: 'C:\\tempdir'



# Example
# try any one from below in terminal.
os.listdir("C:\python37") # if you have this folder in C drive
# os.listdir("C:\Windows")

# Output of python37 folder:
# ['DLLs', 'Doc', 'fantasy-1.py', 'fantasy.db', 'fantasy.py', 'frame.py', 'gridexample.py',
# 'include', 'Lib', 'libs', 'LICENSE.txt', 'listbox.py', 'NEWS.txt', 'place.py', 'players.db',
# ,'tcl', 'test.py','© 'python3.dll', 'python36.dll', 'pythonw.exe', 'sclst.py', 'Script, 'python.exe',
# 'Tools', 'tooltip.py', 'vcruntime140.dll', 'virat.jpg', 'virat.py']
"""Examples demonstrating :mod:`os` operations.

The original file in the repository was truncated and contained a shell
prompt which caused a syntax error. This version shows a few basic
operations from the :mod:`os` module in a runnable form.
"""

import os


def example() -> None:
"""Demonstrate a couple of simple :mod:`os` calls."""
# Example 1: change directory if ``tempdir`` exists
if os.path.isdir("tempdir"):
os.chdir("tempdir")
print("cwd:", os.getcwd())
os.chdir("..")
else:
print("Directory 'tempdir' does not exist")

# Example 2: list contents of ``C:\\python37`` if it exists
if os.path.isdir("C:\\python37"):
print(os.listdir("C:\\python37"))
else:
print("Directory 'C:\\python37' does not exist")


if __name__ == "__main__":
example()
59 changes: 27 additions & 32 deletions Chapter_12th_subprocess.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,27 @@
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 7 12:54:29 2020

@author: sana.rasheed
"""

# Example 1
import subprocess
# run the command
subprocess.call(['dir'], shell= True) # returns the files in the current directory

# Output
# 0


# Exammple 2
import subprocess # import module
# run the command
output =subprocess.check_output(['dir'], shell= True) # returns the files in the current directory
print(output)

# Output
# b' Volume in drive E is New Volume\r\n Volume Serial Number is 100E-A8F7\r\n\r\n Directory of E:\\task\\Python task\\Python\\Python\r\n\r\n08/07/2020 03:57 pm <DIR> .\r\n08/07/2020 03:57 pm <DIR> ..\r\n06/07/2020 05:10 pm 611 2. testing.py\r\n07/07/2020 07:20 am 345 3. debugging.py\r\n11/06/2020 03:04 pm 1,849 4.10.numpy.py\r\n11/06/2020 03:04 pm 833 4.10.numpy_linear_algebra.py\r\n11/06/2020 03:04 pm 906 4.4.lxml.py\r\n08/07/2020 03:57 pm 1,311 4.6.configparser.py\r\n07/07/2020 09:13 pm 682 4.8.Threading.py\r\n11/06/2020 03:04 pm 252 4.9.temperature.csv\r\n


# Example 3
# data_read.py file is available in repository. Make sure it's available in current working directory
import subprocess
# it will read data and store in theproc variable
theproc = subprocess.check_output("python chapter_12th_data_read.py", shell = True)
print(theproc) # to see the output of theproc
"""Examples demonstrating :mod:`subprocess` usage."""

import subprocess


def example_call() -> None:
"""Run a simple command using :func:`subprocess.call`."""
subprocess.call(["echo", "hello"])


def example_check_output() -> None:
"""Capture the output of a command."""
output = subprocess.check_output(["echo", "hello"])
print(output.decode().strip())


def example_run_other_script() -> None:
"""Run ``Chapter_12th_data_read.py`` and print its output."""
output = subprocess.check_output(["python", "Chapter_12th_data_read.py"])
print(output.decode())


if __name__ == "__main__":
example_call()
example_check_output()
# Uncomment the line below if you want to run the data read example
# example_run_other_script()
83 changes: 35 additions & 48 deletions Chapter_17th_unittest.py
Original file line number Diff line number Diff line change
@@ -1,48 +1,35 @@

# Example 1
import unittest

def join_names(first, last):
return ' '.join([first.capitalize(), last.capitalize()])

return_data = join_names('ahmed', 'hadi')
print(return_data)

class TestStringMethods(unittest.TestCase): #class is inherited from unittest .testcases
def test_is_capitalized(self):
temp1, temp2 = return_data.split(' ')
self.assertTrue(temp1.istitle()) # moves to the next line if true
self.assertTrue(temp2.istitle()) # moves to the next line if true
def test_length(self):
self.assertTrue(len(return_data.split(' ')), 2)
def test_split(self):
self.assertEqual(type(return_data), str) # moves to the next line if both are of str type
# End of TestStringMethods class

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


# Output
# Ahmed Hadi
# ----------------------------------------------------------------------
# Ran 3 tests in 0.008s
# OK

# Example 2
return_data = 'Ahmed hadi' # 'Shabir ahmed'
if __name__ == '__main__':
unittest.main()

# Output
# F..ahmed hadi
# ======================================================================
# FAIL: test_is_capitalized (__main__.TestStringMethods)
# ----------------------------------------------------------------------
# Traceback (most recent call last):
# File "E:\task\Python task\Python\Python\untitled5.py", line 9, in test_is_capitalized
# self.assertTrue(temp1.istitle())
# AssertionError: False is not true
# ----------------------------------------------------------------------
# Ran 3 tests in 0.076s
# FAILED (failures=1)
"""Demonstration of :mod:`unittest` usage.

The previous revision contained truncated code and a minor bug in one of the
assertions. This version provides a minimal, functional example.
"""

import unittest


def join_names(first: str, last: str) -> str:
"""Return the capitalised full name."""
return " ".join([first.capitalize(), last.capitalize()])


return_data = join_names("ahmed", "hadi")
print(return_data)


class TestStringMethods(unittest.TestCase):
"""Unit tests for :func:`join_names`."""

def test_is_capitalized(self) -> None:
temp1, temp2 = return_data.split(" ")
self.assertTrue(temp1.istitle())
self.assertTrue(temp2.istitle())

def test_length(self) -> None:
self.assertEqual(len(return_data.split(" ")), 2)

def test_split(self) -> None:
self.assertIsInstance(return_data, str)


if __name__ == "__main__":
unittest.main()
0