Header Graphic

Page 0

cURL in Python

As a QA professional, I've encountered various tools and methodologies that enhance testing processes. Among these, Unix cURL stands out for its utility in handling network requests. In this blog, I'll delve into how we can leverage cURL within Python to streamline our testing and automation tasks.

What is cURL?

cURL, short for 'Client for URLs', is a command-line tool used to transfer data to or from a server. It supports a variety of protocols, including HTTP, HTTPS, FTP, and more. While cURL is inherently a Unix-based tool, its functionality is crucial for testing APIs, web applications, and automating network requests.

Why Use cURL in Python?

Python's extensive libraries like requests are commonly used for handling HTTP requests. However, cURL offers a different approach with its command-line driven method, which is sometimes more flexible and powerful, especially when dealing with complex scenarios or when reproducing requests copied from browsers' developer tools.

Integrating cURL with Python

There are several ways to integrate cURL commands into Python, with the most common method being the use of subprocess module. Here's a basic example:

import subprocess

def curl_command(url):
    command = f"curl {url}"
    process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
    output, error = process.communicate()
    if error:
        print(f"Error: {error}")
        return output.decode('utf-8')

# Example Usage
response = curl_command("https://api.example.com/data")

This script uses subprocess.Popen to execute a cURL command and fetch data from a given URL. It's a straightforward way to integrate cURL's capabilities into a Python script.

Handling Complex cURL Commands

For more complex scenarios, like sending data, handling headers, or dealing with authentication, the cURL command string can be modified accordingly. For instance:

def complex_curl_command(url, data, headers):
    command = f"curl -X POST -d '{data}' -H '{headers}' {url}"
    # Rest of the code remains similar

Advantages and Limitations

Advantages: 1. Direct Transfer from Browsers: cURL commands can often be copied as-is from browsers' developer tools, which is handy for reproducing and automating specific requests. 2. Support for Multiple Protocols: cURL's versatility across different protocols makes it a powerful tool in a QA's arsenal.

Limitations: 1. Security Concerns: Running shell commands from within Python can pose security risks, especially when dealing with untrusted input. 2. Complexity: For simple HTTP requests, using Python libraries like requests is more straightforward and Pythonic.


Integrating Unix cURL with Python scripts provides a robust method for handling complex network requests. It's particularly useful for QA professionals looking to automate and test applications with specific network interactions. However, it's essential to weigh its benefits against potential security risks and complexity.

For those interested in exploring further, I recommend experimenting with different cURL options and understanding how they translate into the Python context. Happy testing!

Giving Thanks to Python

Python Thanksgiving

As a Quality Assurance (QA) professional with five years of hands-on experience in automation programming, I've developed a deep appreciation for the tools and languages that make my work both possible and enjoyable. With Thanksgiving around the corner, it feels like the perfect time to reflect on what makes Python such an invaluable asset in our field. Let's delve into the reasons why we, as QA professionals, are especially thankful for Python.

Simplifying Complexity: Python's Readability

One of the most immediate aspects of Python that we're thankful for is its readability. Python's syntax is clear, concise, and almost English-like, making it an excellent language for beginners and experts alike. This readability not only makes writing code more straightforward but also simplifies the process of reviewing and maintaining code over time - a crucial factor in QA where clarity is king.

Wide-Ranging Libraries and Frameworks

Python's extensive libraries and frameworks are a boon for QA automation. Selenium for web automation, PyTest for writing test scripts, and Behave for behavior-driven development, to name just a few, are all powerful tools that help streamline our testing processes. These libraries save us from reinventing the wheel and allow us to focus on creating more sophisticated and effective test cases.

Cross-Platform Compatibility

Python's ability to run on various platforms ? Windows, macOS, Linux ? is a significant advantage. This compatibility ensures that our test scripts are versatile and adaptable, mirroring the diverse environments in which the software we test operates. For a QA professional, this universality is invaluable.

Strong Community and Support

The Python community is a vibrant and supportive ecosystem. From forums and discussion boards to conferences and meetups, the wealth of shared knowledge and resources is something to be truly thankful for. This community support makes problem-solving more collaborative and learning continuous.

Automation Made Easy

Python excels in automating repetitive tasks, a core part of QA work. With its simplicity and powerful scripting capabilities, Python makes it easier to automate test cases, data generation, and even setup and teardown processes in test environments. This efficiency is something every QA professional appreciates.

Integration Capabilities

Python's ability to integrate with other tools and technologies is another reason for gratitude. Whether it's integrating with CI/CD pipelines, cloud services, or other programming languages, Python's flexibility makes it a Swiss Army knife in the QA toolkit.

The Joy of Learning and Growing

