Intro to Python Mocks | Python tutorial

แชร์
ฝัง
  • เผยแพร่เมื่อ 28 มิ.ย. 2024
  • 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

ความคิดเห็น • 146

  • @vikrantmahajan142
    @vikrantmahajan142 ปีที่แล้ว +15

    It's an amazing video! You have really broken the concepts into very easily understandable components. Loved your way of explanation! Thanks

  • @bonnymunga2969
    @bonnymunga2969 4 หลายเดือนก่อน

    You're a saviour man. I had issues with DI and mocks but this video has simplified everything for me. Great explanation!👏

  • @williamgillett1756
    @williamgillett1756 ปีที่แล้ว +1

    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 4 หลายเดือนก่อน

    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.

  • @AVISH747
    @AVISH747 3 หลายเดือนก่อน

    Excellent. I was breaking my head on mock and patch.. now its crystal clear.

  • @uchesamuelottah559
    @uchesamuelottah559 7 หลายเดือนก่อน

    This is the best explanation ive ever seen in my life+!! You're aweskme

  • @JonhMalcovich
    @JonhMalcovich ปีที่แล้ว

    Exelent !!! Thanks for sharing this!

  • @drystack86
    @drystack86 ปีที่แล้ว +3

    Fantastic tutorial. Took me from almost no knowlege of python unittest and mocks to very confident. Thank you!

  • @nishugurung2339
    @nishugurung2339 ปีที่แล้ว

    This has been an awesome video. Thanks a bunch!

  • @Spayke201
    @Spayke201 ปีที่แล้ว

    Amazing video! Congrats and thanks a lot!! So helpful!

  • @bikkinarohith1006
    @bikkinarohith1006 ปีที่แล้ว

    One of the best vedioes on Python Mocks👏👏👏

  • @sergeyshevtsov5125
    @sergeyshevtsov5125 2 ปีที่แล้ว +8

    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 ปีที่แล้ว +1

      Thank you very much for your kind words :) Glad that you like my stuff.

    • @meriem623
      @meriem623 ปีที่แล้ว

      +1 !

    • @RedEyedCoderClub
      @RedEyedCoderClub  ปีที่แล้ว

      @@meriem623 Thank you

  • @vibhourjain
    @vibhourjain 5 หลายเดือนก่อน

    this is great video, with this one video i wrote my 1st unit test case of my project. Thanks

  • @rugmaable
    @rugmaable 4 หลายเดือนก่อน

    Thanks for the explanation. The mock is very powerful. I feel conformable starting to use it now

  • @user-fj7cg1qn2r
    @user-fj7cg1qn2r 11 หลายเดือนก่อน

    Great explanation and easy to understand, thanks!

  • @bactran7799
    @bactran7799 2 หลายเดือนก่อน

    amazing, I can understand mock and patch now. Thank you so much

  • @shiblyaziz4528
    @shiblyaziz4528 ปีที่แล้ว

    Your work is excellent, thank you!

  • @sandeepamarnath2272
    @sandeepamarnath2272 ปีที่แล้ว

    Very well explained!! Thank you!

  • @stelecoms00
    @stelecoms00 10 หลายเดือนก่อน

    OMG - you have made it so easy !! Thank you so much ❤

  • @brajesh42
    @brajesh42 11 หลายเดือนก่อน

    Amazing video. Simplified demo on how to write UT with mocks. Thanks

  • @PlanetLogical
    @PlanetLogical 6 หลายเดือนก่อน

    Great video. The explanations are extremely clear and easy to follow.

  • @user-xc7ow8rf9w
    @user-xc7ow8rf9w ปีที่แล้ว

    Excellent tutorial. Thanks!

  • @durgeshkshirsagar5160
    @durgeshkshirsagar5160 ปีที่แล้ว

    Great tutorial. Thank you for sharing the knowledge.

  • @philveo
    @philveo ปีที่แล้ว

    hi, i have seen many and many tutos python mocks, but this one is simple, clear and understable. 👍 and many thanks !

  • @user-fw4od8cg5s
    @user-fw4od8cg5s 2 ปีที่แล้ว

    I get a lot of knowledge by watching your video lessons. Thank you very much!

  • @emma_promise_smartnbc4331
    @emma_promise_smartnbc4331 2 หลายเดือนก่อน

    Thanks. Was finding it difficult understanding, U made it clear

  • @khadija3246
    @khadija3246 ปีที่แล้ว

    Thank you! This is a great explanation. :)

  • @hummels11001
    @hummels11001 ปีที่แล้ว

    Amazing video!

  • @odint.serega1099
    @odint.serega1099 2 ปีที่แล้ว

    Thank you, everything is clear and understandable!

  • @abdulmagomedov
    @abdulmagomedov ปีที่แล้ว

    Awesome! Thank you very much!

  • @user-ep1rd5pw1w
    @user-ep1rd5pw1w 2 ปีที่แล้ว

    Thank you for a detailed and informative video tutorial. I look forward to new lessons from you.

  • @user-fs3yf5gq9i
    @user-fs3yf5gq9i 2 ปีที่แล้ว +2

    Your work is excellent, you help me a lot, thank you!

  • @arinamiheeva2554
    @arinamiheeva2554 2 ปีที่แล้ว

    Great. Just what I was looking for.

  • @abrikosa717
    @abrikosa717 2 ปีที่แล้ว +1

    Thank you for the guide. It's indeed very interesting and useful. Subscribed!

  • @josesalgado3540
    @josesalgado3540 ปีที่แล้ว

    Great video!!! Thank you so much.

  • @von-fur-wegen-gegenolli9196
    @von-fur-wegen-gegenolli9196 11 หลายเดือนก่อน

    Great explanation!

  • @meabhgrogan
    @meabhgrogan 5 หลายเดือนก่อน

    This was so helpful thank you 🙏

  • @user-fl7px4hz9d
    @user-fl7px4hz9d ปีที่แล้ว +1

    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

  • @maximoarceci9424
    @maximoarceci9424 ปีที่แล้ว

    that was a amazing video. Thank you!

  • @scottwickersham2408
    @scottwickersham2408 ปีที่แล้ว

    Excellent explanation! Nice job!

  • @joaosousa6427
    @joaosousa6427 ปีที่แล้ว

    Excelent information and examples, thanks bro!

  • @annaaniytkina5963
    @annaaniytkina5963 2 ปีที่แล้ว

    Thank you for the video. Always very informative.

  • @kostya9169
    @kostya9169 2 ปีที่แล้ว

    Cool and clear video tutorial. Thank you this is very helpful.

  • @evanliu6158
    @evanliu6158 ปีที่แล้ว

    🎉 very nice explanation

  • @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

  • @Slone-uk1is
    @Slone-uk1is ปีที่แล้ว

    I am appreciated for this great tutorial!

  • @_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!

  • @user-fc9gq1on1w
    @user-fc9gq1on1w 2 ปีที่แล้ว

    This is something new for me. Thank you.

  • @user-oo6fi3hk4t
    @user-oo6fi3hk4t 2 ปีที่แล้ว

    This is a helpful video. For me exactly. Thank you.

  • @Bholu420
    @Bholu420 21 วันที่ผ่านมา

    Nice tutorial

  • @kostya9169
    @kostya9169 2 ปีที่แล้ว

    Thank you very much for such a detailed and informative video tutorial, this information is very important to me.

  • @serg_D
    @serg_D 2 ปีที่แล้ว

    The video review is very informative and useful. Thank you.

  • @freelife1000
    @freelife1000 ปีที่แล้ว

    thx, crystal clear.

  • @munibarshad7454
    @munibarshad7454 ปีที่แล้ว

    Thank you, beautifully explained

  • @ygr4943
    @ygr4943 13 ชั่วโมงที่ผ่านมา +1

    شكرا ❤❤

  • @suprajakarumanchi9683
    @suprajakarumanchi9683 2 ปีที่แล้ว

    Very good Video. Example chosen is very apt to the real world programming

  • @OlegBosi
    @OlegBosi 2 ปีที่แล้ว

    Very good!!!!!

  • @user-ej5sh7et8s
    @user-ej5sh7et8s 2 ปีที่แล้ว

    This is an interesting video. For more of these in TH-cam 👍👍👍

  • @user-jp3cz7ul6m
    @user-jp3cz7ul6m 2 ปีที่แล้ว

    Video is great! It was interesting.👍👍👍

  • @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 ปีที่แล้ว +1

      Yep, that's right. I knew that it's too basic for you, and planned to make more.

  • @jantttez
    @jantttez 4 หลายเดือนก่อน

    братишка лучше гайда не видел успехов тебе от души

  • @duke007x3
    @duke007x3 2 ปีที่แล้ว

    Thanks🙏

    • @RedEyedCoderClub
      @RedEyedCoderClub  2 ปีที่แล้ว

      Thanks for comment, and have a nice day!

  • @RedEyedCoderClub
    @RedEyedCoderClub  2 ปีที่แล้ว +4

    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

  • @EmadRahman_eee
    @EmadRahman_eee ปีที่แล้ว

    Amazing tutorial. Please make a series on Pytest. Thank you.

  • @user-lz8lx1cg3y
    @user-lz8lx1cg3y 2 ปีที่แล้ว

    Thanks to the author --- interesting video

  • @yanuareko4307
    @yanuareko4307 5 หลายเดือนก่อน

    Thanks

  • @ininim
    @ininim 2 ปีที่แล้ว +1

    Thanks you so much for this interesting and detailed guide. Will there be videos on testing with pytest?

    • @RedEyedCoderClub
      @RedEyedCoderClub  2 ปีที่แล้ว +2

      Thank you! Yes, a planned to make videos about pytest. Stay tuned.

  • @sutischolar
    @sutischolar ปีที่แล้ว

    My god, thank you

  • @Evilflesh666
    @Evilflesh666 ปีที่แล้ว

    Дай обниму братюнь, отличный видос, спасибо.

  • @avbolshakov
    @avbolshakov 2 ปีที่แล้ว

    Спасибо! Хорошо бы возобновить рубрику "ответы на вопросы") Но уже на английском

    • @RedEyedCoderClub
      @RedEyedCoderClub  2 ปีที่แล้ว

      Ага, только вопросов что-то не много совсем

  • @maxjokar7920
    @maxjokar7920 ปีที่แล้ว

    Hello, or privet,
    Whatever, thanks ever so much for ur video. Ure superman 👍🏻🌹👍🏻

  • @sagarhm2237
    @sagarhm2237 ปีที่แล้ว

    sir how to write unit test for url loding , and websit proper loding

  • @maronthehill
    @maronthehill 6 หลายเดือนก่อน

    2:10 How is the test_add() method called?

  • @alexdzehil7194
    @alexdzehil7194 2 ปีที่แล้ว +2

    Спасибо)) Только в работе как раз необходимость возникла в тестирование углубиться, а тут такой подгон. Спасибо Олег, во многом и благодаря вашим роликам сменил профессию с тренера по футболу, на пайтон разработчика!)

    • @RedEyedCoderClub
      @RedEyedCoderClub  2 ปีที่แล้ว

      Вау, это круто! Не поделитесь ли историей перехода?

    • @alexdzehil7194
      @alexdzehil7194 2 ปีที่แล้ว

      @@RedEyedCoderClub если коротко то можно глянуть на ютубе "Moscow Python Podcast из преподавателя в разработчики". Если чуть длиннее, то переход занял у меня ровно год активного изучения питона. Начал с бесплатных курсов на степике, там же курс по линуксу, затем книги и в том числе делал блоги на джанго и фласке по вашим обучающим видео с русскоязычного канала. Затем платные курсы от создателей подкаста в который меня потом и пригласили. Скажу что то что прошел ваш курс и сделал блог на джанго мне очень пригодилось при прохождении платных курсов. Там суть в том что короткая вводная часть и затем проект на фласке или джанго, я выбрал джанго и чувствовал себя поувереннее своих сокурсников, успешно защитил проект и устроился на работу. Компания у нас небольшая да и в современных реалиях от разработчика при постановке задачи также требуется грамотная систем логирования и тестирование. Вот сейчас углубляюсь в тестирование и логирование также по вашим роликам, так как на курсах этому уделяется очень мало времени.

    • @RedEyedCoderClub
      @RedEyedCoderClub  2 ปีที่แล้ว +2

      @@alexdzehil7194 Спасибо большое за ответ. Я вас от всей души поздравляю и желаю вам успехов! Действительно очень здорово, что вы вот так взяли и переключились. Это очень тяжело. Не каждый так может, а вы смогли. Просто прекрасно!

  • @Mehdi-hw6yi
    @Mehdi-hw6yi ปีที่แล้ว

    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  ปีที่แล้ว +1

      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 ปีที่แล้ว

      @@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  ปีที่แล้ว

      It's great!

  • @LuisAlonsoLopezLopez
    @LuisAlonsoLopezLopez ปีที่แล้ว

    Can you make a video but using Pytest please?

  • @ulisespallares8
    @ulisespallares8 ปีที่แล้ว

    👍👍👍👍👍👍👍👍👍👍👏👏👏👏👏👏👏👏 THANKS

  • @user-yq4bg1sy7m
    @user-yq4bg1sy7m ปีที่แล้ว

    Many Thanks. Can we get code written?

  • @subrinalazad3215
    @subrinalazad3215 ปีที่แล้ว

    Thanks for the video.
    I'm facing a error when running the test.py
    ModuleNotFoundError: No module named 'main'

    • @RedEyedCoderClub
      @RedEyedCoderClub  ปีที่แล้ว

      Ok, have you the `main.py` module?
      What's you directory/files structure?
      Did you check your code twice?

  • @benjamintanchingjui6741
    @benjamintanchingjui6741 ปีที่แล้ว +1

    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 7 หลายเดือนก่อน

    Your voice sounds exactly like Oleg Molchanov. Where are you from?

    • @Flowmastaz
      @Flowmastaz 7 หลายเดือนก่อน

      А, уже увидел, что это ты и есть) Класс, часто твои ролики на русском смотрю, теперь видать и на английском буду. Кстати, у тебя хороший английский. Долго учил?

    • @RedEyedCoderClub
      @RedEyedCoderClub  7 หลายเดือนก่อน

      Не знаю, трудно сказать. Думаю если бы занимался систематично и регулярно знал бы его значительно лучше.

  • @kacperwodarczyk9349
    @kacperwodarczyk9349 ปีที่แล้ว

    Finally I found great and not arabian tutorial

  • @4rtcrt321
    @4rtcrt321 2 ปีที่แล้ว +1

    Олег Молчанов енто ты?

    • @RedEyedCoderClub
      @RedEyedCoderClub  2 ปีที่แล้ว +1

      Да, это я

    • @4rtcrt321
      @4rtcrt321 2 ปีที่แล้ว

      @@RedEyedCoderClub узнал по голосу.
      Спасибо за отличный контент!
      Потдержу тебя чем смогу)

    • @RedEyedCoderClub
      @RedEyedCoderClub  2 ปีที่แล้ว

      Спасибо! Рад, что нравится

  • @tamarastepanova6435
    @tamarastepanova6435 2 ปีที่แล้ว

    This is something new for me. Thank you.