MongoMock Python function that inserts list of dictionaries and returns a response

99
April 07, 2022, at 07:30 AM

I am pretty new to mongomock and having some trouble with some examples of it on the internet. I am trying to mock a python function that gets passed the db_name and a list of dictionaries to be inserted into a collection. If the collection already exists, then drop it.

Am I mocking the initial database connection and subsequent python function to create a collection and insert data (I'm connecting to MongoDB Atlas)?

Is there a better way of doing this with something like pytest?

representatives_collection_service.py:

def get_database():
    """
    Get MongoDB database
    :return: client['Representatives']
    """
    CONNECTION_STRING = f"mongodb+srv://{os.getenv('MONGODB_USERNAME')}:{os.getenv('MONGODB_PASSWORD')}@{os.getenv('MONGODB_CLUSTER_NAME')}" \
                        f".ljllt.mongodb.net/myFirstDatabase?retryWrites=true&w=majority"
    client = MongoClient(CONNECTION_STRING)
    return client['Representatives']

def create_representative_collection(db_name, representatives):
    """
    Create representative collection
    If Representative Collection exists then drop it
    :param representatives:
    :param db_name:
    """
    try:
        if "representative_collection" in db_name.list_collection_names():
            db_name["representative_collection"].drop()
            print("Dropped Representatives collection!")
            representative_collection = db_name["representative_collection"]
            representative_collection.insert_many(representatives)
            print(f"Finished inserting {len(representatives)} Representatives!")
            response = "Success"
            return response
        else:
            representative_collection = db_name["representative_collection"]
            representative_collection.insert_many(representatives)
            print(f"Finished inserting {len(representatives)} Representatives!")
            response = "Success"
            return response
    except BulkWriteError:
        print("Error")
        response = "Failure"
        return response

test_representatives_collection_service.py:

def test_get_database() -> None:
    load_dotenv()
    response = get_database()
    assert response.name == 'Representatives'

@mongomock.patch(servers=((os.getenv('CONNECTION_STRING'), 27017),))
def test_create_representative_collection():
    representatives = [
        dict({'_id': 'C001127', 'First Name': 'Sheila', 'Last Name': 'Cherfilus-McCormick', 'Party': 'Democrat',
              'State': 'FL', 'District': 'FL20', 'Committee(s)': []}),
        dict({'_id': 'C001126', 'First Name': 'Mike', 'Last Name': 'Carey', 'Party': 'Republican', 'State': 'OH',
              'District': 'OH15', 'Committee(s)': []}),
        dict({'_id': 'E000071', 'First Name': 'Jake', 'Last Name': 'Ellzey', 'Party': 'Republican', 'State': 'TX',
              'District': 'TX06', 'Committee(s)': [{'Type': 'house', 'Rank': 18, 'Party': 'minority', 'Title': 'None',
                                                    'Name': 'House Committee on Science, Space, and Technology',
                                                    'Url': 'https://science.house.gov/', 'Thomas Id': 'HSSY',
                                                    'Jurisdiction': 'The Committee on Science, Space, and Technology has a jurisdiction over a range of matters related to energy research and development, federally owned or operated non-military energy laboratories, astronautical research and development, civil aviation, environmental research and development; marine research, and more. The Committee oversees the National Institute of Standards and Technology, National Aeronautics and Space Administration, National Science Foundation, and National Weather Service. It also reviews laws, programs, and Government activities relating to non-military research and development to report back to the House.'},
                                                   {'Type': 'house', 'Rank': 14, 'Party': 'minority', 'Title': 'None',
                                                    'Name': "House Committee on Veterans' Affairs",
                                                    'Url': 'https://veterans.house.gov/', 'Thomas Id': 'HSVR',
                                                    'Jurisdiction': "The House Committee on Veterans' Affairs is the authorizing committee for the Department of Veterans Affairs (VA). The committee is responsible for recommending legislation expanding, curtailing, or fine-tuning existing laws relating to veterans' benefits. The Committee also has oversight responsibility, which means monitoring and evaluating the operations of the VA. If the Committee finds that VA is not administering laws as Congress intended, then it is addressed through the hearing process and legislation."}]})
    ]
    collection = mongomock.MongoClient().db.collection
    db_name = collection.name()
    response = create_representative_collection(db_name, representatives)
    assert response == 'Success'
Rent Charter Buses Company
READ ALSO
Text Comparing Program

Text Comparing Program

I'm making a program where I am supposed to compare text files by returning a list of all the words that come up in the file, and the number of times they come upI have to disregard a list of words called stopwords so they won't be checked for the number...

113
Why won't my Django template display the correct date listed in the database?

Why won't my Django template display the correct date listed in the database?

My model contains a datefield, 'valid_until'Even though an entry contains the date '12/25/2022', the update template literally displays as its contents 'mm/dd/yyyy' when the user tries to modify the date

75
Best way to import custom packages [duplicate]

Best way to import custom packages [duplicate]

I use python for data analysisA lot of pandas

121
Sound notification in python when eberytime IF codition satisfies

Sound notification in python when eberytime IF codition satisfies

I want to play a sound every time an IF condition satisfies, I tried playsound module but it plays once & ask for unique alias device id but as per my IF condition, I should be get different answer every time whereas sound only plays once

116