投稿時間:2021-12-12 23:17:29 RSSフィード2021-12-12 23:00 分まとめ(20件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
python Pythonタグが付けられた新着投稿 - Qiita AMD製とかのGPU使用率を取得(Python) https://qiita.com/ppza53893/items/b3303ebd62aff1e406b6 自分へのメモ用に…はじめにふと、AMDとかのGPU使用率ってどうやって取るんだという疑問をもったRadeonソフトとか、パフォーマンスモニター、タスクマネージャーを使うとできるんだけど、それを数値で取得したいなぁと思ったというのは、ちょうど、モニタリングアプリケーションを作っていたので、なんか最後にpythonでできないかなーと思い、いろいろ調べてみた。 2021-12-12 22:57:18
python Pythonタグが付けられた新着投稿 - Qiita 雑なアルゴリズムと最新のCPUはどちらが速いのか? https://qiita.com/t_nakayama0714/items/eca885a1b99022a81703 正多角形ゼータ関数モンテカルロ法Chudnovskyの公式それでは、順に計算してみましょう。 2021-12-12 22:51:49
js JavaScriptタグが付けられた新着投稿 - Qiita ReactのpropsとuseState()の分割代入でカッコ{}[]が違うのはなぜ!!!?? https://qiita.com/kiyoG/items/f9bf163994f3eb9aa0b3 ReactのpropsとuseStateの分割代入でカッコが違うのはなぜpropsで受け取る場合と、useStateで受け取る場合が違う・・・propsは親から子へパラメータを受け渡すときに使うヤツ。 2021-12-12 22:46:29
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) bits/stdc++のコンパイルでエラーが出る https://teratail.com/questions/373497?rss=all bitsstdcのコンパイルでエラーが出るbitsstdcのコンパイルのエラーを解消したいMacをアップデートして、Montereyにするとgでコンパイルすると下記の警告が出るようになりました。 2021-12-12 22:38:55
Ruby Rubyタグが付けられた新着投稿 - Qiita [Ruby on Rails]Twitter API利用方法 https://qiita.com/kyosuke_takimoto/items/a618fead1f17d22ba16c TwitterのAPI利用申請APIを使用するには、Twitterアカウントが必要ですので事前に作成してください。 2021-12-12 23:00:13
Ruby Rubyタグが付けられた新着投稿 - Qiita 【Rails】Active Recordのメソッドまとめ https://qiita.com/jibirian999/items/d370e7083c6c19cb775b 【Rails】ActiveRecordのメソッドまとめ概要RailsのActiveRecordのメソッドの違いがよくわからなくなるため、Railsチュートリアルの第章をもとに、備忘としてまとめ。 2021-12-12 22:17:22
Ruby Rubyタグが付けられた新着投稿 - Qiita 【Ruby】二次元配列に要素を代入すると、他の要素まで変更されてしまうときの対処法 https://qiita.com/rich_m/items/daf8cc4d60e68f2899a5 間違った方法↓aArraynewArraynewpagtこれは、newメソッドで長さの配列をつくって、中の要素にArraynewを代入初期化しています。 2021-12-12 22:16:24
Git Gitタグが付けられた新着投稿 - Qiita 俺のgitチートシート https://qiita.com/kandalog/items/8aac620c2963ae90348a 俺のgitチートシートはじめに個人学習でしか使ったことないです。 2021-12-12 22:33:35
Ruby Railsタグが付けられた新着投稿 - Qiita [Ruby on Rails]Twitter API利用方法 https://qiita.com/kyosuke_takimoto/items/a618fead1f17d22ba16c TwitterのAPI利用申請APIを使用するには、Twitterアカウントが必要ですので事前に作成してください。 2021-12-12 23:00:13
Ruby Railsタグが付けられた新着投稿 - Qiita 【Rails】Active Recordのメソッドまとめ https://qiita.com/jibirian999/items/d370e7083c6c19cb775b 【Rails】ActiveRecordのメソッドまとめ概要RailsのActiveRecordのメソッドの違いがよくわからなくなるため、Railsチュートリアルの第章をもとに、備忘としてまとめ。 2021-12-12 22:17:22
技術ブログ Developers.IO Coc.nvimを触ってみようアドベントカレンダー 12日目 – coc-translator https://dev.classmethod.jp/articles/cocnvim-adventcalendar-day12/ adventcalendar 2021-12-12 13:35:50
海外TECH MakeUseOf Is Your iPhone Home Button Not Working? 5 Quick Fixes to Try https://www.makeuseof.com/tag/iphone-home-button-working-fix/ button 2021-12-12 13:45:12
海外TECH MakeUseOf 6 Problems With Twitter That the New CEO Needs to Fix Quickly https://www.makeuseof.com/twitter-problems-that-need-fixing/ leadership 2021-12-12 13:30:11
海外TECH DEV Community TailwindCSS v3 released! A look at the new features 🎨 https://dev.to/avneesh0612/tailwindcss-v3-released-a-look-at-the-new-features-37b3 TailwindCSS v released A look at the new features IntroTailwind CSS v just got released and they have added a lot of cool features so let s have a look at them JIT is now inbuiltThe JIT mod is now inbuilt in TailwindCSS so it is way faster now and also enables some cool new features like stackable variants arbitrary value support Lot s of new colorsThere are many new colors now and they are in total There are also different gray s now Colored box shadowColored box shadow was an important feature that wasn t in tailwind until v But it is finally here and so easy to use D lt button class shadow lg shadow green text center bg green text white px py rounded full text xl gt Button lt button gt A few classes can you give you this beautiful button Aspect ratioNow you don t have to use any plugins to use the aspect class you can use the various types provided like aspect video aspect auto aspect square or use custom values like aspect as JIT is now inbuilt Scroll snapThis is a great feature that allows you to have a list of scrollable elements which snap to center start or end In this demo I am using center snap lt div class snap x flex overflow scroll gt lt img class mx snap center w px src ixid MnwxMjAfDFMHxwaGbywYWdlfHxfGVufDBfHx amp auto format amp fit crop amp w amp q gt lt img class mx snap center w px src ixid MnwxMjAfDBMHxwaGbywYWdlfHxfGVufDBfHx amp auto format amp fit crop amp w amp q gt lt img class mx snap center w px src ixid MnwxMjAfDBMHxwaGbywYWdlfHxfGVufDBfHx amp auto format amp fit crop amp w amp q gt lt img class mx snap center w px src ixid MnwxMjAfDBMHxwaGbywYWdlfHxfGVufDBfHx amp auto format amp fit crop amp w amp q gt lt div gt This will give a nice snap scrolling effect like this Scroll behaviorYou can now add smooth scrolling in tailwind CSS by adding the scroll smooth class If you want to add margin to some places for scroll it can be done by prefixing scroll like scroll m Multi column layoutTailwind now supports multi column newspaper like layouts You can give a specific number of columns you need or just set it to auto for the browser to decide how many columns to use based on size Accent color amp file uploadAccent colorYou can now customize your forms to match the theme of your brand and it will change the colors of things like checkboxes and radio buttons You can achieve this by just adding the accent lt color gt lt shade gt to the div form tag File upload buttonYou can also customize the file upload buttons to look beautiful like this You can add styles like you do normally but prefix file To get the same button as I did you can use this lt input type file class file bg emerald file px file py file rounded full file border none file text emerald file text lg file font semibold gt Fancy underlinesYou can now change the color thickness and style of your underlines as well To use these styles you need to use decoration red decoration wavy so the styles will look like this lt p class underline decoration red decoration wavy gt I have squigly underline lt h gt ConclusionThe team at TailwindCSS has also released some more cool stuff I just highlighted the things that I found the most exciting To know more about Tailwind you can check out their website See ya next time ️ Useful linksTailwindCSSTailwind s video on the releaseConnect with me 2021-12-12 13:19:02
海外TECH DEV Community Test-Driven-Development with Django: Unit Testing & Integration testing with Docker, Flask & Github Actions https://dev.to/koladev/test-driven-development-with-django-unit-testing-integration-testing-with-docker-flask-github-actions-2047 Test Driven Development with Django Unit Testing amp Integration testing with Docker Flask amp Github ActionsSoftware testing is an essential step in the software development process It s a method to check whether the software is aligned with the requirements of the business or the project However many developers ignore this step and only rely on manual testing Manual testing becomes difficult as the application size grows By writing automated tests unit tests integrations tests and EE tests we can make sure that every component added to the codebase or application works without breaking the whole application There are two main types of tests mostly used in Sofware development Unit tests and Integration tests We ll focus on these concepts for this article Unit TestingA Unit Test is an isolated test that tests one specific function For example if you have an API to help you manage discount creation and this application relied on a function to compute the discounted amount named apply discount a unit test here will be to test the function apply discount to make sure it behaves accordingly Or even more simple you want to make sure that your sum a b function returns exactly when you do sum Unit tests need a lot of focus It s a great habit to write a lot of these Setup projectWe ll be working on a simple project to create an e commerce cart Here are the requirements of this project Be able to create and list discountBe able to create a cart and apply a discountBe able to pay the amount on the cart First of all let s configure the environment I ll be using virtualenv to create a virtual python environment virtualenv python usr bin python venvsource venv bin activateNow let s install Django and create a project pip install djangodjango admin startproject CoreRoot python manage py migrate amp amp python manage py runserverWell let s create our application and start coding Discount applicationAt the root of the project enter this commandpython manage py startapp discountThe application is created but we need to register it in the settings py file INSTALLED APPS django contrib admin django contrib auth django contrib contenttypes django contrib sessions django contrib messages django contrib staticfiles discount Discount ModelThe discount model comes with the following fields codevaluedescriptioncreatedendedFollowing the TDD methodology we ll write the tests first and then write the features Let s write a test for the model But first we have to install the modules we ll be using pip install pytest pytest djangoOnce the installation is finished create a directory named tests in the discount application It ll contain the tests we ll write for the models and the viewsets └ーtests ├ー init py └ーtest models py └ーtest viewsets py └ーtest serializers pyAt the root of the project add pytest ini file This will contain configurations such as the DJANGO SETTINGS MODULE and the python files to watch for the tests Let s write the test for the Discount model import pytestfrom django utils timezone import now timedeltafrom discount models import Discount pytest mark django dbdef test discount model discount Discount code DIS value description Some discount created now ended now timedelta days discount save assert discount code DIS assert discount created lt discount ended assert discount value Now use the python manage py test command to run the tests Naturally the tests will fail As the Discount model is not created Found test s System check identified no issues silenced E ERROR discount tests test model unittest loader FailedTest ImportError Failed to import test module discount tests test modelTraceback most recent call last File usr lib python unittest loader py line in find test path module self get module from name name File usr lib python unittest loader py line in get module from name import name File home koladev PycharmProjects Django Testing discount tests test model py line in lt module gt from discount models import DiscountImportError cannot import name Discount from discount models home koladev PycharmProjects Django Testing discount models py Ran test in sFAILED errors Let s create the Discount model then from django db import modelsclass Discount models Model code models CharField max length unique True db index True value models FloatField description models TextField max length created models DateTimeField auto now add True ended models DateTimeField Now let s create the migrations for this model python manage py makemigrationsAnd let s run the migration python manage py migrateAnd now run the test again python manage py testAnd everything looks good Found test s System check identified no issues silenced Ran tests in sOKAnd voila We ve just written our first unit test for this project For the next steps we ll be adding a serializer and a viewset Discount SerializerFor this we ll install the Django Rest Framework package It contains tools needed to create RESTful APIs with Django pip install djangorestframeworkOnce it s done add rest framework to your INSTALLED APPS settings INSTALLED APPS rest framework Great we can now create the serializer But first of all let s write a test for that discount tests test serializers pyimport pytestfrom django utils timezone import now timedeltafrom discount serializers import DiscountSerializer pytest mark django dbdef test valid discount serializer valid serializer data code DIS value description Some lines ended now timedelta days serializer DiscountSerializer data valid serializer data assert serializer is valid raise exception True assert serializer validated data valid serializer dataIf you are not familiar with DRF Serializer allows you to convert complex Django complex data structures such as querysets or model instances in Python native objects that can be easily converted JSON XML format but Serializer also serializes JSON XML to naive Python If you run the tests it ll fail Let s add the DiscountSerializer discount serializers pyfrom rest framework import serializersfrom discount models import Discountclass DiscountSerializer serializers ModelSerializer class Meta model Discount fields id code description created value created ended read only fields id created Here we created a serializer class named DiscountSerializer which outputs all the fields from the Discount model Having read only fields we ensure that they won t be updated or created via the serializer And now run the tests again pytestYou ll get similar output test session starts platform linux Python pytest py pluggy django settings CoreRoot settings from ini rootdir home koladev PycharmProjects Django Testing configfile pytest iniplugins django collected items discount tests test model py discount tests test serializers py passed in s Now that we have the model and the serializer set up we can use them together to create our viewsets and endpoint which represent the logic of the business Discount ViewsetsWe ll have three endpoints RoutesHTTP MethodResultapi discount POSTCreate a discountapi discount GETGet all Discountsapi discount discount id GETGet a discountLet s start by writing tests discount tests test viewsets pyimport jsonimport pytestfrom django utils timezone import now timedeltafrom discount models import Discount pytest mark django dbdef test add discount client discounts Discount objects all assert discounts count response client post api discount code DIS value description Some lines ended now timedelta days content type application json assert response status code assert response data code DIS discounts Discount objects all assert discounts count pytest mark django dbdef test get all discounts client response client get api discount assert response status code pytest mark django dbdef test retrieve discount client response client post api discount code DIS value description Some lines ended now timedelta days content type application json assert response status code response data response data response client get f api discount response data id assert response status code If you run the tests they will fail To make sure the tests pass we ll be adding the discount viewset and registering it in the project routes Create a file called viewsets py in the discount application from rest framework import viewsetsfrom rest framework permissions import AllowAnyfrom discount serializers import DiscountSerializerclass DiscountViewSet viewsets ModelViewSet http method names get post serializer class DiscountSerializer permission classes AllowAny queryset Discount objects all For the moment we are only allowing GET and POST methods and for simplicity no permissions are required to access this route Let s add now the routers In the route of the project create a file called routers py We ll register the viewsets into this file from rest framework import routersfrom discount viewsets import DiscountViewSetrouter routers SimpleRouter router register r discount DiscountViewSet basename discount urlpatterns router urlsAnd the last step let s add the new urlpatterns to the project urls py file here located in CoreRoot dir from django contrib import adminfrom django urls import path includeurlpatterns path admin admin site urls path api include routers api namespace core api Now run pytest again and the tests should pass test session starts platform linux Python pytest py pluggy django settings CoreRoot settings from ini rootdir home koladev PycharmProjects Django Testing configfile pytest iniplugins django collected items discount tests test model py discount tests test serializers py discount tests test viewset py passed in s Great now we have written unit tests for each part of the application We can now move to integration testing Integration TestingIntegration testing is a phase of software testing where individual modules of the same software or external services are combined and tested as a group Notice here the emphasis on modules of the same software or external services For example integration testing will be combining a module handling authentication and permissions and a module handling payments A test scenario will be to make sure that only authenticated and authorized users can initialize a payment We will call this internal integration testing Another case will be when you are using an external service for payment and you want to include this service in your test We will call external integration testing Here in our project we ll add another module and integrate it with our discount application We ll also be adding a service for payment and integrating it into our environment For this we will create a cart application It ll behave as a cart as you see on an e commerce website But for sake of simplicity we ll just tackle a few requirements and ignore some rules Just keep it in mind the client can create a cart with a total items number and currencythe client can apply a discount to the cartA cart here can be created with just the total the items number and the currency Cart applicationLet s create the application using the django admin command django admin startapp cartNow go into the settings py file of the project and register the newly created application INSTALLED APPS django contrib admin django contrib auth django contrib contenttypes django contrib sessions django contrib messages django contrib staticfiles discount cart As we did for the discount application let s follow the TDD rules Create a directory named tests containing files such as test models py test serializers py and test viewsets py Adding the Cart modelLet s write the test to create a Cart instance first import pytestfrom cart models import Cart pytest mark django dbdef test cart model cart Cart total currency USD items number cart save assert cart total assert cart currency USD assert cart items number assert cart payment status pending Make sure the tests fail test session starts platform linux Python pytest py pluggy django settings CoreRoot settings from ini rootdir home koladev PycharmProjects Django Testing configfile pytest iniplugins django collected items error selected ERRORS ERROR collecting cart tests test models py ImportError while importing test module home koladev PycharmProjects Django Testing cart tests test models py Hint make sure your test modules packages have valid Python names Traceback usr lib python importlib init py in import module return bootstrap gcd import name level package level cart tests test models py in lt module gt from cart models import CartE ImportError cannot import name Cart from cart models home koladev PycharmProjects Django Testing cart models py short test summary info ERROR cart tests test models py Interrupted error during collection error in s Let s create the Cart model from django db import modelsclass Cart models Model total models FloatField default currency models CharField max length items number models IntegerField default total discounted models FloatField default amount discounted models FloatField default payment status models CharField default pending max length created models DateTimeField auto now add True Now let s generate the migrations for this model and migrate it python manage py makemigrationspython manage py migrateOnce it s done run the tests again and everything should be green test session starts platform linux Python pytest py pluggy django settings CoreRoot settings from ini rootdir home koladev PycharmProjects Django Testing configfile pytest iniplugins django collected items cart tests test models py discount tests test model py discount tests test serializers py discount tests test viewset py passed in s Great let s add the tests for the serializer and write the serializer import pytestfrom cart serializers import CartSerializer pytest mark django dbdef test valid cart serializer valid serializer data total currency USD items number serializer CartSerializer data valid serializer data assert serializer is valid raise exception True assert serializer validated data valid serializer dataMake sure the tests fail and now let s add the serializer from rest framework import serializersfrom cart models import Cartclass CartSerializer serializers ModelSerializer class Meta model Cart fields id total total discounted amount discounted items number created currency payment status read only fields id total discounted amount discounted created payment status Run the tests and it should pass now And finally let s add the routes and viewsets Here we ll need an endpoint to apply a discount It should be a POST request containing a discount code in the body We ll add it as an action to CartViewset import pytestfrom cart models import Cart pytest mark django dbdef test add cart client carts Cart objects all assert carts count response client post api cart total currency USD items number content type application json assert response status code carts Cart objects all assert carts count pytest mark django dbdef test get all carts client response client get api cart assert response status code pytest mark django dbdef test retrieve cart client response client post api cart total currency USD items number content type application json assert response status code response data response data response client get f api cart response data id assert response status code Make sure the tests fail Let s now add the Viewset from rest framework import viewsetsfrom rest framework permissions import AllowAnyfrom cart serializers import CartSerializerfrom cart models import Cartclass CartViewSet viewsets ModelViewSet http method names get post serializer class CartSerializer permission classes AllowAny queryset Cart objects all And register the viewset into the routers py file from rest framework import routersfrom discount viewsets import DiscountViewSetfrom cart viewsets import CartViewSetrouter routers SimpleRouter router register r discount DiscountViewSet basename discount router register r cart CartViewSet basename cart urlpatterns router urls Applying the discountTo apply the discount we ll need to verify that a discount with the provided code exists and that this discount has not expired And once it s done we can now apply this discount to the cart Then here s how we can proceed add a method to the Cart model which applies the discount and the value to the totalWrite a serializer specific to the apply discount endpointFollowing the TDD principles let s write a test for the apply discount method on the Cart model cart tests test model py pytest mark django dbdef test apply discount to cart cart Cart total currency USD items number cart save Creating the discount discount Discount code DIS value description Some discount ended now timedelta days discount save cart apply discount discount assert cart amount discounted assert cart total assert cart total discounted Make sure the tests fail We can now add the apply discount method from django db import modelsclass Cart models Model total models FloatField default currency models CharField max length items number models IntegerField default total discounted models FloatField default amount discounted models FloatField default created models DateTimeField auto now add True def apply discount self discount self amount discounted discount value self total discounted self total self amount discounted self total self total discounted self save update fields total amount discounted total discounted Run the tests again and it should pass This is the beginning of the integration testing between cart and discount applications But it s only done at a model level Let s add the apply discount serializer ApplyDiscount SerializerLet s add the tests first discount tests test serializers py pytest mark django dbdef test apply discount serializer CREATING THE DISCOUNT discount Discount code DIS value description Some discount created now ended now timedelta days discount save discount data code DIS serializer ApplyDiscountSerializer data discount data assert serializer is valid pytest mark django dbdef test apply expired discount serializer CREATING THE DISCOUNT discount Discount code DIS value description Some discount created now ended now timedelta days discount save discount data code DIS serializer ApplyDiscountSerializer data discount data assert not serializer is valid pytest mark django dbdef test apply non exist discount serializer discount data code DIS serializer ApplyDiscountSerializer data discount data assert not serializer is valid Make sure the test fails and let s add the serializer discount serializer Let s add this serializer in the serializer py file of the discount application class ApplyDiscountSerializer serializers Serializer code serializers CharField max length def validate self attrs code attrs get code try discount Discount objects get code code except Discount DoesNotExist raise validators ValidationError This discount doesn t exist if discount ended lt now raise validators ValidationError This discount has expired attrs discount discount return attrsRun the tests again and it should pass We are now sure that a valid discount will pass and be applied Next step we ll be adding an extra route for this on the CartViewset thanks to viewsets action apply discount action on CartViewSetapply discount will be an action on the CartViewSet As described in the official docs of DRF if you have ad hoc methods that should be routable you can mark them as such with the action decorator Like regular actions extra actions may be intended for either a single object or an entire collection Let s add some tests for this in the test viewsets py file of the cart application pytest mark django dbdef test apply discount to cart client CREATING THE DISCOUNT discount Discount code DIS value description Some discount ended now timedelta days discount save response client post api cart total currency USD items number content type application json assert response status code response data response data response client post f api cart response data id apply discount code DIS content type application json assert response status code assert response data total assert response data total discounted assert response data amount discounted Make sure the tests fail Once it s done we can now add the apply discount action from rest framework import viewsets statusfrom rest framework permissions import AllowAnyfrom rest framework decorators import actionfrom rest framework response import Responsefrom cart serializers import CartSerializerfrom cart models import Cartfrom discount serializers import ApplyDiscountSerializer action methods post detail True def apply discount self request pk None obj self get object serializer ApplyDiscountSerializer data request data serializer is valid raise exception True obj apply discount serializer validated data discount return Response CartSerializer obj data status status HTTP OK We are passing to the action decorator two parameters The list of HTTP methods accepted here POST And the detail parameter This will tell Django that the client has to provide an id and also the URL will have this structure cart lt cart id gt apply discount Now let s run the tests again And everything should be green Congratulations We ve just written integrations tests But there is the last feature we have to develop Yes the payment feature External Integration testingIf your application depends on external services it s a good industrial habit to include those services in your testing But this comes with some questions Are you going to integrate a Real API into your tests Even if the service provides a testing environment how do you come with solutions if your tests are firing many requests and they get blocked Or what if the service is unavailable We can avoid hitting the real services API by running our own fake servers while running the integrations tests Then most of the time you have two choices Mock the API using unittest mock But what is Mocking Mocking means substituting or imitating a real object or service within a testing environment This article from RealPython illustrates it well Building your own fake server for integration tests This solution is a good idea in some scenarios As stated in this article you should go with this if the integration is not core to your application i e it s an incidental featureif the bulk of the code you write and the feedback you want is not about integration issues but about other things in your appif you really can t figure out how to fix the problems with your integration tests another way retries perhaps they d be a good idea anyway For this tutorial we ll go with the second choice We ll build a simple server to imitate a card payment API and spin it up in a docker container Then we ll need to dockerize our project Bur first of all let s quickly create the Flask server Flask applicationFlask is a very lightweight framework coming with the necessary tools to create an API or start a simple server We ll use this to imitate a payment provider API for our tests First of all make sure to have flask installed on your project We ll also install python dotenv to load environment variables pip install flask python dotenvOnce it s done create a file called fake payment server py And add the following content from flask import Flask jsonifyapp Flask name app route inspect def inspect return jsonify available if name main app run Create a env file at the root of the project This will contain some configs for the Flask server but also the Django server FAKE PAYMENT API fake payment api FLASK APP fake payment server pyNow run the Flask server with flask run The server will normally be running at localhost This is to make sure there is no issue before we proceed to the next step Now we can dockerize the project Dockerizing the projectBut why Docker It helps you separate your applications from your infrastructure and helps in delivering code faster In this case Docker allows us to run your tests in containers as well as isolate your tests in development and deployment If it s your first time working with Docker I highly recommend you go through a quick tutorial and read some documentation about it Here are some great resources that helped me Docker Tutorial Docker curriculum For this step make sure you have docker and docker compose installed on your machine At the root of the project create a file named Dockerfile pull the official base imageFROM python alpine set work directoryWORKDIR app set environment variablesENV PYTHONDONTWRITEBYTECODE ENV PYTHONUNBUFFERED install psycopg dependenciesRUN apk update amp amp apk add gcc python dev musl dev install python dependenciesCOPY requirements txt app requirements txtRUN pip install upgrade pipRUN pip install no cache dir r requirements txt copy projectCOPY Here we started with an Alpine based Docker Image for Python It s a lightweight Linux distribution designed for security and resource efficiency After that we set a working directory followed by two environment variables PYTHONDONTWRITEBYTECODE to prevent Python from writing pyc files to disc PYTHONUNBUFFERED to prevent Python from buffering stdout and stderrAfter that we perform operations like Setting up environment variablesCopying there requirements txt file to our app path upgrading pip and installing the python package to run our applicationAnd last copying the entire projectAlso let s add a dockerignore file envvenv dockerignoreDockerfileOnce it s done create a file called docker compose yml Docker Compose is a great tool lt You can use it to define and run multi container Docker applications What do we need Well just a YAML file containing all the configuration of our application s services Then with the docker compose command we can create and start all those services version services api container name api build restart always env file env ports command gt sh c python manage py migrate amp amp gunicorn CoreRoot wsgi application bind volumes app flask api container name fake payment api build restart on failure ports command gt sh c flask run host port volumes app Now we can build the containers and start running the services docker compose up d buildTo make sure everything works well we can run the tests on the API and see how it goes docker compose exec api pytestGreat we can start integrating the Flask server to our API now Testing Flask server availabilityWe ll simply make a GET request on the inspect endpoint of the flask server And as we are running these tests into the docker environment we will be using the name of the flask container as a network host That s why into the env file we ve included the FAKE PAYMENT API fake payment api line In the settings py file import dotenv and force env vars loading at the beginning of the file from dotenv import load dotenvload dotenv ENV os environ get ENV DEV FAKE PAYMENT API os environ get FAKE PAYMENT API Inside the test viewsets py file of the cart application let s add a test to check the fake server is reachable Before this make sure to have the requests package installed and make sure to have it in your requirements txt file import requestsfrom django conf import settings def test inspect payment api client response requests get f http settings FAKE PAYMENT API inspect assert response status code assert response json available Rebuild the containers again and run the tests docker compose exec api pytestEverything should be green We can now add an endpoint to the flask API which will handle payments Payment featureIn a real world scenario you ll be integrating services like Stripe or Paypal APIs for such things For the sake of simplicity here we ll suppose that there is actually USD on the wallet the card used for the payment To make a payment then a request will be made on request payment endpoint of the Flask server This request should contain in the body the cart id and the amount to be debited We ll then compare the amount to the balance constant of to make sure the payment is doable If the amount is superior or equal to we authorize the payment and return the cart id and a payment status set to success of successful payment and failed for failed payment Here s the endpoint app Flask name CARD BALANCE app route request payment methods POST def request payment data request get json force True cart id data get cart id amount data get amount if cart id is None abort cart id This field is required if amount is None abort amount This field is required if not isinstance cart id int or not isinstance amount int abort type The fields should be integers if amount gt CARD BALANCE return jsonify cart id cart id payment status failed return jsonify cart id cart id payment status success And very simple we have a payment endpoint Let s integrate it to the cart application Integrating the payment APIA good practice when integrating API is to write a wrapper This is actually useful if the API doesn t provide a module in the language your are working with An API wrapper is a language specific package or kit that encapsulates multiple API calls to make complicated functions easy to use It creates an abstraction from the API endpoints providing readable methods or functions that can be reused anywhere in the code We ll be adding pay method on the Cart model But first of all let s write a test for that and make it crash pytest mark django dbdef test cart pay cart Cart total currency USD items number cart save assert cart total assert cart currency USD assert cart items number assert cart payment status pending cart pay assert cart payment status success Let s add the pay method on the Cart model to handle the payment def pay self initialized payment PaymentAPI payment initialized payment request payment cart id self pk amount self total assert payment cart id self pk self payment status payment payment status self save update fields payment status The last thing remaining is to add the PaymentAPI wrapper here a class Create a file called utils py at the root of the project and enter the following code from typing import Optionalfrom django conf import settingsimport requestsclass PaymentAPI API URL None def init self if settings ENV in PROD self API URL settings REAL PAYMENT API else self API URL settings FAKE PAYMENT API def request payment self cart id int amount int gt Optional dict data cart id cart id amount amount response requests post f http self API URL request payment json data return response json And here we have the wrapper As you can see we are rewriting the init method to assign a value to API URL And then we have the request payment method to make a request on the API and returns the response Run the tests again and everything should be green Let s finally add a test to check payment failure In this case the amount is superior to pytest mark django dbdef test cart pay failed cart Cart total currency USD items number cart save assert cart total assert cart payment status pending cart pay assert cart payment status failed And here it is We have write some external integration tests Github actionsAs a bonus part let s create CI CD pipeline using Github actions This is useful when you want to make sure you are deploying non failing software in a production environment GitHub actions are one of the greatest features of Github it helps you build test or deploy your application and more Here we ll create a YAML file named django yml to run some Django tests In the root project create a directory named github Inside that directory create another directory named workflows and create the django yml file Here s the code name Django CIon push branches main pull request branches main jobs test runs on ubuntu latest steps uses actions checkout v name Creating env file run touch env echo FAKE PAYMENT API fake payment api gt gt env echo FLASK APP fake payment server py gt gt env name Building containers run docker compose up d build name Running Tests run docker compose exec T api pytestBasically what we are doing here is setting rules for the GitHub action workflow installing dependencies and running the tests Make sure that this workflow is triggered only when there is a push or pull request on the main branchChoose ubuntu latest as the OS Next we create a env file which Docker will use to run the containers After that as we build the containers and run the tests And voilà Here s how you can start with Unit testing and Integration testing in your Django projects using Docker Flask and Github actions But let s quickly talk about good testing practices Best practicesThis part of the article I believe is the most important The world of Software Testing is not only limited to unit test and integration testing There is a lot more You can have EE End to end testing contract testing Exploratory Testing Acceptance testing and a lot more The good news about this is that it s up to you what testing strategy you are adopting and what type of tests to include as well Just make sure that the quality of the software at the end is always high You can learn more about testing in the article on the Martin Fowler blog which I recommend Now that there is some clarification about the testing terminology here are some good practices when writing tests Avoid Test duplication Avoid having the same tests at a different parts of the project Test one thing at time If you find yourself writing testing code unrelated to the role of what the function tests just write another testing function Tests should be fast To make sure you can have very fast tests focus on writing a lot of unit tests ConclusionIn this article we ve learned how to write unit and integrations tests for a Django application using Docker Flask and Github actions too And as every article can be made better so your suggestion or questions are welcome in the comment section Check the code of this tutorial here Article posted using bloggu io Try it for free 2021-12-12 13:07:45
海外TECH DEV Community Host React/Angular/Vue Site on Netlify https://dev.to/yashvant/host-reactangularvue-site-on-netlify-20gb Host React Angular Vue Site on NetlifyHosting your own site is really easy In this article we gonna see how can we host our front end in netlify Also hosting concept will be the same whether it is netlify or vercel or heroku If you learn any of them then you will be able to host your static site anywhere So let s startStep Create sample website maybe in react angular nextjs and push it in GitHubStep Sign up to NetlifyOnce you have singed up you will see the following screen Now click on the new site from git button After click on it you will see the following screen Step Select the platform where you have pushed your code in our case it will be github Once you select the platform you need to authorize the platform to access the repo of your site You will see the following screen once you click on github or any button You can search select any private public repo of your GitHub etc and can select it Once you select repo project to deploy you will see below screen Now you can select relevent branch of your project and you need to set command to build your project and you have to provide the path of your site build If you have react project the it will be npm run build and for angular it will be ng build you also can find build command in package json or just google it You will see below screen after you clicked on deploy site button Here my site name will be thirsty hoover netlify app you can also change the domain name or you can provide custom domain You can change domain name in domain setting which will be similar to below image So that s it how easy it was Note If you want to make update in your website you need to push latest code to your repo and you need to redeploy it you will find the option for redeployment in your project on netlify Thanks for reading let me know in comment section if there is anything which is difficult to understand 2021-12-12 13:03:25
ニュース BBC News - Home Covid: First people in UK hospitals with Omicron variant https://www.bbc.co.uk/news/uk-59627188?at_medium=RSS&at_campaign=KARANGA nadhim 2021-12-12 13:26:03
ニュース BBC News - Home Covid: Double-vaccinated contacts in England told to take daily rapid tests https://www.bbc.co.uk/news/uk-59628609?at_medium=RSS&at_campaign=KARANGA isolate 2021-12-12 13:35:34
ニュース BBC News - Home Omicron: What are the Covid self-isolation rules now? https://www.bbc.co.uk/news/explainers-54239922?at_medium=RSS&at_campaign=KARANGA omicron 2021-12-12 13:54:32
LifeHuck ライフハッカー[日本版] 小柄でも収納力抜群な「ミニマル財布」厳選3つ【今日のライフハックツールまとめ】 https://www.lifehacker.jp/2021/12/247662lht-conpact-wallet-matome.html 財布 2021-12-12 22:05:00

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)