Course Overview:
This course offers a comprehensive exploration of recommender systems, focusing on both theoretical foundations and practical applications. Through a combination of lectures, hands-on exercises, and real-world case studies, you will gain a deep understanding of the key principles, methodologies, and evaluation techniques that drive effective recommendation algorithms.
Course Objectives:
Acquire a solid understanding of recommender systems, including their significance and impact in various domains.
Explore different types of recommendation algorithms, such as collaborative filtering, content-based filtering, and hybrid approaches.
Study cutting-edge techniques, including deep learning, matrix factorization, and graph-based methods, for enhanced recommendation accuracy.
Gain hands-on experience with popular recommendation frameworks and libraries, and learn how to implement and evaluate recommendation models.
Investigate advanced topics in recommender systems, such as fairness, diversity, and explainability, and their ethical implications.
Analyze and discuss real-world case studies and research papers to gain insights into the challenges and future directions of recommender systems.
Course Structure:
Introduction to Recommender Systems
Collaborative Filtering Techniques
Content-Based Filtering and Hybrid Approaches
Matrix Factorization Methods
Deep Learning for Recommender Systems
Graph-Based Recommendation Approaches
Evaluation Metrics and Experimental Design
Ethical Considerations in Recommender Systems
Fairness, Diversity, and Explainability in Recommendations
Case Studies and Research Trends
Course Delivery:
The course will be delivered through a combination of lectures, interactive discussions, hands-on coding exercises, and group projects. You will have access to state-of-the-art resources, including relevant research papers, datasets, and software tools, to enhance your learning experience.
카카오 광고 플랫폼 MSA 적용 사례 및 API Gateway와 인증 구현에 대한 소개if kakao
황민호(robin.hwang) / kakao corp. DSP개발파트
---
최근 Spring Cloud와 Netflix OSS로 MSA를 구성하는 시스템 기반의 서비스들이 많아지는 추세입니다.
카카오에서도 작년에 오픈한 광고 플랫폼 모먼트에 Spring Cloud 기반의 MSA환경을 구성하여, API Gateway도 적용하였는데 1년 반 정도 운영한 경험을 공유할 예정입니다. 더불어 MSA 환경에서는 API Gateway를 통해 인증을 어떻게 처리하는지 알아보고 OAuth2 기반의 JWT Token을 이용한 인증에 대한 이야기도 함께 나눌 예정입니다.
[NDC18] 야생의 땅 듀랑고의 데이터 엔지니어링 이야기: 로그 시스템 구축 경험 공유Hyojun Jeon
NDC18에서 발표하였습니다. 현재 보고 계신 슬라이드는 1부 입니다.(총 2부)
- 1부 링크: https://goo.gl/3v4DAa
- 2부 링크: https://goo.gl/wpoZpY
(SlideShare에 슬라이드 300장 제한으로 2부로 나누어 올렸습니다. 불편하시더라도 양해 부탁드립니다.)
Course Overview:
This course offers a comprehensive exploration of recommender systems, focusing on both theoretical foundations and practical applications. Through a combination of lectures, hands-on exercises, and real-world case studies, you will gain a deep understanding of the key principles, methodologies, and evaluation techniques that drive effective recommendation algorithms.
Course Objectives:
Acquire a solid understanding of recommender systems, including their significance and impact in various domains.
Explore different types of recommendation algorithms, such as collaborative filtering, content-based filtering, and hybrid approaches.
Study cutting-edge techniques, including deep learning, matrix factorization, and graph-based methods, for enhanced recommendation accuracy.
Gain hands-on experience with popular recommendation frameworks and libraries, and learn how to implement and evaluate recommendation models.
Investigate advanced topics in recommender systems, such as fairness, diversity, and explainability, and their ethical implications.
Analyze and discuss real-world case studies and research papers to gain insights into the challenges and future directions of recommender systems.
Course Structure:
Introduction to Recommender Systems
Collaborative Filtering Techniques
Content-Based Filtering and Hybrid Approaches
Matrix Factorization Methods
Deep Learning for Recommender Systems
Graph-Based Recommendation Approaches
Evaluation Metrics and Experimental Design
Ethical Considerations in Recommender Systems
Fairness, Diversity, and Explainability in Recommendations
Case Studies and Research Trends
Course Delivery:
The course will be delivered through a combination of lectures, interactive discussions, hands-on coding exercises, and group projects. You will have access to state-of-the-art resources, including relevant research papers, datasets, and software tools, to enhance your learning experience.
카카오 광고 플랫폼 MSA 적용 사례 및 API Gateway와 인증 구현에 대한 소개if kakao
황민호(robin.hwang) / kakao corp. DSP개발파트
---
최근 Spring Cloud와 Netflix OSS로 MSA를 구성하는 시스템 기반의 서비스들이 많아지는 추세입니다.
카카오에서도 작년에 오픈한 광고 플랫폼 모먼트에 Spring Cloud 기반의 MSA환경을 구성하여, API Gateway도 적용하였는데 1년 반 정도 운영한 경험을 공유할 예정입니다. 더불어 MSA 환경에서는 API Gateway를 통해 인증을 어떻게 처리하는지 알아보고 OAuth2 기반의 JWT Token을 이용한 인증에 대한 이야기도 함께 나눌 예정입니다.
[NDC18] 야생의 땅 듀랑고의 데이터 엔지니어링 이야기: 로그 시스템 구축 경험 공유Hyojun Jeon
NDC18에서 발표하였습니다. 현재 보고 계신 슬라이드는 1부 입니다.(총 2부)
- 1부 링크: https://goo.gl/3v4DAa
- 2부 링크: https://goo.gl/wpoZpY
(SlideShare에 슬라이드 300장 제한으로 2부로 나누어 올렸습니다. 불편하시더라도 양해 부탁드립니다.)
Composition is a fundamental principle of functional programming, but how is it different from an object-oriented approach, and how do you use it in practice?
In this talk for beginners, we'll start by going over the basic concepts of functional programming, and then look at some different ways that composition can be used to build large things from small things.
After that, we'll see how composition is used in practice, beginning with a simple FizzBuzz example, and ending with a complete (object-free!) web application.
"손코딩뇌컴파일눈디버깅" 모임을 소개합니다.
백문이 불여일런, 트라이얼앤에러(Trial and Error) 식의 몹쓸 교육을 받아 온 개발자들이 코딩하기 전에 신중하고 꼼꼼하게 생각해보기란 쉽지 않습니다.
개발 시간 중 디버깅 시간이 절반 이상을 차지하고 있는 실정에 버그를 줄이기 위해 TDD니 유닛테스트니 많은 방법들이 개발되고 있지만 가장 일차적으로 중요한 것은 개발자들이 꼼꼼히 따져보는 것이 아니겠는지요?
미국의 선진 SW회사들은 이미 화이트보드에 PS문제를 푸는 것을 인터뷰 방식으로 채택하고 있습니다. 이는 이와 같은 풀이 방식이 개발자들의 기본 역량을 측정하기에 알맞은 지표라는 것이고, 개발자들이 기본적으로 갖춰야 할 역량이기도 하다는 것 입니다.
또한 자신의 생각을 명확하게 정리하고 다른 사람이 이해할 수 있도록 전달하는 Communication Skill 도 개발자가 갖춰야 할 역량 중 하나 입니다. 알고리즘을 어떻게 구현할 것인가를 팀원들과 소통하면서 자연스럽게 생각을 정리하고 전달하는 연습도 할 수 있습니다.
컴퓨터에 앉아 코딩하기 전 펜과 종이를 들고 눈과 머리와 손을 굴려 보시는 것은 어떠신지요??
Domain Driven Design with the F# type System -- F#unctional Londoners 2014Scott Wlaschin
(Video of these slides here http://fsharpforfunandprofit.com/ddd)
Statically typed functional programming languages like F# encourage a very different way of thinking about types. The type system is your friend, not an annoyance, and can be used in many ways that might not be familiar to OO programmers.
Types can be used to represent the domain in a fine-grained, self documenting way. And in many cases, types can even be used to encode business rules so that you literally cannot create incorrect code. You can then use the static type checking almost as an instant unit test — making sure that your code is correct at compile time.
In this talk, we'll look at some of the ways you can use types as part of a domain driven design process, with some simple real world examples in F#. No jargon, no maths, and no prior F# experience necessary.
Code, links to video, etc., at http://fsharpforfunandprofit.com/ddd
NEW AND IMPROVED - added sections on:
* why OO, not FP is scary
* designing with states and transitions
Machine Learning Model Serving with Backend.AIJeongkyu Shin
머신러닝 모델을 서비스 단에서 서빙하는 것은 손이 많이 갑니다.
서비스 과정을 편리하게 하기 위하여 TensorFlow serving 등 서빙 과정을 돕는 다양한 도구들이 공개되고 개발되고 있습니다만, 여전히 서빙 과정은 귀찮고 불편합니다. 이 세션에서는 Backend.AI 와 TensorFlow serving을 이용하여 간단하게 TensorFlow 모델을 서빙하는 법에 대해 다루어 봅니다.
Backend.AI 서빙 모드를 소개하고, 여러 TF serving 모델 등을 Backend.AI 로 서비스하는 과정을 통해 실제로 사용하는 법을 알아봅니다.
Serving the machine learning model at the service level is a lot of work. A variety of tools are being developed and released to facilitate the process of serving. TensorFlow serving is the greatest one for serving now, but the docker image baking-based serving process is not easy, not flexible and controllable enough. In this session, I will discuss how to simplify the serving process of TensorFlow models by using Backend.AI and TensorFlow serving.
I will introduce the Backend.AI serving mode (on the trunk but will be official since 1.6). After that, I will demonstrate how to use the Backend.AI serving mode that conveniently provides various TensorFlow models with TensorFlow serving on the fly.
넥슨코리아 사내 발표자료로 왓 스튜디오에서 파이썬으로 《야생의 땅: 듀랑고》 서버를 비롯한 여러가지 도구를 만든 경험을 공유합니다.
- 게임서버와 각종 툴, 테스트/빌드/배포 시스템을 만들 때 사용한 재료
- 파이썬 코드 품질 개선, 디버깅, 프로파일링, 최적화
- 파이썬 오픈소스 생태계와 왓 스튜디오가 하는 오픈소스 활동
[논문리뷰] Data Augmentation for 1D 시계열 데이터Donghyeon Kim
* 1D 시계열 신호에 Data Augmentation 을 진행한 연구논문을 간단하게 리뷰합니다.
* 웨어러블 가속도 신호와 뇌전도 신호에 대한 논문 3편을 준비했습니다.
* 광주과학기술원 인공지능 스터디 A-GIST 모임에서 발표했습니다.
* 발표 영상 (한국어, 유튜브): https://youtu.be/NpUMFKaDCU4
Advanced Python Testing Techniques (Pycon KR 2019) [Korean Ver.]Jaeman An
• 기본적인 테스트 구현하기
• Sure를 이용하여 더 직관적으로 테스트 코드를 구현하기
• Behavior Driven Development (BDD) 를 이용하여 더 재미있게 테스트 코드를 구현하기 • HTTP Mocking과 monkey patching으로 독립적인 테스트 코드 구현하기
• Randomized testing을 이용하여 온전한 테스트 코드 구현하기
• Benchmark testing을 이용하여 로직 시간 측정하기
• 간단한 pytest plugin 만들기
Composition is a fundamental principle of functional programming, but how is it different from an object-oriented approach, and how do you use it in practice?
In this talk for beginners, we'll start by going over the basic concepts of functional programming, and then look at some different ways that composition can be used to build large things from small things.
After that, we'll see how composition is used in practice, beginning with a simple FizzBuzz example, and ending with a complete (object-free!) web application.
"손코딩뇌컴파일눈디버깅" 모임을 소개합니다.
백문이 불여일런, 트라이얼앤에러(Trial and Error) 식의 몹쓸 교육을 받아 온 개발자들이 코딩하기 전에 신중하고 꼼꼼하게 생각해보기란 쉽지 않습니다.
개발 시간 중 디버깅 시간이 절반 이상을 차지하고 있는 실정에 버그를 줄이기 위해 TDD니 유닛테스트니 많은 방법들이 개발되고 있지만 가장 일차적으로 중요한 것은 개발자들이 꼼꼼히 따져보는 것이 아니겠는지요?
미국의 선진 SW회사들은 이미 화이트보드에 PS문제를 푸는 것을 인터뷰 방식으로 채택하고 있습니다. 이는 이와 같은 풀이 방식이 개발자들의 기본 역량을 측정하기에 알맞은 지표라는 것이고, 개발자들이 기본적으로 갖춰야 할 역량이기도 하다는 것 입니다.
또한 자신의 생각을 명확하게 정리하고 다른 사람이 이해할 수 있도록 전달하는 Communication Skill 도 개발자가 갖춰야 할 역량 중 하나 입니다. 알고리즘을 어떻게 구현할 것인가를 팀원들과 소통하면서 자연스럽게 생각을 정리하고 전달하는 연습도 할 수 있습니다.
컴퓨터에 앉아 코딩하기 전 펜과 종이를 들고 눈과 머리와 손을 굴려 보시는 것은 어떠신지요??
Domain Driven Design with the F# type System -- F#unctional Londoners 2014Scott Wlaschin
(Video of these slides here http://fsharpforfunandprofit.com/ddd)
Statically typed functional programming languages like F# encourage a very different way of thinking about types. The type system is your friend, not an annoyance, and can be used in many ways that might not be familiar to OO programmers.
Types can be used to represent the domain in a fine-grained, self documenting way. And in many cases, types can even be used to encode business rules so that you literally cannot create incorrect code. You can then use the static type checking almost as an instant unit test — making sure that your code is correct at compile time.
In this talk, we'll look at some of the ways you can use types as part of a domain driven design process, with some simple real world examples in F#. No jargon, no maths, and no prior F# experience necessary.
Code, links to video, etc., at http://fsharpforfunandprofit.com/ddd
NEW AND IMPROVED - added sections on:
* why OO, not FP is scary
* designing with states and transitions
Machine Learning Model Serving with Backend.AIJeongkyu Shin
머신러닝 모델을 서비스 단에서 서빙하는 것은 손이 많이 갑니다.
서비스 과정을 편리하게 하기 위하여 TensorFlow serving 등 서빙 과정을 돕는 다양한 도구들이 공개되고 개발되고 있습니다만, 여전히 서빙 과정은 귀찮고 불편합니다. 이 세션에서는 Backend.AI 와 TensorFlow serving을 이용하여 간단하게 TensorFlow 모델을 서빙하는 법에 대해 다루어 봅니다.
Backend.AI 서빙 모드를 소개하고, 여러 TF serving 모델 등을 Backend.AI 로 서비스하는 과정을 통해 실제로 사용하는 법을 알아봅니다.
Serving the machine learning model at the service level is a lot of work. A variety of tools are being developed and released to facilitate the process of serving. TensorFlow serving is the greatest one for serving now, but the docker image baking-based serving process is not easy, not flexible and controllable enough. In this session, I will discuss how to simplify the serving process of TensorFlow models by using Backend.AI and TensorFlow serving.
I will introduce the Backend.AI serving mode (on the trunk but will be official since 1.6). After that, I will demonstrate how to use the Backend.AI serving mode that conveniently provides various TensorFlow models with TensorFlow serving on the fly.
넥슨코리아 사내 발표자료로 왓 스튜디오에서 파이썬으로 《야생의 땅: 듀랑고》 서버를 비롯한 여러가지 도구를 만든 경험을 공유합니다.
- 게임서버와 각종 툴, 테스트/빌드/배포 시스템을 만들 때 사용한 재료
- 파이썬 코드 품질 개선, 디버깅, 프로파일링, 최적화
- 파이썬 오픈소스 생태계와 왓 스튜디오가 하는 오픈소스 활동
[논문리뷰] Data Augmentation for 1D 시계열 데이터Donghyeon Kim
* 1D 시계열 신호에 Data Augmentation 을 진행한 연구논문을 간단하게 리뷰합니다.
* 웨어러블 가속도 신호와 뇌전도 신호에 대한 논문 3편을 준비했습니다.
* 광주과학기술원 인공지능 스터디 A-GIST 모임에서 발표했습니다.
* 발표 영상 (한국어, 유튜브): https://youtu.be/NpUMFKaDCU4
Advanced Python Testing Techniques (Pycon KR 2019) [Korean Ver.]Jaeman An
• 기본적인 테스트 구현하기
• Sure를 이용하여 더 직관적으로 테스트 코드를 구현하기
• Behavior Driven Development (BDD) 를 이용하여 더 재미있게 테스트 코드를 구현하기 • HTTP Mocking과 monkey patching으로 독립적인 테스트 코드 구현하기
• Randomized testing을 이용하여 온전한 테스트 코드 구현하기
• Benchmark testing을 이용하여 로직 시간 측정하기
• 간단한 pytest plugin 만들기
Automating Django Functional Tests Using Selenium on CloudJonghyun Park
테스트 코드는 작성한 코드가 제대로 동작하고 있는지 점검하는 코드이다. 경우의 수가 많아질수록 사람이 직접 테스트를 하기 어려워지므로, 테스트 코드를 작성해서 최소한의 코드 안정성을 항상 담보해둘 수 있다. 리팩토링할 때는 테스트 코드를 통해 바뀐 코드에 문제가 있는지 금방 확인할 수 있어 특히 유용하다고 할 수 있다.
Django는 자체적으로 테스트를 위한 기능을 제공하고 있다. 파이썬의 unittest 모듈을 확장해서 유용한 기능을 제공하고, 테스트 유닛마다 DB를 새로 생성해 각 테스트 단위의 독립성을 보장한다. 이를 통해 모델(model), 폼(form), 뷰(view) 단위에서 단위 테스트(unit test)를 작성할 수 있다. 하지만 실제 웹상에서 사용자의 동작에 반응하는 기능 테스트(functional test)를 하기는 매우 어려우므로, 이를 위한 별도의 테스트 프레임워크가 필요하다.
Selenium은 브라우저상에서 직접 사용자의 동작을 에뮬레이션할 수 있는 프레임워크로, Python+Django 환경에서 기능 테스트를 수행하기에 알맞은 기능을 제공한다. 웹드라이버(web driver)를 이용해서 실제 브라우저를 동작시키고, 각 페이지의 DOM에 존재하는 객체를 실제로 조작하는 과정을 파이썬 코드로 작성할 수 있다. 개발자가 원하는 방식으로 다양한 기능 테스트 코드를 작성하고 실행함으로써, 웹페이지와 사용자의 상호작용을 직접 테스트할 수 있다. Django가 제공하는 테스트 프레임워크와 결합하면 보다 더 촘촘한 테스트 망을 구축할 수 있다.
Selenium을 이용한 기능 테스트를 작성할 때 가장 중요한 점 중 하나는, 조작하고자 하는 DOM 객체가 준비(ready)될 때까지 기다리는 것이다. 기능 테스트는 단위 테스트와는 다르게 실제 웹브라우저 상에서 이루어지므로, 브라우저에서 DOM이 작동하는 과정에 대한 고려가 필요하다. 예를 들어, 어떤 페이지를 방문하자마자 DOM 객체에 명령을 내린다고 생각해보자. CPU가 빨리 동작하는 환경이라면 다행히 문제가 없을 수도 있겠지만, 그렇지 않고 객체가 아직 준비되지 않았다면 'undefined'가 반환되면서 적절한 테스트가 불가능하게 될 수 있다. 이런 상황을 피하고자 Selenium은 DOM 객체가 로딩될 때까지 기다리는 두 가지 방법을 가지고 있다. Implicit Wait(암시적 기다림)와 Explicit Wait(명시적 기다림)라고 부르는 방법인데, 이번 세션에서는 이들 기다림과 그 차이에 대해 알아볼 것이다. 이 외에 테스트를 작성하면서 얻은 나름의 팁에 대해서도 최대한 설명하고자 한다.
잘 작성한 테스트가 있다고 하더라도 개발자가 매번 테스트하는 것은 여간 귀찮은 일이 아닐 수 없다. 그래서 우리가 사용하고 있는 테스트 자동화에 대해서도 간단하게 이야기하고자 한다. 작성된 Selenium 기능 테스트를 클라우드(AWS) 상에 올려두고, 단위 테스트는 Github 커밋이 올라올 때마다, 기능 테스트는 하루에 한 번 자동으로 수행되도록 하고 있다. 이 테스트 환경 구축에 관한 개인적인 경험을 나누려고 한다.
Baekjoon Online Judge(https://www.acmicpc.net) 에서 채점할 때 사용하는 샌드박스에 대한 간단한 설명을 담고 있습니다.
2012년 10월에 작성한 파일이라서 현재 사용하는 방식과는 많은 차이가 있고, 기초적인 수준의 샌드박싱을 다룹니다.
A creative copywriter with years of experience, excellent English and Spanish is looking for a job. Check out my portfolio - maybe I'm the one to fit your company in a best way!
More and more web projects require interfacing with the backend using a REST-ful interface. In this presentation we'll discuss Django-REST-Framework's features and walk through how to integrate it into your next project!
17. PortfolioPortfolio
# portfolio.py from http://nedbatchelder.com/text/st.html#7
class Portfolio(object):
"""간단한 주식 포트폴리오"""
def __init__(self):
# stocks is a list of lists:
# [[name, shares, price], ...]
self.stocks = []
def buy(self, name, shares, price):
"""name 주식을 shares 만큼 주당 price 에 삽니다"""
self.stocks.append([name, shares, price])
def cost(self):
"""이 포트폴리오의 총액은 얼마일까요?"""
amt = 0.0
for name, shares, price in self.stocks:
amt += shares * price
return amt
18. 첫번째첫번째 테스트테스트 -- 쉘쉘
Python 3.4.0 (default, Jun 19 2015, 14:20:21)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more informati
>>> from portfolio import Portfolio
>>> p = Portfolio()
>>> print(p.cost())
0.0
>>> p.buy('Google', 100, 176.48)
>>> p.cost()
17648.0
>>> p.buy('Yahoo', 100, 36.15)
>>> p.cost()
21263.0
Good
테스트 했어요!
Bad
다시 테스트 하려면?
직접 입력
그래서 잘 된건가?
19. 두번째두번째 테스트테스트 -- 기대값기대값
from portfolio import Portfolio
p = Portfolio()
print("Empty portfolio cost: %s, should be 0.0" % p.cost())
p.buy('Google', 100, 176.48)
print("With 100 Google @ 176.48: %s, should be 17648.0" % p.cost())
p.buy('Yahoo', 100, 36.15)
print("With 100 Yahoo @ 36.15: %s, should be 21263.0" % p.cost())
Good
테스트 했음
다시 테스트 할 수 있음
잘 된건지 확인 가능
Bad
눈으로 확인 해야 함
Empty portfolio cost: 0.0, should be 0.0
With 100 Google @ 176.48: 17648.0, should be 17648.0
With 100 Yahoo @ 36.15: 21263.0, should be 21263.0
20. 세번째세번째 테스트테스트 -- 결과결과 확인확인
from portfolio import Portfolio
p = Portfolio()
print("Empty portfolio cost: %s, should be 0.0" % p.cost())
p.buy('Google', 100, 176.48)
assert p.cost() == 17649.0 # Failed
print("With 100 Google @ 176.48: %s, should be 17648.0" % p.cost())
p.buy('Yahoo', 100, 36.15)
assert p.cost() == 21263.0
print("With 100 Yahoo @ 36.15: %s, should be 21263.0" % p.cost())
Good
다시 테스트 할 수 있음
잘 된건지 자동으로 확인 가
능
Bad
왜 틀렸는지 알기 힘듬
두번째 테스트가 실행 되지
않음
Empty portfolio cost: 0.0, should be 0.0
Traceback (most recent call last):
File "portfolio_test2.py", line 6, in <module>
assert p.cost() == 17649.0 # Failed
AssertionError
29. First UnittestFirst Unittest
# portfolio_test3.py
import unittest
from portfolio import Portfolio
class PortfolioTest(unittest.TestCase):
def test_google(self):
p = Portfolio()
p.buy("Google", 100, 176.48)
self.assertEqual(17648.0, p.cost())
if __name__ == '__main__':
unittest.main()
$ python portfolio_test3.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
31. 테스트테스트 추가추가
# portfolio_test4.py
import unittest
from portfolio import Portfolio
class PortfolioTestCase(unittest.TestCase):
def test_google(self):
p = Portfolio()
p.buy("Goole", 100, 176.48)
self.assertEqual(17648.0, p.cost())
def test_google_yahoo(self):
p = Portfolio()
p.buy("Google", 100, 176.48)
p.buy("Yahoo", 100, 36.15)
self.assertEqual(21264.0, p.cost()) # 21263.0
if __name__ == '__main__':
unittest.main()
32. UnittestUnittest 실패실패
$ python portfolio_test4.py
.F
======================================================================
FAIL: test_google_yahoo (__main__.PortfolioTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "portfolio_test4.py", line 15, in test_google_yahoo
self.assertEqual(21264.0, p.cost())
AssertionError: 21264.0 != 21263.0
----------------------------------------------------------------------
Ran 2 tests in 0.005s
FAILED (failures=1)
Good
테스트 실패가 다른 테스트에 영향을 미치지 않음
실패한 위치와 이유를 알 수 있음
34. TestTest 고르기고르기
$ python portfolio_test4.py PortfolioTestCase.test_google_yahoo
F
======================================================================
FAIL: test_google_yahoo (__main__.PortfolioTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "portfolio_test4.py", line 15, in test_google_yahoo
self.assertEqual(21264.0, p.cost())
AssertionError: 21264.0 != 21263.0
----------------------------------------------------------------------
Ran 1 test in 0.005s
FAILED (failures=1)
Good
원하는 테스트만 빠르게 실행 해 볼 수 있음
출력이 간단해짐
36. 테스트테스트 한꺼번에한꺼번에 실행하기실행하기
$ python -m unittest discover --help
Usage: python -m unittest discover [options]
Options:
,,,
-s START, --start-directory=START
Directory to start discovery ('.' default)
-p PATTERN, --pattern=PATTERN
Pattern to match tests ('test*.py' default)
-t TOP, --top-level-directory=TOP
Top level directory of project (defaults to start
directory)
$ python -m unittest discover
----------------------------------------------------------------------
Ran 15 tests in 0.130s
OK
Good
복수개의 파일을 한꺼번에 테스트를 실행 할 수있음
38. Portfolio -Portfolio - 타입타입 확인확인
class Portfolio(object):
"""간단한 주식 포트폴리오"""
def __init__(self):
# stocks is a list of lists:
# [[name, shares, price], ...]
self.stocks = []
def buy(self, name, shares, price):
"""name 주식을 shares 만큼 주당 price 에 삽니다"""
self.stocks.append([name, shares, price])
if not isinstance(shares, int):
raise Exception("shares must be an integer")
def cost(self):
"""이 포트폴리오의 총액은 얼마일까요?"""
amt = 0.0
for name, shares, price in self.stocks:
amt += shares * price
return amt
39. ExceptionException 을을 발생시키는발생시키는 테스트테스트
import unittest
from portfolio import Portfolio
class PortfolioTestCase(unittest.TestCase):
def test_google(self):
p = Portfolio()
p.buy("Goole", "many", 176.48)
self.assertEqual(17648.0, p.cost())
if __name__ == '__main__':
unittest.main()
$ python ./portfolio_test5.py
E
======================================================================
ERROR: test_google (__main__.PortfolioTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "./portfolio_test5.py", line 8, in test_google
p.buy("Goole", "many", 176.48)
File "/home/leclipse/git/pycon-testing/unit_test/portfolio.py", line 14, in buy
raise Exception("shares must be an integer")
Exception: shares must be an integer
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
40. ExceptionException 을을 테스트테스트
import unittest
from portfolio import Portfolio
class PortfolioTestCase(unittest.TestCase):
def test_google(self):
p = Portfolio()
with self.assertRaises(Exception) as context:
p.buy("Goole", "many", 176.48)
self.assertTrue("shares must be an integer", context.exception)
if __name__ == '__main__':
unittest.main()
$ python ./portfolio_test6.py
.
----------------------------------------------------------------------
Ran 1 test in 0.004s
OK
48. 반복되는반복되는 테스트테스트 실행하기실행하기
import unittest
class NumberTest(unittest.TestCase):
def test_even(self):
for i in range(0, 6):
self.assertEqual(i % 2, 0)
def test_even_with_subtest(self):
for i in range(0, 6):
with self.subTest(i=i):
self.assertEqual(i % 2, 0)
unittest.main()
0 부터 5 까지 짝수인지를 테스트 합니다.
49. SubtestSubtest 실행실행 결과결과
$ python ./subtest.py
F
======================================================================
FAIL: test_even (__main__.NumberTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "./subtest.py", line 7, in test_even
self.assertEqual(i % 2, 0)
AssertionError: 1 != 0
======================================================================
FAIL: test_even_with_subtest (__main__.NumberTest) (i=1)
----------------------------------------------------------------------
Traceback (most recent call last):
File "./subtest.py", line 12, in test_even_with_subtest
self.assertEqual(i % 2, 0)
AssertionError: 1 != 0
======================================================================
FAIL: test_even_with_subtest (__main__.NumberTest) (i=3)
----------------------------------------------------------------------
Traceback (most recent call last):
File "./subtest.py", line 12, in test_even_with_subtest
self.assertEqual(i % 2, 0)
AssertionError: 1 != 0
======================================================================
FAIL: test_even_with_subtest (__main__.NumberTest) (i=5)
----------------------------------------------------------------------
Traceback (most recent call last):
File "./subtest.py", line 12, in test_even_with_subtest
self.assertEqual(i % 2, 0)
AssertionError: 1 != 0
----------------------------------------------------------------------
Ran 2 tests in 0.001s
FAILED (failures=4)
Good
중단 되지 않고 모두 테
스트
변경 되는 값을 확인 할
수 있다.
python 3.4 에 추가 되었음
58. unittest.mockunittest.mock
파이썬 표준 라이브러리 (3.3 부터)
이전 버젼은 pip install mock
python object 들을 동적으로 대체하고
사용 결과를 확인 하기 위한 다양한 기능들을 제공
의존성이 있는것들을 실제로 실행시키지 말고 호출 여
부, 인터페이스만 확인 하자
59. Monkey PatchMonkey Patch
>>> class Class():
... def add(self, x, y):
... return x + y
...
>>> inst = Class()
>>> def not_exactly_add(self, x, y):
... return x * y
...
>>> Class.add = not_exactly_add
>>> inst.add(3, 3)
9
런타임에 클래스, 함수등을 변경하는 것
60. mockmock 사용사용 예예
>>> from unittest.mock import MagicMock
>>> thing = ProductionClass()
>>> thing.method = MagicMock(return_value=3)
>>> thing.method(3, 4, 5, key='value')
3
>>> thing.method.assert_called_with(3, 4, 5, key='value')
thing.method 가 monkey patch 되었음
이를 테스트에 어떻게 활용 할까?
61. test rmtest rm
# Rm.py
import os
def rm(filename):
os.remove(filename)
# test_rm.py
from Rm import rm
class RmTestCase(unittest.TestCase):
tmpfilepath = os.path.join(tempfile.gettempdir(), 'temp-testfile')
def setUp(self):
with open(self.tmpfilepath, 'w') as f:
f.write('Delete me!')
def tearDown(self):
if os.path.isfile(self.tmpfilepath):
os.remove(self.tmpfilepath)
def test_rm(self):
rm(self.tmpfilepath)
self.assertFalse(os.path.isfile(self.tmpfilepath), 'Failed to remove the file')
62. 첫번째첫번째 Mock testMock test
import os.path
import tempfile
import unittest
from unittest import mock
from Rm import rm
class RmTestCase(unittest.TestCase):
@mock.patch('Rm.os')
def test_rm(self, mock_os):
rm('/tmp/tmpfile')
mock_os.remove.assert_called_with('/tmp/tmpfile')
if __name__ == '__main__':
unittest.main()
Good
setUp, tearDown 이 없어졌음
실제로 os.remove 이 호출되지 않았음
os.remove 가 호출되었는지는 확인 했음
test_rm
Rm.rm
os.remove
mock_os.
remove
63. 어떻게어떻게 된걸까된걸까??
# Rm.py
import os
def rm(filename):
print(os.remove)
os.remove(filename)
$ python ./test_rm.py
<built-in function remove>
.
----------------------------------------------------------------------
Ran 1 test in 0.007s
OK
$ python ./mock_rm.py
<MagicMock name='os.remove' id='139901238735592'>
.
----------------------------------------------------------------------
Ran 1 test in 0.002s
OK
64. MockMock 대상이대상이 되는되는 것것
시간이 오래 걸리는 것
값이 변하는 것
상태가 유지 되는 것
(다른 테스트에 영향을 주는 것)
시스템 콜
네트워크로 연결된 것
준비하기 복잡한 것
65. Realworld exampleRealworld example
class SimpleFacebook(object):
def __init__(self, oauth_token):
self.graph = facebook.GraphAPI(oauth_token)
def post_message(self, message):
self.graph.put_object('me', 'feed', message=message)
class SimpleFacebookTestCase(unittest.TestCase):
@mock.patch.object(facebook.GraphAPI, 'put_object', autospect=True)
def test_post_message(self, mock_put_object):
sf = SimpleFacebook('fake oauth token')
sf.post_message('Hello World!')
mock_put_object.assert_called_with('me', 'feed', message='Hello World!')
facebook 이 다운되어도 내 테스트는 실패 하지 않는다.
66. Mock -Mock - 조건조건 확인확인
# 24시간이 지난 경우에만 삭제 합니다.
def rm(filename):
file_modified = datetime.datetime.fromtimestamp(os.path.getmtime(filename
if datetime.datetime.now() - file_modified > datetime.timedelta(hours=24)
os.remove(filename)
class RmTestCase(unittest.TestCase):
@mock.patch('__main__.os')
def test_rm(self, mock_os):
mock_os.path.getmtime.return_value = time.time()
rm('/tmp/tmpfile')
self.assertFalse(mock_os.remove.called)
mock_os.path.getmtime.return_value = time.time() - 86400*2
rm('/tmp/tmpfile')
mock_os.remove.assert_called_with('/tmp/tmpfile')
보통 분기를 따라가면서 테스트 하기는 쉽지 않음
67. MockMock 예외예외
# Rm.py
class MyError(Exception):
pass
def rm(filename):
try:
os.remove(filename)
except FileNotFoundError:
raise MyError
class RmTestCase(unittest.TestCase):
@mock.patch.object(os, 'remove', side_effect=FileNotFoundError)
def test_rm_without_file(self, mock_remove):
with self.assertRaises(MyError) as context:
rm('not_exist_file')
Exception 이 발생되는 경우를 만들지 않아도 됨
69. Integration TestIntegration Test
테스트 환경이 동작하지 않아요.
프로덕션 환경이랑 테스트 환경이 다른 것 같은데요?
저 지금 테스트 환경에 배포 해도 돼요?
제가 지금 테스트 하고 있으니, 다른 분은 나중에 테스트 해주세
요.
다른 모듈,서비스 등을 붙여서 그 관계에서의
문제점을 확인하는 과정
77. docker-compose updocker-compose up
Good
Localhost 에서 모든 테스트가 가능
Host 에 영향 없음
CI 에서도 실행 가능
$ docker-compose up
redis_1 | 1:M 28 Aug 06:05:53.613 # Server started, Redis version 3.0.3
redis_1 | 1:M 28 Aug 06:05:53.613 # WARNING overcommit_memory is set to 0! Background save may fai
redis_1 | 1:M 28 Aug 06:05:53.613 # WARNING you have Transparent Huge Pages (THP) support enabled
redis_1 | 1:M 28 Aug 06:05:53.613 # WARNING: The TCP backlog setting of 511 cannot be enforced bec
redis_1 | 1:M 28 Aug 06:05:53.614 * DB loaded from disk: 0.000 seconds
redis_1 | 1:M 28 Aug 06:05:53.614 * The server is now ready to accept connections on port 6379
client_1 | .
client_1 | ----------------------------------------------------------------------
client_1 | Ran 1 test in 1.003s
client_1 |
client_1 | OK
integrationtest_client_1 exited with code 0
Gracefully stopping... (press Ctrl+C again to force)
Stopping integrationtest_redis_1... done
$
82. Test Pycon 2015Test Pycon 2015
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class PyconUserTestCase(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def test_log_in_pycon_2015(self):
driver = self.driver
driver.get("http://www.pycon.kr/2015/login")
# US1 : 사용자는 Pycon Korea 2015 페이지 제목을 볼 수 있습니다.
self.assertIn("PyCon Korea 2015", driver.title)
# US2 : 사용자는 로그인을 할 수 있습니다.
# 로그인 하면 "One-time login token ..." 메시지를 볼 수 있습니다.
elem = driver.find_element_by_id("id_email")
elem.send_keys("email-me@gmail.com")
elem.send_keys(Keys.RETURN)
self.assertIn("One-time login token url was sent to your mail",
driver.page_source)
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main(warnings='ignore')