Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Getting Started With Nose Testing in Python
Next article icon

Python | Testing Output to stdout

Last Updated : 12 Jun, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report
Testing is a critical part of development as there is no compiler to analyze the code before Python executes it. Given a program that has a method whose output goes to standard Output (sys.stdout). This almost always means that it emits text to the screen. One likes to write a test for the code to prove that, given the proper input, the proper output is displayed. Using the unittest.mock module’s patch() function, it’s pretty simple to mock out sys.stdout for just a single test, and put it back again, without messy temporary variables or leaking mocked-out state between test cases. Code #1 : Example Python3 1==
def urlprint(protocol, host, domain):     url = '{}://{}.{}'.format(protocol, host, domain)     print(url) 
The built-in print function, by default, sends output to sys.stdout. In order to test that output is actually getting there, it is to be mocked out using a stand-in object, and then make assertions about what happened. Using the unittest.mock module’s patch() method makes it convenient to replace objects only within the context of a running test, returning things to their original state immediately after the test is complete.   Code #2 : Test code for the above code Python3 1==
from io import StringIO from unittest import TestCase from unittest.mock import patch import mymodule  class TestURLPrint(TestCase):          def test_url_gets_to_stdout(self):         protocol = 'http'         host = 'www'         domain = 'example.com'         expected_url = '{}://{}.{}\n'.format(protocol, host, domain)                  with patch('sys.stdout', new = StringIO()) as fake_out:             mymodule.urlprint(protocol, host, domain)             self.assertEqual(fake_out.getvalue(), expected_url) 
 
  • The urlprint() function takes three arguments, and the test starts by setting up dummy arguments for each one. The expected_url variable is set to a string containing the expected output.
  • To run the test, the unittest.mock.patch() function is used as a context manager to replace the value of sys.stdout with a StringIO object as a substitute.
  • The fake_out variable is the mock object that’s created in this process. This can be used inside the body of the with statement to perform various checks. When the with statement completes, patch conveniently puts everything back the way it was before the test ever ran.
  • It’s worth noting that certain C extensions to Python may write directly to standard output, bypassing the setting of sys.stdout.

Next Article
Getting Started With Nose Testing in Python

M

manikachandna97
Improve
Article Tags :
  • Python
  • Python Testing
Practice Tags :
  • python

Similar Reads

  • Python | Logging Test Output to a File
    Problem - Writing the results of running unit tests to a file instead of printed to standard output. A very common technique for running unit tests is to include a small code fragment (as shown in the code given below) at the bottom of your testing file. Code #1 : import unittest class MyTest(unitte
    2 min read
  • sys.stdout.write in Python
    sys.stdout.write() is a built-in Python method that writes output directly to the console without automatically adding a newline (\n). It is part of the sys module and requires import sys before use. Unlike print(), it does not insert spaces between multiple arguments, allowing precise control over
    3 min read
  • Python - sys.stdout.flush()
    A data buffer is a region of physical memory storage used to temporarily store data while it is being moved from one place to another. The data is stored in a buffer as it is retrieved from an input device or just before it is sent to an output device or when moving data between processes within a c
    3 min read
  • Getting Started With Unit Testing in Python
    In Python, unit tests are the segments of codes that are written to test other modules and files that we refer to as a unit. Python Unit Testing is a very important part of the software development process that helps us to ensure that the code works properly without any errors. In this article, we w
    8 min read
  • Getting Started With Nose Testing in Python
    Testing is essential for software development, ensuring that programs work reliably. Python offers various testing frameworks, but Nose stands out for being simple, flexible, and easy to extend. This article will explore Nose testing, covering its fundamentals, fixtures, and advanced features. Table
    4 min read
  • Python Testing
    Python testing is a fundamental aspect of software development that plays a crucial role in ensuring the reliability, correctness, and maintainability of your code. By adopting effective testing strategies, leveraging robust testing frameworks, and adhering to best practices, you can build high-qual
    15 min read
  • Python Falcon - Testing
    Testing is an integral part of software development, ensuring the reliability and functionality of applications. Python Falcon is a lightweight web framework for building APIs rapidly. In this article, we will explore how to test Python Falcon APIs using two popular testing frameworks: unittest and
    4 min read
  • Take input from stdin in Python
    In this article, we will read How to take input from stdin in Python. There are a number of ways in which we can take input from stdin in Python. sys.stdininput()fileinput.input()Read Input From stdin in Python using sys.stdin First we need to import sys module. sys.stdin can be used to get input fr
    2 min read
  • Python Pyramid - Testing
    In the realm of web development, Python Pyramid stands out as a robust framework known for its flexibility and scalability. Testing is an integral part of any software development process, ensuring the reliability and stability of applications. In this article, we delve into the world of testing wit
    3 min read
  • How to print to stderr and stdout in Python?
    In Python, whenever we use print() the text is written to Python’s sys.stdout, whenever input() is used, it comes from sys.stdin, and whenever exceptions occur it is written to sys.stderr.  We can redirect the output of our code to a file other than stdout. But you may be wondering why one should do
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences