How to mock at the descriptor level?How to merge two dictionaries in a single expression?How do I check if a list is empty?How do I check whether a file exists without exceptions?How can I safely create a nested directory?How do I sort a dictionary by value?How to make a chain of function decorators?How to make a flat list out of list of listsHow to make mock to void methods with MockitoHow do I list all files of a directory?What's the difference between a mock & stub?

How is water heavier than petrol, even though its molecular weight is less than petrol?

What's up with this leaf?

1980s live-action movie where individually-coloured nations on clouds fight

Compiling c files on ubuntu and using the executable on Windows

Recommended tools for graphs and charts

How to construct an hbox with negative height?

Passing multiple files through stdin (over ssh)

Soft question: Examples where lack of mathematical rigour cause security breaches?

Frame failure sudden death?

Watts vs. volts amperes

Is using haveibeenpwned to validate password strength rational?

Arriving at the same result with the opposite hypotheses

Can I make plugins required?

Taxi Services at Didcot

Why would future John risk sending back a T-800 to save his younger self?

Overlapping String-Blocks

What is the actual quality of machine translations?

How to handle self harm scars on the arm in work environment?

A planet of ice and fire

When 2-pentene reacts with HBr, what will be the major product?

C++ Arduino IDE receiving garbled `char` from function

At what point in time did Dumbledore ask Snape for this favor?

Mobile App Appraisal

Confusion about off peak timings of London trains



How to mock at the descriptor level?


How to merge two dictionaries in a single expression?How do I check if a list is empty?How do I check whether a file exists without exceptions?How can I safely create a nested directory?How do I sort a dictionary by value?How to make a chain of function decorators?How to make a flat list out of list of listsHow to make mock to void methods with MockitoHow do I list all files of a directory?What's the difference between a mock & stub?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















It appears uuid4 is not mocked within the Field descriptor's initializer, but it is within Foo.get_uid. Why is this?



# file.py

from uuid import uuid4


class Field:

def __init__(self, default):
print(uuid4)
self.default = default()

def __get__(self, instance, owner):
return self.default


class Foo:
uid = Field(uuid4)

def get_uid(self):
print(uuid4)
return self.uid


# test_file.py

import unittest
from unittest.mock import patch

from file import Foo


@patch("file.uuid4")
class TestFoo(unittest.TestCase):
def test_get_uid(self, patched_uuid4):
self.assertEqual(Foo().get_uid(), patched_uuid4())


if __name__ == "__main__":
unittest.main()


Running python test_file.py results in:



<function uuid4 at 0x110923598>
<MagicMock name='uuid4' id='4570221984'>
F
======================================================================
FAIL: test_get_uid (__main__.TestFoo)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/peteralisandratos/.pyenv/versions/3.6.6/lib/python3.6/unittest/mock.py", line 1179, in patched
return func(*args, **keywargs)
File "test_file.py", line 10, in test_get_uid
self.assertEqual(Foo().get_uid(), patched_uuid4())
AssertionError: UUID('a8273b4a-5d93-44d1-9041-54476e15fdf7') != <MagicMock name='uuid4()' id='4572959912'>


How can I get Field to respect the patch?










share|improve this question






















  • The class definition, including the uid attribute is run on import. The patch is applied later and has no effect anymore. Use an instance attribute or patch Foo.uid.

    – Klaus D.
    Mar 24 at 17:43

















0















It appears uuid4 is not mocked within the Field descriptor's initializer, but it is within Foo.get_uid. Why is this?



# file.py

from uuid import uuid4


class Field:

def __init__(self, default):
print(uuid4)
self.default = default()

def __get__(self, instance, owner):
return self.default


class Foo:
uid = Field(uuid4)

def get_uid(self):
print(uuid4)
return self.uid


# test_file.py

import unittest
from unittest.mock import patch

from file import Foo


@patch("file.uuid4")
class TestFoo(unittest.TestCase):
def test_get_uid(self, patched_uuid4):
self.assertEqual(Foo().get_uid(), patched_uuid4())


if __name__ == "__main__":
unittest.main()


Running python test_file.py results in:



<function uuid4 at 0x110923598>
<MagicMock name='uuid4' id='4570221984'>
F
======================================================================
FAIL: test_get_uid (__main__.TestFoo)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/peteralisandratos/.pyenv/versions/3.6.6/lib/python3.6/unittest/mock.py", line 1179, in patched
return func(*args, **keywargs)
File "test_file.py", line 10, in test_get_uid
self.assertEqual(Foo().get_uid(), patched_uuid4())
AssertionError: UUID('a8273b4a-5d93-44d1-9041-54476e15fdf7') != <MagicMock name='uuid4()' id='4572959912'>


How can I get Field to respect the patch?










share|improve this question






















  • The class definition, including the uid attribute is run on import. The patch is applied later and has no effect anymore. Use an instance attribute or patch Foo.uid.

    – Klaus D.
    Mar 24 at 17:43













0












0








0








It appears uuid4 is not mocked within the Field descriptor's initializer, but it is within Foo.get_uid. Why is this?



# file.py

from uuid import uuid4


class Field:

def __init__(self, default):
print(uuid4)
self.default = default()

def __get__(self, instance, owner):
return self.default


class Foo:
uid = Field(uuid4)

def get_uid(self):
print(uuid4)
return self.uid


# test_file.py

import unittest
from unittest.mock import patch

from file import Foo


@patch("file.uuid4")
class TestFoo(unittest.TestCase):
def test_get_uid(self, patched_uuid4):
self.assertEqual(Foo().get_uid(), patched_uuid4())


if __name__ == "__main__":
unittest.main()


Running python test_file.py results in:



<function uuid4 at 0x110923598>
<MagicMock name='uuid4' id='4570221984'>
F
======================================================================
FAIL: test_get_uid (__main__.TestFoo)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/peteralisandratos/.pyenv/versions/3.6.6/lib/python3.6/unittest/mock.py", line 1179, in patched
return func(*args, **keywargs)
File "test_file.py", line 10, in test_get_uid
self.assertEqual(Foo().get_uid(), patched_uuid4())
AssertionError: UUID('a8273b4a-5d93-44d1-9041-54476e15fdf7') != <MagicMock name='uuid4()' id='4572959912'>


How can I get Field to respect the patch?










share|improve this question














It appears uuid4 is not mocked within the Field descriptor's initializer, but it is within Foo.get_uid. Why is this?



# file.py

from uuid import uuid4


class Field:

def __init__(self, default):
print(uuid4)
self.default = default()

def __get__(self, instance, owner):
return self.default


class Foo:
uid = Field(uuid4)

def get_uid(self):
print(uuid4)
return self.uid


# test_file.py

import unittest
from unittest.mock import patch

from file import Foo


@patch("file.uuid4")
class TestFoo(unittest.TestCase):
def test_get_uid(self, patched_uuid4):
self.assertEqual(Foo().get_uid(), patched_uuid4())


if __name__ == "__main__":
unittest.main()


Running python test_file.py results in:



<function uuid4 at 0x110923598>
<MagicMock name='uuid4' id='4570221984'>
F
======================================================================
FAIL: test_get_uid (__main__.TestFoo)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/peteralisandratos/.pyenv/versions/3.6.6/lib/python3.6/unittest/mock.py", line 1179, in patched
return func(*args, **keywargs)
File "test_file.py", line 10, in test_get_uid
self.assertEqual(Foo().get_uid(), patched_uuid4())
AssertionError: UUID('a8273b4a-5d93-44d1-9041-54476e15fdf7') != <MagicMock name='uuid4()' id='4572959912'>


How can I get Field to respect the patch?







python mocking python-unittest






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 24 at 17:04









PalisandPalisand

6831626




6831626












  • The class definition, including the uid attribute is run on import. The patch is applied later and has no effect anymore. Use an instance attribute or patch Foo.uid.

    – Klaus D.
    Mar 24 at 17:43

















  • The class definition, including the uid attribute is run on import. The patch is applied later and has no effect anymore. Use an instance attribute or patch Foo.uid.

    – Klaus D.
    Mar 24 at 17:43
















The class definition, including the uid attribute is run on import. The patch is applied later and has no effect anymore. Use an instance attribute or patch Foo.uid.

– Klaus D.
Mar 24 at 17:43





The class definition, including the uid attribute is run on import. The patch is applied later and has no effect anymore. Use an instance attribute or patch Foo.uid.

– Klaus D.
Mar 24 at 17:43












0






active

oldest

votes












Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55326299%2fhow-to-mock-at-the-descriptor-level%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55326299%2fhow-to-mock-at-the-descriptor-level%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해