Intro to Python Mocks | Python tutorial

  Рет қаралды 80,852

Red Eyed Coder Club

Red Eyed Coder Club

Күн бұрын

This video is an Intro to Python Mocks from unittest.mock library: what are Python mocks, why we have to use mocks, and when to do it.
How to write Python tests for functions that make a request to external API.
How to use the patch function to test Requests based functions with Python unittest.mock library.
It's a Python unittest mock tutorial for beginners.
Follow me @:
Telegram: t.me/red_eyed_coder_club
Twitter: / codereyed
Facebook: redeyedcoderclub
Timecodes:
00:00 - ideal testable function, and a unit test for it.
02:29 - example of a function with a dependency on another function.
06:02 - a test for the function with a dependency on another function. Problems that Mocks will solve.
07:48 - patch() function from unittest.mock
11:28 - an example of unit test of a function that makes a request to external API and returns a different result each time it's been called. A mock returns another mock. How to test requests.
Why Python mocks are important:
- Mocks eliminate dependency on network, database calls, calls to OS (it will speed testing)
- we get isolated unit tests,
- we can test methods that have no return value
- reduce test complexity. We don't have to write complex logic to handle behavior of methods under tests.
- don't have to wait to implement other methods.
When should you mock?
When you don't want to actually call an object
Intro to Python Mocks | Python tutorial
• Intro to Python Mocks ...
#python #testing #redeyedcoderclub

