SlideShare a Scribd company logo
型ヒントとテストを追加し
ている話
誰に向けて話すのか
型ヒント、テストの経験が無い or 億劫な人。
話す事
● ツールの紹介、どのように使っているか
● 型ヒント
● テスト
話さない事
テストの書き方
お前誰よ
名前: Makoto Mochizuki
所属: 株式会社DataSign
居住地: 静岡県静岡市
型ヒント、テストの経験: 1年半くらい
プロダクトの宣伝&紹介
技術スタック
● Django
● Celery
● Crawler(requests + Headless Chrome)
プロダクトの特徴
● 管理画面
○ スキャンしたいサイトを入力
○ スキャンしたサイトを管理
● クローラー
○ Webサイトをクロール
● サービス解析機能
○ 入手した複数のHARを使って外部サービスを検出
型ヒント
簡単に型ヒントをおさらい
型ヒント
# before
def sum(num, num2):
return num1 + num2
# after
def sum(num1: int, num2: int) -> int:
return num1 + num2
実行エラーをなんとかしたい
型ヒント
# cat test.py
def sum(num1: int, num2: int) -> int:
return num1 + num2
sum(1, "1") # error
mypy
CI に組み込もう!
型ヒント
# cat test.py
def sum(num1: int, num2: int) -> int:
return num1 + num2
sum(1, "1") # error
# mypy test.py
error: Argument 2 to "sum" has incompatible type "str";
expected "int"
既存コードに型ヒントついてないよ...
型ヒント
既存コードに型ヒントついてないよ...
→ 自動で型ヒントつけるツールあります
型ヒント
型ヒント自動生成ツール
● PyAnnotate
● MonkeyType
○ こっちを使いました(特に理由は無い)
■ mypyのドキュメントに初めに書いてあった
■ MonkeyType の方がスター数が多かった
型ヒント
プロダクトの問題を型ヒントで解決していく
プロダクト問題を型ヒントで解決していく
● 引数の数が多い
○ 何があるか把握にしくい
○ どんな型か把握しにくい
● dictの構造が判り辛い
型ヒント
● 引数の数が多い
○ 何があるか把握にしくい
○ どんな型か把握しにくい
→ dataclassで用途ごとに引数をまとめる
型ヒント
from dataclasses import dataclass
@dataclass
class Item:
name: str
price: int
item = Item(name="item", price=1)
print(item.name) # item
print(item.price) # 1
# dataclass を使った場合
@dataclass
class Item:
name: str
price: int
@dataclass
class Person:
name: str
age: int
def create(item: Item, person: Person):
create_x(item)
create_y(item, person)
型ヒント
# dataclass を使わない場合
def create(item_name: str, item_price: int, person_name: str, person_age: int):
create_x(item_name, item_price)
create_y(item_name, item_price, person_name, person_age)
dataclass と mypy を組み合わせる
型ヒント
# cat test.py
from dataclasses import dataclass
@dataclass
class Item:
name: str
price: int
item = Item(name=1, price=1)
# mypy test.py
error: Argument "name" to "Item" has incompatible
type "int"; expected "str"
dataclass ≠ dict
型ヒント
item = Item(name="item", unit_price=1)
item_dict = {“name”: “item”, “unit_price”: 1}
item == item_dict # False
型ヒント
● dictの構造が判り辛い
→ TypedDict を使う
型ヒント
# とても辛い
x: dict[str, Union[int, dict[str, Optional[str]]]]
x = {"key1": 1, "key2": {"key3": "val"}}
型ヒント TIPS
TypedDict from typing import TypedDict
class ItemDict(TypedDict):
name: str
price: float
item_dict = ItemDict(name="item", price=1)
item_dict == {'name': 'item', 'price': 1} #True
TypedDict と mypy を組み合わせる
型ヒント
# mypy test.py
Incompatible types (expression has type "int",
TypedDict item "name" has type "str")
# cat test.py
from typing import TypedDict
class Item(TypedDict):
name: str
price: int
item = Item(name=1, price=1)
型ヒント
class Item(TypedDict):
name: str
price: float
Item(name="name", hoge="hoge")
# mypy test.py
Extra key 'hoge' for TypedDict "Item"
型ヒント
Typed Dictだと何が嬉しいのか
- データの参照方法が変わらない
- item[“name”] のまま
- celery にタスクを投げる時そのまま渡せる
- accept_content = [“pickle”] は避けたい
型ヒント
Q: 全部 Typed Dict にするの辛いんだけど?
A: 弊チームも全部 Typed Dict にしてません。他は dict にしてます。
ちなみに
型ヒント
HARなどの階層が深いDictも
TypedDict 使えます
型ヒント
そもそもHARとは?
HTTP Archive format (HAR)は、ウェブブラウザとサイトと
のやり取りを記録するためのJSON形式のアーカイブファイ
ルフォーマットです。これらのファイルの一般的な拡張子
は.harです。
https://en.wikipedia.org/wiki/HAR_(file_format)
https://gist.github.com/igrigorik/3
495174
型ヒント
class Item(TypedDict):
name: str
price: float
class Person(TypedDict):
name: str
item: Item
class Data(TypedDict):
person: list[Person]
json_str = """
{
"person":[
{
"name":"person1",
"item":{"name": "item1", "price": 1.1}
},
{
"name": "person1",
"item": {"name": "item2", "price": 1.1}
}
]
}
"""
data: Data = json.loads(json_str)
● とりあえずmypy を入れる
● 既存コードが多い場合は 自動で型ヒントをつけるツ
ールを検討
● dataclass, Typed Dict を使ってデータをまとめていく
● とりあえずmypy を入れる
型ヒントまとめ
テストを書く
ツール
● Testing tool: pytest
● pytest-plugin: pytest-django
● カバレッジ計測: pytest-cov
ちなみに
celeryで実行するタスクは、celery経由でテストしていません。
pytest でテストしています。
テストを書く
最終的にプロダクトの機能追加や修正を容易にするのが目標
手段としてカバレッジをあげる事が目標、しかし単にカバレッジを上げるだけだ
と機能追加や修正が容易になるわけではない。
どこからテストを書くか
どこからテストを書くか
● 管理画面
○ スキャンしたいサイトを入力
○ スキャンしたサイトを管理
● クローラー
○ Webサイトをクロール
● サービス解析機能
○ 入手した複数のHARを使って外部サービスを検出
どこからテストを書くか
● 管理画面
○ スキャンしたいサイトを入力
○ スキャンしたサイトを管理
● クローラー
○ Webサイトをクロール
● サービス解析機能
○ 入手した複数のHARを使って外部サービスを検出
一般的なViewの機能
プロダクトの肝となる機能は無い
どこからテストを書くか
● 管理画面
○ スキャンしたいサイトを入力
○ スキャンしたサイトを管理
● クローラー
○ Webサイトをクロール
● サービス解析機能
○ 入手した複数のHARを使って外部サービスを検出
クローラー、解析機能が重要
どうやってテストを書くか
どうやってテストを書くか
● メソッドのユースケースごとに書く
○ カバレッジはそこまで気にしない
● テスト対象の内部で実行しているメソッドにテストがない時
○ とりあえず放置
○ リファクタ or 機能追加で変更する時に書く
● リファクタ or 機能追加の時はテストを追加してから
カバレッジ 40% → 80% に🎉
1年程テストを書いた感想
1年ほどテストを書いた感想
● テスト怖い → テスト安心
● 自分のコードの質を確認する1つの指標になった
○ テスト容易性
● 失敗したこと
○ yaml などでデータ生成を行う
■ なぜ
● どのようなデータでテストしているのか不透明
● カラム変更の追従が辛い
■ どう修正したか
● コードでデータ生成する
テストまとめ
● とりあえず pytest を入れる
● プロダクトの肝となる機能からテストを追加する
● 機能改修する部分だけテストを追加すると良いかも
● テストは怖くない
おわり