Lastly, Python makes the journey of learning and professional growth enjoyable. Its welcoming community, vast resources, and the satisfaction of writing efficient code make Python not just a tool, but a path to continuous learning and improvement.


As we gather around the Thanksgiving table, it's worth reflecting on the tools and technologies that enrich our professional lives. Python, with its versatility, ease of use, and strong community support, is certainly high on the list for many QA professionals. It has not just made our jobs easier but also more enjoyable.

Call to Action

Are you a QA professional who uses Python? What aspects of Python are you most thankful for? Share your thoughts and experiences in the comments below!

Duck Typing using Python

Duck Python Code

As a QA professional with five years of experience in automation programming using Python, I've come to appreciate the language's flexibility and expressiveness. One of the concepts that stand out in Python is Duck Typing. It's not just a programming principle; it's a philosophy that Python embraces wholeheartedly. In this blog, I'll share some fun tricks and insights into Duck Typing, showing how it can make your Python code more flexible and intuitive.

What is Duck Typing?

Duck Typing is a concept derived from the saying, "If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck." In Python, this means that you don't check the type of an object; you check for the presence of a specific method or attribute.

Why is Duck Typing Fun?

  • Flexibility: Duck Typing allows for more generic and flexible code. You can write functions that accept any object, as long as it has the methods or attributes you need.
  • Simplicity: It simplifies the code. You don?t have to write complex type-checking code.
  • Surprise Factor: It's always fun to see an object work seamlessly in a place where you wouldn't traditionally expect it to.

Duck typing is a concept in Python that allows you to use objects without knowing their specific type. This can be helpful when you're working with objects from different libraries or third-party code. For example, you could use the len() function to get the length of a list, a string, or even a tuple:

print(len([1, 2, 3]))
print(len("Hello, world!"))
print(len((1, 2, 3)))

All of these statements will work because the len() function doesn't care about the specific type of object it's given. It only cares that the object has a __len__() method defined.

Getting the Current URL Using Python in MacOS

Welcome to my latest blog post! As a QA professional with five years of experience in automation programming using Python, I've often encountered scenarios where I needed to fetch the current URL from a browser - be it for testing, automation, or data extraction. Today, I'm going to walk you through a simple yet effective way to get the current URL from Chrome or Safari on MacOS using Python.

Why Fetch URLs Programmatically?

Fetching URLs programmatically can be useful in various scenarios, such as:

  • Automating tests that require validating the current page in a browser.
  • Monitoring web usage or collecting data for analysis.
  • Building extensions or integrations that react to URL changes.

Python Code Chrome


Before we dive in, ensure you have Python installed on your MacOS. You can check this by running python -version in your terminal. Additionally, install the required libraries using pip:

pip install pyobjc-framework-ScriptingBridge


python3 -m pip install pyobjc-framework-ScriptingBridge --user

This library allows Python to interact with MacOS applications via the ScriptingBridge framework.

Fetching URL from Chrome

Let's start with Google Chrome. Chrome, like many modern browsers, exposes its current state through AppleScript, which we can access in Python using the ScriptingBridge framework.

The Python Script

import ScriptingBridge
def get_chrome_url():
    chrome = ScriptingBridge.SBApplication.applicationWithBundleIdentifier_("com.google.Chrome")
    if not chrome.windows():
        return "No active window"
    window = chrome.windows()[0]  # Get the first window
    tab = window.activeTab()  # Get the active tab in the window
    return tab.URL()  # Return the URL of the active tab

This script initializes a connection to Chrome, checks if there are any open windows, and then fetches the URL of the active tab in the first window.

Chrome Example

Fetching URL from Safari

The process for Safari is quite similar. However, Safari's bundle identifier differs.

The Python Script for Safari

import ScriptingBridge
def get_safari_url():
    safari = ScriptingBridge.SBApplication.applicationWithBundleIdentifier_("com.apple.Safari")
    if not safari.windows():
        return "No active window"
    window = safari.windows()[0]
    return window.currentTab().URL()

Here, we connect to Safari and fetch the URL from the current tab of the first window.

Safari Python Example

Handling Multiple Windows or Tabs

If you need to handle multiple windows or tabs, you can loop through the windows array and fetch URLs from each tab. This can be particularly useful for comprehensive testing or data extraction tasks.

Security and Permissions

Since MacOS Mojave, apps need explicit permissions to control other apps. The first time you run these scripts, MacOS should prompt you to grant Terminal (or your Python IDE) access to control the browser. Make sure to allow this for the script to function correctly.


Fetching the current URL from browsers like Chrome and Safari is straightforward with Python and ScriptingBridge in MacOS. This technique opens up a range of possibilities for automation, testing, and data collection. Experiment with it, and you'll find it a valuable addition to your Python automation toolkit.

