mocking

Mocking gRPC status code ('RpcError' object has no attribute 'code') in Flask App

北慕城南 提交于 2021-01-29 14:51:50
问题 I have to create a unittest that should mock a specific grpc status code (in my case I need NOT_FOUND status). This is what i want to mock: try: # my mocked function except grpc.RpcError as e: if e.code() == grpc.StatusCode.NOT_FOUND: # do something My unittest until now looks like this: def mock_function_which_raise_RpcError(): e = grpc.RpcError(grpc.StatusCode.NOT_FOUND) raise e class MyTestCase(BaseViewTestCase): @property def base_url(self): return '/myurl' @mock.patch('my_func', mock

RestTemplate Mock throws NullPointerException

夙愿已清 提交于 2021-01-29 08:20:35
问题 I have a rest template that makes a call in a method in a service class like so: public CustomerResponse someMethod() { CustomerResponse response = restTemplate.exchange(url, HttpMethod.GET, null, CustomerRes.class).getBody(); return response; } When trying to mock the restTemplate in my test class, it keeps throwing a NullPointerException on the line where the mock restTemplate is called: public void checkResponseIsNotNull() { CustomerResponse customerResponseMock = mock(CustomerResponse

mock.patch and multiprocessing

Deadly 提交于 2021-01-29 08:20:22
问题 I'm struggling to use mock.patch in a multiprocessing environment while without multiprocessing mock.patch works fine. Filename: test_mp.py import multiprocessing import mock def inner(): return sub() def sub(): return "abc" def test_local(): assert inner()=="abc" def test_mp(): with multiprocessing.Pool() as pool: assert pool.apply(inner,args=[])=='abc' def test_mock(): with mock.patch('test_mp.sub', return_value='xxx') as xx: assert inner()=="xxx" xx.assert_called_once() def test_mp_mock():

I am mocking two functions exactly the same way. In one case the mock value is returned and in another case the real function is called. Why?

醉酒当歌 提交于 2021-01-29 08:14:15
问题 I have a file that exports some functions: function getNow() { console.log('real now'); return dayjs(); } function groupProducts(productInfos, now) { console.log('real group'); return productInfos.reduce((groups, productInfo) => { const groupKey = dayjs(productInfo.saleStartDate) > now ? dayjs(productInfo.saleStartDate).format('YYYY-MM-DD') : dayjs(now).format('YYYY-MM-DD'); let group = groups[groupKey]; if (!group) { group = []; // eslint-disable-next-line no-param-reassign groups[groupKey]

Did I properly mock the API Call?

半腔热情 提交于 2021-01-29 08:08:10
问题 I'm not sure if I got it right so please - feel free to provide any kind of explanation. I'm trying to write a test for the function responsible for calling the API. I know that the good practice is to mock the API function instead of calling the real API. I've done it and my test is passing but can I be really sure that I'm not calling the real API? How do I check that ? domain.js export const getCountriesData = () => { return fetch("https://restcountries.eu/rest/v2/all").then((response) =>

JUnit: mock a method called inside another method

馋奶兔 提交于 2021-01-29 07:11:54
问题 Consider I have a class Tournament with methods register() and isAlreadyRegistered() . Below is the sample code. public class Tournament { private boolean register(String teamName) { if(!isAlreadyRegistered(teamName)) { // register team return True; } return False; } private boolean isAlreadyRegistered(String teamName) { // Check if team is already registered, involves DB calls } public static void main(String[] args) throws Exception { Tournament tournament = new Tournament(); tournament

RSpec double/mock print method from call

谁说我不能喝 提交于 2021-01-29 06:43:38
问题 My method prints in the console a list of viewed TV Shows. I want to test call method which trigger private print_result method: def initialize(parser) @parser = parser @views_hash = parser.page_views end def call puts "\n" puts 'LIST OF MOST POPULAR TV SHOWS' print_results(sort_all) puts "\n\n" end private def print_results(sorted_hash) puts "\n" puts "#{'TV Show'.center(20)} | VIEWS" puts '---------------------+----------' sorted_hash.each do |page, views_no| puts "#{page.ljust(20)} | #

How to mock google cloud storage bucket and link it to client object?

大兔子大兔子 提交于 2021-01-29 06:27:40
问题 I have a function in cloud run and trying to test using mock in Python. How can I mock bucket with a blob and attach it to storage client? Assert fails and it's displaying output in this format Display File content: <MagicMock name='mock.get_bucket().get_blob().download_as_string().decode()' id='140590658508168'> # test def test_read_sql(self): storage_client = mock.create_autospec(storage.Client) mock_bucket = storage_client.get_bucket('test-bucket') mock_blob = mock_bucket.blob('blob1')

How to mock a member variable of dependency?

て烟熏妆下的殇ゞ 提交于 2021-01-28 14:34:43
问题 I've got a class and member: class A { B obj; public: int f(int i){return obj.g(i);} } Here "B obj" is a dependency that requires run-time creation from a file. In my unit test for class A, I wish to mock "B obj", with a function g typed int(int). How can I write my test code, to mock "B obj", and then test A::f. Thanks a lot. 回答1: You need to use dependency injection to achieve this. To this end, have class B inherit from an interface, and have class A hold a pointer to that interface: class

Using mock to test if directory exists or not

坚强是说给别人听的谎言 提交于 2021-01-28 07:44:48
问题 I have been exploring mock and pytest for a few days now. I have the following method: def func(): if not os.path.isdir('/tmp/folder'): os.makedirs('/tmp/folder') In order to unit test it, I have decided to patch os.path.isdir and os.makedirs, as shown: @patch('os.path.isdir') @patch('os.makedirs') def test_func(patch_makedirs, patch_isdir): patch_isdir.return_value = False assert patch_makedirs.called == True The assertion fails, irrespective of the return value from patch_isdir. Can someone