More Related Content

Similar to 型ヒントとテストを追加している話

Django tutorial 2009
Django tutorial 2009Django tutorial 2009
Django tutorial 2009
Ferenc Szalai
 
Structured web programming
Structured web programmingStructured web programming
Structured web programming
ahfast
 
BDD Testing and Automating from the trenches - Presented at Into The Box June...
BDD Testing and Automating from the trenches - Presented at Into The Box June...BDD Testing and Automating from the trenches - Presented at Into The Box June...
BDD Testing and Automating from the trenches - Presented at Into The Box June...
Gavin Pickin
 
ITB2016 -BDD testing and automation from the trenches
ITB2016 -BDD testing and automation from the trenchesITB2016 -BDD testing and automation from the trenches
ITB2016 -BDD testing and automation from the trenches
Ortus Solutions, Corp
 
Python Novice to Ninja
Python Novice to NinjaPython Novice to Ninja
Python Novice to Ninja
Al Sayed Gamal
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
MuskanSony
 
Boost.Dispatch
Boost.DispatchBoost.Dispatch
Boost.Dispatch
Joel Falcou
 
Intro to object oriented programming
Intro to object oriented programmingIntro to object oriented programming
Intro to object oriented programming
David Giard
 
Visual Basic 6.0
Visual Basic 6.0Visual Basic 6.0
Visual Basic 6.0
Palitha Baddegama
 
09 Methods
09 Methods09 Methods
09 Methods
maznabili
 
The Ring programming language version 1.10 book - Part 39 of 212
The Ring programming language version 1.10 book - Part 39 of 212The Ring programming language version 1.10 book - Part 39 of 212
The Ring programming language version 1.10 book - Part 39 of 212
Mahmoud Samir Fayed
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
PranavSB
 
ADLAB.pdf
ADLAB.pdfADLAB.pdf
ADLAB.pdf
ycpthalachira
 
