1

I am basically using magic mock and context manager to test my code, I was successfully able to mock my get_urls function, But I am having trouble mocking out my access_all_repos_pr(): function which contains data of PR newer than 7 days, can anyone help me out on how to mock that data.

Here is the test code for my get_urls():

import unittest
from mock import MagicMock, patch
from contextlib2 import ExitStack
from GithubAPIpackage.GithubAPI import get_urls


class Test_GithubApi(unittest.TestCase):
    def test_get_urls_returns_valid_urls(self):
        with ExitStack() as stack:

            mock_get_urls = stack.enter_context(
                patch("GithubAPIpackage.GithubAPI._fetch_url")
            )
            fake_data = {"current_user_repositories_url": "http://FAKEURL.com"}
            mock_get_urls.return_value = fake_data
            print(type(fake_data))

            result = get_urls()
            self.assertEqual(result, "http://FAKEURL.com")

I want to mock out the response for the function access_all_repo_pr, can anyone help me out in what I need to do exactly to create a mock for my access_all_repo_pr function. Do I need to refactor my code in some way? (relatively new to python)

what I am trying is:

class Test_GithubApi_newer_than_7_days(unittest.TestCase):
    def test_access_all_repo_pr_returns_valid_response(self):
        with ExitStack() as stack:

            mock_access_all_repo_pr = stack.enter_context(
                patch("GithubAPIpackage.GithubAPI._fetch_url")
            )
            fake_data = {"current_user_repositories_url": "http://myfakeurl.com"}
            mock_access_all_repo_pr.return_value = fake_data


            result = access_all_repo_pr()

            self.assertEqual(result, "")
1
  • did you resolve this issue? I want to test my pygithub based AWS lambda function as well. i was wondering what library to use for mocking Github API for python. where did you learn about magicmock? did it work well? Commented Aug 16, 2020 at 19:15

1 Answer 1

1

Since you are using requests under the hood, may I suggest using responses for your testing? Not trying to skirt the question, but in my experience, I have found this to be the path of least resistance when it comes to writing tests that deal with the requests module. The tests end up being a lot cleaner, safer, and easier to write.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.