def test_get_bundle(): """ Ensure the expected calls are made to get the referenced bundle and the result is unzipped to the expected location. """ # All these mocks stop IO side effects and allow us to spy on the code to # ensure the expected calls are made with the correct values. Warning! Here # Be Dragons! (If in doubt, ask ntoll for details). mock_progress = mock.MagicMock() mock_progress().__enter__ = mock.MagicMock(return_value=["a", "b", "c"]) mock_progress().__exit__ = mock.MagicMock() with mock.patch("circup.requests") as mock_requests, mock.patch( "circup.click") as mock_click, mock.patch( "circup.open", mock.mock_open()) as mock_open, mock.patch( "circup.os.path.isdir", return_value=True), mock.patch( "circup.shutil") as mock_shutil, mock.patch( "circup.zipfile") as mock_zipfile: mock_click.progressbar = mock_progress mock_requests.get().status_code = mock_requests.codes.ok mock_requests.get.reset_mock() tag = "12345" circup.get_bundle(tag) assert mock_requests.get.call_count == 3 assert mock_open.call_count == 3 assert mock_shutil.rmtree.call_count == 3 assert mock_zipfile.ZipFile.call_count == 3 assert mock_zipfile.ZipFile().__enter__().extractall.call_count == 3
def test_get_bundle_network_error(): """ Ensure that if there is a network related error when grabbing the bundle then the error is logged and re-raised for the HTTP status code. """ with mock.patch("circup.requests") as mock_requests, mock.patch( "circup.tags_data_load", return_value=dict() ), mock.patch("circup.logger") as mock_logger: # Force failure with != requests.codes.ok mock_requests.get().status_code = mock_requests.codes.BANG # Ensure raise_for_status actually raises an exception. mock_requests.get().raise_for_status.return_value = Exception("Bang!") mock_requests.get.reset_mock() tag = "12345" with pytest.raises(Exception) as ex: bundle = circup.Bundle(TEST_BUNDLE_NAME) circup.get_bundle(bundle, tag) assert ex.value.args[0] == "Bang!" url = ( "https://github.com/" + TEST_BUNDLE_NAME + "/releases/download" "/{tag}/adafruit-circuitpython-bundle-py-{tag}.zip".format(tag=tag) ) mock_requests.get.assert_called_once_with(url, stream=True) assert mock_logger.warning.call_count == 1 mock_requests.get().raise_for_status.assert_called_once_with()