Python for web security - beginner
Python for web security - beginnerPython for web security - beginner
Python for web security - beginner
Sanjeev Kumar Jaiswal
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)
Gianluca Padovani
 
Software testing lab manual
Software testing lab manualSoftware testing lab manual
Software testing lab manual
Tanzeem Syed
 
Fast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDBFast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDB
MongoDB
 
Python-oop
Python-oopPython-oop
Python-oop
RTS Tech
 
C#
C#C#
C#
Joni
 
Introduction to TypeScript
Introduction to TypeScriptIntroduction to TypeScript
Introduction to TypeScript
Jeremy Likness
 

Similar to 型ヒントとテストを追加している話 (20)

Django tutorial 2009
Django tutorial 2009Django tutorial 2009
Django tutorial 2009
 
Structured web programming
Structured web programmingStructured web programming
Structured web programming
 
BDD Testing and Automating from the trenches - Presented at Into The Box June...
BDD Testing and Automating from the trenches - Presented at Into The Box June...BDD Testing and Automating from the trenches - Presented at Into The Box June...
BDD Testing and Automating from the trenches - Presented at Into The Box June...
 
ITB2016 -BDD testing and automation from the trenches
ITB2016 -BDD testing and automation from the trenchesITB2016 -BDD testing and automation from the trenches
ITB2016 -BDD testing and automation from the trenches
 
Python Novice to Ninja
Python Novice to NinjaPython Novice to Ninja
Python Novice to Ninja
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
 
Boost.Dispatch
Boost.DispatchBoost.Dispatch
Boost.Dispatch
 
Intro to object oriented programming
Intro to object oriented programmingIntro to object oriented programming
Intro to object oriented programming
 
Visual Basic 6.0
Visual Basic 6.0Visual Basic 6.0
Visual Basic 6.0
 
09 Methods
09 Methods09 Methods
09 Methods
 
The Ring programming language version 1.10 book - Part 39 of 212
The Ring programming language version 1.10 book - Part 39 of 212The Ring programming language version 1.10 book - Part 39 of 212
The Ring programming language version 1.10 book - Part 39 of 212
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
 
ADLAB.pdf
ADLAB.pdfADLAB.pdf
ADLAB.pdf
 
Python for web security - beginner
Python for web security - beginnerPython for web security - beginner
Python for web security - beginner
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)
 
Software testing lab manual
Software testing lab manualSoftware testing lab manual
Software testing lab manual
 
Fast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDBFast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDB
 
Python-oop
Python-oopPython-oop
Python-oop
 
C#
C#C#
C#
 
Introduction to TypeScript
Introduction to TypeScriptIntroduction to TypeScript
Introduction to TypeScript
 

Recently uploaded

原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
ydzowc
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
Gino153088
 
Software Quality Assurance-se412-v11.ppt
Software Quality Assurance-se412-v11.pptSoftware Quality Assurance-se412-v11.ppt
Software Quality Assurance-se412-v11.ppt
TaghreedAltamimi
 
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
shadow0702a
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
KrishnaveniKrishnara1
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
gowrishankartb2005
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
Divyanshu
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
co23btech11018
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
171ticu
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
abbyasa1014
 
An improved modulation technique suitable for a three level flying capacitor ...
An improved modulation technique suitable for a three level flying capacitor ...An improved modulation technique suitable for a three level flying capacitor ...
An improved modulation technique suitable for a three level flying capacitor ...
IJECEIAES
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
ElakkiaU
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
VANDANAMOHANGOUDA
 
artificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptxartificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptx
GauravCar
 
integral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdfintegral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdf
gaafergoudaay7aga
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
Hitesh Mohapatra
 
Data Control Language.pptx Data Control Language.pptx
Data Control Language.pptx Data Control Language.pptxData Control Language.pptx Data Control Language.pptx
Data Control Language.pptx Data Control Language.pptx
ramrag33
 
Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...
bijceesjournal
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
Prakhyath Rai
 
CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1
PKavitha10
 

Recently uploaded (20)

原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
 
Software Quality Assurance-se412-v11.ppt
Software Quality Assurance-se412-v11.pptSoftware Quality Assurance-se412-v11.ppt
Software Quality Assurance-se412-v11.ppt
 
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
 
An improved modulation technique suitable for a three level flying capacitor ...
An improved modulation technique suitable for a three level flying capacitor ...An improved modulation technique suitable for a three level flying capacitor ...
An improved modulation technique suitable for a three level flying capacitor ...
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
 
artificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptxartificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptx
 
integral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdfintegral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdf
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
 
Data Control Language.pptx Data Control Language.pptx
Data Control Language.pptx Data Control Language.pptxData Control Language.pptx Data Control Language.pptx
Data Control Language.pptx Data Control Language.pptx
 
Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
 
CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1
 

型ヒントとテストを追加している話

Editor's Notes

  1. テスト怖い 実装の変更とテストも変更しないといけない、億劫。 でも、安心。 自分では気づかないところでテストが失敗。デグレが起こっていた可能性。