Ghost Writing in Python

Ghost Writing Python

As a QA Engineer, you're always looking for ways to improve your testing process. Python is a powerful language that can be used to automate many QA tasks, but it can also be used to generate text. This can be useful for creating test cases, writing reports, and even ghostwriting blog posts.

On this Halloween, let's take a look at how to use Python to do ghostwriting.

What is ghost writing?

Ghost writing is the practice of writing content for someone else, but not taking credit for it. This is often done for clients who need help writing blog posts, articles, or even books.

Why use Python for ghost writing?

There are a few reasons why Python is a good choice for ghost writing:

It's a powerful language that can be used to generate text in a variety of formats. It's relatively easy to learn, especially for QA Engineers who are already familiar with programming. There are a number of libraries and tools available that can make it easier to generate text with Python.

How to do ghost writing in Python

Here is a simple example of how to do ghost writing in Python:

import random
def generate_sentence():
  """Generates a random sentence."""
  words = ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."]
  sentence = ""
  for word in random.choices(words, k=10):
    sentence += word + " "
  return sentence
# Generate 10 random sentences
sentences = []
for i in range(10):
# Write the sentences to a file
with open("ghost_written_sentences.txt", "w") as f:
  for sentence in sentences:
    f.write(sentence + "n")

This code will generate 10 random sentences and write them to a file called ghost_written_sentences.txt.

Generating text with Python for QA purposes

Of course, you can use Python to generate more sophisticated text than just random sentences. For example, you could use it to generate test cases, write reports, or even ghostwrite blog posts.

Here are a few ideas:

  • Generate test cases: You could use Python to generate test cases for your QA testing. This could be especially useful for generating complex or data-driven test cases.
  • Write reports: You could use Python to generate reports from your QA testing results. This could save you time and help you to communicate your results more effectively.
  • Ghostwrite blog posts: If you're a QA Engineer with expertise in a particular area, you could use Python to ghostwrite blog posts for other people. This is a great way to share your knowledge and build your reputation.

Shuffle Text File

Halloween Python

Halloween is a time for tricks, treats, and... Python coding? That's right! Python is a powerful language that can be used for a variety of tasks, including automating QA tests and creating fun and spooky Halloween projects.

In this blog post, we'll show you how to use Python to convert a text file containing names to a dictionary and then randomly shuffle the dictionary. This could be useful for creating a Halloween game or activity, such as a costume contest or raffle.

Step 1: Create a text file containing names

The first step is to create a text file containing the names of the people who will be participating in your Halloween activity. You can do this by creating a new text file in a text editor such as BBEdit or Sublime Text.

Once you have created the text file, add the names of the participants to the file, one name per line. When you are finished, save the text file.

Step 2: Import the necessary Python libraries

To convert the text file to a dictionary and shuffle the dictionary, you will need to import the following Python libraries:

import random

import string

Step 3: Define a function to convert the text file to a dictionary

Next, you will need to define a function to convert the text file to a dictionary. This function will take the text file as input and return a dictionary containing the names of the participants as keys and a random string as values.

def convert_text_file_to_dictionary(text_file):
  """Converts a text file containing names to a dictionary.
    text_file: The path to the text file.
    A dictionary containing the names of the participants as keys and a random string as values.
  name_dict = {}
  with open(text_file, "r") as f:
    for line in f:
      name = line.strip()
      random_string = ''.join(random.choice(string.ascii_letters) for i in range(10))
      name_dict[name] = random_string
  return name_dict

Step 4: Define a function to shuffle the dictionary

Next, you will need to define a function to shuffle the dictionary. This function will take the dictionary as input and return a shuffled dictionary.

def shuffle_dictionary(dictionary):
  """Shuffles a dictionary.
    dictionary: The dictionary to shuffle.
    A shuffled dictionary.
  shuffled_dictionary = {}
  keys = list(dictionary.keys())
  for key in keys:
    shuffled_dictionary[key] = dictionary[key]
  return shuffled_dictionary

Step 5: Use the functions to convert the text file to a randomly shuffled dictionary

Now that you have defined the necessary functions, you can use them to convert the text file to a randomly shuffled dictionary.

To do this, you will first need to call the convert_text_file_to_dictionary() function to convert the text file to a dictionary. Then, you can call the shuffle_dictionary() function to shuffle the dictionary.

# Convert the text file to a dictionary.
name_dict = convert_text_file_to_dictionary("names.txt")
# Shuffle the dictionary.
shuffled_name_dict = shuffle_dictionary(name_dict)

Step 6: Use the shuffled dictionary in your Halloween project