Пікірлер: 147
@bonnymunga2969
@bonnymunga2969 5 ай бұрын
You're a saviour man. I had issues with DI and mocks but this video has simplified everything for me. Great explanation!👏
@vikrantmahajan142
@vikrantmahajan142 Жыл бұрын
It's an amazing video! You have really broken the concepts into very easily understandable components. Loved your way of explanation! Thanks
@williamgillett1756
@williamgillett1756 Жыл бұрын
Excellent video - great examples - so simple, but complete, I agree with others that your commentary is incredible. You describe what is going on at every step - both in the code and in the underlying logic. Mocks can be confusing to me and you really help break down the concepts so thoroughly. This is my first experience watching videos by you. I will be back for more! PS - I usually use pytest, but it was helpful to see the more traditional unittest methodology applied to mocks. Translating your code to pytest was a good exercise for a newbie like me.
@TheSirgo23
@TheSirgo23 5 ай бұрын
This video is just awesome. I was stuck reading docs and couldn't apply it in my test cases. Thanks a lot for this great explanation.
@uchesamuelottah559
@uchesamuelottah559 8 ай бұрын
This is the best explanation ive ever seen in my life+!! You're aweskme
@rugmaable
@rugmaable 5 ай бұрын
Thanks for the explanation. The mock is very powerful. I feel conformable starting to use it now
@AVISH747
@AVISH747 3 ай бұрын
Excellent. I was breaking my head on mock and patch.. now its crystal clear.
@vibhourjain
@vibhourjain 6 ай бұрын
this is great video, with this one video i wrote my 1st unit test case of my project. Thanks
@aashrayzaveri9510
@aashrayzaveri9510 17 күн бұрын
Great explanation. Was struggling with the concept. Now I am confident with the topic
@bikkinarohith1006
@bikkinarohith1006 Жыл бұрын
One of the best vedioes on Python Mocks👏👏👏
@brajesh42
@brajesh42 Жыл бұрын
Amazing video. Simplified demo on how to write UT with mocks. Thanks
@bactran7799
@bactran7799 3 ай бұрын
amazing, I can understand mock and patch now. Thank you so much
@durgeshkshirsagar5160
@durgeshkshirsagar5160 Жыл бұрын
Great tutorial. Thank you for sharing the knowledge.
@JonhMalcovich
@JonhMalcovich Жыл бұрын
Exelent !!! Thanks for sharing this!
@PlanetLogical
@PlanetLogical 7 ай бұрын
Great video. The explanations are extremely clear and easy to follow.
@nishugurung2339
@nishugurung2339 Жыл бұрын
This has been an awesome video. Thanks a bunch!
@user-fj7cg1qn2r
@user-fj7cg1qn2r 11 ай бұрын
Great explanation and easy to understand, thanks!
@Spayke201
@Spayke201 Жыл бұрын
Amazing video! Congrats and thanks a lot!! So helpful!
@emma_promise_smartnbc4331
@emma_promise_smartnbc4331 3 ай бұрын
Thanks. Was finding it difficult understanding, U made it clear
@stelecoms00
@stelecoms00 11 ай бұрын
OMG - you have made it so easy !! Thank you so much ❤
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
What video should I make next? Any suggestions? Write me in comments! Follow me @: Telegram: t.me/red_eyed_coder_club Twitter: twitter.com/CoderEyed Facebook: fb.me/redeyedcoderclub
@goodevening2144
@goodevening2144 Жыл бұрын
github?
@user-ep1rd5pw1w
@user-ep1rd5pw1w 2 жыл бұрын
Thank you for a detailed and informative video tutorial. I look forward to new lessons from you.
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thank you!
@user-fw4od8cg5s
@user-fw4od8cg5s 2 жыл бұрын
I get a lot of knowledge by watching your video lessons. Thank you very much!
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thank you
@philveo
@philveo Жыл бұрын
hi, i have seen many and many tutos python mocks, but this one is simple, clear and understable. 👍 and many thanks !
@RedEyedCoderClub
@RedEyedCoderClub Жыл бұрын
Thank you very much!
@roberto_camp
@roberto_camp 2 жыл бұрын
Fantastic tutorial. Took me from almost no knowlege of python unittest and mocks to very confident. Thank you!
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thank you very much!
@shiblyaziz4528
@shiblyaziz4528 Жыл бұрын
Your work is excellent, thank you!
@sandeepamarnath2272
@sandeepamarnath2272 Жыл бұрын
Very well explained!! Thank you!
@user-xc7ow8rf9w
@user-xc7ow8rf9w Жыл бұрын
Excellent tutorial. Thanks!
@sergeyshevtsov5125
@sergeyshevtsov5125 2 жыл бұрын
That's just what i needed right now. Oleg, thank you! Been watching your channel since 2017, some time supported on patreon, your content never disappoints. You make very clear and understandable explanation on every important nuance, incrementally from easy to advanced stuff. Sometimes I miss, when there are no new videos for a long time :) Big thank you anyway. I personally think that you made a huge, or even biggest contribution(not size, but in terms of quality, for sure) into instructional videos for Russian self-taught python developers, and now for International community. Time ago your videos helped me to learn a lot of things, to get a first paid developer job and etc. Legend!
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thank you very much for your kind words :) Glad that you like my stuff.
@meriem623
@meriem623 2 жыл бұрын
+1 !
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
@@meriem623 Thank you
@evanliu6158
@evanliu6158 Жыл бұрын
🎉 very nice explanation
@abrikosa717
@abrikosa717 2 жыл бұрын
Thank you for the guide. It's indeed very interesting and useful. Subscribed!
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thank you very much!
@khadija3246
@khadija3246 Жыл бұрын
Thank you! This is a great explanation. :)
@joaosousa6427
@joaosousa6427 Жыл бұрын
Excelent information and examples, thanks bro!
@RedEyedCoderClub
@RedEyedCoderClub Жыл бұрын
Thank you for the comment!
@user-fs3yf5gq9i
@user-fs3yf5gq9i 2 жыл бұрын
Your work is excellent, you help me a lot, thank you!
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thank you
@pythongabi
@pythongabi Жыл бұрын
Thank you, a really helpful video. I like the examples chosen for the video. +1 subscriber
@a_mortal7511
@a_mortal7511 2 жыл бұрын
Thanks for the perfect example, I wish I could like more than once 👍
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thank you! There are more videos to like and comment :D
@odint.serega1099
@odint.serega1099 2 жыл бұрын
Thank you, everything is clear and understandable!
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thank you!
@kostya9169
@kostya9169 2 жыл бұрын
Cool and clear video tutorial. Thank you this is very helpful.
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thank you!
@von-fur-wegen-gegenolli9196
@von-fur-wegen-gegenolli9196 Жыл бұрын
Great explanation!
@scottwickersham2408
@scottwickersham2408 2 жыл бұрын
Excellent explanation! Nice job!
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thank you very much! Have a nice day!
@suprajakarumanchi9683
@suprajakarumanchi9683 2 жыл бұрын
Very good Video. Example chosen is very apt to the real world programming
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thank you!
@kostya9169
@kostya9169 2 жыл бұрын
Thank you very much for such a detailed and informative video tutorial, this information is very important to me.
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thank you!
@josesalgado3540
@josesalgado3540 Жыл бұрын
Great video!!! Thank you so much.
@RedEyedCoderClub
@RedEyedCoderClub Жыл бұрын
Thanks for comment!
@meabhgrogan
@meabhgrogan 5 ай бұрын
This was so helpful thank you 🙏
@annaaniytkina5963
@annaaniytkina5963 2 жыл бұрын
Thank you for the video. Always very informative.
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thank you!
@arinamiheeva2554
@arinamiheeva2554 2 жыл бұрын
Great. Just what I was looking for.
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thanks for comment!
@hummels11001
@hummels11001 Жыл бұрын
Amazing video!
@serg_D
@serg_D 2 жыл бұрын
The video review is very informative and useful. Thank you.
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thank you!
@maximoarceci9424
@maximoarceci9424 Жыл бұрын
that was a amazing video. Thank you!
@RedEyedCoderClub
@RedEyedCoderClub Жыл бұрын
Thank you!
@abdulmagomedov
@abdulmagomedov Жыл бұрын
Awesome! Thank you very much!
@RedEyedCoderClub
@RedEyedCoderClub Жыл бұрын
Thank you for the comment!
@user-fc9gq1on1w
@user-fc9gq1on1w 2 жыл бұрын
This is something new for me. Thank you.
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thank you!
@user-oo6fi3hk4t
@user-oo6fi3hk4t 2 жыл бұрын
This is a helpful video. For me exactly. Thank you.
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thanks for comment!
@user-fl7px4hz9d
@user-fl7px4hz9d Жыл бұрын
THATS what happened to your previous channel. Such a great surprise to occasionally find out that you are not done with youtube. Since me watching my first video on your channel many things happened, and even after all those years i can definitely say that your material is way beyond the others in terms of quality. Keep it up man
@RedEyedCoderClub
@RedEyedCoderClub Жыл бұрын
Thank you very much!
@user-ej5sh7et8s
@user-ej5sh7et8s 2 жыл бұрын
This is an interesting video. For more of these in KZfaq 👍👍👍
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thanks for comment
@Slone-uk1is
@Slone-uk1is Жыл бұрын
I am appreciated for this great tutorial!
@RedEyedCoderClub
@RedEyedCoderClub Жыл бұрын
Thank you!
@user-jp3cz7ul6m
@user-jp3cz7ul6m 2 жыл бұрын
Video is great! It was interesting.👍👍👍
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thanks for comment!
@jantttez
@jantttez 4 ай бұрын
братишка лучше гайда не видел успехов тебе от души
@munibarshad7454
@munibarshad7454 Жыл бұрын
Thank you, beautifully explained
@RedEyedCoderClub
@RedEyedCoderClub Жыл бұрын
Thanks for watching!
@_KREKHOVETSKYI_
@_KREKHOVETSKYI_ Жыл бұрын
I'm taking courses that have this topic. I didn't understand anything there at all. However, as soon as I watched the first 10 minutes of your video, everything immediately became clear. Thank you very much!
@RedEyedCoderClub
@RedEyedCoderClub Жыл бұрын
Glad to hear! Thank you for the comment!
@Bholu420
@Bholu420 Ай бұрын
Nice tutorial
@OlegBosi
@OlegBosi 2 жыл бұрын
Very good!!!!!
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thank you!
@user-lz8lx1cg3y
@user-lz8lx1cg3y 2 жыл бұрын
Thanks to the author --- interesting video
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thank you!
@ygr4943
@ygr4943 24 күн бұрын
شكرا ❤❤
@freelife1000
@freelife1000 Жыл бұрын
thx, crystal clear.
@RedEyedCoderClub
@RedEyedCoderClub Жыл бұрын
Thank you!
@zakchips
@zakchips 2 жыл бұрын
What a gift! Thanks.
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Isn't it too basic for you?
@zakchips
@zakchips 2 жыл бұрын
@@RedEyedCoderClub But it was only introduction. And may be you'll find some time to continue this topic comparing different approaches in mocking. what are advantages if present in module requests_mocking (or responses) comparing with unittest.mock patch. Or creating custom exceptions working with raise_for_status (had some troubles testing them at my work). Thank you very much.
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Yep, that's right. I knew that it's too basic for you, and planned to make more.
@EmadRahman_eee
@EmadRahman_eee Жыл бұрын
Amazing tutorial. Please make a series on Pytest. Thank you.
@RedEyedCoderClub
@RedEyedCoderClub Жыл бұрын
Thank you! I'll try!
@maxjokar7920
@maxjokar7920 Жыл бұрын
Hello, or privet, Whatever, thanks ever so much for ur video. Ure superman 👍🏻🌹👍🏻
@RedEyedCoderClub
@RedEyedCoderClub Жыл бұрын
Thank you!
@Evilflesh666
@Evilflesh666 Жыл бұрын
Дай обниму братюнь, отличный видос, спасибо.
@RedEyedCoderClub
@RedEyedCoderClub Жыл бұрын
Всегда пожалуйста
@sagarhm2237
@sagarhm2237 Жыл бұрын
sir how to write unit test for url loding , and websit proper loding
@maronthehill
@maronthehill 7 ай бұрын
2:10 How is the test_add() method called?
@avbolshakov
@avbolshakov 2 жыл бұрын
Спасибо! Хорошо бы возобновить рубрику "ответы на вопросы") Но уже на английском
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Ага, только вопросов что-то не много совсем
@duke007x3
@duke007x3 2 жыл бұрын
Thanks🙏
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thanks for comment, and have a nice day!
@sutischolar
@sutischolar Жыл бұрын
My god, thank you
@RedEyedCoderClub
@RedEyedCoderClub Жыл бұрын
Thank you for the comment!
@ininim
@ininim 2 жыл бұрын
Thanks you so much for this interesting and detailed guide. Will there be videos on testing with pytest?
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thank you! Yes, a planned to make videos about pytest. Stay tuned.
@LuisAlonsoLopezLopez
@LuisAlonsoLopezLopez Жыл бұрын
Can you make a video but using Pytest please?
@yanuareko4307
@yanuareko4307 6 ай бұрын
Thanks
@RedEyedCoderClub
@RedEyedCoderClub 6 ай бұрын
Thank you very much!
@subrinalazad3215
@subrinalazad3215 2 жыл бұрын
Thanks for the video. I'm facing a error when running the test.py ModuleNotFoundError: No module named 'main'
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Ok, have you the `main.py` module? What's you directory/files structure? Did you check your code twice?
@alexdzehil7194
@alexdzehil7194 2 жыл бұрын
Спасибо)) Только в работе как раз необходимость возникла в тестирование углубиться, а тут такой подгон. Спасибо Олег, во многом и благодаря вашим роликам сменил профессию с тренера по футболу, на пайтон разработчика!)
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Вау, это круто! Не поделитесь ли историей перехода?
@alexdzehil7194
@alexdzehil7194 2 жыл бұрын
@@RedEyedCoderClub если коротко то можно глянуть на ютубе "Moscow Python Podcast из преподавателя в разработчики". Если чуть длиннее, то переход занял у меня ровно год активного изучения питона. Начал с бесплатных курсов на степике, там же курс по линуксу, затем книги и в том числе делал блоги на джанго и фласке по вашим обучающим видео с русскоязычного канала. Затем платные курсы от создателей подкаста в который меня потом и пригласили. Скажу что то что прошел ваш курс и сделал блог на джанго мне очень пригодилось при прохождении платных курсов. Там суть в том что короткая вводная часть и затем проект на фласке или джанго, я выбрал джанго и чувствовал себя поувереннее своих сокурсников, успешно защитил проект и устроился на работу. Компания у нас небольшая да и в современных реалиях от разработчика при постановке задачи также требуется грамотная систем логирования и тестирование. Вот сейчас углубляюсь в тестирование и логирование также по вашим роликам, так как на курсах этому уделяется очень мало времени.
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
@@alexdzehil7194 Спасибо большое за ответ. Я вас от всей души поздравляю и желаю вам успехов! Действительно очень здорово, что вы вот так взяли и переключились. Это очень тяжело. Не каждый так может, а вы смогли. Просто прекрасно!
@Mehdi-hw6yi
@Mehdi-hw6yi 2 жыл бұрын
Thank you for the video, very clear but how can you mock multiple elements in one function? For example if a function calls two functions.
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
It's a good question! First of all you can use more then one @patch decorator @patch('main.one_func') @patch('main.two_func') def test_function(): pass Also you can use patch as a context manager. Smth like this: with patch('main.one_func') as mock_one_func: pass Also you can use patch() inline. Smth like this: mock_one_func = patch('main.one_func').start() ... mock_one_func.stop() It's all about the scope.
@Mehdi-hw6yi
@Mehdi-hw6yi 2 жыл бұрын
@@RedEyedCoderClub Thank you, I have tried the first two solutions and they work well. Not sure how to use the last one though.
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
It's great!
@user-yq4bg1sy7m
@user-yq4bg1sy7m Жыл бұрын
Many Thanks. Can we get code written?
@RedEyedCoderClub
@RedEyedCoderClub Жыл бұрын
Sorry, no. It's just an example
@ulisespallares8
@ulisespallares8 Жыл бұрын
👍👍👍👍👍👍👍👍👍👍👏👏👏👏👏👏👏👏 THANKS
@RedEyedCoderClub
@RedEyedCoderClub Жыл бұрын
Thanks for comment!
@benjamintanchingjui6741
@benjamintanchingjui6741 Жыл бұрын
I think the url no longer works for the jokes?
@RedEyedCoderClub
@RedEyedCoderClub Жыл бұрын
it's a pity, but you can use any other API or a website.
@Flowmastaz
@Flowmastaz 8 ай бұрын
Your voice sounds exactly like Oleg Molchanov. Where are you from?
@Flowmastaz
@Flowmastaz 8 ай бұрын
А, уже увидел, что это ты и есть) Класс, часто твои ролики на русском смотрю, теперь видать и на английском буду. Кстати, у тебя хороший английский. Долго учил?
@RedEyedCoderClub
@RedEyedCoderClub 8 ай бұрын
Не знаю, трудно сказать. Думаю если бы занимался систематично и регулярно знал бы его значительно лучше.
@kacperwodarczyk9349
@kacperwodarczyk9349 Жыл бұрын
Finally I found great and not arabian tutorial
@4rtcrt321
@4rtcrt321 2 жыл бұрын
Олег Молчанов енто ты?
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Да, это я
@4rtcrt321
@4rtcrt321 2 жыл бұрын
@@RedEyedCoderClub узнал по голосу. Спасибо за отличный контент! Потдержу тебя чем смогу)
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Спасибо! Рад, что нравится
@tamarastepanova6435
@tamarastepanova6435 2 жыл бұрын
This is something new for me. Thank you.
@RedEyedCoderClub
@RedEyedCoderClub 2 жыл бұрын
Thanks for comment!
Intro to Python Mocks #2: Mocking Exceptions | Python tutorial
15:54
Red Eyed Coder Club
Рет қаралды 16 М.
How To Write Unit Tests in Python • Pytest Tutorial
35:34
pixegami
Рет қаралды 134 М.
路飞被小孩吓到了#海贼王#路飞
00:41
路飞与唐舞桐
Рет қаралды 77 МЛН
تجربة أغرب توصيلة شحن ضد القطع تماما
00:56
صدام العزي
Рет қаралды 57 МЛН
Does size matter? BEACH EDITION
00:32
Mini Katana
Рет қаралды 20 МЛН
LOVE LETTER - POPPY PLAYTIME CHAPTER 3 | GH'S ANIMATION
00:15
Professional Python Testing with Mocks
21:19
NeuralNine
Рет қаралды 46 М.
The Ultimate Guide to Writing Classes in Python
25:39
ArjanCodes
Рет қаралды 108 М.
PyTest • REST API Integration Testing with Python
37:24
pixegami
Рет қаралды 78 М.
5 Useful Dunder Methods In Python
16:10
Indently
Рет қаралды 55 М.
Python Tutorial: Unit Testing Your Code with the unittest Module
39:13
Corey Schafer
Рет қаралды 1,3 МЛН
PLEASE Use These 5 Python Decorators
20:12
Tech With Tim
Рет қаралды 103 М.
Please Master These 10 Python Functions…
22:17
Tech With Tim
Рет қаралды 92 М.
Python TDD Workflow - Unit Testing Code Example for Beginners
25:33
Python Simplified
Рет қаралды 75 М.
Unit Tests and Test Doubles like Mocks, Stubs & Fakes
17:32
Cognitive Programmer
Рет қаралды 132 М.
路飞被小孩吓到了#海贼王#路飞
00:41
路飞与唐舞桐
Рет қаралды 77 МЛН