Once you have the shuffled dictionary, you can use it in your Halloween project. For example, you could use it to create a costume contest or raffle.

To do this, you would simply iterate through the shuffled dictionary and display the names of the participants in a random order.

Commify in Python

Back when I was doing a lot of Perl programing, commify was the function that I used to add commas to numbers.

Here's a sample code:

# Comma Formating
# This area is where the FORMATING will be done to change the
# variable from ######.####### to #,###.##
sub commify {
    local($_) = shift;
    1 while s/^(-?d+)(d{3})/$1,$2/;
    return $_;

Python Style

In Python, you don't need a function to add commas to numbers.

#!/usr/bin/env /usr/bin/python3
# Using format() function
x = 124908120
# f-strings (Python 3.9 and later)
# With f-strings, you can directly include the :, 
# inside the curly braces to format the number with commas.

PyTest Example

Py Test Graphic

Over the past couple of years, I have been doing various automation programs. I have spent a lot of time using PyTest to test various websites and web objects.

If you are new to PyTest, here's a sample code that can help you get started. This piece of code will check to see if Google changed the text on the footer of the page.

The "/Library/Frameworks/Python.framework/Versions/3.9/bin/pytest" is the path to pytest, and makes this script easy to run from the command line.

#!/usr/bin/env /Library/Frameworks/Python.framework/Versions/3.9/bin/pytest
# Verify the Pytest was installed
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
def test_google():
	global chrome_driver
	chrome_driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))    
	title = "Google"
	assert title == chrome_driver.title
	pageSource = chrome_driver.page_source
	gateway = "Our third decade of climate action"
	if not gateway in pageSource:
		pytest.fail( "Google Changed their Webpage")

Install Modules

To get this to work, you need to install, PyTest, Selenium, and Webdriver. From the command line, run these commands:

pip3 install pytest
pip3 install selenium
pip3 install webdriver_manager

SQL Database Connector

It's really easy to query a database in Python. There's more than one way to do it, and there are plenty of third-party libraries that can offer better performance and cache capabilities.

Here's the basic to query a database:

hostname = 'localhost';
username = 'cryan';
password = 'Uniramous2';
database = 'webuser';
def doQuery( conn ) :
    cur = conn.cursor()
    content = ""
    cur.execute( "select date, title, comment from guestbook where topic = " + topic + "  order by title desc )
    records = cur.fetchall()
    for row in records:
        content = row[4]
    return content;    
myConnection = mysql.connector.connect( host=hostname, user=username, passwd=password, db=database )
content += doQuery( myConnection )

Technical Notes

You have to set the hostname, username, password, and database before calling the mysql.connector.connect function.

For security you should set up a READ-ONLY user for public database reads. This way if the code is ever displayed, someone can't just write a simple query to wipe out the database.

I use a Python function to handle the queries. Obviously, this isn't required, but it's a good habit to get into.

cur.execute handles all the database interactions.

Using cur.fetchall() returns an array of entries, you need to call the specific row entry, for example: row[3].

Simple Lottery Program

One of the books that got me into programming was "Perl by Example" by Ellie Quigley. I learned a lot about how to perform certain tasks using simple examples.

This week's post is highlighting an example of how I learned using the book. The following is an example of creating a "Lottery Picker" Python application. This is a pretty basic example of using various Python functionality to generate a random set of numbers.

Power Python

PowerBall Quick Pick

Players must select 5 numbers from 1 to 69. Then they must pick one additional number from a range of 1 to 26.

In this example, the program outputs 4 games. I use the sort list function to display the smaller numbers first.

import random
# Powerball Quick Pick
GameBalls = list(range(1,69))
PowerBall = list(range(1,26))
for x in range(4):
	mywin = GameBalls[0:5]
	print(f"Winning Numbers: {mywin} with a Powerball number {PowerBall[0]}")

Sample Output

Winning Numbers: [2, 11, 15, 27, 58] with a Powerball number 10
Winning Numbers: [9, 54, 58, 63, 67] with a Powerball number 3
Winning Numbers: [10, 16, 18, 47, 62] with a Powerball number 4
Winning Numbers: [3, 35, 38, 41, 56] with a Powerball number 3

Odds of Winning Powerball

The odds of winning the PowerBall is 11,688,053 to 1. You have a one in 91 chance of matching at least 1 number.

Things This Code Demonstrates

The above piece of code answers some common "how do I" questions:

  • How do I create a python list not starting from 0?
  • How doI shuffle a list in Python?
  • In Python, How do I create a new list from another list?
  • How do I sort a randomize python list?
  • After shuffling a list how do I sort it?

Future Site Content

I'll add a PowerBall number picker to the Random selection.