index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
64,187
SUPEngineer/webAuto
refs/heads/master
/testing/test_js.py
# @Time : 2021/2/24 16:08 # @Author : qiulingfeng # @File : test_js.py from time import sleep from selenium.webdriver.common.by import By from testing.base import Base class TestJS(Base): def test_js(self): self.driver.get('http://www.baidu.com') self.driver.find_element(By.ID, 'kw').send_keys('selenium测试') # 执行JS脚本 element = self.driver.execute_script("return document.getElementById('su')") element.click() self.driver.execute_script("document.documentElement.scrollTop=10000") sleep(3) # 输出页面加载时间信息 print(self.driver.execute_script('return JSON.stringify(performance.timing)')) # 修改12306的出发时间 def test_dateTime(self): self.driver.get('https://www.12306.cn/index/') js_scrip = "a=document.getElementById('train_date');a.removeAttribute('readonly');a.value='2020-02-03'" self.driver.execute_script(js_scrip) sleep(10) print(self.driver.execute_script("return document.getElementById('train_date').value"))
{"/testing/test_file.py": ["/testing/base.py"], "/testing/test_js.py": ["/testing/base.py"], "/testing/test_alert.py": ["/testing/base.py"], "/testing/test_frame.py": ["/testing/base.py"], "/testing/addStuff/page/main_page.py": ["/testing/addStuff/page/address_page.py"], "/testing/addStuff/testCase/test_addStuff.py": ["/testing/addStuff/page/main_page.py"], "/testing/test_windows.py": ["/testing/base.py"]}
64,188
SUPEngineer/webAuto
refs/heads/master
/testing/test_ActionChains.py
import time import pytest from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys class TestActionChains: def setup(self): self.driver = webdriver.Chrome() self.driver.maximize_window() self.driver.implicitly_wait(3) def teardown(self): self.driver.quit() @pytest.mark.skip def test_clicks(self): self.driver.get('http://sahitest.com/demo/clicks.htm') click_ele = self.driver.find_element(By.XPATH, '/html/body/form/input[3]') double_click_ele = self.driver.find_element(By.XPATH, '/html/body/form/input[2]') right_click_ele = self.driver.find_element(By.XPATH, '/html/body/form/input[4]') actions = ActionChains(self.driver) # 单击 actions.click(click_ele) # 双击 actions.double_click(double_click_ele) # 右键点击 actions.context_click(right_click_ele) # 执行 actions.perform() time.sleep(3) def test_move_to(self): self.driver.get('https://cn.bing.com/') elem = self.driver.find_element(By.XPATH, '//*[@id="office"]') action = ActionChains(self.driver) action.move_to_element(elem) action.perform() time.sleep(3) def test_drag_drop(self): self.driver.get('http://sahitest.com/demo/dragDropMooTools.htm') source_elem = self.driver.find_element(By.ID, 'dragger') target_elem = self.driver.find_element(By.XPATH, '/html/body/div[2]') action = ActionChains(self.driver) action.drag_and_drop(source_elem, target_elem) action.perform() time.sleep(3) def test_keys(self): self.driver.get('http://sahitest.com/demo/label.htm') elem = self.driver.find_element(By.XPATH, '/html/body/label[1]/input') action = ActionChains(self.driver) action.click(elem) action.send_keys('web').pause(3) action.send_keys(Keys.SPACE) action.send_keys('test').pause(3) action.send_keys(Keys.BACK_SPACE) action.perform() time.sleep(3)
{"/testing/test_file.py": ["/testing/base.py"], "/testing/test_js.py": ["/testing/base.py"], "/testing/test_alert.py": ["/testing/base.py"], "/testing/test_frame.py": ["/testing/base.py"], "/testing/addStuff/page/main_page.py": ["/testing/addStuff/page/address_page.py"], "/testing/addStuff/testCase/test_addStuff.py": ["/testing/addStuff/page/main_page.py"], "/testing/test_windows.py": ["/testing/base.py"]}
64,189
SUPEngineer/webAuto
refs/heads/master
/testing/test_remote.py
# @Time : 2021/2/26 11:49 # @Author : qiulingfeng # @File : test_remote.py import json from selenium import webdriver from time import sleep class TestRemote(): def setup(self): # 设置option参数,打开调试窗口 chrome_arg = webdriver.ChromeOptions() chrome_arg.debugger_address = '127.0.0.1:9222' self.driver = webdriver.Chrome() def teardown(self): self.driver.quit() # def test_remote(self): # self.driver.get("https://www.bilibili.com/") # # sleep(3) def test_cookie(self): """ 使用cookie跳过登录 :return: """ self.driver.get("https://work.weixin.qq.com/wework_admin/frame") # 获取cookies # cookies = self.driver.get_cookies() # with open("cookies.txt", "w", encoding="utf-8") as f: # json.dump(cookies, f) # 读取cookies with open("cookies.txt", "r", encoding="utf-8") as f: cookies = json.load(f) # 注入cookies for i in cookies: self.driver.add_cookie(i) self.driver.refresh() sleep(6)
{"/testing/test_file.py": ["/testing/base.py"], "/testing/test_js.py": ["/testing/base.py"], "/testing/test_alert.py": ["/testing/base.py"], "/testing/test_frame.py": ["/testing/base.py"], "/testing/addStuff/page/main_page.py": ["/testing/addStuff/page/address_page.py"], "/testing/addStuff/testCase/test_addStuff.py": ["/testing/addStuff/page/main_page.py"], "/testing/test_windows.py": ["/testing/base.py"]}
64,190
SUPEngineer/webAuto
refs/heads/master
/testing/test_alert.py
# @Time : 2021/2/24 20:10 # @Author : qiulingfeng # @File : test_alert.py from time import sleep from selenium.webdriver import ActionChains from selenium.webdriver.common.by import By from testing.base import Base class TestAlert(Base): def test_alert(self): self.driver.get("https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable") self.driver.switch_to.frame('iframeResult') drag = self.driver.find_element_by_id('draggable') drop = self.driver.find_element_by_id('droppable') action = ActionChains(self.driver) action.drag_and_drop(drag, drop) action.perform() # 切换到alert,点击确认 self.driver.switch_to.alert.accept() # 返回到原来的页面 self.driver.switch_to.default_content() # 点击运行 self.driver.find_element_by_id('submitBTN').click() sleep(3)
{"/testing/test_file.py": ["/testing/base.py"], "/testing/test_js.py": ["/testing/base.py"], "/testing/test_alert.py": ["/testing/base.py"], "/testing/test_frame.py": ["/testing/base.py"], "/testing/addStuff/page/main_page.py": ["/testing/addStuff/page/address_page.py"], "/testing/addStuff/testCase/test_addStuff.py": ["/testing/addStuff/page/main_page.py"], "/testing/test_windows.py": ["/testing/base.py"]}
64,191
SUPEngineer/webAuto
refs/heads/master
/testing/test_frame.py
# @Time : 2021/2/24 15:02 # @Author : qiulingfeng # @File : test_frame.py from selenium.webdriver.common.by import By from testing.base import Base class TestFrame(Base): def test_frame(self): self.driver.get("https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable") self.driver.switch_to.frame('iframeResult') print(self.driver.find_element(By.ID, 'draggable').text) # 返回原页面中 self.driver.switch_to.parent_frame() # 或者使用下面的方法回到原来默认的页面中,效果与self.driver.switch_to.parent_frame()相同 # self.driver.switch_to.default_content() print(self.driver.find_element(By.ID, 'submitBTN').text)
{"/testing/test_file.py": ["/testing/base.py"], "/testing/test_js.py": ["/testing/base.py"], "/testing/test_alert.py": ["/testing/base.py"], "/testing/test_frame.py": ["/testing/base.py"], "/testing/addStuff/page/main_page.py": ["/testing/addStuff/page/address_page.py"], "/testing/addStuff/testCase/test_addStuff.py": ["/testing/addStuff/page/main_page.py"], "/testing/test_windows.py": ["/testing/base.py"]}
64,192
SUPEngineer/webAuto
refs/heads/master
/testing/addStuff/page/address_page.py
from selenium.webdriver.support.wait import WebDriverWait class AddressPage: def __init__(self, driver): self.driver = driver def add_stuff(self): """ 在通讯录中添加成员 :return: """ def waite_username(x): self.driver.find_elements_by_xpath("//*[@class='qui_btn ww_btn js_add_member']")[1].click() elem = self.driver.find_elements_by_xpath("//*[@id='username']") return len(elem) > 0 WebDriverWait(self.driver, 10).until(waite_username) # 输入姓名 self.driver.find_element_by_id("username").send_keys("韩立") # 输入账号名 self.driver.find_element_by_id("memberAdd_acctid").send_keys("hanli") # 输入电话号码 self.driver.find_element_by_id("memberAdd_phone").send_keys("17300000001") # 点击保存 # self.driver.find_element_by_xpath("//*[@class='qui_btn ww_btn js_btn_save']").click()
{"/testing/test_file.py": ["/testing/base.py"], "/testing/test_js.py": ["/testing/base.py"], "/testing/test_alert.py": ["/testing/base.py"], "/testing/test_frame.py": ["/testing/base.py"], "/testing/addStuff/page/main_page.py": ["/testing/addStuff/page/address_page.py"], "/testing/addStuff/testCase/test_addStuff.py": ["/testing/addStuff/page/main_page.py"], "/testing/test_windows.py": ["/testing/base.py"]}
64,193
SUPEngineer/webAuto
refs/heads/master
/testing/addStuff/page/main_page.py
from selenium import webdriver from testing.addStuff.page.address_page import AddressPage class MainPage: def __init__(self): # 设置option参数,打开调试窗口 chrome_arg = webdriver.ChromeOptions() chrome_arg.debugger_address = '127.0.0.1:9222' # 复用浏览器 self.driver = webdriver.Chrome(options=chrome_arg) def goto_address_page(self): """ 点击进入通讯录 :return: AddressPage """ self.driver.find_element_by_xpath("//*[@id='menu_contacts']/span").click() return AddressPage(self.driver)
{"/testing/test_file.py": ["/testing/base.py"], "/testing/test_js.py": ["/testing/base.py"], "/testing/test_alert.py": ["/testing/base.py"], "/testing/test_frame.py": ["/testing/base.py"], "/testing/addStuff/page/main_page.py": ["/testing/addStuff/page/address_page.py"], "/testing/addStuff/testCase/test_addStuff.py": ["/testing/addStuff/page/main_page.py"], "/testing/test_windows.py": ["/testing/base.py"]}
64,194
SUPEngineer/webAuto
refs/heads/master
/testing/base.py
# @Time : 2021/2/23 15:24 # @Author : qiulingfeng # @File : base.py ''' 执行时使用命令执行 browser=firefox pytest test_frame.py 即可方便得指定浏览器运行测试用例 ''' import os from selenium import webdriver class Base(): def setup(self): browser = os.getenv('browser') if browser == 'firefox': self.driver = webdriver.Firefox() elif browser == 'headless': self.driver = webdriver.PhantomJS() else: self.driver = webdriver.Chrome() self.driver.implicitly_wait(5) self.driver.maximize_window() def teardown(self): self.driver.quit()
{"/testing/test_file.py": ["/testing/base.py"], "/testing/test_js.py": ["/testing/base.py"], "/testing/test_alert.py": ["/testing/base.py"], "/testing/test_frame.py": ["/testing/base.py"], "/testing/addStuff/page/main_page.py": ["/testing/addStuff/page/address_page.py"], "/testing/addStuff/testCase/test_addStuff.py": ["/testing/addStuff/page/main_page.py"], "/testing/test_windows.py": ["/testing/base.py"]}
64,195
SUPEngineer/webAuto
refs/heads/master
/testing/addStuff/testCase/test_addStuff.py
from testing.addStuff.page.main_page import MainPage class TestAddStuff: def test_add_stuff(self): """ 测试添加成员 1.复用浏览器 2.进入通讯录 3.添加成员 :return: """ mainPage =MainPage() mainPage.goto_address_page().add_stuff()
{"/testing/test_file.py": ["/testing/base.py"], "/testing/test_js.py": ["/testing/base.py"], "/testing/test_alert.py": ["/testing/base.py"], "/testing/test_frame.py": ["/testing/base.py"], "/testing/addStuff/page/main_page.py": ["/testing/addStuff/page/address_page.py"], "/testing/addStuff/testCase/test_addStuff.py": ["/testing/addStuff/page/main_page.py"], "/testing/test_windows.py": ["/testing/base.py"]}
64,196
SUPEngineer/webAuto
refs/heads/master
/testing/test_windows.py
# @Time : 2021/2/23 15:24 # @Author : qiulingfeng # @File : test_windows.py from selenium.webdriver.common.by import By from testing.base import Base from time import sleep class TestWindows(Base): def test_windows(self): self.driver.get("http://www.baidu.com/") self.driver.find_element(By.LINK_TEXT, '登录').click() sleep(2) self.driver.find_element(By.LINK_TEXT, '立即注册').click() sleep(2) # 切换新窗口 self.driver.switch_to.window(self.driver.window_handles[-1]) self.driver.find_element(By.NAME, 'userName').send_keys("username") # 返回原来的窗口,点击用户名登录 self.driver.switch_to.window(self.driver.window_handles[0]) sleep(2) self.driver.find_element(By.XPATH, '//*[@title="用户名登录"]').click() self.driver.find_element(By.NAME, "userName").send_keys('user') self.driver.find_element(By.NAME, "password").send_keys('password') sleep(2)
{"/testing/test_file.py": ["/testing/base.py"], "/testing/test_js.py": ["/testing/base.py"], "/testing/test_alert.py": ["/testing/base.py"], "/testing/test_frame.py": ["/testing/base.py"], "/testing/addStuff/page/main_page.py": ["/testing/addStuff/page/address_page.py"], "/testing/addStuff/testCase/test_addStuff.py": ["/testing/addStuff/page/main_page.py"], "/testing/test_windows.py": ["/testing/base.py"]}
64,197
SUPEngineer/webAuto
refs/heads/master
/testing/test_pageObject.py
from selenium import webdriver from time import sleep from selenium.webdriver.support.wait import WebDriverWait class TestPageObjec(): def setup(self): chrome_arg = webdriver.ChromeOptions() chrome_arg.debugger_address = '127.0.0.1:9222' self.driver = webdriver.Chrome(options=chrome_arg) self.driver.implicitly_wait(5) def teardown(self): self.driver.quit() def test_add_stuff(self): # self.driver.get("https://work.weixin.qq.com/wework_admin/frame") self.driver.find_element_by_xpath("//*[@id='menu_contacts']/span").click() def waite_username(x): self.driver.find_elements_by_xpath("//*[@class='qui_btn ww_btn js_add_member']")[1].click() elem = self.driver.find_elements_by_xpath("//*[@id='username']") return len(elem) > 0 WebDriverWait(self.driver, 10).until(waite_username) self.driver.find_element_by_id("username").send_keys("韩立") self.driver.find_element_by_id("memberAdd_acctid").send_keys("hanli") self.driver.find_element_by_id("memberAdd_phone").send_keys("17300000001") self.driver.find_element_by_xpath("//*[@class='qui_btn ww_btn js_btn_save']").click()
{"/testing/test_file.py": ["/testing/base.py"], "/testing/test_js.py": ["/testing/base.py"], "/testing/test_alert.py": ["/testing/base.py"], "/testing/test_frame.py": ["/testing/base.py"], "/testing/addStuff/page/main_page.py": ["/testing/addStuff/page/address_page.py"], "/testing/addStuff/testCase/test_addStuff.py": ["/testing/addStuff/page/main_page.py"], "/testing/test_windows.py": ["/testing/base.py"]}
64,200
bernardogbecker/UnfollowInstagramBot
refs/heads/master
/FollowWeb.py
from selenium import webdriver from time import sleep from FollowList import Follow import pyautogui class InstaBot: def __init__(self, username, pw, usernameToFollow): self.driver = webdriver.Edge(path) self.username = username self.pw = pw self.usernameToFollow = usernameToFollow self.driver.get("https://instagram.com") sleep(2) self.driver.find_element_by_xpath("//input[@name=\"username\"]")\ .send_keys(username) self.driver.find_element_by_xpath("//input[@name=\"password\"]")\ .send_keys(pw) self.driver.find_element_by_xpath('//button[@type="submit"]')\ .click() sleep(5) self.driver.find_element_by_xpath("//button[contains(text(), 'Agora não')]")\ .click() sleep(2) if not self.driver.find_elements_by_xpath("//button[contains(text(), 'Agora não')]") == []: self.driver.find_element_by_xpath("//button[contains(text(), 'Agora não')]")\ .click() sleep(2) def getfollow(self): self.driver.find_element_by_xpath('//*[@id="react-root"]/section/nav/div[2]/div/div/div[2]/input')\ .send_keys(self.usernameToFollow) sleep(2) self.driver.find_element_by_xpath('//*[@id="react-root"]/section/nav/div[2]/div/div/div[2]/div[3]/div[2]/div/a')\ .click() Seguir = Follow(self.driver) for i in range (0, len(Seguir)): self.driver.find_element_by_xpath('//*[@id="react-root"]/section/nav/div[2]/div/div/div[2]/input')\ .send_keys(Seguir[i]) sleep(2) self.driver.find_element_by_xpath('//*[@id="react-root"]/section/nav/div[2]/div/div/div[2]/div[3]/div[2]/div/a')\ .click() sleep(4) try: self.driver.find_element_by_xpath("//button[contains(text(), 'Seguir')]")\ .click() sleep(2) print(f'Seguindo: {i}') except: print('erro') if i in range(10, len(Seguir), 20): sleep(600) USERNAME = '' #Write your USERNAME here PASS = '' #Write your PASSWORD here USERNAMETOFOLLOW = '' #Write the user you want to steal all the following path = 'C:\Program Files\msedgedriver' #Write your path to msedgedriver, download at https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/ x = InstaBot(USERNAME, PASS, USERNAMETOFOLLOW) x.getfollow()
{"/FollowWeb.py": ["/FollowList.py"], "/UnfollowWeb.py": ["/UnfollowList.py"]}
64,201
bernardogbecker/UnfollowInstagramBot
refs/heads/master
/UnfollowWeb.py
from selenium import webdriver from time import sleep from UnfollowList import unFollow import pyautogui class InstaBot: def __init__(self, username, pw): self.driver = webdriver.Edge(path) self.username = username self.pw = pw self.driver.get("https://instagram.com") sleep(2) self.driver.find_element_by_xpath("//input[@name=\"username\"]")\ .send_keys(username) self.driver.find_element_by_xpath("//input[@name=\"password\"]")\ .send_keys(pw) self.driver.find_element_by_xpath('//button[@type="submit"]')\ .click() sleep(3) self.driver.find_element_by_xpath("//button[contains(text(), 'Agora não')]")\ .click() sleep(2) if not self.driver.find_elements_by_xpath("//button[contains(text(), 'Agora não')]") == []: self.driver.find_element_by_xpath("//button[contains(text(), 'Agora não')]")\ .click() sleep(2) def getUnfollow(self): DeixardeSeguir = unFollow(self.username, self.pw) for i in range (0, len(DeixardeSeguir)): self.driver.find_element_by_xpath('//*[@id="react-root"]/section/nav/div[2]/div/div/div[2]/input')\ .send_keys(DeixardeSeguir[i]) sleep(2) self.driver.find_element_by_xpath('//*[@id="react-root"]/section/nav/div[2]/div/div/div[2]/div[3]/div[2]/div/a')\ .click() sleep(4) try: self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/div/header/section/div[1]/div[2]/div/span/span[1]/button')\ .click() sleep(1) self.driver.find_element_by_xpath('/html/body/div[4]/div/div/div/div[3]/button[1]')\ .click() sleep(2) print(f'NonFollowers: {len(DeixardeSeguir) - i}') except: print('erro') if i in range(10, len(DeixardeSeguir), 10): sleep(600) USERNAME = '' #Write your USERNAME here PASS = '' #Write your PASSWORD here path = 'C:\Program Files\msedgedriver' #Write your path to msedgedriver, download at https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/ x = InstaBot(USERNAME, PASS) x.getUnfollow()
{"/FollowWeb.py": ["/FollowList.py"], "/UnfollowWeb.py": ["/UnfollowList.py"]}
64,202
bernardogbecker/UnfollowInstagramBot
refs/heads/master
/UnfollowList.py
import time from InstagramAPI import InstagramAPI import random def getTotalFollowers(api, user_id): """ Returns the list of followers of the user. """ followers = [] next_max_id = True while next_max_id: # first iteration hack if next_max_id is True: next_max_id = '' _ = api.getUserFollowers(user_id, maxid=next_max_id) followers.extend(api.LastJson.get('users', [])) next_max_id = api.LastJson.get('next_max_id', '') return followers def getTotalFollowings(api, user_id): """ Returns the list of followers of the user. """ followers = [] next_max_id = True while next_max_id: # first iteration hack if next_max_id is True: next_max_id = '' _ = api.getUserFollowings(user_id, maxid=next_max_id) followers.extend(api.LastJson.get('users', [])) next_max_id = api.LastJson.get('next_max_id', '') return followers def nonFollowers(followers, followings): nonFollowers = {} dictFollowers = {} for follower in followers: dictFollowers[follower['username']] = follower['pk'] for followedUser in followings: if followedUser['username'] not in dictFollowers: nonFollowers[followedUser['username']] = followedUser['pk'] return nonFollowers def unFollow(USERNAME, PASS): api = InstagramAPI(USERNAME, PASS) api.login() listNonFollow = [] user_id = api.username_id followers = getTotalFollowers(api, user_id) following = getTotalFollowings(api, user_id) nonFollow = nonFollowers(followers, following) print('Number of followers:', len(followers)) print('Number of followings:', len(following)) print('Number of nonFollowers:', len(nonFollow)) for i in nonFollow: listNonFollow.append(i) listNonFollow.sort() return listNonFollow
{"/FollowWeb.py": ["/FollowList.py"], "/UnfollowWeb.py": ["/UnfollowList.py"]}
64,203
bernardogbecker/UnfollowInstagramBot
refs/heads/master
/FollowList.py
from time import sleep import pyautogui def Follow(driver): sleep(2) driver.find_element_by_xpath('/html/body/div[1]/section/main/div/header/section/ul/li[3]')\ .click() sleep(2) scroll_box = driver.find_element_by_xpath("/html/body/div[4]/div/div/div[2]/ul/div") scroll() links = scroll_box.find_elements_by_tag_name('a') names = [name.text for name in links if name.text != ''] print(names) # close button driver.find_element_by_xpath("/html/body/div[4]/div/div/div[1]/div/div[2]/button")\ .click() return names def scroll(): x, y = pyautogui.size() pyautogui.moveTo(x/2, y/2) for i in range(0, 10): pyautogui.scroll(-1000) sleep(0.1) print(i)
{"/FollowWeb.py": ["/FollowList.py"], "/UnfollowWeb.py": ["/UnfollowList.py"]}
64,229
emiliotebar/Kwranking
refs/heads/master
/inicio.py
""" KWRANKING Emilio Tébar Reto semanal --> https://j2logo.com/#retoSemanal """ import requests from bs4 import BeautifulSoup import db from models import Keyword from datos import exportar_resultados_a_xlsx keywords = [] dominio = "https://cookpad.com/" dominio_google_search = "https://www.google.com/search?q={kw}&start={start}" def mostrar_menu(): print("------------Kwranking------------") print("\n\n[1] Importar palabras clave") print("[2] Mostrar palabras clave") print("[3] Comprobar palabras clave") print("[4] Exportar a xlsx") print("[0] Salir") print("\n\n") def carga_keywords(): try: with open('fichero.txt','r') as fichero: for linea in fichero: linea = linea.strip('\n') objKeyword = Keyword(linea) objKeyword.save() print("Importación correcta") return Keyword.get_all() except FileNotFoundError: print("No se encuentra el fichero fichero.txt") except: print("Error en la importación.\nContacte con el departamento de informática.") def listar_keywords(keywords): contador = 0 try: if keywords: print("LISTADO DE PALABRAS CLAVE") for key in keywords: #print("{}. {}".format(contador+1 ,key)) print(f'{contador+1}. KW: {key.keywords} > {key.posicion}') contador += 1 if contador % 20 == 0: input("Presione enter para mostrar más palabras clave") else: print("SIN PALABRAS") except: print("Error en la importación.\nContacte con el departamento de informática.") def aparece_el_dominio(link, dominio): encontrado = False fin = link.find('&') pagina = link[:fin] if dominio in pagina: encontrado = True return encontrado def comprueba_keywords(kw, dominio): posicion = 1 continuar = True start = 0 encontrado = False while continuar and not encontrado: parametros = {'q': kw, 'start': start} resp = requests.get(f'https://www.google.com/search', params= parametros) if resp.status_code == 200: soup = BeautifulSoup(resp.text, 'lxml') div_principal = soup.find('div', {'id': 'main'}) resultados = div_principal.find_all('div', class_ = 'ZINbbc xpd O9g5cc uUPGi') for res in resultados: if res.div and res.div.a: if aparece_el_dominio(res.div.a['href'], dominio): encontrado = True break else: posicion += 1 if not encontrado: footer = div_principal.find('footer') siguiente = footer.find('a', {'aria-label': 'Página siguiente'}) if siguiente: start += 10 if start == 100: continuar = False else: continuar = False else: continuar = False if not encontrado: posicion = 100 return posicion def actualiza_posicion(keywords): for key in keywords: posicion = comprueba_keywords(key.keywords, dominio) key.posicion = posicion if posicion < 100 else None key.save() def keywords_como_lista_de_valores(keywords): lista_valores = [(key.keywords, key.posicion) for key in keywords] return lista_valores def run(): keywords = Keyword.get_all() while True: mostrar_menu() opcion = input("Introduce una opción:") if opcion == "1": keywords = carga_keywords() elif opcion == "2": listar_keywords(keywords) elif opcion == "3": actualiza_posicion(keywords) elif opcion == "4": exportar_resultados_a_xlsx(keywords_como_lista_de_valores(keywords)) elif opcion == "0": print("Nos vemos!") break else: print("Opción incorrecta") ### INICIO DEL PROGRAMA if __name__ == '__main__': db.Base.metadata.create_all(db.engine) run()
{"/inicio.py": ["/db.py", "/models.py", "/datos.py"], "/models.py": ["/db.py"]}
64,230
emiliotebar/Kwranking
refs/heads/master
/models.py
import db from sqlalchemy.exc import IntegrityError from sqlalchemy import Column, Integer, String class Keyword(db.Base): __tablename__ = 'keyword' id = Column(Integer, primary_key = True) keywords = Column(String, nullable = False, unique = True) posicion = Column(Integer, nullable = True) def __init__(self, keywords, posicion = None): self.keywords = keywords self.posicion = posicion def __repr__(self): return f'Ranking({self.keywords}, {self.posicion})' def __str__(self): return f'La palabra clave {self.keywords} rankea en la posición {self.posicion}' #return f'{self.keywords}' def save(self): try: db.session.add(self) db.session.commit() except IntegrityError: # Si las palabras clave ya existen, se hace un rollback de la base de datos db.session.rollback() def delete(self): db.session.delete(self) db.session.commit() @staticmethod def get_all(): return db.session.query(Keyword).all()
{"/inicio.py": ["/db.py", "/models.py", "/datos.py"], "/models.py": ["/db.py"]}
64,231
emiliotebar/Kwranking
refs/heads/master
/db.py
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base # Crea el engine indicando la cadena de conexión a la base de datos engine = create_engine('sqlite:///keywords.sqlite') # Crea el objeto para manejar la sesión de base de datos Session = sessionmaker(bind = engine) session = Session() # Crea la clase base de la que hereden los modelos de la aplicación Base = declarative_base()
{"/inicio.py": ["/db.py", "/models.py", "/datos.py"], "/models.py": ["/db.py"]}
64,232
emiliotebar/Kwranking
refs/heads/master
/datos.py
import openpyxl def exportar_resultados_a_xlsx(keywords): wb = openpyxl.Workbook() hoja = wb.active hoja.title = "Valores" # Fila del encabezado con los títulos hoja.append(('Keywords','Posición')) for key in keywords: hoja.append(key) wb.save('keywords.xlsx')
{"/inicio.py": ["/db.py", "/models.py", "/datos.py"], "/models.py": ["/db.py"]}
64,234
annyeremchenko/my_project
refs/heads/master
/job/migrations/0002_auto_20170415_0916.py
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-04-15 03:16 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('job', '0001_initial'), ] operations = [ migrations.AlterField( model_name='job', name='type', field=models.IntegerField(choices=[(0, 'Прогулянка із псом'), (1, 'Похід за продуктами'), (2, 'Миття вікон'), (3, 'Ремонт меблів'), (4, 'Супровід дитини у школу'), (5, 'Ремонт одягу'), (6, 'Миття машини'), (7, 'Послуги няні'), (8, 'Ремонт велосипеду'), (9, 'Догляд за домашньою твариною на певний час'), (10, 'Допомога з перевезенням речей'), (11, 'Фарбування паркану'), (12, 'Прибирання квартири'), (13, 'Миття посуду')]), ), ]
{"/user/admin.py": ["/user/models.py"], "/job/views.py": ["/job/models.py"], "/job/models.py": ["/user/models.py"], "/user/views.py": ["/job/models.py", "/user/models.py"]}
64,235
annyeremchenko/my_project
refs/heads/master
/user/admin.py
from django.contrib import admin from .models import UserInfo, Location admin.site.register(UserInfo) admin.site.register(Location) # Register your models here.
{"/user/admin.py": ["/user/models.py"], "/job/views.py": ["/job/models.py"], "/job/models.py": ["/user/models.py"], "/user/views.py": ["/job/models.py", "/user/models.py"]}
64,236
annyeremchenko/my_project
refs/heads/master
/user/urls.py
from django.conf.urls import url, include from django.contrib import admin import user from . import views urlpatterns = [ url(r'login/', views.Login.as_view(), name='log in'), # вхід url(r'logout/', views.Logout.as_view(), name='sign out'), # вихід url(r'signup/', views.Signup.as_view(), name='sign up'), # реєстрація url(r'home/', views.Home.as_view(), name='home'), # домашня сторінка url(r'(\d+)/', views.UserInformation.as_view(), name='another user home'), # домашня сторінка іншого користувача url(r'$', views.Index.as_view(), name='index') # початкова сторінка ]
{"/user/admin.py": ["/user/models.py"], "/job/views.py": ["/job/models.py"], "/job/models.py": ["/user/models.py"], "/user/views.py": ["/job/models.py", "/user/models.py"]}
64,237
annyeremchenko/my_project
refs/heads/master
/job/views.py
from django.shortcuts import render, redirect from django.views.generic import View from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required from .models import Job, Location from django.shortcuts import HttpResponse from django.db.models import Q import math, json class JobSearch(View): @method_decorator(login_required(login_url='/login/')) def get(self, request): location = request.user.info.location delta_lat = 0.1 delta_lng = delta_lat / math.cos(math.radians(location.y)) jobs = Job.objects.filter(~Q(customer=request.user), performer=None, location__x__lte=location.x + delta_lng, location__x__gte=location.x - delta_lng, location__y__lte=location.y + delta_lat, location__y__gte=location.y - delta_lat) #return HttpResponse(json.dumps([i.dict() for i in jobs], indent=4, sort_keys=True), content_type='application/json') return render(request, "mapJobs.html", {'jobs': jobs, 'nav': { 'text': 'View all jobs', 'href': '/jobs/all/' }}) @method_decorator(login_required(login_url='/login/')) def post(self, request): if request.POST.__contains__('id'): id = int(request.POST['id']) job = Job.objects.get(id=id) print (job.dict()) if (job.performer is not None): return HttpResponse(json.dumps({"status": "occupied"}), content_type='application/json') job.performer = request.user job.save() return HttpResponse(json.dumps({"status": "ok"}), content_type='application/json') elif request.POST.__contains__('lat') and request.POST.__contains__('lng'): lat = float(request.POST['lat']) lng = float(request.POST['lng']) location = Location.objects.create(x=lng, y=lat) request.user.info.location = location request.user.info.save() return self.get(request) return HttpResponse(json.dumps({"status": "error key"}), content_type='application/json') class JobAll(View): @method_decorator(login_required(login_url='/login/')) def get(self, request): jobs = Job.objects.all() return render(request, "mapJobs.html", {'jobs': jobs, 'nav': { 'text': 'View nearly jobs', 'href': '/jobs/' }}) @method_decorator(login_required(login_url='/login/')) def post(self, request): view = JobSearch() view.get = self.get return view.post(request) class Map(View): @method_decorator(login_required(login_url='/login/')) def get(self, request): location = {} if (request.GET.__contains__('lat') and request.GET.__contains__('lng')): location = {'lat': request.GET['lat'], 'lng': request.GET['lng']} return render(request, "map.html", location) # Create your views here.
{"/user/admin.py": ["/user/models.py"], "/job/views.py": ["/job/models.py"], "/job/models.py": ["/user/models.py"], "/user/views.py": ["/job/models.py", "/user/models.py"]}
64,238
annyeremchenko/my_project
refs/heads/master
/job/models.py
from django.db import models from django.contrib.auth.models import User from user.models import Location class Job(models.Model): allTypes = ((0, "Прогулянка із псом"), (1, "Похід за продуктами"), (2, "Миття вікон"), (3, "Ремонт меблів"), (4, "Супровід дитини у школу"), (5, "Ремонт одягу"), (6, "Миття машини"), (7, "Послуги няні"), (8, "Ремонт велосипеду"), (9, "Догляд за домашньою твариною на певний час"), (10, "Допомога з перевезенням речей"), (11, "Фарбування паркану"), (12, "Прибирання квартири"), (13, "Миття посуду"), ) points = models.IntegerField() description = models.TextField(null=True) type = models.IntegerField(choices=allTypes) deadline = models.DateField() customer = models.ForeignKey(User, related_name="jobs") performer = models.ForeignKey(User, related_name="todo", null=True) location = models.ForeignKey(Location, related_name="job", null=True) done = models.BooleanField(default=False) def dict(self): return {"points": self.points, "description": self.description, "type": self.type, "deadline": self.deadline.__str__(), "customer": self.customer.__str__(), "performer": self.performer.__str__(), "location": self.location.dict()} # Create your models here.
{"/user/admin.py": ["/user/models.py"], "/job/views.py": ["/job/models.py"], "/job/models.py": ["/user/models.py"], "/user/views.py": ["/job/models.py", "/user/models.py"]}
64,239
annyeremchenko/my_project
refs/heads/master
/user/views.py
from django.shortcuts import render from django.views.generic import View from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required from django.contrib.auth import login, authenticate from django.contrib.auth.models import User from django.contrib.auth import logout from django.shortcuts import redirect from job.models import Job, Location from .models import UserInfo from django.shortcuts import HttpResponse import sys, json, math class Index(View): def get(self, request): return render(request, "index.html", {}) class Home(View): @method_decorator(login_required(login_url='/login/')) def get(self, request, **params): return render(request, "home.html", params) @method_decorator(login_required(login_url='/login/')) def post(self, request): print(request.POST) if request.POST.__contains__('key') and request.POST.__contains__('value'): key = request.POST['key'] val = request.POST['value'] if key == 'firstname': request.user.first_name = val request.user.save() return HttpResponse(json.dumps({"status": "ok"}), content_type='application/json') elif key == 'lastname': request.user.last_name = val request.user.save() return HttpResponse(json.dumps({"status": "ok"}), content_type='application/json') elif key == 'email': request.user.email = val request.user.save() return HttpResponse(json.dumps({"status": "ok"}), content_type='application/json') else: return HttpResponse(json.dumps({"status": "error key"}), content_type='application/json') elif request.POST.__contains__('type') \ and request.POST.__contains__('points') \ and request.POST.__contains__('description') \ and request.POST.__contains__('deadline') \ and request.POST.__contains__('lng') \ and request.POST.__contains__('lat'): job_type = int(request.POST['type']) points = int(request.POST['points']) description = request.POST['description'] deadline = request.POST['deadline'] lng = float(request.POST['lng']) lat = float(request.POST['lat']) if request.user.info.points < points or points < 1: return self.get(request, error='Not enough points to post job') location = Location.objects.create(x=lng, y=lat) Job.objects.create(type=job_type, points=points, description=description, deadline=deadline, customer=request.user, location=location) request.user.info.points -= points request.user.info.save() request.method = 'get' # виправлення багу із повторним надсиланням форми return redirect('/home/') elif request.POST.__contains__('done'): user = request.user id = int(request.POST['done']) job = Job.objects.get(id=id) if job.performer is not None and job.performer.id == user.id: job.done = True job.save() elif job.customer.id == user.id and job.done: job.performer.info.points += job.points job.performer.info.save() job.delete() else: return HttpResponse(json.dumps({"status": "error request"}), content_type='application/json') return HttpResponse(json.dumps({"status": "ok"}), content_type='application/json') else: return HttpResponse(json.dumps({"status": "error request"}), content_type='application/json') @method_decorator(login_required(login_url='/login/')) def delete(self, request): user = request.user id = int(request.GET['id']) job = Job.objects.get(id=id) if job.performer is not None and job.performer.id == user.id and not job.done: job.performer = None job.save() elif job.customer.id == user.id and not job.done: user.info.points += job.points user.info.save() job.delete() else: return HttpResponse(json.dumps({"status": "error request"}), content_type='application/json') return HttpResponse(json.dumps({"status": "ok"}), content_type='application/json') class UserInformation(View): def get(self, request, id): user = User.objects.get(id=int(id)) return render(request, "info.html", {'another': user}) class Signup(View): def get(self, request, params={}): return render(request, "signup.html", params) def post(self, request): params = request.POST try: try: user = User.objects.get(username=params['username']) if user is not None: self.get(request, {'error': 'Error, we already have a user with such name'}) except: print(params) try: print(params['email']) user = User.objects.get(email=params['email']) if user is not None: self.get(request, {'error': 'Error, we already have a user with such email'}) except: print(sys.exc_info()) print('success') if params['password'] != params['password_repeat']: return render(request, 'auth.html', {'error': "Passwords don't matches"}) user = User.objects.create_user(params['username'], params['email'], params['password']) user.last_name = params['lastname'] user.first_name = params['firstname'] lat = float(params['lat']) lng = float(params['lng']) user.save() location = Location.objects.create(x=lng, y=lat) UserInfo.objects.create(location=location, user=user) user = authenticate(username=params['username'], password=params['password']) if user is not None: if user.is_active: login(request, user) if request.GET.__contains__('next'): return redirect(request.GET['next']) else: return redirect('/home/') else: self.get(request, {'error': 'Some error'}) else: self.get(request, {'error': 'Some error'}) login(request, user) return redirect('/home/') except ValueError: self.get(request, {'error': 'Some error on server'}) class Login(View): def get(self, request, params={}): return render(request, "login.html", params) def post(self, request): params = request.POST if params['email'].find('@') == -1: username = params['email'] else: try: username = User.objects.get(email=params['email']) except: print('error') return self.get(request, {'login': "password don't match"}) user = authenticate(username=username, password=params['password']) if user is not None: if user.is_active: login(request, user) try: print(request.GET['next']) return redirect(request.GET['next']) except: return redirect('/home/') else: return self.get(request, {'login': 'error disabled'}) else: return self.get(request, {'login': "password don't match"}) class Logout(View): @method_decorator(login_required(login_url='/login/')) def get(self, request): logout(request) return redirect("/login/") # Create your views here.
{"/user/admin.py": ["/user/models.py"], "/job/views.py": ["/job/models.py"], "/job/models.py": ["/user/models.py"], "/user/views.py": ["/job/models.py", "/user/models.py"]}
64,240
annyeremchenko/my_project
refs/heads/master
/user/models.py
from django.db import models from django.contrib.auth.models import User # Create your models here. class Location(models.Model): x = models.FloatField() y = models.FloatField() info = models.TextField(null=True) def dict(self): return {"x": self.x, "y": self.y} class UserInfo(models.Model): user = models.OneToOneField(User, related_name="info") points = models.IntegerField(default=100) location = models.ForeignKey(Location, null=True, related_name="user")
{"/user/admin.py": ["/user/models.py"], "/job/views.py": ["/job/models.py"], "/job/models.py": ["/user/models.py"], "/user/views.py": ["/job/models.py", "/user/models.py"]}
64,241
annyeremchenko/my_project
refs/heads/master
/job/migrations/0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-04-09 05:07 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('user', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Job', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('points', models.IntegerField()), ('description', models.TextField(null=True)), ('type', models.IntegerField()), ('deadline', models.DateField()), ('customer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='jobs', to=settings.AUTH_USER_MODEL)), ('location', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='job', to='user.Location')), ('performer', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='todo', to=settings.AUTH_USER_MODEL)), ], ), ]
{"/user/admin.py": ["/user/models.py"], "/job/views.py": ["/job/models.py"], "/job/models.py": ["/user/models.py"], "/user/views.py": ["/job/models.py", "/user/models.py"]}
64,242
annyeremchenko/my_project
refs/heads/master
/job/urls.py
from django.conf.urls import url, include from django.contrib import admin import user from . import views urlpatterns = [ url(r'map/', views.Map.as_view(), name='job location'), # дорога до роботи url(r'all/', views.JobAll.as_view(), name='all jobs'), # усі роботи url(r'$', views.JobSearch.as_view(), name='job search'), # пошук роботи ]
{"/user/admin.py": ["/user/models.py"], "/job/views.py": ["/job/models.py"], "/job/models.py": ["/user/models.py"], "/user/views.py": ["/job/models.py", "/user/models.py"]}
64,243
mozilla/marketplace-api-mock
refs/heads/master
/factory/langpack.py
# -*- coding: utf-8 -*- import random import uuid from factory.utils import text LANGUAGES = { 'fr': u'Français', 'it': u'Italiano', 'de': u'Deutsch', 'en-US': u'English (US)', 'pt-BR': u'Português (do Brasil)', 'pl': u'Polski' } def langpack(url_root): uuid_ = uuid.uuid4() language = random.choice(LANGUAGES.keys()) return { 'active': True, 'name': '%s language pack for Firefox OS v2.2' % text(LANGUAGES[language]), 'fxos_version': '2.2', 'language': language, 'language_display': text(LANGUAGES[language]), 'manifest_url': '%s%s/manifest.webapp' % (url_root, unicode(uuid_)), 'size': 666, 'uuid': uuid_.hex, 'version': '1.0.1' }
{"/factory/langpack.py": ["/factory/utils.py"], "/factory/feed.py": ["/factory/__init__.py", "/factory/constants.py", "/factory/utils.py"], "/factory/__init__.py": ["/factory/constants.py", "/factory/utils.py"], "/main.py": ["/app.py", "/factory/__init__.py", "/factory/constants.py"], "/factory/comm.py": ["/factory/__init__.py"], "/app.py": ["/factory/__init__.py"]}
64,244
mozilla/marketplace-api-mock
refs/heads/master
/factory/feed.py
""" Generate Feed-related objects. """ import random from mpconstants.collection_colors import COLLECTION_COLORS from factory import app, carrier, preview, region from factory.constants import AUTHORS, SAMPLE_BG from factory.utils import rand_bool, rand_text, text counter = 0 COLLECTION_COLORS = COLLECTION_COLORS.items() FEED_APP_TYPES = [ 'icon', 'image', 'description', 'quote', 'preview' ] def feed_item(**kw): global counter counter += 1 return dict({ 'app': feed_app(), 'brand': brand(), 'carrier': carrier()['slug'], 'collection': collection(), 'id': counter, 'item_type': random.choice(['app', 'collection', 'brand']), 'url': '/api/v2/feed/items/%d/' % counter, 'region': region()['slug'], 'shelf': shelf() }, **kw) def feed_app(**kw): pullquote_text = '"' + rand_text(n=12) + '"' description = random.choice([rand_text(n=20), '']) feedapp_type = random.choice(FEED_APP_TYPES) rand_color = random.choice(COLLECTION_COLORS) return dict({ 'app': app(), 'background_color': rand_color[1], 'color': rand_color[0], 'description': description, 'type': FEED_APP_TYPES[0], 'background_image': SAMPLE_BG, 'id': counter, 'preview': preview(), 'pullquote_attribute': random.choice(AUTHORS), 'pullquote_rating': random.randint(1, 5), 'pullquote_text': pullquote_text, 'slug': 'feed-app-%d' % counter, 'url': '/api/v2/feed/apps/%d' % counter }, **kw) def brand(**kw): global counter counter += 1 app_count = kw.get('app_count', 6) data = { 'app_count': app_count, 'apps': [app() for i in xrange(app_count)], 'id': counter, 'layout': random.choice(['list', 'grid']), 'slug': 'brand-%d' % counter, 'type': random.choice(['hidden-gem', 'music', 'travel']), 'url': '/api/v2/feed/brand%d' % counter } data = dict(data, **kw) if data['slug'] == 'brand-grid': data.update({ 'layout': 'grid' }) elif data['slug'] == 'brand-list': data.update({ 'layout': 'list' }) return data def collection(**kw): global counter counter += 1 slug = 'collection-%s' % counter rand_color = random.choice(COLLECTION_COLORS) app_count = kw.get('app_count', 6) data = { 'name': text('Collection %s' % counter), 'id': counter, 'slug': slug, 'app_count': app_count, 'type': 'listing', 'description': '', 'apps': [app() for i in xrange(app_count)], 'background_color': rand_color[1], 'color': rand_color[0], 'icon': 'http://f.cl.ly/items/103C0e0I1d1Q1f2o3K2B/' 'mkt-collection-logo.png', 'url': '/api/v2/feed/collections/%d/' % counter } if rand_bool(): data['background_image'] = SAMPLE_BG, data['type'] = 'promo' data = dict(data, **kw) if data['slug'] == 'grouped': # Divide into three groups for mega collections. data.update({ 'background_image': SAMPLE_BG, 'description': rand_text(n=100), 'name': 'Mega Collection', 'type': 'promo' }) for i, _app in enumerate(data['apps']): if i < data['app_count'] / 3: _app['group'] = 'Group 1' elif i < data['app_count'] * 2 / 3: _app['group'] = 'Group 2' else: _app['group'] = 'Group 3' elif data['slug'] == 'coll-promo': data.update({ 'name': 'Coll Promo', 'type': 'promo', }) elif data['slug'] == 'coll-promo-desc': data.update({ 'background_image': '', 'description': rand_text(n=100), 'name': 'Coll Promo Desc', 'type': 'promo', }) elif data['slug'] == 'coll-promo-bg': data.update({ 'background_image': SAMPLE_BG, 'description': '', 'name': 'Coll Promo Background', 'type': 'promo', }) elif data['slug'] == 'coll-promo-bg-desc': data.update({ 'background_image': SAMPLE_BG, 'description': rand_text(n=100), 'name': 'Coll Promo Background Desc', 'type': 'promo', }) elif data['slug'] == 'coll-listing': data.update({ 'name': 'Coll Listing', 'type': 'listing', }) elif data['slug'] == 'coll-listing-desc': data.update({ 'description': rand_text(n=100), 'name': 'Coll Listing Desc', 'type': 'listing', }) return data def shelf(**kw): global counter counter += 1 _carrier = carrier()['slug'] app_count = kw.get('app_count', 6) data = { 'apps': [app() for i in xrange(app_count)], 'app_count': app_count, 'background_image': SAMPLE_BG, 'background_image_landing': SAMPLE_BG, 'carrier': _carrier, 'description': '', 'id': counter, 'name': '%s Op Shelf' % _carrier.replace('_', ' ').capitalize(), 'region': 'restofworld', 'slug': 'shelf-%d' % counter, 'url': '/api/v2/feed/shelves/%d/' % counter } data = dict(data, **kw) if data['slug'] == 'shelf': data.update({ 'name': 'Shelf' }) elif data['slug'] == 'shelf-desc': data.update({ 'description': rand_text(), 'name': 'Shelf Description' }) return data def feed(): """ Generates a Feed, with at least one of every type of Feed module. Note that the existence of these Feed Items are tied to continuous integration such as the slugs for UA tracking. Keep in mind before changing. """ data = [ feed_item(item_type='shelf', shelf=shelf(slug='shelf')), feed_item(item_type='shelf', shelf=shelf(slug='shelf-desc')), feed_item(item_type='brand', brand=brand(slug='brand-grid')), feed_item(item_type='brand', brand=brand(slug='brand-list')), feed_item(item_type='collection', collection=collection(slug='grouped')), feed_item(item_type='collection', collection=collection(slug='coll-promo')), feed_item(item_type='collection', collection=collection(slug='coll-promo-desc')), feed_item(item_type='collection', collection=collection(slug='coll-promo-bg')), feed_item(item_type='collection', collection=collection(slug='coll-promo-bg-desc')), feed_item(item_type='collection', collection=collection(slug='coll-listing')), feed_item(item_type='collection', collection=collection(slug='coll-listing-desc')), ] for feed_app_type in FEED_APP_TYPES: data.append(feed_item(item_type='app', app=feed_app(type=feed_app_type, slug='feedapp-%s' % feed_app_type))) return data
{"/factory/langpack.py": ["/factory/utils.py"], "/factory/feed.py": ["/factory/__init__.py", "/factory/constants.py", "/factory/utils.py"], "/factory/__init__.py": ["/factory/constants.py", "/factory/utils.py"], "/main.py": ["/app.py", "/factory/__init__.py", "/factory/constants.py"], "/factory/comm.py": ["/factory/__init__.py"], "/app.py": ["/factory/__init__.py"]}
64,245
mozilla/marketplace-api-mock
refs/heads/master
/factory/__init__.py
import random import string from cgi import escape from uuid import uuid4 from factory.constants import (AUTHORS, CARRIERS, MESSAGES, PROMO_IMAGES, SPECIAL_APP_SLUGS, REGIONS, SAMPLE_BG, SCREENSHOT_MAP, SPECIAL_SLUGS_TO_IDS, USER_NAMES) from factory.utils import rand_bool, rand_text, rand_datetime, text counter = 0 extension_counter = 0 preview_counter = 0 review_counter = 0 website_counter = 0 CDN_URL = 'https://marketplace-dev-cdn.allizom.org' def _app_preview(): """Generate app preview object.""" url = ('https://marketplace.cdn.mozilla.net/' 'img/uploads/previews/%%s/%d/%d.png' % random.choice(SCREENSHOT_MAP)) return { 'caption': rand_text(n=5), 'filetype': 'image/png', 'thumbnail_url': url % 'thumbs', 'image_url': url % 'full', } def carrier(**kw): slug = kw.get('slug') if not slug: # No slug ? Pick a random carrier from the dict. slug, name = random.choice(CARRIERS.items()) else: # A slug was given ? Pick the corresponding carrier name or just make # one up. name = CARRIERS.get(slug, 'Seavan Sellular') return { 'id': kw.get('id', 1), 'name': name, 'slug': slug, } def _category(slug, name): """Creates a category object.""" return { 'name': text(name), 'slug': slug, } def region(**kw): slug = kw.get('slug') if not slug: # No slug ? Pick a random region from the dict. slug, name = random.choice(REGIONS.items()) else: # A slug was given ? Pick the corresponding region name or just make # one up. name = REGIONS.get(slug, 'Cvanistan') return { 'id': kw.get('id', 1), 'name': name, 'slug': slug, } def _user_apps(): """Returns user's apps object.""" return { 'installed': [SPECIAL_SLUGS_TO_IDS['installed']], 'developed': [SPECIAL_SLUGS_TO_IDS['developed']], 'purchased': [SPECIAL_SLUGS_TO_IDS['purchased']] } def app(**kw): """ In the API everything here except `user` should be serialized and keyed off counter:region:locale. """ global counter counter += 1 num_previews = kw.get('num_previews', 4) slug = kw.get('slug', 'app-%d' % counter) data = { 'id': SPECIAL_SLUGS_TO_IDS.get(slug, counter), 'author': random.choice(AUTHORS), 'categories': ['social', 'games'], 'content_ratings': { 'body': 'generic', 'rating': '12', 'descriptors': ['scary', 'lang', 'drugs'], 'interactives': ['users-interact', 'shares-info'] }, 'current_version': text('%d.0' % int(random.random() * 20)), 'description': {'en-US': escape(kw.get('description', rand_text(100)))}, 'device_types': ['desktop', 'firefoxos', 'android-mobile', 'android-tablet', 'firefoxos-tv'], 'file_size': 12345, 'homepage': 'http://marketplace.mozilla.org/', 'icons': { 64: '/media/img/logos/64.png' }, 'is_packaged': slug == 'packaged' or rand_bool(), 'last_updated': rand_datetime(), 'manifest_url': # Minifest if packaged 'http://%s.testmanifest.com/manifest.webapp' % slug, 'name': text('App %d' % counter), 'notices': random.choice(MESSAGES), 'premium_type': 'free', 'previews': [_app_preview() for i in range(num_previews)], 'price': None, 'price_locale': '$0.00', 'promo_images': { 'small': random.choice(PROMO_IMAGES), 'large': random.choice(PROMO_IMAGES), }, 'privacy_policy': kw.get('privacy_policy', rand_text()), 'public_stats': False, 'slug': slug, 'ratings': { 'average': random.random() * 4 + 1, 'count': int(random.random() * 500), }, 'release_notes': kw.get('release_notes', rand_text(100)), 'support_email': text('support@%s.com' % slug), 'support_url': text('support.%s.com' % slug), 'tv_featured': random.choice([True, False]), 'upsell': False, } data.update(app_user_data(slug)) data = dict(data, **kw) # Special apps. if slug == 'paid': data.update( price=3.50, price_locale='$3.50', payment_required=True ) elif slug == 'upsell': data['upsell'] = { 'id': random.randint(1, 10000), 'name': rand_text(), 'icon_url': '/media/img/logos/firefox-256.png', 'app_slug': 'upsold', 'resource_uri': '/api/v1/fireplace/app/%s/' % 'upsold', } elif slug == 'packaged': data['current_version'] = '1.0' elif slug == 'unrated': data['ratings'] = { 'average': 0, 'count': 0, } elif slug == 'tracking': data['id'] = 1234 data['author'] = 'Tracking' data['name'] = 'Tracking' elif slug.startswith('num-previews-'): data['previews'] = [_app_preview() for x in range(int(slug.split('num-previews-')[1]))] if slug in SPECIAL_APP_SLUGS or slug.startswith('num-previews-'): data['name'] = string.capwords( slug.replace('_', ' ').replace('-', ' ')) return data def review_user_data(slug=None): data = { 'user': { 'has_rated': False, 'can_rate': True, } } if data['user']['can_rate']: data['rating'] = random.randint(1, 5) data['user']['has_rated'] = False # Conditional slugs for great debugging. if slug == 'has_rated': data['user']['has_rated'] = True data['user']['can_rate'] = True elif slug == 'can_rate': data['user']['has_rated'] = False data['user']['can_rate'] = True elif slug == 'cant_rate': data['user']['can_rate'] = False return data def app_user_data(slug=None): data = { 'user': { 'developed': rand_bool(), } } # Conditional slugs for great debugging. if slug == 'developed': data['user']['developed'] = True elif slug == 'user': data['user']['developed'] = False return data def app_user_review(slug, **kw): data = { 'body': kw.get('review', rand_text()), 'rating': 4 } return data def review(slug=None, **kw): global review_counter review_counter += 1 version = None if rand_bool(): version = { 'name': random.randint(1, 3), 'latest': False, } data = dict({ 'rating': random.randint(1, 5), 'body': rand_text(n=20), 'created': rand_datetime(), 'has_flagged': False, 'is_author': False, 'modified': rand_datetime(), 'report_spam': '/api/v1/apps/rating/%d/flag/' % review_counter, 'resource_uri': '/api/v1/apps/rating/%d/' % review_counter, 'user': { 'display_name': text(random.choice(USER_NAMES)), 'id': review_counter, }, 'version': version, }, **kw) if slug == 'has_flagged': data['has_flagged'] = True return data def preview(): global preview_counter preview_counter += 1 return { 'id': preview_counter, 'position': 1, 'thumbnail_url': 'http://f.cl.ly/items/103C0e0I1d1Q1f2o3K2B/' 'mkt-collection-logo.png', 'image_url': SAMPLE_BG, 'filetype': 'image/png', 'resource_uri': 'pi/v1/apps/preview/%d' % preview_counter } def extension(**kw): global extension_counter extension_counter += 1 slug = kw.get('slug', 'add-on-%d' % extension_counter) uuid = unicode(uuid4()).replace('-', '') data = { 'id': SPECIAL_SLUGS_TO_IDS.get(slug, extension_counter), 'author': random.choice(AUTHORS), 'description': { 'en-US': escape(kw.get('description', rand_text(20))), }, 'device_types': [ 'firefoxos' ], 'disabled': False, 'icons': { '64': '%s/media/img/mkt/logos/64.png' % CDN_URL, '128': '%s/media/img/mkt/logos/128.png' % CDN_URL, }, 'last_updated': '2015-10-30T15:50:40', 'latest_public_version': { 'id': 294, 'created': '2015-10-29T13:53:12', 'download_url': '/extension/%s/42/extension-0.1.zip' % uuid, 'reviewer_mini_manifest_url': '/extension/reviewers/%s/42/manifest.json' % uuid, 'unsigned_download_url': '/downloads/extension/unsigned/%s/42/extension-0.1.zip' % uuid, 'size': 19062, 'status': 'public', 'version': '0.1' }, 'mini_manifest_url': '/extension/%s/manifest.json' % uuid, 'name': { 'en-US': text('Add-on %d' % extension_counter), }, 'slug': slug, 'status': 'public', 'uuid': uuid, } data = dict(data, **kw) return data def website(**kw): global website_counter website_counter += 1 domain = '%s.example.com' % rand_text(2, separator='') data = { 'categories': [ 'news-weather' ], 'description': { 'en-US': escape(kw.get('description', rand_text(30))), }, 'device_types': [ 'firefoxos' ], 'icons': { '64': '%s/media/img/mkt/logos/64.png' % CDN_URL, '128': '%s/media/img/mkt/logos/128.png' % CDN_URL, }, 'id': website_counter, 'mobile_url': 'http://m.%s/' % domain, 'name': { 'en-US': text('Website %d' % website_counter), }, 'short_name': { 'en-US': text('Site %d' % website_counter), }, 'title': { 'en-US': text('Website Title %d' % website_counter), }, 'url': 'http://%s/' % domain } data = dict(data, **kw) return data
{"/factory/langpack.py": ["/factory/utils.py"], "/factory/feed.py": ["/factory/__init__.py", "/factory/constants.py", "/factory/utils.py"], "/factory/__init__.py": ["/factory/constants.py", "/factory/utils.py"], "/main.py": ["/app.py", "/factory/__init__.py", "/factory/constants.py"], "/factory/comm.py": ["/factory/__init__.py"], "/app.py": ["/factory/__init__.py"]}
64,246
mozilla/marketplace-api-mock
refs/heads/master
/factory/utils.py
from datetime import datetime, timedelta import random XSS = False xss_text = '"\'><script>alert("poop");</script><\'"' def text(default): return xss_text if XSS else default dummy_text = ('foo bar zip zap cvan fizz buzz something martian salad ' 'potato quality space ship rotfl alfalfa platypus dinosaur ' 'shark bear dog cat snake elephant enough of this').split() def rand_text(n=10, separator=' '): """Generate random string.""" return text(separator.join(random.choice(dummy_text) for i in xrange(n))) def rand_bool(): """Randomly returns True or False.""" return bool(random.getrandbits(1)) def rand_datetime(): """Randomly returns a datetime within the last 600 days.""" rand_date = datetime.now() - timedelta(days=random.randint(0, 600)) return rand_date.strftime('%Y-%m-%dT%H:%M:%S')
{"/factory/langpack.py": ["/factory/utils.py"], "/factory/feed.py": ["/factory/__init__.py", "/factory/constants.py", "/factory/utils.py"], "/factory/__init__.py": ["/factory/constants.py", "/factory/utils.py"], "/main.py": ["/app.py", "/factory/__init__.py", "/factory/constants.py"], "/factory/comm.py": ["/factory/__init__.py"], "/app.py": ["/factory/__init__.py"]}
64,247
mozilla/marketplace-api-mock
refs/heads/master
/main.py
""" This is a simple application which mocks out the APIs used by Fireplace. Pointing your instance of Fireplace using settings.js will allow you to quickly get up and running without needing your own installation of Zamboni or without needing to use -dev (offline mode). """ import json import random from flask import make_response, request import app import factory from factory.constants import CARRIERS, REGIONS from factory import comm from factory import feed as feed_factory from factory import langpack as langpack_factory DEFAULT_API_VERSION = 'v1' def app_generator(**kw): while True: yield factory.app(**kw) def extension_generator(**kw): while True: yield factory.extension(**kw) def langpack_generator(): while True: yield langpack_factory.langpack(url_root=request.url_root) def review_generator(**kw): while True: yield factory.review(**kw) def website_generator(**kw): while True: yield factory.website(**kw) def multi_generator(doc_types=None, **kw): doc_types_to_factories = { 'extension': factory.extension, 'webapp': factory.app, 'website': factory.website, } while True: yield doc_types_to_factories[random.choice(doc_types)](**kw) @app.route('/api/<version>/account/fxa-login/', methods=['POST'], endpoint='fxa-login') @app.route('/api/<version>/account/login/', methods=['POST']) def login(version=DEFAULT_API_VERSION): """TODO: update for FxA.""" return { 'error': None, 'token': 'some token', 'settings': { 'display_name': 'user', 'email': 'user123@mozilla.com', 'enable_recommendations': True, 'region': 'us', }, 'permissions': {}, 'apps': factory._user_apps(), } @app.route('/api/<version>/account/logout/', methods=['DELETE']) def logout(version=DEFAULT_API_VERSION): return '' @app.route('/api/<version>/account/settings/mine/', methods=['GET', 'PATCH']) def settings(version=DEFAULT_API_VERSION): return { 'display_name': 'Joe User', 'email': request.args.get('email'), 'region': 'us', } @app.route('/api/<version>/abuse/app/', methods=['POST']) def app_abuse(version=DEFAULT_API_VERSION): if not request.form.get('text'): return {'error': True} return {'error': False} @app.route('/api/<version>/account/feedback/', methods=['POST']) def feedback(version=DEFAULT_API_VERSION): if not request.form.get('feedback'): return {'error': True} return {'error': False} @app.route('/api/<version>/apps/app/<slug>/privacy/', methods=['GET']) def privacy(version=DEFAULT_API_VERSION, slug=''): return { 'privacy_policy': factory.rand_text(), } @app.route('/api/<version>/account/installed/mine/') def installed(version=DEFAULT_API_VERSION): query = request.args.get('q') data = app._paginated('objects', app_generator, 0 if query == 'empty' else 42) return data @app.route('/api/<version>/fireplace/search/', endpoint='search-fireplace') @app.route('/api/<version>/apps/search/') def search(version=DEFAULT_API_VERSION): query = request.args.get('q', '') num_results = 0 if query == 'empty' else 42 app_kw = {} if query.startswith('num-previews-'): app_kw['num_previews'] = int(query.split('num-previews-')[1]) data = app._paginated('objects', app_generator, num_results, **app_kw) return data @app.route('/api/<version>/extensions/search/') def extension_search(version=DEFAULT_API_VERSION): query = request.args.get('q', '') num_results = 0 if query == 'empty' else 42 extension_kw = {} data = app._paginated('objects', extension_generator, num_results, **extension_kw) return data @app.route('/api/<version>/fireplace/search/featured/', endpoint='featured-fireplace') @app.route('/api/<version>/apps/recommend/', endpoint='apps-recommended') def category(version=DEFAULT_API_VERSION): return app._paginated('objects', app_generator) @app.route('/api/v2/langpacks/', endpoint='langpacks') def langpacks(): fxos_version = request.args.get('fxos_version') return app._paginated('objects', langpack_generator, 0 if fxos_version == 'empty' else 42) @app.route('/api/<version>/apps/rating/', methods=['GET', 'POST']) def app_ratings(version=DEFAULT_API_VERSION): if request.method == 'POST': return {'error': False} slug = request.form.get('app') or request.args.get('app') if slug == 'unrated': return { 'info': { 'average': 0, 'slug': slug, }, 'meta': { 'next': None, 'prev': None, 'total_count': 0, }, 'objects': [], } data = app._paginated('objects', review_generator, slug=slug) data['info'] = { 'average': random.random() * 4 + 1, 'current_version': '2.0', 'slug': slug, } data.update(factory.review_user_data(slug)) if slug == 'has_rated': data['objects'][0]['has_flagged'] = False data['objects'][0]['is_author'] = True elif slug == 'old-reviews': for review in data['objects']: review['version'] = { 'version': '1.0' } return data @app.route('/api/<version>/apps/rating/<id>/', methods=['GET', 'PUT', 'DELETE']) def app_rating(version=DEFAULT_API_VERSION, id=None): if request.method in ('PUT', 'DELETE'): return {'error': False} return factory.review() @app.route('/api/<version>/apps/rating/<id>/flag/', methods=['POST']) def app_rating_flag(version=DEFAULT_API_VERSION, id=None): return '' @app.route('/api/<version>/fireplace/app/<slug>/') def app_(version=DEFAULT_API_VERSION, slug=None): return factory.app(slug=slug) @app.route('/api/<version>/installs/record/', methods=['POST']) def record_free(version=DEFAULT_API_VERSION): return {'error': False} @app.route('/api/<version>/receipts/install/', methods=['POST']) def record_paid(version=DEFAULT_API_VERSION): return {'error': False} @app.route('/api/<version>/apps/<id>/statistics/', methods=['GET']) def app_stats(version=DEFAULT_API_VERSION, id=None): return json.loads(open('./fixtures/3serieschart.json', 'r').read()) @app.route('/api/<version>/fireplace/consumer-info/', methods=['GET']) def consumer_info(version=DEFAULT_API_VERSION): return { 'region': 'us', 'apps': factory._user_apps(), # New users default to recommendations enabled. 'enable_recommendations': True } @app.route('/api/<version>/extensions/extension/<slug>/') def extension(version=DEFAULT_API_VERSION, slug=None): return factory.extension(slug=slug) @app.route('/api/<version>/feed/get/', methods=['GET', 'POST']) def feed(version=DEFAULT_API_VERSION): return app._paginated('objects', None, 30, feed_factory.feed()) @app.route('/api/<version>/fireplace/feed/brands/<slug>/', methods=['GET']) def feed_brand(version=DEFAULT_API_VERSION, slug=''): return feed_factory.brand(slug=slug) @app.route('/api/<version>/fireplace/feed/collections/<slug>/', methods=['GET']) def feed_collection(version=DEFAULT_API_VERSION, slug=''): return feed_factory.collection(name='slug', slug=slug) @app.route('/api/<version>/fireplace/feed/shelves/<slug>/', methods=['GET']) def feed_shelf(version=DEFAULT_API_VERSION, slug=''): return feed_factory.shelf(slug=slug) @app.route('/api/<version>/account/newsletter/', methods=['POST']) def newsletter(version=DEFAULT_API_VERSION, id=None): return make_response('', 204) @app.route('/api/<version>/services/config/site/') def site_config(version=DEFAULT_API_VERSION): return { 'fxa': { 'fxa_auth_state': 'bfd87ff4410049c0a8db9807661acaf3', 'fxa_auth_url': 'https://oauth-stable.dev.lcip.org/v1/authorization?scope=profile&state=bfd87ff4410049c0a8db9807661acaf3&client_id=11c73e2d918ae5d9', }, 'waffle': {} } @app.route('/api/<version>/services/region/') def regions_list(version=DEFAULT_API_VERSION): def gen(): return [factory.region(id=i, name=REGIONS[slug], slug=slug) for i, slug in enumerate(REGIONS)] data = app._paginated('objects', gen, len(REGIONS)) return data @app.route('/api/<version>/services/region/<slug>/') def regions_get(version=DEFAULT_API_VERSION, slug=None): return factory.region(slug=slug) @app.route('/api/<version>/services/carrier/') def carriers_list(version=DEFAULT_API_VERSION): def gen(): return [factory.carrier(id=i, name=CARRIERS[slug], slug=slug) for i, slug in enumerate(CARRIERS)] data = app._paginated('objects', gen, len(CARRIERS)) return data @app.route('/api/<version>/services/carrier/<slug>/') def carriers_get(version=DEFAULT_API_VERSION, slug=None): return factory.carrier(slug=slug) @app.route('/api/<version>/comm/thread/<id>/') def comm_thread(version=DEFAULT_API_VERSION, id=None): return comm.thread(id=id) @app.route('/api/<version>/fireplace/multi-search/', endpoint='multi-search-fireplace') @app.route('/api/<version>/multi-search/', endpoint='multi-search') def multi_search(version=DEFAULT_API_VERSION): query = request.args.get('q', '') num_results = 0 if query == 'empty' else 42 kw = { # The doc_type parameter in the API is singular even though it can # contain multiple document types, separated by a comma. It defaults to # webapp,website if absent. 'doc_types': request.args.get('doc_type', 'webapp,website').split(',') } if query.startswith('num-previews-'): kw['num_previews'] = int(query.split('num-previews-')[1]) data = app._paginated('objects', multi_generator, num_results, **kw) return data @app.route('/api/<version>/tv/multi-search/', endpoint='multi-search-tv') def multi_search_tv(version=DEFAULT_API_VERSION): query = request.args.get('q', '') num_results = 0 if query == 'empty' else 42 kw = { # The doc_type parameter in the API is singular even though it can # contain multiple document types, separated by a comma. It defaults to # webapp,website if absent. 'doc_types': request.args.get('doc_type', 'webapp,website').split(',') } if query.startswith('num-previews-'): kw['num_previews'] = int(query.split('num-previews-')[1]) data = app._paginated('objects', multi_generator, num_results, **kw) return data @app.route('/api/<version>/websites/website/<pk>/') def website(version=DEFAULT_API_VERSION, pk=None): return factory.website(id=pk) @app.route('/api/<version>/abuse/website/', methods=['POST']) def website_issue(version=DEFAULT_API_VERSION): if request.form.get('text') and request.form.get('website'): return { 'text': request.form['text'], 'reporter': request.form.get('reporter'), 'website': request.form['website'] } else: return make_response('', 400) @app.route('/api/<version>/websites/search/') def website_search(version=DEFAULT_API_VERSION): query = request.args.get('q', '') num_results = 0 if query == 'empty' else 42 data = app._paginated('objects', website_generator, num_results) return data @app.route('/api/<version>/games/daily/') def daily_games(version=DEFAULT_API_VERSION): with open('fixtures/daily-games.json') as f: return json.load(f) if __name__ == '__main__': app.run()
{"/factory/langpack.py": ["/factory/utils.py"], "/factory/feed.py": ["/factory/__init__.py", "/factory/constants.py", "/factory/utils.py"], "/factory/__init__.py": ["/factory/constants.py", "/factory/utils.py"], "/main.py": ["/app.py", "/factory/__init__.py", "/factory/constants.py"], "/factory/comm.py": ["/factory/__init__.py"], "/app.py": ["/factory/__init__.py"]}
64,248
mozilla/marketplace-api-mock
refs/heads/master
/factory/comm.py
from factory import app counter = 0 def thread(**kw): global counter counter += 1 return { 'app': app(), 'id': counter, 'notes_count': 5, 'version': { 'deleted': False, 'id': 45, 'version': '1.6' } } def note(**kw): return { 'attachments': [{ 'id': 1, 'created': '2013-06-14T11:54:48', 'display_name': 'Screenshot of my app.', 'url': 'http://marketplace.cdn.mozilla.net/someImage.jpg', }], 'author': 1, 'author_meta': { 'name': 'Admin' }, 'body': 'hi there', 'created': '2013-06-14T11:54:48', 'id': 2, 'note_type': 0, 'thread': 2, }
{"/factory/langpack.py": ["/factory/utils.py"], "/factory/feed.py": ["/factory/__init__.py", "/factory/constants.py", "/factory/utils.py"], "/factory/__init__.py": ["/factory/constants.py", "/factory/utils.py"], "/main.py": ["/app.py", "/factory/__init__.py", "/factory/constants.py"], "/factory/comm.py": ["/factory/__init__.py"], "/app.py": ["/factory/__init__.py"]}
64,249
mozilla/marketplace-api-mock
refs/heads/master
/factory/constants.py
from utils import text AUTHORS = [ text('Lord Basta of the Iron Isles'), text('Chris Van Halen'), text('Ngo Way'), text('Huck Charmston'), text('Davor van der Beergulpen') ] CARRIERS = { 'america_movil': 'America Movil', 'kddi': 'Kddi', 'o2': 'O2', 'telefonica': 'Telefonica', 'deutsche_telekom': 'DT', } REGIONS = { 'de': 'Germany', 'es': 'Spain', 'mx': 'Mexico', 'jp': 'Japan', 'us': 'United States', } MESSAGES = [ ['be careful, cvan made it', 'loljk'], ["it's probably a game or something"], None ] PROMO_IMAGES = [ 'https://camo.githubusercontent.com/2b57d6cab55a353ad3527886d7c1d29e2fed4bda/687474703a2f2f66696c65732e6d6f6b612e636f2f73637265656e732f74616e785f30342e6a7067', 'http://cdn.akamai.steamstatic.com/steam/apps/327310/header.jpg?t=1423847161', 'http://8bitchimp.com/wp-content/uploads/2015/04/Bastion-2012-02-10-12-23-31-59.jpg', 'https://lh3.ggpht.com/sobmPoqky8bnZZ14BZ87OusQPzD_c3BJM89E_hb1oUwACiT_s4C9WP2r5hC31C4IPzc=h900', ] SCREENSHOT_MAP = [ (126, 126144), (131, 131610), (92, 92498), (118, 118204) ] SAMPLE_BG = '/media/img/logos/firefox-256.png' # App slugs that return special data. SPECIAL_APP_SLUGS = [ 'can_rate', 'cant_rate', 'developed', 'has_rated', 'packaged', 'paid', 'unrated', 'upsell', ] # Mapping between special app slug to their ids. SPECIAL_SLUGS_TO_IDS = { 'free': 1, 'installed': 414141, 'developed': 424242, 'purchased': 434343, } USER_NAMES = ['Von Cvan', 'Lord Basta', 'Ser Davor', 'Queen Krupa', 'Le Ngoke']
{"/factory/langpack.py": ["/factory/utils.py"], "/factory/feed.py": ["/factory/__init__.py", "/factory/constants.py", "/factory/utils.py"], "/factory/__init__.py": ["/factory/constants.py", "/factory/utils.py"], "/main.py": ["/app.py", "/factory/__init__.py", "/factory/constants.py"], "/factory/comm.py": ["/factory/__init__.py"], "/app.py": ["/factory/__init__.py"]}
64,250
mozilla/marketplace-api-mock
refs/heads/master
/app.py
import json import os import sys import time import traceback import urllib import urlparse from functools import wraps from optparse import OptionParser from flask import Flask, make_response, request, Response import factory LATENCY = 0 PER_PAGE = 25 Response.default_mimetype = 'application/json' app = Flask('Flue', static_url_path='/fireplace') def _paginated(field, generator, result_count=42, objects=None, **kw): per_page = int(request.args.get('limit', PER_PAGE)) offset = int(request.args.get('offset', 0)) if offset >= result_count: items = [] elif objects: items = objects else: items = [gen for i, gen in zip(xrange(min(per_page, result_count - offset)), generator(**kw))] next_page = None if result_count > offset + per_page: next_page = request.url next_page = next_page[len(request.base_url) - len(request.path + request.script_root):] if '?' in next_page: next_page_qs = urlparse.parse_qs( next_page[next_page.index('?') + 1:], keep_blank_values=True) next_page_qs = dict(zip(next_page_qs.keys(), [x[0] for x in next_page_qs.values()])) next_page = next_page[:next_page.index('?')] else: next_page_qs = {} next_page_qs['offset'] = offset + per_page next_page_qs['limit'] = per_page next_page = next_page + '?' + urllib.urlencode(next_page_qs) return { field: items, 'meta': { 'limit': per_page, 'offset': offset, 'next': next_page, 'total_count': result_count, }, } # Monkeypatching for CORS and JSON. ar = app.route def inject_cors_headers(response, methods=None): allow_methods = set([request.method] if methods is None else methods) allow_methods.add('OPTIONS') response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Methods'] = ','.join(allow_methods) response.headers['Access-Control-Allow-Headers'] = ( 'API-Filter, X-HTTP-METHOD-OVERRIDE') @wraps(ar) def route(*args, **kwargs): methods = kwargs.get('methods') or ['GET'] def decorator(func): @wraps(func) def wrap(*args, **kwargs): resp = func(*args, **kwargs) if isinstance(resp, (dict, list, tuple, str, unicode)): resp = make_response(json.dumps(resp, indent=2), 200) inject_cors_headers(resp, methods) if LATENCY: time.sleep(LATENCY) return resp if 'methods' in kwargs: kwargs['methods'].append('OPTIONS') registered_func = ar(*args, **kwargs)(wrap) registered_func._orig = func return registered_func return decorator @app.errorhandler(404) def handler404(err): response = make_response(err, 404) inject_cors_headers(response) return response def run(): parser = OptionParser() parser.add_option('--port', dest='port', help='port', metavar='PORT', default=os.getenv('PORT', '5000')) parser.add_option('--host', dest='hostname', help='hostname', metavar='HOSTNAME', default='0.0.0.0') parser.add_option('--latency', dest='latency', help='latency (sec)', metavar='LATENCY', default=0) parser.add_option('--xss', dest='xss', help='xss?', metavar='XSS', default=0) parser.add_option('--no-debug', dest='debug', action='store_false', help='disable debug mode', default=True) options, args = parser.parse_args() if options.debug: app.debug = True else: @app.errorhandler(500) def error(error): exc_type, exc_value, tb = sys.exc_info() content = ''.join(traceback.format_tb(tb)) response = make_response(content, 500) inject_cors_headers(response) return response global LATENCY LATENCY = int(options.latency) if options.xss: factory.XSS = bool(options.xss) app.run(host=options.hostname, port=int(options.port))
{"/factory/langpack.py": ["/factory/utils.py"], "/factory/feed.py": ["/factory/__init__.py", "/factory/constants.py", "/factory/utils.py"], "/factory/__init__.py": ["/factory/constants.py", "/factory/utils.py"], "/main.py": ["/app.py", "/factory/__init__.py", "/factory/constants.py"], "/factory/comm.py": ["/factory/__init__.py"], "/app.py": ["/factory/__init__.py"]}
64,282
shahsarick/clueless
refs/heads/master
/StartServer.py
#!/usr/bin/env python import logging import socket from server.CluelessServer import CluelessServer # Setup logger logging.basicConfig(level=logging.DEBUG, format='%(asctime)s.%(msecs)d | %(levelname)s | %(module)s.%(funcName)s : %(message)s', datefmt="%H:%M:%S") # Create the server host = socket.gethostbyname(socket.gethostname()) port = 14415 server = CluelessServer(host, port) # Start the server server.start_server()
{"/StartServer.py": ["/server/CluelessServer.py"], "/server/CluelessServer.py": ["/common/MessageProtocol.py", "/server/ServerMessage.py"], "/server/ServerModel.py": ["/common/Gameboard.py", "/common/Player.py", "/common/PlayerEnum.py", "/common/RoomEnum.py", "/common/TurnEnum.py", "/common/WeaponEnum.py"], "/client/ClientMessage.py": ["/client/Client.py", "/client/ClientModel.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/common/RoomEnum.py"], "/common/Gameboard.py": ["/common/Room.py", "/common/RoomEnum.py"], "/server/ServerMessage.py": ["/common/Message.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/server/ServerModel.py"], "/client/Client.py": ["/observer/observer.py", "/common/MessageProtocol.py"]}
64,283
shahsarick/clueless
refs/heads/master
/server/CluelessServer.py
#!/usr/bin/env python import logging import Queue import select import socket import threading from common.MessageProtocol import MessageProtocol from server.ServerMessage import ServerMessage class CluelessServer: __connection_backlog = 10 __select_timeout = 0.5 __read_size = 4096 def __init__(self, host, port): self._host = host self._port = port self._socket_list = [] self._logger = logging.getLogger('CluelessServer') self._output_queue = Queue.Queue() self._server_message = ServerMessage(self._output_queue) # Starts the server def start_server(self): # Create the server socket self._logger.debug('Creating server socket.') self._server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Listen for connections self._logger.debug('Listening for connections.') self._server_socket.bind((self._host, self._port)) self._server_socket.listen(self.__connection_backlog) self._socket_list.append(self._server_socket) server_thread = threading.Thread(target=self.run) server_thread.start() def run(self): while True: ready_to_read, ready_to_write, input_error = select.select(self._socket_list, [], [], self.__select_timeout) # Loop through list of sockets that have data for sock in ready_to_read: # Received new connection request if sock == self._server_socket: # Accept the connection and append it to the socket list self._logger.debug('Received connection request. Establishing connection with client.') new_sock, address = self._server_socket.accept() new_sock.settimeout(0.5) #TODO: Remove this and while loop below if we start running into issues (workaround for while loop timeout-blocking issue) # Check the number of players currently connected to the server if len(self._socket_list) < 7: self._logger.debug('Client connected from %s on port %s' % address) # Add the socket to the socket list self._socket_list.append(new_sock) # Add a new player to the server model self._server_message.add_player(address) # Send all messages in the output queue self.send_all_messages(new_sock) # Game is full else: self._logger.debug('Closed connection with %s on port %s' % address) new_sock.close() # Received message from client else: # This should ensure all the data from the socket is received message_list = [] while 1: message, bytes_read = MessageProtocol.recv_msg(sock) if bytes_read > 0: message_list.append(message) else: break # Check to see if data is available message_list_length = len(message_list) if message_list_length > 0: # Retrieve the player associated with this socket address = sock._sock.getpeername() player = self._server_message.get_player(address) # Handle the request self._server_message.handle_message(message_list, player) # Send response to the client(s) self._logger.debug('Sending message(s) to client(s).') # Send all messages in the output queue self.send_all_messages(sock) # Client disconnected else: self._logger.error('Client disconnected.') self.remove_client(sock) self._server_socket.close() # Send all of the messages in the output queue def send_all_messages(self, sock): while self._output_queue.qsize() > 0: broadcast, message = self._output_queue.get() self.send_message(broadcast, sock, message) # Sends a reply message or broadcasts the message to all clients def send_message(self, broadcast, sock, message): # Check to see if this is a broadcast message if broadcast == True: for client_socket in self._socket_list: if client_socket != self._server_socket: MessageProtocol.send_msg(client_socket, message) # Send the message to the specified socket (sock) else: MessageProtocol.send_msg(sock, message) # Remove the specified client from the server def remove_client(self, sock): address = sock._sock.getpeername() self._logger.debug('Removing the connection to (%s, %s).' % address) self._socket_list.remove(sock) self._server_message.remove_player(address) sock.close()
{"/StartServer.py": ["/server/CluelessServer.py"], "/server/CluelessServer.py": ["/common/MessageProtocol.py", "/server/ServerMessage.py"], "/server/ServerModel.py": ["/common/Gameboard.py", "/common/Player.py", "/common/PlayerEnum.py", "/common/RoomEnum.py", "/common/TurnEnum.py", "/common/WeaponEnum.py"], "/client/ClientMessage.py": ["/client/Client.py", "/client/ClientModel.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/common/RoomEnum.py"], "/common/Gameboard.py": ["/common/Room.py", "/common/RoomEnum.py"], "/server/ServerMessage.py": ["/common/Message.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/server/ServerModel.py"], "/client/Client.py": ["/observer/observer.py", "/common/MessageProtocol.py"]}
64,284
shahsarick/clueless
refs/heads/master
/pseudoGUI.py
__author__ = 'Stephen Bailey' #!/usr/bin/env python import logging import socket import sys from client.ClientMessage import ClientMessage from common.Message import Message from common.MessageEnum import MessageEnum from observer.observer import Observer, observerObject from time import sleep #TODO: Move all relevant code to GUI # GUI methods def prompt_move(): print 'Please enter a room number to move to (see RoomEnum.py)' try: room = int(sys.stdin.readline().rstrip()) return room except ValueError: return -1 def lobby_ready(): message = Message(MessageEnum.LOBBY_READY, 1, [True]) client_message.send_message(message) def lobby_unready(): message = Message(MessageEnum.LOBBY_UNREADY, 1, [False]) client_message.send_message(message) def move(): room = prompt_move() if room != -1: message_args = [room] message = Message(MessageEnum.MOVE, 1, message_args) client_message.send_message(message) else: print 'Invalid room number' # Setup logger logging.basicConfig(level=logging.DEBUG, format='%(asctime)s.%(msecs)d | %(levelname)s | %(module)s.%(funcName)s : %(message)s', datefmt="%H:%M:%S") # Create the client #TODO: Get IP from GUi host = socket.gethostbyname(socket.gethostname()) port = 14415 client_message = ClientMessage() connected = client_message.connect_to_server(host, port) # Create the observer if connected == True: obsObj = observerObject() observer = Observer(obsObj.subject) observer.registerCallback(client_message.handle_message) else: print 'Failed to connect with server.' sleep(2) #loop to simulate GUI actions while True: print "Enter a command: " player_input = sys.stdin.readline().rstrip() if player_input == "lobby ready": lobby_ready() sleep(3) elif player_input == "lobby unready": lobby_unready() sleep(3) elif player_input == 'move': move() sleep(3) else: print "command not recognized"
{"/StartServer.py": ["/server/CluelessServer.py"], "/server/CluelessServer.py": ["/common/MessageProtocol.py", "/server/ServerMessage.py"], "/server/ServerModel.py": ["/common/Gameboard.py", "/common/Player.py", "/common/PlayerEnum.py", "/common/RoomEnum.py", "/common/TurnEnum.py", "/common/WeaponEnum.py"], "/client/ClientMessage.py": ["/client/Client.py", "/client/ClientModel.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/common/RoomEnum.py"], "/common/Gameboard.py": ["/common/Room.py", "/common/RoomEnum.py"], "/server/ServerMessage.py": ["/common/Message.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/server/ServerModel.py"], "/client/Client.py": ["/observer/observer.py", "/common/MessageProtocol.py"]}
64,285
shahsarick/clueless
refs/heads/master
/common/MessageProtocol.py
#!/usr/bin/env python import cPickle as pickle import struct import time class MessageProtocol: timeout = 0.5 @staticmethod def send_msg(sock, message): data_string = pickle.dumps(message) length = len(data_string) sock.sendall(struct.pack('!I', length)) sock.sendall(data_string) @staticmethod def recv_msg(sock): length_buffer = MessageProtocol.recvall(sock, 4) if length_buffer is not None: length, = struct.unpack('!I', length_buffer) data_string = MessageProtocol.recvall(sock, length) message = pickle.loads(data_string) return message, length else: return '', 0 @staticmethod def recvall(sock, count): buf = b'' start = time.time() while count: # Check to see if timeout has occurred if time.time() - start > MessageProtocol.timeout: return None try: new_buffer = sock.recv(count) if not new_buffer: return None buf += new_buffer count -= len(new_buffer) except: pass return buf
{"/StartServer.py": ["/server/CluelessServer.py"], "/server/CluelessServer.py": ["/common/MessageProtocol.py", "/server/ServerMessage.py"], "/server/ServerModel.py": ["/common/Gameboard.py", "/common/Player.py", "/common/PlayerEnum.py", "/common/RoomEnum.py", "/common/TurnEnum.py", "/common/WeaponEnum.py"], "/client/ClientMessage.py": ["/client/Client.py", "/client/ClientModel.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/common/RoomEnum.py"], "/common/Gameboard.py": ["/common/Room.py", "/common/RoomEnum.py"], "/server/ServerMessage.py": ["/common/Message.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/server/ServerModel.py"], "/client/Client.py": ["/observer/observer.py", "/common/MessageProtocol.py"]}
64,286
shahsarick/clueless
refs/heads/master
/common/PlayerEnum.py
#!/usr/bin/env python class PlayerEnum(object): MISS_SCARLET = 1 COLONEL_MUSTARD = 2 PROFESSOR_PLUM = 3 MR_GREEN = 4 MRS_WHITE = 5 MRS_PEACOCK = 6 ENVELOPE = 7 @staticmethod def to_string(player_enum): if player_enum == PlayerEnum.MISS_SCARLET: return 'Miss Scarlet' elif player_enum == PlayerEnum.COLONEL_MUSTARD: return 'Colonel Mustard' elif player_enum == PlayerEnum.PROFESSOR_PLUM: return 'Professor Plum' elif player_enum == PlayerEnum.MR_GREEN: return 'Mr. Green' elif player_enum == PlayerEnum.MRS_WHITE: return 'Mrs. White' elif player_enum == PlayerEnum.MRS_PEACOCK: return 'Mrs. Peacock' else: return ''
{"/StartServer.py": ["/server/CluelessServer.py"], "/server/CluelessServer.py": ["/common/MessageProtocol.py", "/server/ServerMessage.py"], "/server/ServerModel.py": ["/common/Gameboard.py", "/common/Player.py", "/common/PlayerEnum.py", "/common/RoomEnum.py", "/common/TurnEnum.py", "/common/WeaponEnum.py"], "/client/ClientMessage.py": ["/client/Client.py", "/client/ClientModel.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/common/RoomEnum.py"], "/common/Gameboard.py": ["/common/Room.py", "/common/RoomEnum.py"], "/server/ServerMessage.py": ["/common/Message.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/server/ServerModel.py"], "/client/Client.py": ["/observer/observer.py", "/common/MessageProtocol.py"]}
64,287
shahsarick/clueless
refs/heads/master
/server/ServerModel.py
#!/usr/bin/env python import logging from random import randint from common.Gameboard import Gameboard from common.Player import Player from common.PlayerEnum import PlayerEnum from common.RoomEnum import RoomEnum from common.TurnEnum import TurnEnum from common.WeaponEnum import WeaponEnum class ServerModel: def __init__(self): self._logger = logging.getLogger('ServerModel') # Create character dictionary and player list for lobby and socket use self._character_list = {PlayerEnum.MISS_SCARLET : False, \ PlayerEnum.COLONEL_MUSTARD : False, \ PlayerEnum.PROFESSOR_PLUM : False, \ PlayerEnum.MR_GREEN : False, \ PlayerEnum.MRS_WHITE : False, \ PlayerEnum.MRS_PEACOCK : False} self._player_list = [] # Set card locations self._player_positions = {PlayerEnum.MISS_SCARLET : RoomEnum.HALLWAY_HALL_LOUNGE, \ PlayerEnum.COLONEL_MUSTARD : RoomEnum.HALLWAY_LOUNGE_DINING_ROOM, \ PlayerEnum.PROFESSOR_PLUM : RoomEnum.HALLWAY_LIBRARY_STUDY, \ PlayerEnum.MR_GREEN : RoomEnum.HALLWAY_BALLROOM_CONSERVATORY, \ PlayerEnum.MRS_WHITE : RoomEnum.HALLWAY_KITCHEN_BALLROOM, \ PlayerEnum.MRS_PEACOCK : RoomEnum.HALLWAY_CONSERVATORY_LIBRARY} self._weapon_locations = {WeaponEnum.CANDLESTICK : RoomEnum.STUDY, \ WeaponEnum.ROPE : RoomEnum.BALLROOM, \ WeaponEnum.LEAD_PIPE : RoomEnum.HALL, \ WeaponEnum.REVOLVER : RoomEnum.BILLIARD_ROOM, \ WeaponEnum.WRENCH : RoomEnum.CONSERVATORY, \ WeaponEnum.KNIFE : RoomEnum.KITCHEN} # Set turn order self._turn_order = [PlayerEnum.MISS_SCARLET, PlayerEnum.COLONEL_MUSTARD, PlayerEnum.MRS_WHITE, PlayerEnum.MR_GREEN, PlayerEnum.MRS_PEACOCK, PlayerEnum.PROFESSOR_PLUM] self._turn_state = TurnEnum.MOVE # Create gameboard self._gameboard = Gameboard() self._gameboard.setup_rooms() # Fill envelope with suspect, weapon, and room suspect = randint(1, 6) weapon = randint(1, 6) room = randint(1, 9) self._envelope = [suspect, weapon, room] self._game_started = False # Add a player to the player list using the given address def add_player(self, address): # Assign an available player_enum from the character list to the new player for player_enum in self._character_list: if self._character_list[player_enum] == False: self._character_list[player_enum] = True new_player = Player(address, player_enum) break # Add the new player to the player list player_enum = new_player.get_player_enum() player_enum_str = PlayerEnum.to_string(player_enum) self._logger.debug('Adding (%s, %s) as %s to player list.', address[0], address[1], player_enum_str) self._player_list.append(new_player) # Get the player with the associated address def get_player(self, address): self._logger.debug('Retrieving player mapped to (%s, %s).' % address) for player in self._player_list: player_address = player.get_address() if self.compare_addresses(address, player_address) == True: return player # Remove the player from the game and free the associated player_enum in the character list def remove_player(self, address): self._logger.debug('Removing (%s, %s) from player list.' % address) for player in self._player_list: player_address = player.get_address() if self.compare_addresses(address, player_address) == True: # Make the player_enum in the character list available to be used by someone else player_enum = player.get_player_enum() self._character_list[player_enum] = False # Remove the player from the player list self._player_list.remove(player) break # Compare the address to determine if they are equal def compare_addresses(self, address1, address2): if address1[0] == address2[0] and address1[1] == address2[1]: return True else: return False # Attempt to move the player to the destination room def perform_move(self, player_enum, destination_room): current_room = self._player_positions[player_enum] player_enum_str = PlayerEnum.to_string(player_enum) current_room_str = RoomEnum.to_string(current_room) destination_room_str = RoomEnum.to_string(destination_room) self._logger.debug('Attempting to move %s from "%s" to "%s".', player_enum_str, current_room_str, destination_room_str) # Check to see if the move is valid on the gameboard valid_move = self._gameboard.is_valid_move(current_room, destination_room) # Check to see if the destination is an occupied hallway if self._gameboard.is_hallway(destination_room) == True: for player_position, player_location in self._player_positions.items(): if destination_room == player_location: valid_move = False break # Update the player position if the move is valid if valid_move == True: self._player_positions[player_enum] = destination_room return valid_move # Get the list of players in the lobby and their associated ready status def get_lobby_list(self): self._logger.debug('Retrieving lobby list:') lobby_list = [] for player in self._player_list: player_name = player.get_name() ready_state = player.get_ready_status() self._logger.debug('\t(%s, %s)', player_name, ready_state) lobby_entry = [player_name, ready_state] lobby_list.append(lobby_entry) return lobby_list # Get the position for the specified player_enum def get_player_position(self, player_enum): current_room = self._player_positions[player_enum] return current_room # Check to see if the game is ready to start def is_game_ready(self): self._logger.debug('Checking to see if the game is ready to start.') # Check to make sure the minimum number of players are in the game if len(self._player_list) < 2: return False # Check to see if everyone in the game is ready for player in self._player_list: if player.get_ready_status() == False: return False self._game_started = True return True # Check to see if the game has started def is_game_started(self): return self._game_started
{"/StartServer.py": ["/server/CluelessServer.py"], "/server/CluelessServer.py": ["/common/MessageProtocol.py", "/server/ServerMessage.py"], "/server/ServerModel.py": ["/common/Gameboard.py", "/common/Player.py", "/common/PlayerEnum.py", "/common/RoomEnum.py", "/common/TurnEnum.py", "/common/WeaponEnum.py"], "/client/ClientMessage.py": ["/client/Client.py", "/client/ClientModel.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/common/RoomEnum.py"], "/common/Gameboard.py": ["/common/Room.py", "/common/RoomEnum.py"], "/server/ServerMessage.py": ["/common/Message.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/server/ServerModel.py"], "/client/Client.py": ["/observer/observer.py", "/common/MessageProtocol.py"]}
64,288
shahsarick/clueless
refs/heads/master
/common/WeaponEnum.py
#!/usr/bin/env python class WeaponEnum(object): CANDLESTICK = 1 ROPE = 2 LEAD_PIPE = 3 REVOLVER = 4 WRENCH = 5 KNIFE = 6
{"/StartServer.py": ["/server/CluelessServer.py"], "/server/CluelessServer.py": ["/common/MessageProtocol.py", "/server/ServerMessage.py"], "/server/ServerModel.py": ["/common/Gameboard.py", "/common/Player.py", "/common/PlayerEnum.py", "/common/RoomEnum.py", "/common/TurnEnum.py", "/common/WeaponEnum.py"], "/client/ClientMessage.py": ["/client/Client.py", "/client/ClientModel.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/common/RoomEnum.py"], "/common/Gameboard.py": ["/common/Room.py", "/common/RoomEnum.py"], "/server/ServerMessage.py": ["/common/Message.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/server/ServerModel.py"], "/client/Client.py": ["/observer/observer.py", "/common/MessageProtocol.py"]}
64,289
shahsarick/clueless
refs/heads/master
/observer/observer.py
# basic observer classes class Observable: def __init__(self): self.__observers = [] def register_observer(self, observer): self.__observers.append(observer) def notify_observers(self, *args, **kwargs): for observer in self.__observers: observer.notify(self, *args, **kwargs) class Observer(): def __init__(self, observable): self.callback = None observable.register_observer(self) # this function passed to registerCallBack should be the function invoked upon notify def registerCallback(self, function): self.callback = function def notify(self, observable, *args, **kwargs): self.callback() # singleton subject object containing the observers, the subject should always be referenced through this class class observerObject(object): class __observerObject: def __init__(self): self.subject = Observable() instance = None def __new__(cls): if not observerObject.instance: observerObject.instance = observerObject.__observerObject() return observerObject.instance
{"/StartServer.py": ["/server/CluelessServer.py"], "/server/CluelessServer.py": ["/common/MessageProtocol.py", "/server/ServerMessage.py"], "/server/ServerModel.py": ["/common/Gameboard.py", "/common/Player.py", "/common/PlayerEnum.py", "/common/RoomEnum.py", "/common/TurnEnum.py", "/common/WeaponEnum.py"], "/client/ClientMessage.py": ["/client/Client.py", "/client/ClientModel.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/common/RoomEnum.py"], "/common/Gameboard.py": ["/common/Room.py", "/common/RoomEnum.py"], "/server/ServerMessage.py": ["/common/Message.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/server/ServerModel.py"], "/client/Client.py": ["/observer/observer.py", "/common/MessageProtocol.py"]}
64,290
shahsarick/clueless
refs/heads/master
/common/MessageEnum.py
#!/usr/bin/env python class MessageEnum(object): MOVE = 1 SUGGEST = 2 ACCUSE = 3 LOBBY_ADD = 4 LOBBY_READY = 5 LOBBY_UNREADY = 6 LOBBY_CHANGE_PLAYER = 7 GAME_STATE_CHANGE = 8 TURN_OVER = 9 TURN_BEGIN = 10 ERROR = 11
{"/StartServer.py": ["/server/CluelessServer.py"], "/server/CluelessServer.py": ["/common/MessageProtocol.py", "/server/ServerMessage.py"], "/server/ServerModel.py": ["/common/Gameboard.py", "/common/Player.py", "/common/PlayerEnum.py", "/common/RoomEnum.py", "/common/TurnEnum.py", "/common/WeaponEnum.py"], "/client/ClientMessage.py": ["/client/Client.py", "/client/ClientModel.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/common/RoomEnum.py"], "/common/Gameboard.py": ["/common/Room.py", "/common/RoomEnum.py"], "/server/ServerMessage.py": ["/common/Message.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/server/ServerModel.py"], "/client/Client.py": ["/observer/observer.py", "/common/MessageProtocol.py"]}
64,291
shahsarick/clueless
refs/heads/master
/client/ClientModel.py
#!/usr/bin/env python class ClientModel: def __init__(self): pass # Gets the player_enum def get_player_enum(self): return self._player_enum # Sets the player_enum def set_player_enum(self, player_enum): self._player_enum = player_enum
{"/StartServer.py": ["/server/CluelessServer.py"], "/server/CluelessServer.py": ["/common/MessageProtocol.py", "/server/ServerMessage.py"], "/server/ServerModel.py": ["/common/Gameboard.py", "/common/Player.py", "/common/PlayerEnum.py", "/common/RoomEnum.py", "/common/TurnEnum.py", "/common/WeaponEnum.py"], "/client/ClientMessage.py": ["/client/Client.py", "/client/ClientModel.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/common/RoomEnum.py"], "/common/Gameboard.py": ["/common/Room.py", "/common/RoomEnum.py"], "/server/ServerMessage.py": ["/common/Message.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/server/ServerModel.py"], "/client/Client.py": ["/observer/observer.py", "/common/MessageProtocol.py"]}
64,292
shahsarick/clueless
refs/heads/master
/common/Room.py
#!/usr/bin/env python class Room: def __init__(self, room_list): self._connected_rooms = room_list # Check to see if a move to the destination room is valid def is_valid_move(self, destination_room): # Check to see if the destination room matches any of the rooms connected to this one for room in self._connected_rooms: if room == destination_room: return True return False # Retrieve the list of rooms connected to this one def get_valid_moves(self): return self._connected_rooms
{"/StartServer.py": ["/server/CluelessServer.py"], "/server/CluelessServer.py": ["/common/MessageProtocol.py", "/server/ServerMessage.py"], "/server/ServerModel.py": ["/common/Gameboard.py", "/common/Player.py", "/common/PlayerEnum.py", "/common/RoomEnum.py", "/common/TurnEnum.py", "/common/WeaponEnum.py"], "/client/ClientMessage.py": ["/client/Client.py", "/client/ClientModel.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/common/RoomEnum.py"], "/common/Gameboard.py": ["/common/Room.py", "/common/RoomEnum.py"], "/server/ServerMessage.py": ["/common/Message.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/server/ServerModel.py"], "/client/Client.py": ["/observer/observer.py", "/common/MessageProtocol.py"]}
64,293
shahsarick/clueless
refs/heads/master
/common/RoomEnum.py
#!/usr/bin/env python class RoomEnum(object): STUDY = 1 HALL = 2 LOUNGE = 3 DINING_ROOM = 4 KITCHEN = 5 BALLROOM = 6 CONSERVATORY = 7 LIBRARY = 8 BILLIARD_ROOM = 9 HALLWAY_STUDY_HALL = 10 HALLWAY_HALL_LOUNGE = 11 HALLWAY_LOUNGE_DINING_ROOM = 12 HALLWAY_DINING_ROOM_KITCHEN = 13 HALLWAY_KITCHEN_BALLROOM = 14 HALLWAY_BALLROOM_CONSERVATORY = 15 HALLWAY_CONSERVATORY_LIBRARY = 16 HALLWAY_LIBRARY_STUDY = 17 HALLWAY_BILLIARD_ROOM_HALL = 18 HALLWAY_BILLIARD_ROOM_DINING_ROOM = 19 HALLWAY_BILLIARD_ROOM_BALLROOM = 20 HALLWAY_BILLIARD_ROOM_LIBRARY = 21 @staticmethod def to_string(room_enum): if room_enum == RoomEnum.STUDY: return 'Study' elif room_enum == RoomEnum.HALL: return 'Hall' elif room_enum == RoomEnum.LOUNGE: return 'Lounge' elif room_enum == RoomEnum.DINING_ROOM: return 'Dining room' elif room_enum == RoomEnum.KITCHEN: return 'Kitchen' elif room_enum == RoomEnum.BALLROOM: return 'Ballroom' elif room_enum == RoomEnum.CONSERVATORY: return 'Conservatory' elif room_enum == RoomEnum.LIBRARY: return 'Library' elif room_enum == RoomEnum.BILLIARD_ROOM: return 'Billiard room' elif room_enum == RoomEnum.HALLWAY_STUDY_HALL: return 'Study-Hall hallway' elif room_enum == RoomEnum.HALLWAY_HALL_LOUNGE: return 'Hall-Lounge hallway' elif room_enum == RoomEnum.HALLWAY_LOUNGE_DINING_ROOM: return 'Lounge-Dining room hallway' elif room_enum == RoomEnum.HALLWAY_DINING_ROOM_KITCHEN: return 'Dining room-Kitchen hallway' elif room_enum == RoomEnum.HALLWAY_KITCHEN_BALLROOM: return 'Kitchen-Ballroom hallway' elif room_enum == RoomEnum.HALLWAY_BALLROOM_CONSERVATORY: return 'Ballroom-Conservatory hallway' elif room_enum == RoomEnum.HALLWAY_CONSERVATORY_LIBRARY: return 'Conservatory-Library hallway' elif room_enum == RoomEnum.HALLWAY_LIBRARY_STUDY: return 'Library-Study hallway' elif room_enum == RoomEnum.HALLWAY_BILLIARD_ROOM_HALL: return 'Billiard room-Hall hallway' elif room_enum == RoomEnum.HALLWAY_BILLIARD_ROOM_DINING_ROOM: return 'Billiard room-Dining room hallway' elif room_enum == RoomEnum.HALLWAY_BILLIARD_ROOM_BALLROOM: return 'Billiard room-Ballroom hallway' elif room_enum == RoomEnum.HALLWAY_BILLIARD_ROOM_LIBRARY: return 'Billiard room-Library hallway' else: return ''
{"/StartServer.py": ["/server/CluelessServer.py"], "/server/CluelessServer.py": ["/common/MessageProtocol.py", "/server/ServerMessage.py"], "/server/ServerModel.py": ["/common/Gameboard.py", "/common/Player.py", "/common/PlayerEnum.py", "/common/RoomEnum.py", "/common/TurnEnum.py", "/common/WeaponEnum.py"], "/client/ClientMessage.py": ["/client/Client.py", "/client/ClientModel.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/common/RoomEnum.py"], "/common/Gameboard.py": ["/common/Room.py", "/common/RoomEnum.py"], "/server/ServerMessage.py": ["/common/Message.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/server/ServerModel.py"], "/client/Client.py": ["/observer/observer.py", "/common/MessageProtocol.py"]}
64,294
shahsarick/clueless
refs/heads/master
/observer/__init__.py
__author__ = 'Stephen Bailey'
{"/StartServer.py": ["/server/CluelessServer.py"], "/server/CluelessServer.py": ["/common/MessageProtocol.py", "/server/ServerMessage.py"], "/server/ServerModel.py": ["/common/Gameboard.py", "/common/Player.py", "/common/PlayerEnum.py", "/common/RoomEnum.py", "/common/TurnEnum.py", "/common/WeaponEnum.py"], "/client/ClientMessage.py": ["/client/Client.py", "/client/ClientModel.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/common/RoomEnum.py"], "/common/Gameboard.py": ["/common/Room.py", "/common/RoomEnum.py"], "/server/ServerMessage.py": ["/common/Message.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/server/ServerModel.py"], "/client/Client.py": ["/observer/observer.py", "/common/MessageProtocol.py"]}
64,295
shahsarick/clueless
refs/heads/master
/client/ClientMessage.py
#!/usr/bin/env python import cPickle as pickle import logging import Queue import threading from client.Client import Client from client.ClientModel import ClientModel from common.MessageEnum import MessageEnum from common.PlayerEnum import PlayerEnum from common.RoomEnum import RoomEnum class ClientMessage: def __init__(self): self._logger = logging.getLogger('ClientMessage') self._input_queue = Queue.Queue() self._output_queue = Queue.Queue() self.i = 0 self._client = Client(self._input_queue, self._output_queue) self._client_model = ClientModel() # Connects to the server def connect_to_server(self, host, port): #TODO: May need to move connect_to_server into worker thread to prevent server messages coming back before we're ready for them connected = self._client.connect_to_server(host, port) if connected == True: self.start_client() return True else: return False # Starts the client communication thread def start_client(self): self._logger.debug('Starting client communication thread.') client_thread = threading.Thread(target=self._client.run) client_thread.start() # Send a message to the server def send_message(self, message): self._input_queue.put(message) # Handle the messages sent by the server def handle_message(self): while self._output_queue.qsize() > 0: message = self._output_queue.get() message_enum = message.get_message_enum() num_args = message.get_num_args() message_args = message.get_args() # Handle move messages if message_enum == MessageEnum.MOVE: valid_move = message_args[0] if valid_move == True: player_enum = message_args[1] old_room = message_args[2] new_room = message_args[3] old_room_str = RoomEnum.to_string(old_room) player_enum_str = PlayerEnum.to_string(player_enum) new_room_str = RoomEnum.to_string(new_room) self._logger.debug('%s moved from "%s" to "%s".', player_enum_str, old_room_str, new_room_str) else: self._logger.debug('Invalid move!') # Handle suggest messages elif message_enum == MessageEnum.SUGGEST: self._logger.debug('Received a suggest message.') # Handle accuse message elif message_enum == MessageEnum.ACCUSE: self._logger.debug('Received an accusation message.') # Handle lobby ready and unready messages elif message_enum == MessageEnum.LOBBY_ADD or message_enum == MessageEnum.LOBBY_READY or message_enum == MessageEnum.LOBBY_UNREADY: # Refresh the lobby with the updated list of player names and ready states # This keeps the lobby in sync in case someone leaves and provides the entire lobby list to new players lobby_list = message_args self._logger.debug('Printing lobby list:') for lobby_entry in lobby_list: player_name = lobby_entry[0] ready_state = lobby_entry[1] self._logger.debug('\t(%s, %s).', player_name, ready_state) # Handle lobby change player message elif message_enum == MessageEnum.LOBBY_CHANGE_PLAYER: player_enum = message_args[0] self._logger.debug('You have been assigned the character "%s".', PlayerEnum.to_string(player_enum)) self._client_model.set_player_enum(player_enum) # Handle game state change message elif message_enum == MessageEnum.GAME_STATE_CHANGE: self._logger.debug('Received a game state change message.') # Handle turn over message elif message_enum == MessageEnum.TURN_OVER: self._logger.debug('Received a turn over message.') # Handle turn begin message elif message_enum == MessageEnum.TURN_BEGIN: player_enum = message_args[0] self._logger.debug('It is now "%s\'s" turn!.', PlayerEnum.to_string(player_enum)) if player_enum == self._client_model.get_player_enum(): self._logger.debug('It is now your turn!') # Handle error message elif message_enum == MessageEnum.ERROR: self._logger.debug('Received an error message.')
{"/StartServer.py": ["/server/CluelessServer.py"], "/server/CluelessServer.py": ["/common/MessageProtocol.py", "/server/ServerMessage.py"], "/server/ServerModel.py": ["/common/Gameboard.py", "/common/Player.py", "/common/PlayerEnum.py", "/common/RoomEnum.py", "/common/TurnEnum.py", "/common/WeaponEnum.py"], "/client/ClientMessage.py": ["/client/Client.py", "/client/ClientModel.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/common/RoomEnum.py"], "/common/Gameboard.py": ["/common/Room.py", "/common/RoomEnum.py"], "/server/ServerMessage.py": ["/common/Message.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/server/ServerModel.py"], "/client/Client.py": ["/observer/observer.py", "/common/MessageProtocol.py"]}
64,296
shahsarick/clueless
refs/heads/master
/common/TurnEnum.py
#!/usr/bin/env python class TurnEnum(object): MOVE = 1 SUGGEST = 2 DISPROVE = 3
{"/StartServer.py": ["/server/CluelessServer.py"], "/server/CluelessServer.py": ["/common/MessageProtocol.py", "/server/ServerMessage.py"], "/server/ServerModel.py": ["/common/Gameboard.py", "/common/Player.py", "/common/PlayerEnum.py", "/common/RoomEnum.py", "/common/TurnEnum.py", "/common/WeaponEnum.py"], "/client/ClientMessage.py": ["/client/Client.py", "/client/ClientModel.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/common/RoomEnum.py"], "/common/Gameboard.py": ["/common/Room.py", "/common/RoomEnum.py"], "/server/ServerMessage.py": ["/common/Message.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/server/ServerModel.py"], "/client/Client.py": ["/observer/observer.py", "/common/MessageProtocol.py"]}
64,297
shahsarick/clueless
refs/heads/master
/common/Gameboard.py
#!/usr/bin/env python import logging from common.Room import Room from common.RoomEnum import RoomEnum class Gameboard: def __init__(self): self._logger = logging.getLogger('Gameboard') # Setup the rooms def setup_rooms(self): self._logger.debug('Setting up gameboard.') # Create Study study = Room([RoomEnum.HALLWAY_STUDY_HALL, \ RoomEnum.HALLWAY_LIBRARY_STUDY, \ RoomEnum.KITCHEN]) # Create Hall hall = Room([RoomEnum.HALLWAY_HALL_LOUNGE, \ RoomEnum.HALLWAY_BILLIARD_ROOM_HALL, \ RoomEnum.HALLWAY_STUDY_HALL]) # Create Lounge lounge = Room([RoomEnum.HALLWAY_LOUNGE_DINING_ROOM, \ RoomEnum.HALLWAY_HALL_LOUNGE, \ RoomEnum.CONSERVATORY]) # Create Dining room dining_room = Room([RoomEnum.HALLWAY_LOUNGE_DINING_ROOM, \ RoomEnum.HALLWAY_DINING_ROOM_KITCHEN, \ RoomEnum.HALLWAY_BILLIARD_ROOM_DINING_ROOM]) # Create Kitchen kitchen = Room([RoomEnum.HALLWAY_DINING_ROOM_KITCHEN, \ RoomEnum.HALLWAY_KITCHEN_BALLROOM, \ RoomEnum.STUDY]) # Create Ballroom ballroom = Room([RoomEnum.HALLWAY_BILLIARD_ROOM_BALLROOM, \ RoomEnum.HALLWAY_KITCHEN_BALLROOM, \ RoomEnum.HALLWAY_BALLROOM_CONSERVATORY]) # Create Conservatory conservatory = Room([RoomEnum.HALLWAY_CONSERVATORY_LIBRARY, \ RoomEnum.HALLWAY_BALLROOM_CONSERVATORY, \ RoomEnum.LOUNGE]) # Create Library library = Room([RoomEnum.HALLWAY_LIBRARY_STUDY, \ RoomEnum.HALLWAY_BILLIARD_ROOM_LIBRARY, \ RoomEnum.HALLWAY_CONSERVATORY_LIBRARY]) # Create Billiard room billiard_room = Room([RoomEnum.HALLWAY_BILLIARD_ROOM_HALL, \ RoomEnum.HALLWAY_BILLIARD_ROOM_DINING_ROOM, \ RoomEnum.HALLWAY_BILLIARD_ROOM_BALLROOM, \ RoomEnum.HALLWAY_BILLIARD_ROOM_LIBRARY]) # Create hallways hallway_study_hall = Room([RoomEnum.STUDY, RoomEnum.HALL]) hallway_hall_lounge = Room([RoomEnum.HALL, RoomEnum.LOUNGE]) hallway_lounge_dining_room = Room([RoomEnum.LOUNGE, RoomEnum.DINING_ROOM]) hallway_dining_room_kitchen = Room([RoomEnum.DINING_ROOM, RoomEnum.KITCHEN]) hallway_kitchen_ballroom = Room([RoomEnum.KITCHEN, RoomEnum.BALLROOM]) hallway_ballroom_conservatory = Room([RoomEnum.BALLROOM, RoomEnum.CONSERVATORY]) hallway_conservatory_library = Room([RoomEnum.CONSERVATORY, RoomEnum.LIBRARY]) hallway_library_study = Room([RoomEnum.LIBRARY, RoomEnum.STUDY]) hallway_billiard_room_hall = Room([RoomEnum.BILLIARD_ROOM, RoomEnum.HALL]) hallway_billiard_room_dining_room = Room([RoomEnum.BILLIARD_ROOM, RoomEnum.DINING_ROOM]) hallway_billiard_room_ballroom = Room([RoomEnum.BILLIARD_ROOM, RoomEnum.BALLROOM]) hallway_billiard_room_library = Room([RoomEnum.BILLIARD_ROOM, RoomEnum.LIBRARY]) # Create room dictionary self._rooms = {RoomEnum.STUDY : study, \ RoomEnum.HALL : hall, \ RoomEnum.LOUNGE : lounge, \ RoomEnum.DINING_ROOM : dining_room, \ RoomEnum.KITCHEN : kitchen, \ RoomEnum.BALLROOM : ballroom, \ RoomEnum.CONSERVATORY : conservatory, \ RoomEnum.LIBRARY : library, \ RoomEnum.BILLIARD_ROOM : billiard_room, \ RoomEnum.HALLWAY_STUDY_HALL : hallway_study_hall, \ RoomEnum.HALLWAY_HALL_LOUNGE : hallway_hall_lounge, \ RoomEnum.HALLWAY_LOUNGE_DINING_ROOM : hallway_lounge_dining_room, \ RoomEnum.HALLWAY_DINING_ROOM_KITCHEN : hallway_dining_room_kitchen, \ RoomEnum.HALLWAY_KITCHEN_BALLROOM : hallway_kitchen_ballroom, \ RoomEnum.HALLWAY_BALLROOM_CONSERVATORY : hallway_ballroom_conservatory, \ RoomEnum.HALLWAY_CONSERVATORY_LIBRARY : hallway_conservatory_library, \ RoomEnum.HALLWAY_LIBRARY_STUDY : hallway_library_study, \ RoomEnum.HALLWAY_BILLIARD_ROOM_HALL : hallway_billiard_room_hall, \ RoomEnum.HALLWAY_BILLIARD_ROOM_DINING_ROOM : hallway_billiard_room_dining_room, \ RoomEnum.HALLWAY_BILLIARD_ROOM_BALLROOM : hallway_billiard_room_ballroom, \ RoomEnum.HALLWAY_BILLIARD_ROOM_LIBRARY : hallway_billiard_room_library} # Check to see if a move from the current room to the destination room is valid def is_valid_move(self, current_room, destination_room): room = self._rooms[current_room] current_room_str = RoomEnum.to_string(current_room) destination_room_str = RoomEnum.to_string(destination_room) self._logger.debug('Determining if move from "%s" to "%s" is valid.', current_room_str, destination_room_str) valid_move = room.is_valid_move(destination_room) return valid_move # Retrieve the list of rooms connected to the current room def get_valid_moves(self, current_room): room = self._rooms[current_room] valid_room_list = room.get_valid_moves() return valid_room_list def is_hallway(self, room): if room > 9: return True else: return False
{"/StartServer.py": ["/server/CluelessServer.py"], "/server/CluelessServer.py": ["/common/MessageProtocol.py", "/server/ServerMessage.py"], "/server/ServerModel.py": ["/common/Gameboard.py", "/common/Player.py", "/common/PlayerEnum.py", "/common/RoomEnum.py", "/common/TurnEnum.py", "/common/WeaponEnum.py"], "/client/ClientMessage.py": ["/client/Client.py", "/client/ClientModel.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/common/RoomEnum.py"], "/common/Gameboard.py": ["/common/Room.py", "/common/RoomEnum.py"], "/server/ServerMessage.py": ["/common/Message.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/server/ServerModel.py"], "/client/Client.py": ["/observer/observer.py", "/common/MessageProtocol.py"]}
64,298
shahsarick/clueless
refs/heads/master
/server/ServerMessage.py
#!/usr/bin/env python import logging from common.Message import Message from common.MessageEnum import MessageEnum from common.PlayerEnum import PlayerEnum from server.ServerModel import ServerModel class ServerMessage: def __init__(self, output_queue): self._logger = logging.getLogger('ServerMessage') self._output_queue = output_queue self._server_model = ServerModel() # Handle the messages sent by the client (player) def handle_message(self, message_list, player): for message in message_list: message_enum = message.get_message_enum() message_args = message.get_args() # Handle move message if message_enum == MessageEnum.MOVE: player_enum = player.get_player_enum() current_room = self._server_model.get_player_position(player_enum) destination_room = message_args[0] valid_move = self._server_model.perform_move(player_enum, destination_room) if valid_move == True: new_room = self._server_model.get_player_position(player_enum) response_args = [True, player_enum, current_room, new_room] broadcast = True else: response_args = [False] broadcast = False return_message = Message(MessageEnum.MOVE, 1, response_args) self._output_queue.put((broadcast, return_message)) # Handle suggest message elif message_enum == MessageEnum.SUGGEST: self._logger.debug('Received a suggest message.') # Handle accuse message elif message_enum == MessageEnum.ACCUSE: self._logger.debug('Received an accusation message.') # Handle lobby ready and lobby unready messages elif message_enum == MessageEnum.LOBBY_READY or message_enum == MessageEnum.LOBBY_UNREADY: # Check to see if the game has already started game_started = self._server_model.is_game_started() if game_started == False: # Set player ready status in player entry ready_status = message_args[0] self._logger.debug('Setting ready status for "%s" to %d.', player.get_name(), ready_status) player.set_ready_status(ready_status) # Return player names and ready states response_args = self._server_model.get_lobby_list() return_message = Message(message_enum, 1, response_args) self._output_queue.put((True, return_message)) # Check to see if the game is ready to start if message_enum == MessageEnum.LOBBY_READY: if self._server_model.is_game_ready() == True: self._logger.debug('Starting game!') response_args = [PlayerEnum.MISS_SCARLET] return_message = Message(MessageEnum.TURN_BEGIN, 1, response_args) self._output_queue.put((True, return_message)) # Add a player using the specified address def add_player(self, address): self._server_model.add_player(address) # Send the player_enum chosen by the server back to the client player = self._server_model.get_player(address) player_enum = player.get_player_enum() response_args = [player_enum] return_message = Message(MessageEnum.LOBBY_CHANGE_PLAYER, 1, response_args) self._output_queue.put((False, return_message)) # Send the player added to the lobby to all clients response_args = self._server_model.get_lobby_list() return_message = Message(MessageEnum.LOBBY_ADD, 1, response_args) self._output_queue.put((True, return_message)) # Get the player associated with the specified address def get_player(self, address): return self._server_model.get_player(address) # Remove the player associated with the specified address def remove_player(self, address): self._server_model.remove_player(address)
{"/StartServer.py": ["/server/CluelessServer.py"], "/server/CluelessServer.py": ["/common/MessageProtocol.py", "/server/ServerMessage.py"], "/server/ServerModel.py": ["/common/Gameboard.py", "/common/Player.py", "/common/PlayerEnum.py", "/common/RoomEnum.py", "/common/TurnEnum.py", "/common/WeaponEnum.py"], "/client/ClientMessage.py": ["/client/Client.py", "/client/ClientModel.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/common/RoomEnum.py"], "/common/Gameboard.py": ["/common/Room.py", "/common/RoomEnum.py"], "/server/ServerMessage.py": ["/common/Message.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/server/ServerModel.py"], "/client/Client.py": ["/observer/observer.py", "/common/MessageProtocol.py"]}
64,299
shahsarick/clueless
refs/heads/master
/common/Player.py
#!/usr/bin/env python class Player: def __init__(self, address, player_enum): self._address = address self._player_enum = player_enum self._player_name = '' self._ready_state = False def get_address(self): return self._address def get_player_enum(self): return self._player_enum def set_player_enum(self, player_enum): self._player_enum = player_enum def get_name(self): return self._player_name def set_name(self, player_name): self._player_name = player_name def get_ready_status(self): return self._ready_state def set_ready_status(self, ready_state): self._ready_state = ready_state
{"/StartServer.py": ["/server/CluelessServer.py"], "/server/CluelessServer.py": ["/common/MessageProtocol.py", "/server/ServerMessage.py"], "/server/ServerModel.py": ["/common/Gameboard.py", "/common/Player.py", "/common/PlayerEnum.py", "/common/RoomEnum.py", "/common/TurnEnum.py", "/common/WeaponEnum.py"], "/client/ClientMessage.py": ["/client/Client.py", "/client/ClientModel.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/common/RoomEnum.py"], "/common/Gameboard.py": ["/common/Room.py", "/common/RoomEnum.py"], "/server/ServerMessage.py": ["/common/Message.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/server/ServerModel.py"], "/client/Client.py": ["/observer/observer.py", "/common/MessageProtocol.py"]}
64,300
shahsarick/clueless
refs/heads/master
/common/CardEnum.py
#!/usr/bin/env python class CardEnum(object): STUDY = 1 HALL = 2 LOUNGE = 3 DINING_ROOM = 4 KITCHEN = 5 BALLROOM = 6 CONSERVATORY = 7 LIBRARY = 8 BILLIARD_ROOM = 9 CANDLESTICK = 10 ROPE = 11 LEAD_PIPE = 12 REVOLVER = 13 WRENCH = 14 KNIFE = 15 MISS_SCARLET = 16 COLONEL_MUSTARD = 17 MRS_WHITE = 18 MR_GREEN = 19 MRS_PEACOCK = 20 PROFESSOR_PLUM = 21
{"/StartServer.py": ["/server/CluelessServer.py"], "/server/CluelessServer.py": ["/common/MessageProtocol.py", "/server/ServerMessage.py"], "/server/ServerModel.py": ["/common/Gameboard.py", "/common/Player.py", "/common/PlayerEnum.py", "/common/RoomEnum.py", "/common/TurnEnum.py", "/common/WeaponEnum.py"], "/client/ClientMessage.py": ["/client/Client.py", "/client/ClientModel.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/common/RoomEnum.py"], "/common/Gameboard.py": ["/common/Room.py", "/common/RoomEnum.py"], "/server/ServerMessage.py": ["/common/Message.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/server/ServerModel.py"], "/client/Client.py": ["/observer/observer.py", "/common/MessageProtocol.py"]}
64,301
shahsarick/clueless
refs/heads/master
/client/Client.py
#!/usr/bin/env python import logging import select import socket import sys from observer.observer import observerObject from common.MessageProtocol import MessageProtocol # reference the subject obsObj = observerObject() class Client: __socket_timeout = 2 __select_timeout = 0.5 __read_size = 4096 def __init__(self, input_queue, send_queue): self._logger = logging.getLogger('Client') self._input_queue = input_queue self._output_queue = send_queue # Connect to the server def connect_to_server(self, host, port): # Create the client socket self._logger.debug('Creating client socket.') self._client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._client_socket.settimeout(self.__socket_timeout) # Attempt to connect to the server self._logger.debug('Attempting to connect to server.') try: self._client_socket.connect((host, port)) except: self._logger.error('Unable to connect to the server.') return False self._logger.debug('Connected to %s on port %s', host, port) return True def run(self): while True: fd_list = [self._client_socket] # Get the list of sockets that are readable ready_to_read, ready_to_write, input_error = select.select(fd_list, [], [], self.__select_timeout) for sock in ready_to_read: # Received message from server if sock == self._client_socket: # This should ensure all the data from the socket is received message_list = [] while 1: message, bytes_read = MessageProtocol.recv_msg(sock) if bytes_read > 0: message_list.append(message) else: break # Check to see if data is available message_list_length = len(message_list) if message_list_length > 0: for message in message_list: # Place the server message into the output queue and notify the client that data has been received self._output_queue.put(message) self.notify_client_message() # Disconnected from server else: self._logger.error('Disconnected from the server.') sys.exit() # Check to see if data is available on the input queue # Note: Normally the queue would be in the select call, but I don't think # Queue is implemented as a file descriptor in Python (or Windows sucks) if self._input_queue.qsize() > 0: self._logger.debug('Retrieving message from input queue.') try: message = self._input_queue.get_nowait() except: break # Send message to the server self._logger.debug('Sending message to server.') MessageProtocol.send_msg(self._client_socket, message) # only called if there is a message in the queue def notify_client_message(self): obsObj.subject.notify_observers()
{"/StartServer.py": ["/server/CluelessServer.py"], "/server/CluelessServer.py": ["/common/MessageProtocol.py", "/server/ServerMessage.py"], "/server/ServerModel.py": ["/common/Gameboard.py", "/common/Player.py", "/common/PlayerEnum.py", "/common/RoomEnum.py", "/common/TurnEnum.py", "/common/WeaponEnum.py"], "/client/ClientMessage.py": ["/client/Client.py", "/client/ClientModel.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/common/RoomEnum.py"], "/common/Gameboard.py": ["/common/Room.py", "/common/RoomEnum.py"], "/server/ServerMessage.py": ["/common/Message.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/server/ServerModel.py"], "/client/Client.py": ["/observer/observer.py", "/common/MessageProtocol.py"]}
64,302
shahsarick/clueless
refs/heads/master
/common/Message.py
#!/usr/bin/env python class Message: def __init__(self, message_enum, num_args, arg_list): self._message_enum = message_enum self._num_args = num_args self._arg_list = arg_list def get_message_contents(self): return (self._message_enum, self._num_args, self._arg_list) def get_message_enum(self): return self._message_enum def get_num_args(self): return self._num_args def get_args(self): return self._arg_list
{"/StartServer.py": ["/server/CluelessServer.py"], "/server/CluelessServer.py": ["/common/MessageProtocol.py", "/server/ServerMessage.py"], "/server/ServerModel.py": ["/common/Gameboard.py", "/common/Player.py", "/common/PlayerEnum.py", "/common/RoomEnum.py", "/common/TurnEnum.py", "/common/WeaponEnum.py"], "/client/ClientMessage.py": ["/client/Client.py", "/client/ClientModel.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/common/RoomEnum.py"], "/common/Gameboard.py": ["/common/Room.py", "/common/RoomEnum.py"], "/server/ServerMessage.py": ["/common/Message.py", "/common/MessageEnum.py", "/common/PlayerEnum.py", "/server/ServerModel.py"], "/client/Client.py": ["/observer/observer.py", "/common/MessageProtocol.py"]}
64,303
assertpy/assertpy
refs/heads/main
/tests/test_readme.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import os import datetime from assertpy import assert_that, assert_warn, soft_assertions, contents_of, fail def setup_module(): print('\nTEST test_readme.py : v%d.%d.%d' % (sys.version_info[0], sys.version_info[1], sys.version_info[2])) def test_something(): assert_that(1 + 2).is_equal_to(3) assert_that('foobar').is_length(6).starts_with('foo').ends_with('bar') assert_that(['a', 'b', 'c']).contains('a').does_not_contain('x') def test_strings(): assert_that('').is_not_none() assert_that('').is_empty() assert_that('').is_false() assert_that('').is_type_of(str) assert_that('').is_instance_of(str) assert_that('foo').is_length(3) assert_that('foo').is_not_empty() assert_that('foo').is_true() assert_that('foo').is_alpha() assert_that('123').is_digit() assert_that('foo').is_lower() assert_that('FOO').is_upper() assert_that('foo').is_iterable() assert_that('foo').is_equal_to('foo') assert_that('foo').is_not_equal_to('bar') assert_that('foo').is_equal_to_ignoring_case('FOO') if sys.version_info[0] == 3: assert_that('foo').is_unicode() else: assert_that(u'foo').is_unicode() assert_that('foo').contains('f') assert_that('foo').contains('f', 'oo') assert_that('foo').contains_ignoring_case('F', 'oO') assert_that('foo').does_not_contain('x') assert_that('foo').contains_only('f', 'o') assert_that('foo').contains_sequence('o', 'o') assert_that('foo').contains_duplicates() assert_that('fox').does_not_contain_duplicates() assert_that('foo').is_in('foo', 'bar', 'baz') assert_that('foo').is_not_in('boo', 'bar', 'baz') assert_that('foo').is_subset_of('abcdefghijklmnopqrstuvwxyz') assert_that('foo').starts_with('f') assert_that('foo').ends_with('oo') assert_that('foo').matches(r'\w') assert_that('123-456-7890').matches(r'\d{3}-\d{3}-\d{4}') assert_that('foo').does_not_match(r'\d+') # partial matches, these all pass assert_that('foo').matches(r'\w') assert_that('foo').matches(r'oo') assert_that('foo').matches(r'\w{2}') # match the entire string with an anchored regex pattern, passes assert_that('foo').matches(r'^\w{3}$') # fails try: assert_that('foo').matches(r'^\w{2}$') fail('should have raised error') except AssertionError: pass def test_ints(): assert_that(0).is_not_none() assert_that(0).is_false() assert_that(0).is_type_of(int) assert_that(0).is_instance_of(int) assert_that(0).is_zero() assert_that(1).is_not_zero() assert_that(1).is_positive() assert_that(-1).is_negative() assert_that(123).is_equal_to(123) assert_that(123).is_not_equal_to(456) assert_that(123).is_greater_than(100) assert_that(123).is_greater_than_or_equal_to(123) assert_that(123).is_less_than(200) assert_that(123).is_less_than_or_equal_to(200) assert_that(123).is_between(100, 200) assert_that(123).is_close_to(100, 25) assert_that(1).is_in(0, 1, 2, 3) assert_that(1).is_not_in(-1, -2, -3) def test_floats(): assert_that(0.0).is_not_none() assert_that(0.0).is_false() assert_that(0.0).is_type_of(float) assert_that(0.0).is_instance_of(float) assert_that(123.4).is_equal_to(123.4) assert_that(123.4).is_not_equal_to(456.7) assert_that(123.4).is_greater_than(100.1) assert_that(123.4).is_greater_than_or_equal_to(123.4) assert_that(123.4).is_less_than(200.2) assert_that(123.4).is_less_than_or_equal_to(123.4) assert_that(123.4).is_between(100.1, 200.2) assert_that(123.4).is_close_to(123, 0.5) assert_that(float('NaN')).is_nan() assert_that(123.4).is_not_nan() assert_that(float('Inf')).is_inf() assert_that(123.4).is_not_inf() def test_lists(): assert_that([]).is_not_none() assert_that([]).is_empty() assert_that([]).is_false() assert_that([]).is_type_of(list) assert_that([]).is_instance_of(list) assert_that([]).is_iterable() assert_that(['a', 'b']).is_length(2) assert_that(['a', 'b']).is_not_empty() assert_that(['a', 'b']).is_equal_to(['a', 'b']) assert_that(['a', 'b']).is_not_equal_to(['b', 'a']) assert_that(['a', 'b']).contains('a') assert_that(['a', 'b']).contains('b', 'a') assert_that(['a', 'b']).does_not_contain('x', 'y') assert_that(['a', 'b']).contains_only('a', 'b') assert_that(['a', 'a']).contains_only('a') assert_that(['a', 'b', 'c']).contains_sequence('b', 'c') assert_that(['a', 'b']).is_subset_of(['a', 'b', 'c']) assert_that(['a', 'b', 'c']).is_sorted() assert_that(['c', 'b', 'a']).is_sorted(reverse=True) assert_that(['a', 'x', 'x']).contains_duplicates() assert_that(['a', 'b', 'c']).does_not_contain_duplicates() assert_that(['a', 'b', 'c']).starts_with('a') assert_that(['a', 'b', 'c']).ends_with('c') def test_tuples(): assert_that(()).is_not_none() assert_that(()).is_empty() assert_that(()).is_false() assert_that(()).is_type_of(tuple) assert_that(()).is_instance_of(tuple) assert_that(()).is_iterable() assert_that((1, 2, 3)).is_length(3) assert_that((1, 2, 3)).is_not_empty() assert_that((1, 2, 3)).is_equal_to((1, 2, 3)) assert_that((1, 2, 3)).is_not_equal_to((1, 2, 4)) assert_that((1, 2, 3)).contains(1) assert_that((1, 2, 3)).contains(3, 2, 1) assert_that((1, 2, 3)).does_not_contain(4, 5, 6) assert_that((1, 2, 3)).contains_only(1, 2, 3) assert_that((1, 1, 1)).contains_only(1) assert_that((1, 2, 3)).contains_sequence(2, 3) assert_that((1, 2, 3)).is_subset_of((1, 2, 3, 4)) assert_that((1, 2, 3)).is_sorted() assert_that((3, 2, 1)).is_sorted(reverse=True) assert_that((1, 2, 2)).contains_duplicates() assert_that((1, 2, 3)).does_not_contain_duplicates() assert_that((1, 2, 3)).starts_with(1) assert_that((1, 2, 3)).ends_with(3) def test_dicts(): assert_that({}).is_not_none() assert_that({}).is_empty() assert_that({}).is_false() assert_that({}).is_type_of(dict) assert_that({}).is_instance_of(dict) assert_that({'a': 1, 'b': 2}).is_length(2) assert_that({'a': 1, 'b': 2}).is_not_empty() assert_that({'a': 1, 'b': 2}).is_equal_to({'a': 1, 'b': 2}) assert_that({'a': 1, 'b': 2}).is_equal_to({'b': 2, 'a': 1}) assert_that({'a': 1, 'b': 2}).is_not_equal_to({'a': 1, 'b': 3}) assert_that({'a': 1, 'b': 2}).contains('a') assert_that({'a': 1, 'b': 2}).contains('b', 'a') assert_that({'a': 1, 'b': 2}).does_not_contain('x') assert_that({'a': 1, 'b': 2}).does_not_contain('x', 'y') assert_that({'a': 1, 'b': 2}).contains_only('a', 'b') assert_that({'a': 1, 'b': 2}).is_subset_of({'a': 1, 'b': 2, 'c': 3}) # contains_key() is just an alias for contains() assert_that({'a': 1, 'b': 2}).contains_key('a') assert_that({'a': 1, 'b': 2}).contains_key('b', 'a') # does_not_contain_key() is just an alias for does_not_contain() assert_that({'a': 1, 'b': 2}).does_not_contain_key('x') assert_that({'a': 1, 'b': 2}).does_not_contain_key('x', 'y') assert_that({'a': 1, 'b': 2}).contains_value(1) assert_that({'a': 1, 'b': 2}).contains_value(2, 1) assert_that({'a': 1, 'b': 2}).does_not_contain_value(3) assert_that({'a': 1, 'b': 2}).does_not_contain_value(3, 4) assert_that({'a': 1, 'b': 2}).contains_entry({'a': 1}) assert_that({'a': 1, 'b': 2}).contains_entry({'a': 1}, {'b': 2}) assert_that({'a': 1, 'b': 2}).does_not_contain_entry({'a': 2}) assert_that({'a': 1, 'b': 2}).does_not_contain_entry({'a': 2}, {'b': 1}) # lists of dicts can be flattened on key fred = {'first_name': 'Fred', 'last_name': 'Smith'} bob = {'first_name': 'Bob', 'last_name': 'Barr'} people = [fred, bob] assert_that(people).extracting('first_name').is_equal_to(['Fred', 'Bob']) assert_that(people).extracting('first_name').contains('Fred', 'Bob') def test_dict_compare(): # ignore assert_that({'a': 1, 'b': 2}).is_equal_to({'a': 1}, ignore='b') assert_that({'a': 1, 'b': 2, 'c': 3}).is_equal_to({'a': 1}, ignore=['b', 'c']) assert_that({'a': 1, 'b': {'c': 2, 'd': 3}}).is_equal_to({'a': 1, 'b': {'c': 2}}, ignore=('b', 'd')) # include assert_that({'a': 1, 'b': 2}).is_equal_to({'a': 1}, include='a') assert_that({'a': 1, 'b': 2, 'c': 3}).is_equal_to({'a': 1, 'b': 2}, include=['a', 'b']) assert_that({'a': 1, 'b': {'c': 2, 'd': 3}}).is_equal_to({'b': {'d': 3}}, include=('b', 'd')) # both assert_that({'a': 1, 'b': {'c': 2, 'd': 3, 'e': 4, 'f': 5}}).is_equal_to( {'b': {'d': 3, 'f': 5}}, ignore=[('b', 'c'), ('b', 'e')], include='b' ) def test_sets(): assert_that(set([])).is_not_none() assert_that(set([])).is_empty() assert_that(set([])).is_false() assert_that(set([])).is_type_of(set) assert_that(set([])).is_instance_of(set) assert_that(set(['a', 'b'])).is_length(2) assert_that(set(['a', 'b'])).is_not_empty() assert_that(set(['a', 'b'])).is_equal_to(set(['a', 'b'])) assert_that(set(['a', 'b'])).is_equal_to(set(['b', 'a'])) assert_that(set(['a', 'b'])).is_not_equal_to(set(['a', 'x'])) assert_that(set(['a', 'b'])).contains('a') assert_that(set(['a', 'b'])).contains('b', 'a') assert_that(set(['a', 'b'])).does_not_contain('x', 'y') assert_that(set(['a', 'b'])).contains_only('a', 'b') assert_that(set(['a', 'b'])).is_subset_of(set(['a', 'b', 'c'])) assert_that(set(['a', 'b'])).is_subset_of(set(['a']), set(['b'])) def test_booleans(): assert_that(True).is_true() assert_that(False).is_false() assert_that(True).is_type_of(bool) def test_dates(): today = datetime.datetime.today() yesterday = today - datetime.timedelta(days=1) assert_that(yesterday).is_before(today) assert_that(today).is_after(yesterday) today_0us = today - datetime.timedelta(microseconds=today.microsecond) today_0s = today - datetime.timedelta(seconds=today.second) today_0h = today - datetime.timedelta(hours=today.hour) assert_that(today).is_equal_to_ignoring_milliseconds(today_0us) assert_that(today).is_equal_to_ignoring_seconds(today_0s) assert_that(today).is_equal_to_ignoring_time(today_0h) assert_that(today).is_equal_to(today) middle = today - datetime.timedelta(hours=12) hours_24 = datetime.timedelta(hours=24) assert_that(today).is_greater_than(yesterday) assert_that(yesterday).is_less_than(today) assert_that(middle).is_between(yesterday, today) # note that the tolerance must be a datetime.timedelta object assert_that(yesterday).is_close_to(today, hours_24) # 1980-01-02 03:04:05.000006 x = datetime.datetime(1980, 1, 2, 3, 4, 5, 6) assert_that(x).has_year(1980) assert_that(x).has_month(1) assert_that(x).has_day(2) assert_that(x).has_hour(3) assert_that(x).has_minute(4) assert_that(x).has_second(5) assert_that(x).has_microsecond(6) def test_files(): # setup with open('foo.txt', 'w') as fp: fp.write('foobar') assert_that('foo.txt').exists() assert_that('missing.txt').does_not_exist() assert_that('foo.txt').is_file() # assert_that('mydir').exists() assert_that('missing_dir').does_not_exist() # assert_that('mydir').is_directory() assert_that('foo.txt').is_named('foo.txt') # assert_that('foo.txt').is_child_of('mydir') contents = contents_of('foo.txt', 'ascii') assert_that(contents).starts_with('foo').ends_with('bar').contains('oob') # teardown os.remove('foo.txt') def test_objects(): fred = Person('Fred', 'Smith') assert_that(fred).is_not_none() assert_that(fred).is_true() assert_that(fred).is_type_of(Person) assert_that(fred).is_instance_of(object) assert_that(fred).is_same_as(fred) assert_that(fred.first_name).is_equal_to('Fred') assert_that(fred.name).is_equal_to('Fred Smith') assert_that(fred.say_hello()).is_equal_to('Hello, Fred!') fred = Person('Fred', 'Smith') bob = Person('Bob', 'Barr') people = [fred, bob] assert_that(people).extracting('first_name').is_equal_to(['Fred', 'Bob']) assert_that(people).extracting('first_name').contains('Fred', 'Bob') assert_that(people).extracting('first_name').does_not_contain('Charlie') fred = Person('Fred', 'Smith') joe = Developer('Joe', 'Coder') people = [fred, joe] assert_that(people).extracting('first_name').contains('Fred', 'Joe') assert_that(people).extracting('first_name', 'last_name').contains(('Fred', 'Smith'), ('Joe', 'Coder')) assert_that(people).extracting('name').contains('Fred Smith', 'Joe Coder') assert_that(people).extracting('say_hello').contains('Hello, Fred!', 'Joe writes code.') def test_dyn(): fred = Person('Fred', 'Smith') assert_that(fred.first_name).is_equal_to('Fred') assert_that(fred.name).is_equal_to('Fred Smith') assert_that(fred.say_hello()).is_equal_to('Hello, Fred!') assert_that(fred).has_first_name('Fred') assert_that(fred).has_name('Fred Smith') assert_that(fred).has_say_hello('Hello, Fred!') def test_failure(): try: some_func('foo') fail('should have raised error') except RuntimeError as e: assert_that(str(e)).is_equal_to('some err') def test_expected_exceptions(): assert_that(some_func).raises(RuntimeError).when_called_with('foo') assert_that(some_func).raises(RuntimeError).when_called_with('foo')\ .is_length(8).starts_with('some').is_equal_to('some err') def test_custom_error_message(): try: assert_that(1+2).is_equal_to(2) fail('should have raised error') except AssertionError as e: assert_that(str(e)).is_equal_to('Expected <3> to be equal to <2>, but was not.') try: assert_that(1+2).described_as('adding stuff').is_equal_to(2) fail('should have raised error') except AssertionError as e: assert_that(str(e)).is_equal_to('[adding stuff] Expected <3> to be equal to <2>, but was not.') def test_assert_warn(): assert_warn('foo').is_length(4) assert_warn('foo').is_empty() assert_warn('foo').is_false() assert_warn('foo').is_digit() assert_warn('123').is_alpha() assert_warn('foo').is_upper() assert_warn('FOO').is_lower() assert_warn('foo').is_equal_to('bar') assert_warn('foo').is_not_equal_to('foo') assert_warn('foo').is_equal_to_ignoring_case('BAR') def test_soft_assertions(): try: with soft_assertions(): assert_that('foo').is_length(4) assert_that('foo').is_empty() assert_that('foo').is_false() assert_that('foo').is_digit() assert_that('123').is_alpha() assert_that('foo').is_upper() assert_that('FOO').is_lower() assert_that('foo').is_equal_to('bar') assert_that('foo').is_not_equal_to('foo') assert_that('foo').is_equal_to_ignoring_case('BAR') fail('should have raised error') except AssertionError as e: assert_that(str(e)).contains('1. Expected <foo> to be of length <4>, but was <3>.') assert_that(str(e)).contains('2. Expected <foo> to be empty string, but was not.') assert_that(str(e)).contains('3. Expected <False>, but was not.') assert_that(str(e)).contains('4. Expected <foo> to contain only digits, but did not.') assert_that(str(e)).contains('5. Expected <123> to contain only alphabetic chars, but did not.') assert_that(str(e)).contains('6. Expected <foo> to contain only uppercase chars, but did not.') assert_that(str(e)).contains('7. Expected <FOO> to contain only lowercase chars, but did not.') assert_that(str(e)).contains('8. Expected <foo> to be equal to <bar>, but was not.') assert_that(str(e)).contains('9. Expected <foo> to be not equal to <foo>, but was.') assert_that(str(e)).contains('10. Expected <foo> to be case-insensitive equal to <BAR>, but was not.') def test_chaining(): fred = Person('Fred', 'Smith') joe = Person('Joe', 'Jones') people = [fred, joe] assert_that('foo').is_length(3).starts_with('f').ends_with('oo') assert_that([1, 2, 3]).is_type_of(list).contains(1, 2).does_not_contain(4, 5) assert_that(fred).has_first_name('Fred').has_last_name('Smith').has_shoe_size(12) assert_that(people).is_length(2).extracting('first_name').contains('Fred', 'Joe') def some_func(arg): raise RuntimeError('some err') class Person(object): def __init__(self, first_name, last_name, shoe_size=12): self.first_name = first_name self.last_name = last_name self.shoe_size = shoe_size @property def name(self): return '%s %s' % (self.first_name, self.last_name) def say_hello(self): return 'Hello, %s!' % self.first_name class Developer(Person): def say_hello(self): return '%s writes code.' % self.first_name
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,304
assertpy/assertpy
refs/heads/main
/tests/test_custom_dict.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from assertpy import assert_that, fail def test_custom_dict(): d = CustomDict({ 'Accept-Encoding': 'gzip, deflate', 'Connection': 'keep-alive', 'Accept': 'application/json', 'User-Agent': 'python-requests/2.9.1'}) assert_that(d).is_not_none() assert_that(d.keys()).contains('Accept-Encoding', 'Connection', 'Accept', 'User-Agent') assert_that(d).contains_key('Accept-Encoding', 'Connection', 'Accept', 'User-Agent') assert_that(d.values()).contains('gzip, deflate', 'keep-alive', 'application/json', 'python-requests/2.9.1') assert_that(d).contains_value('application/json') assert_that(d['Accept']).is_equal_to('application/json') assert_that(d).contains_entry({'Accept': 'application/json'}) def test_requests(): try: import requests d = requests.structures.CaseInsensitiveDict({ 'Accept-Encoding': 'gzip, deflate', 'Connection': 'keep-alive', 'Accept': 'application/json', 'User-Agent': 'python-requests/2.9.1'}) assert_that(d).is_not_none() assert_that(d.keys()).contains('Accept-Encoding', 'Connection', 'Accept', 'User-Agent') assert_that(d).contains_key('Accept-Encoding', 'Connection', 'Accept', 'User-Agent') assert_that(d.values()).contains('gzip, deflate', 'keep-alive', 'application/json', 'python-requests/2.9.1') assert_that(d).contains_value('application/json') assert_that(d['Accept']).is_equal_to('application/json') assert_that(d).contains_entry({'Accept': 'application/json'}) except ImportError: pass class CustomDict(object): def __init__(self, d): self._dict = d self._idx = 0 def __iter__(self): return self def __next__(self): try: result = self.keys()[self._idx] except IndexError: raise StopIteration self._idx += 1 return result def __contains__(self, key): return key in self.keys() def keys(self): return list(self._dict.keys()) def values(self): return list(self._dict.values()) def __getitem__(self, key): return self._dict.get(key) def test_check_dict_like(): d = CustomDict({'a': 1}) ab = assert_that(None) ab._check_dict_like(d) ab._check_dict_like(d, True, True, True) ab._check_dict_like(d, True, True, False) ab._check_dict_like(d, True, False, True) ab._check_dict_like(d, False, True, True) ab._check_dict_like(d, True, False, False) ab._check_dict_like(d, False, False, True) ab._check_dict_like(d, False, True, False) ab._check_dict_like(d, False, False, False) ab._check_dict_like(CustomDictNoKeys(), check_keys=False, check_values=False, check_getitem=False) ab._check_dict_like(CustomDictNoKeysCallable(), check_keys=False, check_values=False, check_getitem=False) ab._check_dict_like(CustomDictNoValues(), check_values=False, check_getitem=False) ab._check_dict_like(CustomDictNoValuesCallable(), check_values=False, check_getitem=False) ab._check_dict_like(CustomDictNoGetitem(), check_getitem=False) def test_check_dict_like_bool(): ab = assert_that(None) assert_that(ab._check_dict_like(CustomDictNoKeys(), return_as_bool=True)).is_false() assert_that(ab._check_dict_like(CustomDictNoKeysCallable(), return_as_bool=True)).is_false() assert_that(ab._check_dict_like(CustomDictNoValues(), return_as_bool=True)).is_false() assert_that(ab._check_dict_like(CustomDictNoValuesCallable(), return_as_bool=True)).is_false() assert_that(ab._check_dict_like(CustomDictNoGetitem(), return_as_bool=True)).is_false() def test_check_dict_like_no_keys(): try: ab = assert_that(None) ab._check_dict_like(CustomDictNoKeys()) fail('should have raised error') except TypeError as e: assert_that(str(e)).contains('is not dict-like: missing keys()') def test_check_dict_like_no_keys_callable(): try: ab = assert_that(None) ab._check_dict_like(CustomDictNoKeysCallable()) fail('should have raised error') except TypeError as e: assert_that(str(e)).contains('is not dict-like: missing keys()') def test_check_dict_like_no_values(): try: ab = assert_that(None) ab._check_dict_like(CustomDictNoValues()) fail('should have raised error') except TypeError as e: assert_that(str(e)).contains('is not dict-like: missing values()') def test_check_dict_like_no_values_callable(): try: ab = assert_that(None) ab._check_dict_like(CustomDictNoValuesCallable()) fail('should have raised error') except TypeError as e: assert_that(str(e)).contains('is not dict-like: missing values()') def test_check_dict_like_no_getitem(): try: ab = assert_that(None) ab._check_dict_like(CustomDictNoGetitem()) fail('should have raised error') except TypeError as e: assert_that(str(e)).contains('is not dict-like: missing [] accessor') class CustomDictNoKeys(object): def __iter__(self): return self def __next__(self): return 1 class CustomDictNoKeysCallable(object): def __init__(self): self.keys = 'foo' def __iter__(self): return self def __next__(self): return 1 class CustomDictNoValues(object): def __iter__(self): return self def __next__(self): return 1 def keys(self): return 'foo' class CustomDictNoValuesCallable(object): def __init__(self): self.values = 'foo' def __iter__(self): return self def __next__(self): return 1 def keys(self): return 'foo' class CustomDictNoGetitem(object): def __iter__(self): return self def __next__(self): return 1 def keys(self): return 'foo' def values(self): return 'bar'
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,305
assertpy/assertpy
refs/heads/main
/tests/test_collection.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import collections from assertpy import assert_that, fail def test_is_iterable(): assert_that(['a', 'b', 'c']).is_iterable() assert_that((1, 2, 3)).is_iterable() assert_that('foo').is_iterable() assert_that({'a': 1, 'b': 2, 'c': 3}.keys()).is_iterable() assert_that({'a': 1, 'b': 2, 'c': 3}.values()).is_iterable() assert_that({'a': 1, 'b': 2, 'c': 3}.items()).is_iterable() def test_is_iterable_failure(): try: assert_that(123).is_iterable() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected iterable, but was not.') def test_is_not_iterable(): assert_that(123).is_not_iterable() assert_that({'a': 1, 'b': 2, 'c': 3}).is_iterable() def test_is_not_iterable_failure(): try: assert_that(['a', 'b', 'c']).is_not_iterable() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected not iterable, but was.') def test_is_subset_of(): assert_that(['a', 'b', 'c']).is_subset_of(['a', 'b', 'c']) assert_that(['a', 'b', 'c']).is_subset_of(['a', 'b', 'c', 'd']) assert_that(['a', 'b', 'c']).is_subset_of(['a'], ['b'], ['c']) assert_that(['a', 'b', 'c']).is_subset_of('a', 'b', 'c') assert_that(['a', 'b', 'a']).is_subset_of(['a', 'a', 'b']) assert_that((1, 2, 3)).is_subset_of((1, 2, 3)) assert_that((1, 2, 3)).is_subset_of((1, 2, 3, 4)) assert_that((1, 2, 3)).is_subset_of((1, ), (2, ), (3, )) assert_that((1, 2, 3)).is_subset_of(1, 2, 3) assert_that((1, 2, 1)).is_subset_of(1, 1, 2) assert_that('foo').is_subset_of('abcdefghijklmnopqrstuvwxyz') assert_that('foo').is_subset_of('abcdef', set(['m', 'n', 'o']), ['x', 'y']) assert_that(set([1, 2, 3])).is_subset_of(set([1, 2, 3, 4])) assert_that({'a': 1, 'b': 2}).is_subset_of({'a': 1, 'b': 2, 'c': 3}) assert_that({'a': 1, 'b': 2}).is_subset_of({'a': 3}, {'b': 2}, {'a': 1}) def test_is_subset_of_single_item_superset(): assert_that(['a']).is_subset_of(['a']) assert_that((1, )).is_subset_of((1, )) assert_that('ab').is_subset_of('ab') assert_that(set([1])).is_subset_of(set([1])) assert_that({'a': 1}).is_subset_of({'a': 1}) def test_is_subset_of_failure_empty_superset(): try: assert_that(['a', 'b', 'c']).is_subset_of([]) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains('to be subset of <>') def test_is_subset_of_failure_single_item_superset(): try: assert_that(['a', 'b', 'c']).is_subset_of(['x']) fail('should have raised error') except AssertionError as ex: if sys.version_info[0] == 3: assert_that(str(ex)).contains("to be subset of <{'x'}>") assert_that(str(ex)).contains("but <'a', 'b', 'c'> were missing.") def test_is_subset_of_failure_array(): try: assert_that(['a', 'b', 'c']).is_subset_of(['a', 'b']) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains('but <c> was missing.') def test_is_subset_of_failure_set(): try: assert_that(set([1, 2, 3])).is_subset_of(set([1, 2])) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains('but <3> was missing.') def test_is_subset_of_failure_string(): try: assert_that('abc').is_subset_of('abx') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains('but <c> was missing.') def test_is_subset_of_failure_dict_key(): try: assert_that({'a': 1, 'b': 2}).is_subset_of({'a': 1, 'c': 3}) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains("but <{'b': 2}> was missing") def test_is_subset_of_failure_dict_value(): try: assert_that({'a': 1, 'b': 2}).is_subset_of({'a': 1, 'b': 22}) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains("but <{'b': 2}> was missing.") def test_is_subset_of_failure_bad_dict_arg1(): try: assert_that({'a': 1, 'b': 2}).is_subset_of('foo') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).contains('arg #1').contains('is not dict-like') def test_is_subset_of_failure_bad_dict_arg2(): try: assert_that({'a': 1, 'b': 2}).is_subset_of({'a': 1}, 'foo') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).contains('arg #2').contains('is not dict-like') def test_is_subset_of_bad_val_failure(): try: assert_that(123).is_subset_of(1234) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not iterable') def test_is_subset_of_bad_arg_failure(): try: assert_that(['a', 'b', 'c']).is_subset_of() fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('one or more superset args must be given') def test_is_sorted(): assert_that([1, 2, 3]).is_sorted() assert_that((3, 2, 1)).is_sorted(reverse=True) assert_that(['a', 'b', 'c']).is_sorted() assert_that(['c', 'b', 'a']).is_sorted(reverse=True) assert_that('abcdefghijklmnopqrstuvwxyz').is_sorted() assert_that('zyxwvutsrqponmlkjihgfedcba').is_sorted(reverse=True) assert_that([{'a': 1}, {'a': 2}, {'a': 3}]).is_sorted(key=lambda x: x['a']) assert_that([{'a': 3}, {'a': 2}, {'a': 1}]).is_sorted(key=lambda x: x['a'], reverse=True) assert_that([('a', 2), ('b', 1)]).is_sorted(key=lambda x: x[0]) assert_that([('a', 2), ('b', 1)]).is_sorted(key=lambda x: x[1], reverse=True) assert_that([1, 1, 1]).is_sorted() assert_that([1, 1, 1]).is_sorted(reverse=True) assert_that([]).is_sorted() assert_that([1]).is_sorted() if sys.version_info[0] == 3: import collections ordered = collections.OrderedDict([('a', 2), ('b', 1)]) assert_that(ordered).is_sorted() assert_that(ordered.keys()).is_sorted() def test_is_sorted_failure(): try: assert_that([1, 2, 3, 4, 5, 6, -1, 7, 8, 9]).is_sorted() fail("should have raised error") except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <[1, 2, 3, 4, 5, 6, -1, 7, 8, 9]> to be sorted, but subset <6, -1> at index 5 is not.') def test_is_sorted_reverse_failure(): try: assert_that([1, 2, 3]).is_sorted(reverse=True) fail("should have raised error") except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <[1, 2, 3]> to be sorted reverse, but subset <1, 2> at index 0 is not.') def test_is_sorted_failure_bad_val(): try: assert_that(123).is_sorted() fail("should have raised error") except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not iterable') def test_chaining(): assert_that(['a', 'b', 'c']).is_iterable().is_type_of(list).is_sorted().is_length(3)
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,306
assertpy/assertpy
refs/heads/main
/tests/test_dict.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import collections from assertpy import assert_that, fail def test_is_length(): assert_that({'a': 1, 'b': 2}).is_length(2) def test_is_length_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).is_length(4) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains('to be of length <4>, but was <3>.') def test_contains(): assert_that({'a': 1, 'b': 2, 'c': 3}).contains('a') assert_that({'a': 1, 'b': 2, 'c': 3}).contains('a', 'b') if sys.version_info[0] == 3: ordered = collections.OrderedDict([('z', 9), ('x', 7), ('y', 8)]) assert_that(ordered).contains('x') def test_contains_empty_arg_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).contains() fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('one or more args must be given') def test_contains_single_item_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).contains('x') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains('to contain key <x>, but did not.') def test_contains_single_item_dict_like_failure(): if sys.version_info[0] == 3: ordered = collections.OrderedDict([('z', 9), ('x', 7), ('y', 8)]) try: assert_that(ordered).contains('a') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).ends_with('to contain key <a>, but did not.') def test_contains_multi_item_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).contains('a', 'x', 'z') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains("to contain keys <'a', 'x', 'z'>, but did not contain keys <'x', 'z'>.") def test_contains_multi_item_single_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).contains('a', 'b', 'z') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains("to contain keys <'a', 'b', 'z'>, but did not contain keys <z>.") def test_contains_only(): assert_that({'a': 1, 'b': 2, 'c': 3}).contains_only('a', 'b', 'c') assert_that(set(['a', 'b', 'c'])).contains_only('a', 'b', 'c') def test_contains_only_failure(): try: assert_that({'a': 1, 'b': 2}).contains_only('a', 'x') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains("to contain only <'a', 'x'>, but did contain <b>.") def test_contains_only_multi_failure(): try: assert_that({'a': 1, 'b': 2}).contains_only('x', 'y') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains("to contain only <'x', 'y'>, but did contain <'") def test_contains_key(): assert_that({'a': 1, 'b': 2, 'c': 3}).contains_key('a') assert_that({'a': 1, 'b': 2, 'c': 3}).contains_key('a', 'b') if sys.version_info[0] == 3: ordered = collections.OrderedDict([('z', 9), ('x', 7), ('y', 8)]) assert_that(ordered).contains_key('x') def test_contains_key_bad_val_failure(): try: assert_that(123).contains_key(1) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).contains('is not dict-like') def test_does_not_contain_key(): assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain_key('x') assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain_key('x', 'y') def test_does_not_contain_key_bad_val_failure(): try: assert_that(123).does_not_contain_key(1) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).contains('is not dict-like') def test_contains_key_single_item_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).contains_key('x') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).ends_with('to contain key <x>, but did not.') def test_contains_key_multi_item_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).contains_key('a', 'x', 'z') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).ends_with("to contain keys <'a', 'x', 'z'>, but did not contain keys <'x', 'z'>.") def test_does_not_contain(): assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain('x') assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain('x', 'y') def test_does_not_contain_empty_arg_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain() fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('one or more args must be given') def test_does_not_contain_single_item_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain('a') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains('to not contain item <a>, but did.') def test_does_not_contain_list_item_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain('x', 'y', 'a') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains("to not contain items <'x', 'y', 'a'>, but did contain <a>.") def test_is_empty(): assert_that({}).is_empty() def test_is_empty_failure(): try: assert_that({'a': 1, 'b': 2}).is_empty() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains('to be empty, but was not.') def test_is_not_empty(): assert_that({'a': 1, 'b': 2}).is_not_empty() assert_that(set(['a', 'b'])).is_not_empty() def test_is_not_empty_failure(): try: assert_that({}).is_not_empty() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected not empty, but was empty.') def test_contains_value(): assert_that({'a': 1, 'b': 2, 'c': 3}).contains_value(1) assert_that({'a': 1, 'b': 2, 'c': 3}).contains_value(1, 2) def test_contains_value_empty_arg_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).contains_value() fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('one or more value args must be given') def test_contains_value_bad_val_failure(): try: assert_that('foo').contains_value('x') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).contains('is not dict-like') def test_contains_value_single_item_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).contains_value(4) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains('to contain values <4>, but did not contain <4>.') def test_contains_value_multi_item_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).contains_value(1, 4, 5) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains('to contain values <1, 4, 5>, but did not contain <4, 5>.') def test_does_not_contain_value(): assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain_value(4) assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain_value(4, 5) def test_does_not_contain_value_bad_val_failure(): try: assert_that(123).does_not_contain_value(1) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).contains('is not dict-like') def test_does_not_contain_value_empty_arg_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain_value() fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('one or more value args must be given') def test_does_not_contain_value_single_item_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain_value(1) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains('to not contain values <1>, but did contain <1>.') def test_does_not_contain_value_list_item_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain_value(4, 5, 1) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains('to not contain values <4, 5, 1>, but did contain <1>.') def test_does_not_contain_value_list_multi_item_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain_value(4, 1, 2) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains('to not contain values <4, 1, 2>, but did contain <1, 2>.') def test_contains_entry(): assert_that({'a': 1, 'b': 2, 'c': 3}).contains_entry({'a': 1}) assert_that({'a': 1, 'b': 2, 'c': 3}).contains_entry({'a': 1}, {'b': 2}) assert_that({'a': 1, 'b': 2, 'c': 3}).contains_entry({'a': 1}, {'b': 2}, {'c': 3}) assert_that({'a': 1, 'b': 2, 'c': 3}).contains_entry(a=1) assert_that({'a': 1, 'b': 2, 'c': 3}).contains_entry(a=1, b=2) assert_that({'a': 1, 'b': 2, 'c': 3}).contains_entry(a=1, b=2, c=3) assert_that({'a': 1, 'b': 2, 'c': 3}).contains_entry({'a': 1}, b=2) assert_that({'a': 1, 'b': 2, 'c': 3}).contains_entry({'b': 2}, a=1, c=3) def test_contains_entry_bad_val_failure(): try: assert_that('foo').contains_entry({'a': 1}) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).contains('is not dict-like') def test_contains_entry_empty_arg_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).contains_entry() fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('one or more entry args must be given') def test_contains_entry_bad_arg_type_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).contains_entry('x') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given entry arg must be a dict') def test_contains_entry_bad_arg_too_big_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).contains_entry({'a': 1, 'b': 2}) fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('given entry args must contain exactly one key-value pair') def test_contains_entry_bad_key_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).contains_entry({'x': 1}) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains("to contain entries <{'x': 1}>, but did not contain <{'x': 1}>.") def test_contains_entry_bad_value_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).contains_entry({'a': 2}) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains("to contain entries <{'a': 2}>, but did not contain <{'a': 2}>.") def test_contains_entry_bad_keys_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).contains_entry({'a': 1}, {'x': 2}) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains("to contain entries <{'a': 1}, {'x': 2}>, but did not contain <{'x': 2}>.") def test_contains_entry_bad_values_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).contains_entry({'a': 1}, {'b': 4}) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains("to contain entries <{'a': 1}, {'b': 4}>, but did not contain <{'b': 4}>.") def test_does_not_contain_entry(): assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain_entry({'a': 2}) assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain_entry({'a': 2}, {'b': 1}) assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain_entry(a=2) assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain_entry(a=2, b=3) assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain_entry({'x': 4}, y=5, z=6) def test_does_not_contain_entry_bad_val_failure(): try: assert_that('foo').does_not_contain_entry({'a': 1}) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).contains('is not dict-like') def test_does_not_contain_entry_empty_arg_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain_entry() fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('one or more entry args must be given') def test_does_not_contain_entry_bad_arg_type_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain_entry('x') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given entry arg must be a dict') def test_does_not_contain_entry_bad_arg_too_big_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain_entry({'a': 1, 'b': 2}) fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('given entry args must contain exactly one key-value pair') def test_does_not_contain_entry_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain_entry({'a': 1}) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains("to not contain entries <{'a': 1}>, but did contain <{'a': 1}>.") def test_does_not_contain_entry_multiple_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain_entry({'a': 2}, {'b': 2}) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains("to not contain entries <{'a': 2}, {'b': 2}>, but did contain <{'b': 2}>.") def test_dynamic_assertion(): fred = {'first_name': 'Fred', 'last_name': 'Smith', 'shoe_size': 12} assert_that(fred).is_type_of(dict) assert_that(fred['first_name']).is_equal_to('Fred') assert_that(fred['last_name']).is_equal_to('Smith') assert_that(fred['shoe_size']).is_equal_to(12) assert_that(fred).has_first_name('Fred') assert_that(fred).has_last_name('Smith') assert_that(fred).has_shoe_size(12) def test_dynamic_assertion_failure_str(): fred = {'first_name': 'Fred', 'last_name': 'Smith', 'shoe_size': 12} try: assert_that(fred).has_first_name('Foo') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains('Expected <Fred> to be equal to <Foo> on key <first_name>, but was not.') def test_dynamic_assertion_failure_int(): fred = {'first_name': 'Fred', 'last_name': 'Smith', 'shoe_size': 12} try: assert_that(fred).has_shoe_size(34) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains('Expected <12> to be equal to <34> on key <shoe_size>, but was not.') def test_dynamic_assertion_bad_key_failure(): fred = {'first_name': 'Fred', 'last_name': 'Smith', 'shoe_size': 12} try: assert_that(fred).has_foo('Fred') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected key <foo>, but val has no key <foo>.') def test_dynamic_assertion_on_reserved_word(): fred = {'def': 'Fred'} assert_that(fred).is_type_of(dict) assert_that(fred['def']).is_equal_to('Fred') assert_that(fred).has_def('Fred') def test_dynamic_assertion_on_dict_method(): fred = {'update': 'Foo'} fred.update({'update': 'Fred'}) assert_that(fred).is_type_of(dict) assert_that(fred['update']).is_equal_to('Fred') assert_that(fred).has_update('Fred')
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,307
assertpy/assertpy
refs/heads/main
/tests/test_custom_list.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from assertpy import assert_that, fail class CustomList(object): def __init__(self, s): self._s = s self._idx = 0 def __iter__(self): return self def __next__(self): try: result = self._s[self._idx] except IndexError: raise StopIteration self._idx += 1 return result def __getitem__(self, idx): return self._s[idx] def test_custom_list(): l = CustomList('foobar') assert_that([CustomList('foo'), CustomList('bar')]).extracting(0, -1).is_equal_to([('f', 'o'), ('b', 'r')]) def test_check_iterable(): l = CustomList('foobar') ab = assert_that(None) ab._check_iterable(l) ab._check_iterable(l, check_getitem=True) ab._check_iterable(l, check_getitem=False) def test_check_iterable_not_iterable(): try: ab = assert_that(None) ab._check_iterable(123, name='my-int') fail('should have raised error') except TypeError as e: assert_that(str(e)).contains('my-int <int> is not iterable') def test_check_iterable_no_getitem(): try: ab = assert_that(None) ab._check_iterable(set([1]), name='my-set') fail('should have raised error') except TypeError as e: assert_that(str(e)).contains('my-set <set> does not have [] accessor')
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,308
assertpy/assertpy
refs/heads/main
/assertpy/helpers.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import numbers import datetime import collections if sys.version_info[0] == 3: Iterable = collections.abc.Iterable else: Iterable = collections.Iterable __tracebackhide__ = True class HelpersMixin(object): """Helpers mixin. For internal use only.""" def _fmt_items(self, i): """Helper to format the given items.""" if len(i) == 0: return '<>' elif len(i) == 1 and hasattr(i, '__getitem__'): return '<%s>' % (i[0],) else: return '<%s>' % str(i).lstrip('([').rstrip(',])') def _fmt_args_kwargs(self, *some_args, **some_kwargs): """Helper to convert the given args and kwargs into a string.""" if some_args: out_args = str(some_args).lstrip('(').rstrip(',)') if some_kwargs: out_kwargs = ', '.join([str(i).lstrip('(').rstrip(')').replace(', ', ': ') for i in [ (k, some_kwargs[k]) for k in sorted(some_kwargs.keys())]]) if some_args and some_kwargs: return out_args + ', ' + out_kwargs elif some_args: return out_args elif some_kwargs: return out_kwargs else: return '' def _validate_between_args(self, val_type, low, high): """Helper to validate given range args.""" low_type = type(low) high_type = type(high) if val_type in self._NUMERIC_NON_COMPAREABLE: raise TypeError('ordering is not defined for type <%s>' % val_type.__name__) if val_type in self._NUMERIC_COMPAREABLE: if low_type is not val_type: raise TypeError('given low arg must be <%s>, but was <%s>' % (val_type.__name__, low_type.__name__)) if high_type is not val_type: raise TypeError('given high arg must be <%s>, but was <%s>' % (val_type.__name__, low_type.__name__)) elif isinstance(self.val, numbers.Number): if isinstance(low, numbers.Number) is False: raise TypeError('given low arg must be numeric, but was <%s>' % low_type.__name__) if isinstance(high, numbers.Number) is False: raise TypeError('given high arg must be numeric, but was <%s>' % high_type.__name__) else: raise TypeError('ordering is not defined for type <%s>' % val_type.__name__) if low > high: raise ValueError('given low arg must be less than given high arg') def _validate_close_to_args(self, val, other, tolerance): """Helper for validate given arg and delta.""" if type(val) is complex or type(other) is complex or type(tolerance) is complex: raise TypeError('ordering is not defined for complex numbers') if isinstance(val, numbers.Number) is False and type(val) is not datetime.datetime: raise TypeError('val is not numeric or datetime') if type(val) is datetime.datetime: if type(other) is not datetime.datetime: raise TypeError('given arg must be datetime, but was <%s>' % type(other).__name__) if type(tolerance) is not datetime.timedelta: raise TypeError('given tolerance arg must be timedelta, but was <%s>' % type(tolerance).__name__) else: if isinstance(other, numbers.Number) is False: raise TypeError('given arg must be numeric') if isinstance(tolerance, numbers.Number) is False: raise TypeError('given tolerance arg must be numeric') if tolerance < 0: raise ValueError('given tolerance arg must be positive') def _check_dict_like(self, d, check_keys=True, check_values=True, check_getitem=True, name='val', return_as_bool=False): """Helper to check if given val has various dict-like attributes.""" if not isinstance(d, Iterable): if return_as_bool: return False else: raise TypeError('%s <%s> is not dict-like: not iterable' % (name, type(d).__name__)) if check_keys: if not hasattr(d, 'keys') or not callable(getattr(d, 'keys')): if return_as_bool: return False else: raise TypeError('%s <%s> is not dict-like: missing keys()' % (name, type(d).__name__)) if check_values: if not hasattr(d, 'values') or not callable(getattr(d, 'values')): if return_as_bool: return False else: raise TypeError('%s <%s> is not dict-like: missing values()' % (name, type(d).__name__)) if check_getitem: if not hasattr(d, '__getitem__'): if return_as_bool: return False else: raise TypeError('%s <%s> is not dict-like: missing [] accessor' % (name, type(d).__name__)) if return_as_bool: return True def _check_iterable(self, l, check_getitem=True, name='val'): """Helper to check if given val has various iterable attributes.""" if not isinstance(l, Iterable): raise TypeError('%s <%s> is not iterable' % (name, type(l).__name__)) if check_getitem: if not hasattr(l, '__getitem__'): raise TypeError('%s <%s> does not have [] accessor' % (name, type(l).__name__)) def _dict_not_equal(self, val, other, ignore=None, include=None): """Helper to compare dicts.""" if ignore or include: ignores = self._dict_ignore(ignore) includes = self._dict_include(include) # guarantee include keys are in val if include: missing = [] for i in includes: if i not in val: missing.append(i) if missing: return self.error('Expected <%s> to include key%s %s, but did not include key%s %s.' % ( val, '' if len(includes) == 1 else 's', self._fmt_items(['.'.join([str(s) for s in i]) if type(i) is tuple else i for i in includes]), '' if len(missing) == 1 else 's', self._fmt_items(missing))) # calc val keys given ignores and includes if ignore and include: k1 = set([k for k in val if k not in ignores and k in includes]) elif ignore: k1 = set([k for k in val if k not in ignores]) else: # include k1 = set([k for k in val if k in includes]) # calc other keys given ignores and includes if ignore and include: k2 = set([k for k in other if k not in ignores and k in includes]) elif ignore: k2 = set([k for k in other if k not in ignores]) else: # include k2 = set([k for k in other if k in includes]) if k1 != k2: # different set of keys, so not equal return True else: for k in k1: if self._check_dict_like(val[k], check_values=False, return_as_bool=True) and \ self._check_dict_like(other[k], check_values=False, return_as_bool=True): subdicts_not_equal = self._dict_not_equal( val[k], other[k], ignore=[i[1:] for i in ignores if type(i) is tuple and i[0] == k] if ignore else None, include=[i[1:] for i in self._dict_ignore(include) if type(i) is tuple and i[0] == k] if include else None) if subdicts_not_equal: # fast fail inside the loop since sub-dicts are not equal return True elif val[k] != other[k]: # fast fail inside the loop since values are not equal return True return False else: return val != other def _dict_ignore(self, ignore): """Helper to make list for given ignore kwarg values.""" return [i[0] if type(i) is tuple and len(i) == 1 else i for i in (ignore if type(ignore) is list else [ignore])] def _dict_include(self, include): """Helper to make a list from given include kwarg values.""" return [i[0] if type(i) is tuple else i for i in (include if type(include) is list else [include])] def _dict_err(self, val, other, ignore=None, include=None): """Helper to construct error message for dict comparison.""" def _dict_repr(d, other): out = '' ellip = False for k, v in sorted(d.items()): if k not in other: out += '%s%s: %s' % (', ' if len(out) > 0 else '', repr(k), repr(v)) elif v != other[k]: out += '%s%s: %s' % ( ', ' if len(out) > 0 else '', repr(k), _dict_repr(v, other[k]) if self._check_dict_like( v, check_values=False, return_as_bool=True) and self._check_dict_like( other[k], check_values=False, return_as_bool=True) else repr(v) ) else: ellip = True return '{%s%s}' % ('..' if ellip and len(out) == 0 else '.., ' if ellip else '', out) if ignore: ignores = self._dict_ignore(ignore) ignore_err = ' ignoring keys %s' % self._fmt_items(['.'.join([str(s) for s in i]) if type(i) is tuple else i for i in ignores]) if include: includes = self._dict_ignore(include) include_err = ' including keys %s' % self._fmt_items(['.'.join([str(s) for s in i]) if type(i) is tuple else i for i in includes]) return self.error('Expected <%s> to be equal to <%s>%s%s, but was not.' % ( _dict_repr(val, other), _dict_repr(other, val), ignore_err if ignore else '', include_err if include else '' ))
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,309
assertpy/assertpy
refs/heads/main
/tests/test_same_as.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys from assertpy import assert_that, fail def test_is_same_as(): for obj in [object(), 1, 'foo', True, None, 123.456]: assert_that(obj).is_same_as(obj) def test_is_same_as_failure(): try: obj = object() other = object() assert_that(obj).is_same_as(other) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches('Expected <.+> to be identical to <.+>, but was not.') def test_is_not_same_as(): obj = object() other = object() assert_that(obj).is_not_same_as(other) assert_that(obj).is_not_same_as(1) assert_that(obj).is_not_same_as(True) assert_that(1).is_not_same_as(2) assert_that({'a': 1}).is_not_same_as({'a': 1}) assert_that([1, 2, 3]).is_not_same_as([1, 2, 3]) if sys.version_info[0] == 3 and sys.version_info[1] >= 7: assert_that((1, 2, 3)).is_same_as((1, 2, 3)) # tuples are identical in py 3.7 else: assert_that((1, 2, 3)).is_not_same_as((1, 2, 3)) def test_is_not_same_as_failure(): for obj in [object(), 1, 'foo', True, None, 123.456]: try: assert_that(obj).is_not_same_as(obj) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches('Expected <.+> to be not identical to <.+>, but was.')
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,310
assertpy/assertpy
refs/heads/main
/docs/fixup.py
import os import re # conf PROJECT = 'assertpy' SRC_DIR = os.path.join(os.getcwd(), 'build') SRC = os.path.join(SRC_DIR, 'assertpy.html') OUT_DIR = os.path.join(os.getcwd(), 'out') OUT = os.path.join(OUT_DIR, 'docs.html') def load(filename): with open(filename, 'r') as fp: return fp.read() def save(target, contents): with open(target, 'w') as fp: fp.write(contents) if __name__ == '__main__': print('\nFIXUP') print(f' src={SRC}') print(f' out={OUT}') if not os.path.exists(OUT_DIR): os.makedirs(OUT_DIR) if not os.path.isfile(SRC): print(f'bad src filename {SRC}') html = load(SRC) html = html.replace('<h1>', '<h1 class="title">') html = html.replace('"admonition-title">Tip</p>\n<p>', '"message-header">Tip</p>\n<p class="message-body">') html = html.replace('"admonition-title">Note</p>\n<p>', '"message-header">Note</p>\n<p class="message-body">') html = html.replace('"admonition-title">See also</p>\n<p>', '"message-header">See Also</p>\n<p class="message-body">') html = html.replace('"admonition tip"', '"message is-primary"') html = html.replace('"admonition note"', '"message is-info"') html = html.replace('"admonition seealso"', '"message is-link"') html = html.replace('<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>', '<pre class="code"><code class="python">') html = html.replace('</pre></div>\n</div>', '</code></pre>') html = html.replace('class="code"><code class="python"><span class="mi">2019', 'class="code"><code class="bash"><span class="mi">2019') html = html.replace('class="code"><code class="python"><span class="ne">AssertionError</span><span class="p">:', 'class="code"><code class="bash"><span class="ne">AssertionError</span><span class="p">:') html = html.replace('class="code"><code class="python">AssertionError: soft assertion failures', 'class="code"><code class="bash">AssertionError: soft assertion failures') html = html.replace('<div class="section"', '<div class="section content"') html = html.replace('<p>Usage:</p>', '') html = html.replace('BR', '<br />') margin = 'style="margin:0.2em 0;"' html = html.replace('<dt class="field-odd">Parameters</dt>', f'<dt class="field-odd subtitle"{margin}>Parameters</dt>') html = html.replace('<dt class="field-even">Keyword Arguments</dt>', f'<dt class="field-even subtitle"{margin}>Keyword Arguments</dt>') html = html.replace('<p class="rubric">Examples</p>', f'<p class="rubric subtitle"{margin}>Examples</p>') html = html.replace('<dt class="field-odd">Returns</dt>', f'<dt class="field-odd subtitle"{margin}>Returns</dt>') html = html.replace('<dt class="field-even">Return type</dt>', f'<dt class="field-even subtitle"{margin}>Return type</dt>') html = html.replace('<dt class="field-odd">Raises</dt>', f'<dt class="field-odd subtitle"{margin}>Raises</dt>') html = html.replace('<dt id="assertpy.', '<dt class="title is-5" id="assertpy.') save(OUT, html) print('DONE!')
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,311
assertpy/assertpy
refs/heads/main
/setup.py
from distutils.core import setup import assertpy desc = """ assertpy ======== Simple assertions library for unit testing in Python with a nice fluent API. Supports both Python 2 and 3. Usage ----- Just import the ``assert_that`` function, and away you go...:: from assertpy import assert_that def test_something(): assert_that(1 + 2).is_equal_to(3) assert_that('foobar').is_length(6).starts_with('foo').ends_with('bar') assert_that(['a', 'b', 'c']).contains('a').does_not_contain('x') Of course, assertpy works best with a python test runner like `pytest <http://pytest.org/>`_ (our favorite) or `Nose <http://nose.readthedocs.org/>`_. Install ------- The assertpy library is available via `PyPI <https://pypi.org/project/assertpy/>`_. Just install with:: pip install assertpy Or, if you are a big fan of `conda <https://conda.io/>`_ like we are, there is an `assertpy-feedstock <https://github.com/conda-forge/assertpy-feedstock>`_ for `Conda-Forge <https://conda-forge.org/>`_ that you can use:: conda install assertpy --channel conda-forge """ setup( name='assertpy', packages=['assertpy'], version=assertpy.__version__, description='Simple assertion library for unit testing in python with a fluent API', long_description=desc, author='Justin Shacklette', author_email='justin@saturnboy.com', url='https://github.com/assertpy/assertpy', download_url='https://github.com/assertpy/assertpy/archive/%s.tar.gz' % assertpy.__version__, keywords=['test', 'testing', 'assert', 'assertion', 'assertthat', 'assert_that', 'nose', 'nosetests', 'pytest', 'unittest'], license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Topic :: Software Development', 'Topic :: Software Development :: Testing'])
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,312
assertpy/assertpy
refs/heads/main
/assertpy/contains.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys if sys.version_info[0] == 3: str_types = (str,) xrange = range else: str_types = (basestring,) xrange = xrange __tracebackhide__ = True class ContainsMixin(object): """Containment assertions mixin.""" def contains(self, *items): """Asserts that val contains the given item or items. Checks if the collection contains the given item or items using ``in`` operator. Args: *items: the item or items expected to be contained Examples: Usage:: assert_that('foo').contains('f') assert_that('foo').contains('f', 'oo') assert_that(['a', 'b']).contains('b', 'a') assert_that((1, 2, 3)).contains(3, 2, 1) assert_that({'a': 1, 'b': 2}).contains('b', 'a') # checks keys assert_that({'a', 'b'}).contains('b', 'a') assert_that([1, 2, 3]).is_type_of(list).contains(1, 2).does_not_contain(4, 5) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val does **not** contain the item or items Tip: Use the :meth:`~assertpy.dict.DictMixin.contains_key` alias when working with *dict-like* objects to be self-documenting. See Also: :meth:`~assertpy.string.StringMixin.contains_ignoring_case` - for case-insensitive string contains """ if len(items) == 0: raise ValueError('one or more args must be given') elif len(items) == 1: if items[0] not in self.val: if self._check_dict_like(self.val, return_as_bool=True): return self.error('Expected <%s> to contain key <%s>, but did not.' % (self.val, items[0])) else: return self.error('Expected <%s> to contain item <%s>, but did not.' % (self.val, items[0])) else: missing = [] for i in items: if i not in self.val: missing.append(i) if missing: if self._check_dict_like(self.val, return_as_bool=True): return self.error('Expected <%s> to contain keys %s, but did not contain key%s %s.' % ( self.val, self._fmt_items(items), '' if len(missing) == 0 else 's', self._fmt_items(missing))) else: return self.error('Expected <%s> to contain items %s, but did not contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(missing))) return self def does_not_contain(self, *items): """Asserts that val does not contain the given item or items. Checks if the collection excludes the given item or items using ``in`` operator. Args: *items: the item or items expected to be excluded Examples: Usage:: assert_that('foo').does_not_contain('x') assert_that(['a', 'b']).does_not_contain('x', 'y') assert_that((1, 2, 3)).does_not_contain(4, 5) assert_that({'a': 1, 'b': 2}).does_not_contain('x', 'y') # checks keys assert_that({'a', 'b'}).does_not_contain('x', 'y') assert_that([1, 2, 3]).is_type_of(list).contains(1, 2).does_not_contain(4, 5) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val **does** contain the item or items Tip: Use the :meth:`~assertpy.dict.DictMixin.does_not_contain_key` alias when working with *dict-like* objects to be self-documenting. """ if len(items) == 0: raise ValueError('one or more args must be given') elif len(items) == 1: if items[0] in self.val: return self.error('Expected <%s> to not contain item <%s>, but did.' % (self.val, items[0])) else: found = [] for i in items: if i in self.val: found.append(i) if found: return self.error('Expected <%s> to not contain items %s, but did contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(found))) return self def contains_only(self, *items): """Asserts that val contains *only* the given item or items. Checks if the collection contains only the given item or items using ``in`` operator. Args: *items: the *only* item or items expected to be contained Examples: Usage:: assert_that('foo').contains_only('f', 'o') assert_that(['a', 'a', 'b']).contains_only('a', 'b') assert_that((1, 1, 2)).contains_only(1, 2) assert_that({'a': 1, 'a': 2, 'b': 3}).contains_only('a', 'b') assert_that({'a', 'a', 'b'}).contains_only('a', 'b') Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val contains anything **not** item or items """ if len(items) == 0: raise ValueError('one or more args must be given') else: extra = [] for i in self.val: if i not in items: extra.append(i) if extra: return self.error('Expected <%s> to contain only %s, but did contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(extra))) missing = [] for i in items: if i not in self.val: missing.append(i) if missing: return self.error('Expected <%s> to contain only %s, but did not contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(missing))) return self def contains_sequence(self, *items): """Asserts that val contains the given ordered sequence of items. Checks if the collection contains the given sequence of items using ``in`` operator. Args: *items: the sequence of items expected to be contained Examples: Usage:: assert_that('foo').contains_sequence('f', 'o') assert_that('foo').contains_sequence('o', 'o') assert_that(['a', 'b', 'c']).contains_sequence('b', 'c') assert_that((1, 2, 3)).contains_sequence(1, 2) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val does **not** contains the given sequence of items """ if len(items) == 0: raise ValueError('one or more args must be given') else: try: for i in xrange(len(self.val) - len(items) + 1): for j in xrange(len(items)): if self.val[i+j] != items[j]: break else: return self except TypeError: raise TypeError('val is not iterable') return self.error('Expected <%s> to contain sequence %s, but did not.' % (self.val, self._fmt_items(items))) def contains_duplicates(self): """Asserts that val is iterable and *does* contain duplicates. Examples: Usage:: assert_that('foo').contains_duplicates() assert_that(['a', 'a', 'b']).contains_duplicates() assert_that((1, 1, 2)).contains_duplicates() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val does **not** contain any duplicates """ try: if len(self.val) != len(set(self.val)): return self except TypeError: raise TypeError('val is not iterable') return self.error('Expected <%s> to contain duplicates, but did not.' % self.val) def does_not_contain_duplicates(self): """Asserts that val is iterable and *does not* contain any duplicates. Examples: Usage:: assert_that('fox').does_not_contain_duplicates() assert_that(['a', 'b', 'c']).does_not_contain_duplicates() assert_that((1, 2, 3)).does_not_contain_duplicates() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val **does** contain duplicates """ try: if len(self.val) == len(set(self.val)): return self except TypeError: raise TypeError('val is not iterable') return self.error('Expected <%s> to not contain duplicates, but did.' % self.val) def is_empty(self): """Asserts that val is empty. Examples: Usage:: assert_that('').is_empty() assert_that([]).is_empty() assert_that(()).is_empty() assert_that({}).is_empty() assert_that(set()).is_empty() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** empty """ if len(self.val) != 0: if isinstance(self.val, str_types): return self.error('Expected <%s> to be empty string, but was not.' % self.val) else: return self.error('Expected <%s> to be empty, but was not.' % self.val) return self def is_not_empty(self): """Asserts that val is *not* empty. Examples: Usage:: assert_that('foo').is_not_empty() assert_that(['a', 'b']).is_not_empty() assert_that((1, 2, 3)).is_not_empty() assert_that({'a': 1, 'b': 2}).is_not_empty() assert_that({'a', 'b'}).is_not_empty() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val **is** empty """ if len(self.val) == 0: if isinstance(self.val, str_types): return self.error('Expected not empty string, but was empty.') else: return self.error('Expected not empty, but was empty.') return self def is_in(self, *items): """Asserts that val is equal to one of the given items. Args: *items: the items expected to contain val Examples: Usage:: assert_that('foo').is_in('foo', 'bar', 'baz') assert_that(1).is_in(0, 1, 2, 3) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** in the given items """ if len(items) == 0: raise ValueError('one or more args must be given') else: for i in items: if self.val == i: return self return self.error('Expected <%s> to be in %s, but was not.' % (self.val, self._fmt_items(items))) def is_not_in(self, *items): """Asserts that val is not equal to one of the given items. Args: *items: the items expected to exclude val Examples: Usage:: assert_that('foo').is_not_in('bar', 'baz', 'box') assert_that(1).is_not_in(-1, -2, -3) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val **is** in the given items """ if len(items) == 0: raise ValueError('one or more args must be given') else: for i in items: if self.val == i: return self.error('Expected <%s> to not be in %s, but was.' % (self.val, self._fmt_items(items))) return self
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,313
assertpy/assertpy
refs/heads/main
/assertpy/dynamic.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import collections if sys.version_info[0] == 3: Iterable = collections.abc.Iterable else: Iterable = collections.Iterable __tracebackhide__ = True class DynamicMixin(object): """Dynamic assertions mixin. When testing attributes of an object (or the contents of a dict), the :meth:`~assertpy.base.BaseMixin.is_equal_to` assertion can be a bit verbose:: fred = Person('Fred', 'Smith') assert_that(fred.first_name).is_equal_to('Fred') assert_that(fred.name).is_equal_to('Fred Smith') assert_that(fred.say_hello()).is_equal_to('Hello, Fred!') Instead, use dynamic assertions in the form of ``has_<name>()`` where ``<name>`` is the name of any attribute, property, or zero-argument method on the given object. Dynamic equality assertions test if actual is equal to expected using the ``==`` operator. Using dynamic assertions, we can rewrite the above example as:: assert_that(fred).has_first_name('Fred') assert_that(fred).has_name('Fred Smith') assert_that(fred).has_say_hello('Hello, Fred!') Similarly, dynamic assertions also work on any *dict-like* object:: fred = { 'first_name': 'Fred', 'last_name': 'Smith', 'shoe_size': 12 } assert_that(fred).has_first_name('Fred') assert_that(fred).has_last_name('Smith') assert_that(fred).has_shoe_size(12) """ def __getattr__(self, attr): """Asserts that val has attribute attr and that its value is equal to other via a dynamic assertion of the form ``has_<attr>()``.""" if not attr.startswith('has_'): raise AttributeError('assertpy has no assertion <%s()>' % attr) attr_name = attr[4:] err_msg = False is_namedtuple = isinstance(self.val, tuple) and hasattr(self.val, '_fields') is_dict = isinstance(self.val, Iterable) and hasattr(self.val, '__getitem__') if not hasattr(self.val, attr_name): if is_dict and not is_namedtuple: if attr_name not in self.val: err_msg = 'Expected key <%s>, but val has no key <%s>.' % (attr_name, attr_name) else: err_msg = 'Expected attribute <%s>, but val has no attribute <%s>.' % (attr_name, attr_name) def _wrapper(*args, **kwargs): if err_msg: return self.error(err_msg) # ok to raise AssertionError now that we are inside wrapper else: if len(args) != 1: raise TypeError('assertion <%s()> takes exactly 1 argument (%d given)' % (attr, len(args))) if is_dict and not is_namedtuple: val_attr = self.val[attr_name] else: val_attr = getattr(self.val, attr_name) if callable(val_attr): try: actual = val_attr() except TypeError: raise TypeError('val does not have zero-arg method <%s()>' % attr_name) else: actual = val_attr expected = args[0] if actual != expected: return self.error('Expected <%s> to be equal to <%s> on %s <%s>, but was not.' % (actual, expected, 'key' if is_dict else 'attribute', attr_name)) return self return _wrapper
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,314
assertpy/assertpy
refs/heads/main
/tests/test_numbers.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import math from assertpy import assert_that, fail def test_is_zero(): assert_that(0).is_zero() # assert_that(0L).is_zero() assert_that(0.0).is_zero() assert_that(0 + 0j).is_zero() def test_is_zero_failure(): try: assert_that(1).is_zero() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <1> to be equal to <0>, but was not.') def test_is_zero_bad_type_failure(): try: assert_that('foo').is_zero() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not numeric') def test_is_not_zero(): assert_that(1).is_not_zero() # assert_that(1L).is_not_zero() assert_that(0.001).is_not_zero() assert_that(0 + 1j).is_not_zero() def test_is_not_zero_failure(): try: assert_that(0).is_not_zero() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <0> to be not equal to <0>, but was.') def test_is_not_zero_bad_type_failure(): try: assert_that('foo').is_not_zero() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not numeric') def test_is_nan(): assert_that(float('NaN')).is_nan() assert_that(float('Inf')-float('Inf')).is_nan() def test_is_nan_failure(): try: assert_that(0).is_nan() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <0> to be <NaN>, but was not.') def test_is_nan_bad_type_failure(): try: assert_that('foo').is_nan() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not numeric') def test_is_nan_bad_type_failure_complex(): try: assert_that(1 + 2j).is_nan() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not real number') def test_is_not_nan(): assert_that(1).is_not_nan() assert_that(1.0).is_not_nan() def test_is_not_nan_failure(): try: assert_that(float('NaN')).is_not_nan() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected not <NaN>, but was.') def test_is_not_nan_bad_type_failure(): try: assert_that('foo').is_not_nan() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not numeric') def test_is_not_nan_bad_type_failure_complex(): try: assert_that(1 + 2j).is_not_nan() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not real number') def test_is_inf(): assert_that(float('Inf')).is_inf() assert_that(1e1000).is_inf() def test_is_inf_failure(): try: assert_that(0).is_inf() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <0> to be <Inf>, but was not.') def test_is_inf_bad_type_failure(): try: assert_that('foo').is_inf() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not numeric') def test_is_inf_bad_type_failure_complex(): try: assert_that(1 + 2j).is_inf() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not real number') def test_is_not_inf(): assert_that(1).is_not_inf() assert_that(123.456).is_not_inf() def test_is_not_inf_failure(): try: assert_that(float('Inf')).is_not_inf() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected not <Inf>, but was.') def test_is_not_inf_bad_type_failure(): try: assert_that('foo').is_not_inf() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not numeric') def test_is_not_inf_bad_type_failure_complex(): try: assert_that(1 + 2j).is_not_inf() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not real number') def test_is_greater_than(): assert_that(123).is_greater_than(100) assert_that(123).is_greater_than(0) assert_that(123).is_greater_than(-100) assert_that(123).is_greater_than(122.5) def test_is_greater_than_failure(): try: assert_that(123).is_greater_than(123) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <123> to be greater than <123>, but was not.') def test_is_greater_than_complex_failure(): try: assert_that(1 + 2j).is_greater_than(0) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('ordering is not defined for type <complex>') def test_is_greater_than_bad_value_type_failure(): try: assert_that('foo').is_greater_than(0) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('ordering is not defined for type <str>') def test_is_greater_than_bad_arg_type_failure(): try: assert_that(123).is_greater_than('foo') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be a number, but was <str>') def test_is_greater_than_or_equal_to(): assert_that(123).is_greater_than_or_equal_to(100) assert_that(123).is_greater_than_or_equal_to(123) assert_that(123).is_greater_than_or_equal_to(0) assert_that(123).is_greater_than_or_equal_to(-100) assert_that(123).is_greater_than_or_equal_to(122.5) def test_is_greater_than_or_equal_to_failure(): try: assert_that(123).is_greater_than_or_equal_to(1000) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <123> to be greater than or equal to <1000>, but was not.') def test_is_greater_than_or_equal_to_complex_failure(): try: assert_that(1 + 2j).is_greater_than_or_equal_to(0) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('ordering is not defined for type <complex>') def test_is_greater_than_or_equal_to_bad_value_type_failure(): try: assert_that('foo').is_greater_than_or_equal_to(0) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('ordering is not defined for type <str>') def test_is_greater_than_or_equal_to_bad_arg_type_failure(): try: assert_that(123).is_greater_than_or_equal_to('foo') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be a number, but was <str>') def test_is_less_than(): assert_that(123).is_less_than(1000) assert_that(123).is_less_than(1e6) assert_that(-123).is_less_than(-100) assert_that(123).is_less_than(123.001) def test_is_less_than_failure(): try: assert_that(123).is_less_than(123) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <123> to be less than <123>, but was not.') def test_is_less_than_complex_failure(): try: assert_that(1 + 2j).is_less_than(0) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('ordering is not defined for type <complex>') def test_is_less_than_bad_value_type_failure(): try: assert_that('foo').is_less_than(0) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('ordering is not defined for type <str>') def test_is_less_than_bad_arg_type_failure(): try: assert_that(123).is_less_than('foo') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be a number, but was <str>') def test_is_less_than_or_equal_to(): assert_that(123).is_less_than_or_equal_to(1000) assert_that(123).is_less_than_or_equal_to(123) assert_that(123).is_less_than_or_equal_to(1e6) assert_that(-123).is_less_than_or_equal_to(-100) assert_that(123).is_less_than_or_equal_to(123.001) def test_is_less_than_or_equal_to_failure(): try: assert_that(123).is_less_than_or_equal_to(100) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <123> to be less than or equal to <100>, but was not.') def test_is_less_than_or_equal_to_complex_failure(): try: assert_that(1 + 2j).is_less_than_or_equal_to(0) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('ordering is not defined for type <complex>') def test_is_less_than_or_equal_to_bad_value_type_failure(): try: assert_that('foo').is_less_than_or_equal_to(0) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('ordering is not defined for type <str>') def test_is_less_than_or_equal_to_bad_arg_type_failure(): try: assert_that(123).is_less_than_or_equal_to('foo') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be a number, but was <str>') def test_is_positive(): assert_that(1).is_positive() def test_is_positive_failure(): try: assert_that(0).is_positive() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <0> to be greater than <0>, but was not.') def test_is_negative(): assert_that(-1).is_negative() def test_is_negative_failure(): try: assert_that(0).is_negative() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <0> to be less than <0>, but was not.') def test_is_between(): assert_that(123).is_between(120, 125) assert_that(123).is_between(0, 1e6) assert_that(-123).is_between(-150, -100) assert_that(123).is_between(122.999, 123.001) def test_is_between_failure(): try: assert_that(123).is_between(0, 1) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <123> to be between <0> and <1>, but was not.') def test_is_between_complex_failure(): try: assert_that(1 + 2j).is_between(0, 1) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('ordering is not defined for type <complex>') def test_is_between_bad_value_type_failure(): try: assert_that('foo').is_between(0, 1) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('ordering is not defined for type <str>') def test_is_between_low_arg_type_failure(): try: assert_that(123).is_between('foo', 1) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given low arg must be numeric, but was <str>') def test_is_between_high_arg_type_failure(): try: assert_that(123).is_between(0, 'foo') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given high arg must be numeric, but was <str>') def test_is_between_bad_arg_delta_failure(): try: assert_that(123).is_between(1, 0) fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('given low arg must be less than given high arg') def test_is_not_between(): assert_that(123).is_not_between(124, 125) assert_that(123).is_not_between(1e5, 1e6) assert_that(-123).is_not_between(-1000, -150) assert_that(123).is_not_between(122.999, 122.9999) def test_is_not_between_failure(): try: assert_that(123).is_not_between(0, 1000) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <123> to not be between <0> and <1000>, but was.') def test_is_not_between_complex_failure(): try: assert_that(1 + 2j).is_not_between(0, 1) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('ordering is not defined for type <complex>') def test_is_not_between_bad_value_type_failure(): try: assert_that('foo').is_not_between(0, 1) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('ordering is not defined for type <str>') def test_is_not_between_low_arg_type_failure(): try: assert_that(123).is_not_between('foo', 1) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given low arg must be numeric, but was <str>') def test_is_not_between_high_arg_type_failure(): try: assert_that(123).is_not_between(0, 'foo') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given high arg must be numeric, but was <str>') def test_is_not_between_bad_arg_delta_failure(): try: assert_that(123).is_not_between(1, 0) fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('given low arg must be less than given high arg') def test_is_close_to(): assert_that(123.01).is_close_to(123, 1) assert_that(0.01).is_close_to(0, 1) assert_that(-123.01).is_close_to(-123, 1) def test_is_close_to_failure(): try: assert_that(123.01).is_close_to(100, 1) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <123.01> to be close to <100> within tolerance <1>, but was not.') def test_is_close_to_complex_failure(): try: assert_that(1 + 2j).is_close_to(0, 1) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('ordering is not defined for complex numbers') def test_is_close_to_bad_value_type_failure(): try: assert_that('foo').is_close_to(123, 1) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not numeric or datetime') def test_is_close_to_bad_arg_type_failure(): try: assert_that(123.01).is_close_to('foo', 1) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be numeric') def test_is_close_to_bad_tolerance_arg_type_failure(): try: assert_that(123.01).is_close_to(0, 'foo') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given tolerance arg must be numeric') def test_is_close_to_negative_tolerance_failure(): try: assert_that(123.01).is_close_to(123, -1) fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('given tolerance arg must be positive') def test_is_not_close_to(): assert_that(123.01).is_not_close_to(122, 1) assert_that(0.01).is_not_close_to(0, 0.001) assert_that(-123.01).is_not_close_to(-122, 1) def test_is_not_close_to_failure(): try: assert_that(123.01).is_not_close_to(123, 1) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <123.01> to not be close to <123> within tolerance <1>, but was.') def test_is_not_close_to_complex_failure(): try: assert_that(1 + 2j).is_not_close_to(0, 1) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('ordering is not defined for complex numbers') def test_is_not_close_to_bad_value_type_failure(): try: assert_that('foo').is_not_close_to(123, 1) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not numeric or datetime') def test_is_not_close_to_bad_arg_type_failure(): try: assert_that(123.01).is_not_close_to('foo', 1) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be numeric') def test_is_not_close_to_bad_tolerance_arg_type_failure(): try: assert_that(123.01).is_not_close_to(0, 'foo') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given tolerance arg must be numeric') def test_is_not_close_to_negative_tolerance_failure(): try: assert_that(123.01).is_not_close_to(123, -1) fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('given tolerance arg must be positive') def test_chaining(): assert_that(123).is_greater_than(100).is_less_than(1000).is_between(120, 125).is_close_to(100, 25)
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,315
assertpy/assertpy
refs/heads/main
/assertpy/date.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import datetime __tracebackhide__ = True class DateMixin(object): """Date and time assertions mixin.""" def is_before(self, other): """Asserts that val is a date and is before other date. Args: other: the other date, expected to be after val Examples: Usage:: import datetime today = datetime.datetime.now() yesterday = today - datetime.timedelta(days=1) assert_that(yesterday).is_before(today) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** before the given date See Also: :meth:`~assertpy.string.NumericMixin.is_less_than` - numeric assertion, but also works with datetime BR :meth:`~assertpy.string.NumericMixin.is_less_than_or_equal_to` - numeric assertion, but also works with datetime """ if type(self.val) is not datetime.datetime: raise TypeError('val must be datetime, but was type <%s>' % type(self.val).__name__) if type(other) is not datetime.datetime: raise TypeError('given arg must be datetime, but was type <%s>' % type(other).__name__) if self.val >= other: return self.error('Expected <%s> to be before <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'))) return self def is_after(self, other): """Asserts that val is a date and is after other date. Args: other: the other date, expected to be before val Examples: Usage:: import datetime today = datetime.datetime.now() yesterday = today - datetime.timedelta(days=1) assert_that(today).is_after(yesterday) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** after the given date See Also: :meth:`~assertpy.string.NumericMixin.is_greater_than` - numeric assertion, but also works with datetime BR :meth:`~assertpy.string.NumericMixin.is_greater_than_or_equal_to` - numeric assertion, but also works with datetime """ if type(self.val) is not datetime.datetime: raise TypeError('val must be datetime, but was type <%s>' % type(self.val).__name__) if type(other) is not datetime.datetime: raise TypeError('given arg must be datetime, but was type <%s>' % type(other).__name__) if self.val <= other: return self.error('Expected <%s> to be after <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'))) return self def is_equal_to_ignoring_milliseconds(self, other): """Asserts that val is a date and is equal to other date to the second. Args: other: the other date, expected to be equal to the second Examples: Usage:: import datetime d1 = datetime.datetime(2020, 1, 2, 3, 4, 5, 6) # 2020-01-02 03:04:05.000006 d2 = datetime.datetime(2020, 1, 2, 3, 4, 5, 777777) # 2020-01-02 03:04:05.777777 assert_that(d1).is_equal_to_ignoring_milliseconds(d2) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** equal to the given date to the second """ if type(self.val) is not datetime.datetime: raise TypeError('val must be datetime, but was type <%s>' % type(self.val).__name__) if type(other) is not datetime.datetime: raise TypeError('given arg must be datetime, but was type <%s>' % type(other).__name__) if self.val.date() != other.date() or self.val.hour != other.hour or self.val.minute != other.minute or self.val.second != other.second: return self.error('Expected <%s> to be equal to <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'))) return self def is_equal_to_ignoring_seconds(self, other): """Asserts that val is a date and is equal to other date to the minute. Args: other: the other date, expected to be equal to the minute Examples: Usage:: import datetime d1 = datetime.datetime(2020, 1, 2, 3, 4, 5) # 2020-01-02 03:04:05 d2 = datetime.datetime(2020, 1, 2, 3, 4, 55) # 2020-01-02 03:04:55 assert_that(d1).is_equal_to_ignoring_seconds(d2) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** equal to the given date to the minute """ if type(self.val) is not datetime.datetime: raise TypeError('val must be datetime, but was type <%s>' % type(self.val).__name__) if type(other) is not datetime.datetime: raise TypeError('given arg must be datetime, but was type <%s>' % type(other).__name__) if self.val.date() != other.date() or self.val.hour != other.hour or self.val.minute != other.minute: return self.error('Expected <%s> to be equal to <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M'), other.strftime('%Y-%m-%d %H:%M'))) return self def is_equal_to_ignoring_time(self, other): """Asserts that val is a date and is equal to other date ignoring time. Args: other: the other date, expected to be equal ignoring time Examples: Usage:: import datetime d1 = datetime.datetime(2020, 1, 2, 3, 4, 5) # 2020-01-02 03:04:05 d2 = datetime.datetime(2020, 1, 2, 13, 44, 55) # 2020-01-02 13:44:55 assert_that(d1).is_equal_to_ignoring_time(d2) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** equal to the given date ignoring time """ if type(self.val) is not datetime.datetime: raise TypeError('val must be datetime, but was type <%s>' % type(self.val).__name__) if type(other) is not datetime.datetime: raise TypeError('given arg must be datetime, but was type <%s>' % type(other).__name__) if self.val.date() != other.date(): return self.error('Expected <%s> to be equal to <%s>, but was not.' % (self.val.strftime('%Y-%m-%d'), other.strftime('%Y-%m-%d'))) return self
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,316
assertpy/assertpy
refs/heads/main
/tests/test_dyn.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from assertpy import assert_that, fail class Person(object): def __init__(self, first_name, last_name, shoe_size): self.first_name = first_name self.last_name = last_name self.shoe_size = shoe_size @property def name(self): return '%s %s' % (self.first_name, self.last_name) def say_hello(self): return 'Hello, %s!' % self.first_name def say_goodbye(self, target): return 'Bye, %s!' % target fred = Person('Fred', 'Smith', 12) def test_dynamic_assertion(): assert_that(fred).is_type_of(Person) assert_that(fred).is_instance_of(object) assert_that(fred.first_name).is_equal_to('Fred') assert_that(fred.last_name).is_equal_to('Smith') assert_that(fred.shoe_size).is_equal_to(12) assert_that(fred).has_first_name('Fred') assert_that(fred).has_last_name('Smith') assert_that(fred).has_shoe_size(12) def test_dynamic_assertion_on_property(): assert_that(fred.name).is_equal_to('Fred Smith') assert_that(fred).has_name('Fred Smith') def test_dynamic_assertion_on_method(): assert_that(fred.say_hello()).is_equal_to('Hello, Fred!') assert_that(fred).has_say_hello('Hello, Fred!') def test_dynamic_assertion_failure(): try: assert_that(fred).has_first_name('Joe') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <Fred> to be equal to <Joe> on attribute <first_name>, but was not.') def test_dynamic_assertion_bad_name_failure(): try: assert_that(fred).foo() fail('should have raised error') except AttributeError as ex: assert_that(str(ex)).is_equal_to('assertpy has no assertion <foo()>') def test_dynamic_assertion_unknown_attribute_failure(): try: assert_that(fred).has_foo() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected attribute <foo>, but val has no attribute <foo>.') def test_dynamic_assertion_no_args_failure(): try: assert_that(fred).has_first_name() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('assertion <has_first_name()> takes exactly 1 argument (0 given)') def test_dynamic_assertion_too_many_args_failure(): try: assert_that(fred).has_first_name('Fred', 'Joe') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('assertion <has_first_name()> takes exactly 1 argument (2 given)') def test_dynamic_assertion_on_method_failure(): try: assert_that(fred).has_say_goodbye('Foo') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).contains('val does not have zero-arg method <say_goodbye()>') def test_chaining(): assert_that(fred).has_first_name('Fred').has_last_name('Smith').has_shoe_size(12)
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,317
assertpy/assertpy
refs/heads/main
/tests/test_dict_compare.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import collections from assertpy import assert_that, fail def test_ignore_key(): assert_that({'a': 1}).is_equal_to({}, ignore='a') assert_that({'a': 1, 'b': 2}).is_equal_to({'a': 1}, ignore='b') assert_that({'a': 1, 'b': 2}).is_equal_to({'a': 1, 'b': 2}, ignore='c') assert_that({'a': 1, 'b': {'x': 2, 'y': 3}}).is_equal_to({'a': 1}, ignore='b') def test_ignore_list_of_keys(): assert_that({'a': 1, 'b': 2, 'c': 3}).is_equal_to({'a': 1, 'b': 2, 'c': 3}, ignore=[]) assert_that({'a': 1, 'b': 2, 'c': 3}).is_equal_to({'a': 1, 'b': 2}, ignore=['c']) assert_that({'a': 1, 'b': 2, 'c': 3}).is_equal_to({'a': 1}, ignore=['b', 'c']) assert_that({'a': 1, 'b': 2, 'c': 3}).is_equal_to({}, ignore=['a', 'b', 'c']) assert_that({'a': 1, 'b': 2, 'c': 3}).is_equal_to({'a': 1, 'b': 2, 'c': 3}, ignore=['d']) assert_that({'a': 1, 'b': 2, 'c': 3}).is_equal_to({'b': 2}, ignore=['c', 'd', 'e', 'a']) def test_ignore_deep_key(): assert_that({'a': 1, 'b': {'x': 2, 'y': 3}}).is_equal_to({'a': 1}, ignore=('b')) assert_that({'a': 1, 'b': {'x': 2, 'y': 3}}).is_equal_to({'a': 1}, ignore=[('b', )]) assert_that({'a': 1, 'b': {'x': 2, 'y': 3}}).is_equal_to({'a': 1, 'b': {'x': 2}}, ignore=('b', 'y')) assert_that({'a': 1, 'b': {'x': 2, 'y': 3}}).is_equal_to({'a': 1, 'b': {'x': 2}}, ignore=[('b', 'y')]) assert_that({'a': 1, 'b': {'x': 2, 'y': 3}}).is_equal_to({'a': 1, 'b': {'x': 2}}, ignore=[('b', 'y'), ('b', 'x', 'j')]) assert_that({'a': 1, 'b': {'c': 2, 'd': {'e': 3, 'f': {'x': 4, 'y': 5}}}}).is_equal_to({}, ignore=[('a'), ('b')]) assert_that({'a': 1, 'b': {'c': 2, 'd': {'e': 3, 'f': {'x': 4, 'y': 5}}}}).is_equal_to({'a': 1}, ignore=('b')) assert_that({'a': 1, 'b': {'c': 2, 'd': {'e': 3, 'f': {'x': 4, 'y': 5}}}}).is_equal_to({'a': 1, 'b': {'c': 2}}, ignore=('b', 'd')) assert_that({'a': 1, 'b': {'c': 2, 'd': {'e': 3, 'f': {'x': 4, 'y': 5}}}}).is_equal_to({'a': 1, 'b': {'c': 2, 'd': {'e': 3}}}, ignore=('b', 'd', 'f')) assert_that({'a': 1, 'b': {'c': 2, 'd': {'e': 3, 'f': {'x': 4, 'y': 5}}}}).is_equal_to( {'a': 1, 'b': {'c': 2, 'd': {'e': 3, 'f': {'x': 4, 'y': 6}}}}, ignore=('b', 'd', 'f', 'y')) assert_that({'a': 1, 'b': {'c': 2, 'd': {'e': 3, 'f': {'x': 4, 'y': 5}}}}).is_equal_to( {'a': 1, 'b': {'c': 2, 'd': {'e': 3, 'f': {'x': 4, 'y': 5}}}}, ignore=('b', 'd', 'f', 'y', 'foo')) def test_ordered(): if sys.version_info[0] == 3: ordered = collections.OrderedDict([('a', 1), ('b', 2)]) assert_that(ordered).is_equal_to({'a': 1, 'b': 2}) def test_failure(): try: assert_that({'a': 1, 'b': 2}).is_equal_to({'a': 1, 'b': 3}) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{.., 'b': 2}> to be equal to <{.., 'b': 3}>, but was not.") def test_failure_single_entry(): try: assert_that({'a': 1}).is_equal_to({'a': 2}) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{'a': 1}> to be equal to <{'a': 2}>, but was not.") def test_failure_multi_entry(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).is_equal_to({'a': 1, 'b': 3, 'c': 3}) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{.., 'b': 2}> to be equal to <{.., 'b': 3}>, but was not.") def test_failure_multi_entry_failure(): try: assert_that({'a': 1, 'b': 2, 'c': 3}).is_equal_to({'a': 1, 'b': 3, 'c': 4}) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains("'b': 2").contains("'b': 3").contains("'c': 3").contains("'c': 4").ends_with('but was not.') def test_failure_deep_dict(): try: assert_that({'a': 1, 'b': {'x': 2, 'y': 3}}).is_equal_to({'a': 1, 'b': {'x': 2, 'y': 4}}) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{.., 'b': {.., 'y': 3}}> to be equal to <{.., 'b': {.., 'y': 4}}>, but was not.") def test_failure_deep_dict_single_key(): try: assert_that({'a': 1, 'b': {'x': 2, 'y': 3}}).is_equal_to({'a': 1, 'b': {'x': 2}}) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{.., 'b': {.., 'y': 3}}> to be equal to <{.., 'b': {..}}>, but was not.") def test_failure_very_deep_dict(): try: assert_that({'a': 1, 'b': {'c': 2, 'd': {'e': 3, 'f': {'x': 4, 'y': 5}}}}).is_equal_to({'a': 1, 'b': {'c': 2, 'd': {'e': 3, 'f': {'x': 4, 'y': 6}}}}) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to( "Expected <{.., 'b': {.., 'd': {.., 'f': {.., 'y': 5}}}}> to be equal to <{.., 'b': {.., 'd': {.., 'f': {.., 'y': 6}}}}>, but was not.") def test_failure_ignore(): try: assert_that({'a': 1, 'b': 2}).is_equal_to({'a': 1, 'b': 3}, ignore='c') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{.., 'b': 2}> to be equal to <{.., 'b': 3}> ignoring keys <c>, but was not.") def test_failure_ignore_single_entry(): try: assert_that({'a': 1}).is_equal_to({'a': 2}, ignore='c') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{'a': 1}> to be equal to <{'a': 2}> ignoring keys <c>, but was not.") def test_failure_ignore_multi_keys(): try: assert_that({'a': 1}).is_equal_to({'a': 2}, ignore=['x', 'y', 'z']) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{'a': 1}> to be equal to <{'a': 2}> ignoring keys <'x', 'y', 'z'>, but was not.") def test_failure_ignore_multi_deep_keys(): try: assert_that({'a': 1}).is_equal_to({'a': 2}, ignore=[('q', 'r', 's'), ('x', 'y', 'z')]) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{'a': 1}> to be equal to <{'a': 2}> ignoring keys <'q.r.s', 'x.y.z'>, but was not.") def test_failure_ignore_mixed_keys(): try: assert_that({'a': 1}).is_equal_to({'a': 2}, ignore=['b', ('c'), ('d', 'e'), ('q', 'r', 's'), ('x', 'y', 'z')]) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{'a': 1}> to be equal to <{'a': 2}> ignoring keys <'b', 'c', 'd.e', 'q.r.s', 'x.y.z'>, but was not.") def test_failure_int_keys(): try: assert_that({1: 'a', 2: 'b'}).is_equal_to({1: 'a', 3: 'b'}) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{.., 2: 'b'}> to be equal to <{.., 3: 'b'}>, but was not.") def test_failure_deep_int_keys(): try: assert_that({1: 'a', 2: {3: 'b', 4: 'c'}}).is_equal_to({1: 'a', 2: {3: 'b', 5: 'c'}}, ignore=(2, 3)) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{.., 2: {.., 4: 'c'}}> to be equal to <{.., 2: {.., 5: 'c'}}> ignoring keys <2.3>, but was not.") def test_failure_tuple_keys(): try: assert_that({(1, 2): 'a', (3, 4): 'b'}).is_equal_to({(1, 2): 'a', (3, 4): 'c'}) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{.., (3, 4): 'b'}> to be equal to <{.., (3, 4): 'c'}>, but was not.") def test_failure_tuple_keys_ignore(): try: assert_that({(1, 2): 'a', (3, 4): 'b'}).is_equal_to({(1, 2): 'a', (3, 4): 'c'}, ignore=(1, 2)) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{.., (3, 4): 'b'}> to be equal to <{.., (3, 4): 'c'}> ignoring keys <1.2>, but was not.") def test_failure_deep_tuple_keys_ignore(): try: assert_that({(1, 2): 'a', (3, 4): {(5, 6): 'b', (7, 8): 'c'}}).is_equal_to({(1, 2): 'a', (3, 4): {(5, 6): 'b', (7, 8): 'd'}}, ignore=((3, 4), (5, 6))) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to( "Expected <{.., (3, 4): {.., (7, 8): 'c'}}> to be equal to <{.., (3, 4): {.., (7, 8): 'd'}}> ignoring keys <(3, 4).(5, 6)>, but was not.") def test_failure_single_item_tuple_keys_ignore(): # due to unpacking-fu, single item tuple keys must be tupled in ignore statement, so this works: assert_that({(1,): 'a', (2,): 'b'}).is_equal_to({(1,): 'a', (2,): 'c'}, ignore=((2,), )) # but this fails: try: assert_that({(1,): 'a', (2,): 'b'}).is_equal_to({(1,): 'a'}, ignore=(2, )) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{.., (2,): 'b'}> to be equal to <{..}> ignoring keys <2>, but was not.") def test_failure_single_item_tuple_keys_ignore_error_msg(): try: assert_that({(1,): 'a'}).is_equal_to({(1,): 'b'}, ignore=((2,), )) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{(1,): 'a'}> to be equal to <{(1,): 'b'}> ignoring keys <2>, but was not.") def test_include_key(): assert_that({'a': 1, 'b': 2}).is_equal_to({'a': 1}, include='a') assert_that({'a': 1, 'b': {'x': 2, 'y': 3}}).is_equal_to({'a': 1}, include='a') assert_that({'a': 1, 'b': {'x': 2, 'y': 3}}).is_equal_to({'b': {'x': 2, 'y': 3}}, include='b') def test_include_list_of_keys(): assert_that({'a': 1, 'b': 2, 'c': 3}).is_equal_to({'a': 1, 'b': 2, 'c': 3}, include=['a', 'b', 'c']) assert_that({'a': 1, 'b': 2, 'c': 3}).is_equal_to({'a': 1, 'b': 2}, include=['a', 'b']) assert_that({'a': 1, 'b': 2, 'c': 3}).is_equal_to({'a': 1}, include=['a']) assert_that({'a': 1, 'b': 2, 'c': 3}).is_equal_to({'b': 2}, include=['b']) assert_that({'a': 1, 'b': 2, 'c': 3}).is_equal_to({'c': 3}, include=['c']) def test_include_deep_key(): assert_that({'a': 1, 'b': {'x': 2, 'y': 3}}).is_equal_to({'b': {'x': 2, 'y': 3}}, include=('b')) assert_that({'a': 1, 'b': {'x': 2, 'y': 3}}).is_equal_to({'b': {'x': 2}}, include=('b', 'x')) assert_that({'a': 1, 'b': {'c': 2, 'd': {'e': 3, 'f': {'x': 4, 'y': 5}}}}).is_equal_to({'b': {'c': 2, 'd': {'e': 3, 'f': {'x': 4, 'y': 5}}}}, include=('b')) assert_that({'a': 1, 'b': {'c': 2, 'd': {'e': 3, 'f': {'x': 4, 'y': 5}}}}).is_equal_to({'b': {'c': 2}}, include=('b', 'c')) assert_that({'a': 1, 'b': {'c': 2, 'd': {'e': 3, 'f': {'x': 4, 'y': 5}}}}).is_equal_to({'b': {'d': {'e': 3, 'f': {'x': 4, 'y': 5}}}}, include=('b', 'd')) assert_that({'a': 1, 'b': {'c': 2, 'd': {'e': 3, 'f': {'x': 4, 'y': 5}}}}).is_equal_to({'b': {'d': {'e': 3, }}}, include=('b', 'd', 'e')) assert_that({'a': 1, 'b': {'c': 2, 'd': {'e': 3, 'f': {'x': 4, 'y': 5}}}}).is_equal_to({'b': {'d': {'f': {'x': 4, 'y': 5}}}}, include=('b', 'd', 'f')) assert_that({'a': 1, 'b': {'c': 2, 'd': {'e': 3, 'f': {'x': 4, 'y': 5}}}}).is_equal_to({'b': {'d': {'f': {'x': 4}}}}, include=('b', 'd', 'f', 'x')) assert_that({'a': 1, 'b': {'c': 2, 'd': {'e': 3, 'f': {'x': 4, 'y': 5}}}}).is_equal_to({'b': {'d': {'f': {'y': 5}}}}, include=('b', 'd', 'f', 'y')) def test_failure_include(): try: assert_that({'a': 1}).is_equal_to({'a': 2}, include='a') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{'a': 1}> to be equal to <{'a': 2}> including keys <a>, but was not.") def test_failure_include_missing(): try: assert_that({'a': 1}).is_equal_to({'a': 1}, include='b') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{'a': 1}> to include key <b>, but did not include key <b>.") def test_failure_include_multiple_missing(): try: assert_that({'a': 1}).is_equal_to({'a': 1}, include=['b', 'c']) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{'a': 1}> to include keys <'b', 'c'>, but did not include keys <'b', 'c'>.") def test_failure_include_deep_missing(): try: assert_that({'a': {'b': 2}}).is_equal_to({'a': {'c': 3}}, include=('a', 'c')) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{'b': 2}> to include key <c>, but did not include key <c>.") def test_failure_include_multi_keys(): try: assert_that({'a': 1, 'b': 2}).is_equal_to({'a': 1, 'b': 3}, include=['a', 'b']) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{.., 'b': 2}> to be equal to <{.., 'b': 3}> including keys <'a', 'b'>, but was not.") def test_failure_include_deep_keys(): try: assert_that({'a': {'b': 1}}).is_equal_to({'a': {'b': 2}}, include=('a', 'b')) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{'a': {'b': 1}}> to be equal to <{'a': {'b': 2}}> including keys <a.b>, but was not.") def test_ignore_and_include_key(): assert_that({'a': 1}).is_equal_to({}, ignore='a', include='a') assert_that({'a': 1, 'b': 2}).is_equal_to({'a': 1}, ignore='b', include='a') assert_that({'a': 1, 'b': {'x': 2, 'y': 3}}).is_equal_to({'b': {'y': 3}}, ignore=('b', 'x'), include='b') def test_ignore_and_include_list_of_keys(): assert_that({'a': 1, 'b': 2, 'c': 3}).is_equal_to({'a': 1, 'c': 3}, ignore=['b'], include=['a', 'b', 'c']) assert_that({'a': 1, 'b': 2, 'c': 3}).is_equal_to({'a': 1, 'b': 2}, ignore=['c'], include=['a', 'b']) assert_that({'a': 1, 'b': 2, 'c': 3}).is_equal_to({'a': 1}, ignore=['b', 'c'], include=['a', 'b']) assert_that({'a': 1, 'b': 2, 'c': 3}).is_equal_to({'a': 1}, ignore=['c'], include=['a']) assert_that({'a': 1, 'b': 2, 'c': 3}).is_equal_to({'b': 2}, ignore=['a'], include=['b']) assert_that({'a': 1, 'b': 2, 'c': 3}).is_equal_to({'c': 3}, ignore=['b'], include=['c']) def test_ignore_and_include_deep_key(): assert_that({'a': 1, 'b': {'x': 2, 'y': 3}}).is_equal_to({'b': {'x': 2, 'y': 3}}, ignore=('a'), include=('b')) assert_that({'a': 1, 'b': {'x': 2, 'y': 3}}).is_equal_to({'b': {'x': 2}}, ignore=('b', 'y'), include=('b', 'x')) assert_that({'a': 1, 'b': {'c': 2, 'd': {'e': 3, 'f': {'x': 4, 'y': 5}}}}).is_equal_to( {'b': {'c': 2, 'd': {'e': 3}}}, ignore=('b', 'd', 'f'), include=('b')) def test_ignore_deep_sibling_key(): d1 = {'a': 1, 'b': {'c': 2, 'd': {'e': 3}}} d2 = {'a': 1, 'b': {'c': 3, 'd': {'e': 3}}} assert_that(d1).is_equal_to(d2, ignore=('b', 'c')) def test_ignore_nested_deep_sibling_key(): d1 = {'a': 1, 'b': {'c': 2, 'd': {'e': 3}}} d2 = {'a': 1, 'b': {'c': 2, 'd': {'e': 4}}} assert_that(d1).is_equal_to(d2, ignore=('b', 'd')) def test_failure_deep_mismatch_when_ignoring_nested_deep_key(): d1 = {'a': 1, 'b': {'c': 2, 'd': {'e': 3}}} d2 = {'a': 1, 'b': {'c': 3, 'd': {'e': 4}}} try: assert_that(d1).is_equal_to(d2, ignore=('b', 'd')) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{.., 'b': {'c': 2, 'd': {'e': 3}}}> to be equal to <{.., 'b': {'c': 3, 'd': {'e': 4}}}> ignoring keys <b.d>, but was not.") def test_failure_top_mismatch_when_ignoring_single_nested_key(): d1 = {'a': 1, 'b': {'c': 2}} d2 = {'a': 2, 'b': {'c': 3}} try: assert_that(d1).is_equal_to(d2, ignore=('b', 'c')) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{'a': 1, 'b': {'c': 2}}> to be equal to <{'a': 2, 'b': {'c': 3}}> ignoring keys <b.c>, but was not.") def test_failure_top_mismatch_when_ignoring_single_nested_sibling_key(): d1 = {'a': 1, 'b': {'c': 2, 'd': {'e': 3}}} d2 = {'a': 2, 'b': {'c': 2, 'd': {'e': 4}}} try: assert_that(d1).is_equal_to(d2, ignore=('b', 'd')) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{'a': 1, 'b': {.., 'd': {'e': 3}}}> to be equal to <{'a': 2, 'b': {.., 'd': {'e': 4}}}> ignoring keys <b.d>, but was not.") def test_failure_deep_mismatch_when_ignoring_double_nested_sibling_key(): d1 = {'a': 1, 'b': {'c': 2, 'd': {'e': 3}, 'f': {'g': 5}}} d2 = {'a': 1, 'b': {'c': 2, 'd': {'e': 4}, 'f': {'g': 5}}} try: assert_that(d1).is_equal_to(d2, ignore=('b', 'f', 'g')) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <{.., 'b': {.., 'd': {'e': 3}}}> to be equal to <{.., 'b': {.., 'd': {'e': 4}}}> ignoring keys <b.f.g>, but was not.") def test_ignore_all_nested_keys(): assert_that({'a': {'b': 1}}).is_equal_to({}, ignore='a') assert_that({'a': {'b': 1}}).is_equal_to({'a': {}}, ignore=[('a', 'b')]) assert_that({'a': {'b': 1, 'c': 2}}).is_equal_to({'a': {}}, ignore=[('a', 'b'), ('a', 'c')]) assert_that({'a': 1, 'b': {'c': 2}}).is_equal_to({'b': {}}, ignore=['a', ('b', 'c')])
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,318
assertpy/assertpy
refs/heads/main
/tests/test_extracting.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys from assertpy import assert_that, fail class Person(object): def __init__(self, first_name, last_name, shoe_size): self.first_name = first_name self.last_name = last_name self.shoe_size = shoe_size def full_name(self): return '%s %s' % (self.first_name, self.last_name) def say_hello(self, name): return 'Hello, %s!' % name fred = Person('Fred', 'Smith', 12) john = Person('John', 'Jones', 9.5) people = [fred, john] def test_extracting_property(): assert_that(people).extracting('first_name').contains('Fred', 'John') def test_extracting_multiple_properties(): assert_that(people).extracting('first_name', 'last_name', 'shoe_size').contains(('Fred', 'Smith', 12), ('John', 'Jones', 9.5)) def test_extracting_zero_arg_method(): assert_that(people).extracting('full_name').contains('Fred Smith', 'John Jones') def test_extracting_property_and_method(): assert_that(people).extracting('first_name', 'full_name').contains(('Fred', 'Fred Smith'), ('John', 'John Jones')) def test_extracting_dict(): people_as_dicts = [{'first_name': p.first_name, 'last_name': p.last_name} for p in people] assert_that(people_as_dicts).extracting('first_name').contains('Fred', 'John') assert_that(people_as_dicts).extracting('last_name').contains('Smith', 'Jones') def test_extracting_bad_val_failure(): try: assert_that(123).extracting('bar') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not iterable') def test_extracting_bad_val_str_failure(): try: assert_that('foo').extracting('bar') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val must not be string') def test_extracting_empty_args_failure(): try: assert_that(people).extracting() fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('one or more name args must be given') def test_extracting_bad_property_failure(): try: assert_that(people).extracting('foo') fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('item does not have property or zero-arg method <foo>') def test_extracting_too_many_args_method_failure(): try: assert_that(people).extracting('say_hello') fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('item method <say_hello()> exists, but is not zero-arg method') def test_extracting_dict_missing_key_failure(): people_as_dicts = [{'first_name': p.first_name, 'last_name': p.last_name} for p in people] try: assert_that(people_as_dicts).extracting('foo') fail('should have raised error') except ValueError as ex: assert_that(str(ex)).matches(r'item keys \[.*\] did not contain key <foo>') def test_described_as_with_extracting(): try: assert_that(people).described_as('extra msg').extracting('first_name').contains('Fred', 'Bob') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("[extra msg] Expected <['Fred', 'John']> to contain items <'Fred', 'Bob'>, but did not contain <Bob>.") def test_described_as_with_double_extracting(): try: assert_that(people).described_as('extra msg').extracting('first_name').described_as('other msg').contains('Fred', 'Bob') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("[other msg] Expected <['Fred', 'John']> to contain items <'Fred', 'Bob'>, but did not contain <Bob>.") users = [ {'user': 'Fred', 'age': 36, 'active': True}, {'user': 'Bob', 'age': 40, 'active': False}, {'user': 'Johnny', 'age': 13, 'active': True} ] def test_extracting_filter(): assert_that(users).extracting('user', filter='active').is_equal_to(['Fred', 'Johnny']) assert_that(users).extracting('user', filter={'active': False}).is_equal_to(['Bob']) assert_that(users).extracting('user', filter={'age': 36, 'active': True}).is_equal_to(['Fred']) assert_that(users).extracting('user', filter=lambda x: x['age'] > 20).is_equal_to(['Fred', 'Bob']) assert_that(users).extracting('user', filter=lambda x: x['age'] < 10).is_empty() def test_extracting_filter_bad_type(): assert_that(users).extracting('user', filter=123).is_equal_to([]) def test_extracting_filter_ignore_bad_key_types(): assert_that(users).extracting('user', filter={'active': True, 123: 'foo'}).is_equal_to(['Fred', 'Johnny']) def test_extracting_filter_custom_func(): def _f(x): return x['user'] == 'Bob' or x['age'] == 13 assert_that(users).extracting('user', filter=_f).is_equal_to(['Bob', 'Johnny']) def test_extracting_filter_failure(): try: assert_that(users).extracting('user', filter='foo') fail('should have raised error') except ValueError as ex: assert_that(str(ex)).ends_with("'] did not contain key <foo>") def test_extracting_filter_dict_failure(): try: assert_that(users).extracting('user', filter={'foo': 'bar'}) fail('should have raised error') except ValueError as ex: assert_that(str(ex)).ends_with("'] did not contain key <foo>") def test_extracting_filter_multi_item_dict_failure(): try: assert_that(users).extracting('user', filter={'age': 36, 'active': True, 'foo': 'bar'}) fail('should have raised error') except ValueError as ex: assert_that(str(ex)).ends_with("'] did not contain key <foo>") def test_extracting_filter_lambda_failure(): try: assert_that(users).extracting('user', filter=lambda x: x['foo'] > 0) fail('should have raised error') except KeyError as ex: assert_that(str(ex)).is_equal_to("'foo'") def test_extracting_filter_custom_func_failure(): def _f(x): raise RuntimeError('foobar!') try: assert_that(users).extracting('user', filter=_f) fail('should have raised error') except RuntimeError as ex: assert_that(str(ex)).is_equal_to("foobar!") def test_extracting_filter_bad_values(): bad = [ {'user': 'Fred', 'age': 36}, {'user': 'Bob', 'age': 'bad'}, {'user': 'Johnny', 'age': 13} ] if sys.version_info[0] == 3: try: assert_that(bad).extracting('user', filter=lambda x: x['age'] > 20) fail('should have raised error') except TypeError as ex: if sys.version_info[1] <= 5: assert_that(str(ex)).contains('unorderable types') else: assert_that(str(ex)).contains("not supported between instances of 'str' and 'int'") def test_extracting_sort(): assert_that(users).extracting('user', sort='age').is_equal_to(['Johnny', 'Fred', 'Bob']) assert_that(users).extracting('user', sort=['active', 'age']).is_equal_to(['Bob', 'Johnny', 'Fred']) assert_that(users).extracting('user', sort=('active', 'age')).is_equal_to(['Bob', 'Johnny', 'Fred']) assert_that(users).extracting('user', sort=lambda x: -x['age']).is_equal_to(['Bob', 'Fred', 'Johnny']) def test_extracting_sort_ignore_bad_type(): assert_that(users).extracting('user', sort=123).is_equal_to(['Fred', 'Bob', 'Johnny']) def test_extracting_sort_ignore_bad_key_types(): assert_that(users).extracting('user', sort=['active', 'age', 123]).is_equal_to(['Bob', 'Johnny', 'Fred']) def test_extracting_sort_custom_func(): def _f(x): if x['user'] == 'Johnny': return 0 elif x['age'] == 40: return 1 return 10 assert_that(users).extracting('user', sort=_f).is_equal_to(['Johnny', 'Bob', 'Fred']) def test_extracting_sort_failure(): try: assert_that(users).extracting('user', sort='foo') fail('should have raised error') except ValueError as ex: assert_that(str(ex)).ends_with("'] did not contain key <foo>") def test_extracting_sort_list_failure(): try: assert_that(users).extracting('user', sort=['foo']) fail('should have raised error') except ValueError as ex: assert_that(str(ex)).ends_with("'] did not contain key <foo>") def test_extracting_sort_multi_item_dict_failure(): try: assert_that(users).extracting('user', sort=['active', 'age', 'foo']) fail('should have raised error') except ValueError as ex: assert_that(str(ex)).ends_with("'] did not contain key <foo>") def test_extracting_sort_lambda_failure(): try: assert_that(users).extracting('user', sort=lambda x: x['foo'] > 0) fail('should have raised error') except KeyError as ex: assert_that(str(ex)).is_equal_to("'foo'") def test_extracting_sort_custom_func_failure(): def _f(x): raise RuntimeError('foobar!') try: assert_that(users).extracting('user', sort=_f) fail('should have raised error') except RuntimeError as ex: assert_that(str(ex)).is_equal_to("foobar!") def test_extracting_sort_bad_values(): bad = [ {'user': 'Fred', 'age': 36}, {'user': 'Bob', 'age': 'bad'}, {'user': 'Johnny', 'age': 13} ] if sys.version_info[0] == 3: try: assert_that(bad).extracting('user', sort='age') fail('should have raised error') except TypeError as ex: if sys.version_info[1] <= 5: assert_that(str(ex)).contains('unorderable types') else: assert_that(str(ex)).contains("not supported between instances of 'str' and 'int'") def test_extracting_iterable_of_lists(): l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] assert_that(l).extracting(0).is_equal_to([1, 4, 7]) assert_that(l).extracting(0, 1).is_equal_to([(1, 2), (4, 5), (7, 8)]) assert_that(l).extracting(-1).is_equal_to([3, 6, 9]) assert_that(l).extracting(-1, -2).extracting(0).is_equal_to([3, 6, 9]) def test_extracting_iterable_multi_extracting(): l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] assert_that(l).extracting(-1, 2).is_equal_to([(3, 3), (6, 6), (9, 9)]) assert_that(l).extracting(-1, 1).extracting(1, 0).is_equal_to([(2, 3), (5, 6), (8, 9)]) def test_extracting_iterable_of_tuples(): t = [(1, 2, 3), (4, 5, 6), (7, 8, 9)] assert_that(t).extracting(0).is_equal_to([1, 4, 7]) assert_that(t).extracting(0, 1).is_equal_to([(1, 2), (4, 5), (7, 8)]) assert_that(t).extracting(-1).is_equal_to([3, 6, 9]) def test_extracting_iterable_of_strings(): s = ['foo', 'bar', 'baz'] assert_that(s).extracting(0).is_equal_to(['f', 'b', 'b']) assert_that(s).extracting(0, 2).is_equal_to([('f', 'o'), ('b', 'r'), ('b', 'z')]) def test_extracting_iterable_failure_set(): try: assert_that([set([1])]).extracting(0).contains(1, 4, 7) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('item <set> does not have [] accessor') def test_extracting_iterable_failure_out_of_range(): try: assert_that([[1], [2], [3]]).extracting(4).is_equal_to(0) fail('should have raised error') except IndexError as ex: assert_that(str(ex)).is_equal_to('list index out of range') def test_extracting_iterable_failure_index_is_not_int(): try: assert_that([[1], [2], [3]]).extracting('1').is_equal_to(0) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).contains('list indices must be integers')
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,319
assertpy/assertpy
refs/heads/main
/assertpy/extracting.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import collections if sys.version_info[0] == 3: str_types = (str,) Iterable = collections.abc.Iterable else: str_types = (basestring,) Iterable = collections.Iterable __tracebackhide__ = True class ExtractingMixin(object): """Collection flattening mixin. It is often necessary to test collections of objects. Use the ``extracting()`` helper to reduce the collection on a given attribute. Reduce a list of objects:: alice = Person('Alice', 'Alpha') bob = Person('Bob', 'Bravo') people = [alice, bob] assert_that(people).extracting('first_name').is_equal_to(['Alice', 'Bob']) assert_that(people).extracting('first_name').contains('Alice', 'Bob') assert_that(people).extracting('first_name').does_not_contain('Charlie') Additionally, the ``extracting()`` helper can accept a list of attributes to be extracted, and will flatten them into a list of tuples. Reduce a list of objects on multiple attributes:: assert_that(people).extracting('first_name', 'last_name').contains(('Alice', 'Alpha'), ('Bob', 'Bravo')) Also, ``extracting()`` works on not just attributes, but also properties, and even zero-argument methods. Reduce a list of object on properties and zero-arg methods:: assert_that(people).extracting('name').contains('Alice Alpha', 'Bob Bravo') assert_that(people).extracting('say_hello').contains('Hello, Alice!', 'Hello, Bob!') And ``extracting()`` even works on *dict-like* objects. Reduce a list of dicts on key:: alice = {'first_name': 'Alice', 'last_name': 'Alpha'} bob = {'first_name': 'Bob', 'last_name': 'Bravo'} people = [alice, bob] assert_that(people).extracting('first_name').contains('Alice', 'Bob') **Filtering** The ``extracting()`` helper can include a *filter* to keep only those items for which the given *filter* is truthy. For example:: users = [ {'user': 'Alice', 'age': 36, 'active': True}, {'user': 'Bob', 'age': 40, 'active': False}, {'user': 'Charlie', 'age': 13, 'active': True} ] # filter the active users assert_that(users).extracting('user', filter='active').is_equal_to(['Alice', 'Charlie']) The *filter* can be a *dict-like* object and the extracted items are kept if and only if all corresponding key-value pairs are equal:: assert_that(users).extracting('user', filter={'active': False}).is_equal_to(['Bob']) assert_that(users).extracting('user', filter={'age': 36, 'active': True}).is_equal_to(['Alice']) Or a *filter* can be any function (including an in-line ``lambda``) that accepts as its single argument each item in the collection, and the extracted items are kept if the function evaluates to ``True``:: assert_that(users).extracting('user', filter=lambda x: x['age'] > 20) .is_equal_to(['Alice', 'Bob']) **Sorting** The ``extracting()`` helper can include a *sort* to enforce order on the extracted items. The *sort* can be the name of a key (or attribute, or property, or zero-argument method) and the extracted items are ordered by the corresponding values:: assert_that(users).extracting('user', sort='age').is_equal_to(['Charlie', 'Alice', 'Bob']) The *sort* can be an ``iterable`` of names and the extracted items are ordered by corresponding value of the first name, ties are broken by the corresponding values of the second name, and so on:: assert_that(users).extracting('user', sort=['active', 'age']).is_equal_to(['Bob', 'Charlie', 'Alice']) The *sort* can be any function (including an in-line ``lambda``) that accepts as its single argument each item in the collection, and the extracted items are ordered by the corresponding function return values:: assert_that(users).extracting('user', sort=lambda x: -x['age']).is_equal_to(['Bob', 'Alice', 'Charlie']) """ def extracting(self, *names, **kwargs): """Asserts that val is iterable, then extracts the named attributes, properties, or zero-arg methods into a list (or list of tuples if multiple names are given). Args: *names: the attribute to be extracted (or property or zero-arg method) **kwargs: see below Keyword Args: filter: extract only those items where filter is truthy sort: order the extracted items by the sort key Examples: Usage:: alice = User('Alice', 20, True) bob = User('Bob', 30, False) charlie = User('Charlie', 10, True) users = [alice, bob, charlie] assert_that(users).extracting('user').contains('Alice', 'Bob', 'Charlie') Works with *dict-like* objects too:: users = [ {'user': 'Alice', 'age': 20, 'active': True}, {'user': 'Bob', 'age': 30, 'active': False}, {'user': 'Charlie', 'age': 10, 'active': True} ] assert_that(people).extracting('user').contains('Alice', 'Bob', 'Charlie') Filter:: assert_that(users).extracting('user', filter='active').is_equal_to(['Alice', 'Charlie']) Sort:: assert_that(users).extracting('user', sort='age').is_equal_to(['Charlie', 'Alice', 'Bob']) Returns: AssertionBuilder: returns a new instance (now with the extracted list as the val) to chain to the next assertion """ if not isinstance(self.val, Iterable): raise TypeError('val is not iterable') if isinstance(self.val, str_types): raise TypeError('val must not be string') if len(names) == 0: raise ValueError('one or more name args must be given') def _extract(x, name): if self._check_dict_like(x, check_values=False, return_as_bool=True): if name in x: return x[name] else: raise ValueError('item keys %s did not contain key <%s>' % (list(x.keys()), name)) elif isinstance(x, tuple) and hasattr(x, '_fields') and type(name) is str: if name in x._fields: return getattr(x, name) else: #val has no attribute <foo> raise ValueError('item attributes %s did no contain attribute <%s>' % (x._fields, name)) elif isinstance(x, Iterable): # FIXME, this does __getitem__, but doesn't check for it... self._check_iterable(x, name='item') return x[name] elif hasattr(x, name): attr = getattr(x, name) if callable(attr): try: return attr() except TypeError: raise ValueError('item method <%s()> exists, but is not zero-arg method' % name) else: return attr else: raise ValueError('item does not have property or zero-arg method <%s>' % name) def _filter(x): if 'filter' in kwargs: if isinstance(kwargs['filter'], str_types): return bool(_extract(x, kwargs['filter'])) elif self._check_dict_like(kwargs['filter'], check_values=False, return_as_bool=True): for k in kwargs['filter']: if isinstance(k, str_types): if _extract(x, k) != kwargs['filter'][k]: return False return True elif callable(kwargs['filter']): return kwargs['filter'](x) return False return True def _sort(x): if 'sort' in kwargs: if isinstance(kwargs['sort'], str_types): return _extract(x, kwargs['sort']) elif isinstance(kwargs['sort'], Iterable): items = [] for k in kwargs['sort']: if isinstance(k, str_types): items.append(_extract(x, k)) return tuple(items) elif callable(kwargs['sort']): return kwargs['sort'](x) return 0 extracted = [] for i in sorted(self.val, key=lambda x: _sort(x)): if _filter(i): items = [_extract(i, name) for name in names] extracted.append(tuple(items) if len(items) > 1 else items[0]) # chain on with _extracted_ list (don't chain to self!) return self.builder(extracted, self.description, self.kind)
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,320
assertpy/assertpy
refs/heads/main
/assertpy/file.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import sys if sys.version_info[0] == 3: str_types = (str,) else: str_types = (basestring,) __tracebackhide__ = True def contents_of(file, encoding='utf-8'): """Helper to read the contents of the given file or path into a string with the given encoding. Args: file: a *path-like object* (aka a file name) or a *file-like object* (aka a file) encoding (str): the target encoding. Defaults to ``utf-8``, other useful encodings are ``ascii`` and ``latin-1``. Examples: Usage:: from assertpy import assert_that, contents_of contents = contents_of('foo.txt') assert_that(contents).starts_with('foo').ends_with('bar').contains('oob') Returns: str: returns the file contents as a string Raises: IOError: if file not found TypeError: if file is not a *path-like object* or a *file-like object* """ try: contents = file.read() except AttributeError: try: with open(file, 'r') as fp: contents = fp.read() except TypeError: raise ValueError('val must be file or path, but was type <%s>' % type(file).__name__) except OSError: if not isinstance(file, str_types): raise ValueError('val must be file or path, but was type <%s>' % type(file).__name__) raise if sys.version_info[0] == 3 and type(contents) is bytes: # in PY3 force decoding of bytes to target encoding return contents.decode(encoding, 'replace') elif sys.version_info[0] == 2 and encoding == 'ascii': # in PY2 force encoding back to ascii return contents.encode('ascii', 'replace') else: # in all other cases, try to decode to target encoding try: return contents.decode(encoding, 'replace') except AttributeError: pass # if all else fails, just return the contents "as is" return contents class FileMixin(object): """File assertions mixin.""" def exists(self): """Asserts that val is a path and that it exists. Examples: Usage:: assert_that('myfile.txt').exists() assert_that('mydir').exists() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val does **not** exist """ if not isinstance(self.val, str_types): raise TypeError('val is not a path') if not os.path.exists(self.val): return self.error('Expected <%s> to exist, but was not found.' % self.val) return self def does_not_exist(self): """Asserts that val is a path and that it does *not* exist. Examples: Usage:: assert_that('missing.txt').does_not_exist() assert_that('missing_dir').does_not_exist() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val **does** exist """ if not isinstance(self.val, str_types): raise TypeError('val is not a path') if os.path.exists(self.val): return self.error('Expected <%s> to not exist, but was found.' % self.val) return self def is_file(self): """Asserts that val is a *file* and that it exists. Examples: Usage:: assert_that('myfile.txt').is_file() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val does **not** exist, or is **not** a file """ self.exists() if not os.path.isfile(self.val): return self.error('Expected <%s> to be a file, but was not.' % self.val) return self def is_directory(self): """Asserts that val is a *directory* and that it exists. Examples: Usage:: assert_that('mydir').is_directory() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val does **not** exist, or is **not** a directory """ self.exists() if not os.path.isdir(self.val): return self.error('Expected <%s> to be a directory, but was not.' % self.val) return self def is_named(self, filename): """Asserts that val is an existing path to a file and that file is named filename. Args: filename: the expected filename Examples: Usage:: assert_that('/path/to/mydir/myfile.txt').is_named('myfile.txt') Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val does **not** exist, or is **not** a file, or is **not** named the given filename """ self.is_file() if not isinstance(filename, str_types): raise TypeError('given filename arg must be a path') val_filename = os.path.basename(os.path.abspath(self.val)) if val_filename != filename: return self.error('Expected filename <%s> to be equal to <%s>, but was not.' % (val_filename, filename)) return self def is_child_of(self, parent): """Asserts that val is an existing path to a file and that file is a child of parent. Args: parent: the expected parent directory Examples: Usage:: assert_that('/path/to/mydir/myfile.txt').is_child_of('mydir') assert_that('/path/to/mydir/myfile.txt').is_child_of('to') assert_that('/path/to/mydir/myfile.txt').is_child_of('path') Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val does **not** exist, or is **not** a file, or is **not** a child of the given directory """ self.is_file() if not isinstance(parent, str_types): raise TypeError('given parent directory arg must be a path') val_abspath = os.path.abspath(self.val) parent_abspath = os.path.abspath(parent) if not val_abspath.startswith(parent_abspath): return self.error('Expected file <%s> to be a child of <%s>, but was not.' % (val_abspath, parent_abspath)) return self
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,321
assertpy/assertpy
refs/heads/main
/tests/test_class.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import abc from assertpy import assert_that, fail class Person(object): def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name @property def name(self): return '%s %s' % (self.first_name, self.last_name) def say_hello(self): return 'Hello, %s!' % self.first_name class Developer(Person): def say_hello(self): return '%s writes code.' % self.first_name class AbstractAutomobile(object): __metaclass__ = abc.ABCMeta def __init__(self): pass @abc.abstractproperty def classification(self): raise NotImplementedError('This method must be overridden') class Car(AbstractAutomobile): @property def classification(self): return 'car' class Truck(AbstractAutomobile): @property def classification(self): return 'truck' fred = Person('Fred', 'Smith') joe = Developer('Joe', 'Coder') people = [fred, joe] car = Car() truck = Truck() def test_is_type_of(): assert_that(fred).is_type_of(Person) assert_that(joe).is_type_of(Developer) assert_that(car).is_type_of(Car) assert_that(truck).is_type_of(Truck) def test_is_type_of_class(): assert_that(fred.__class__).is_type_of(Person.__class__) def test_is_type_of_class_failure(): try: assert_that(fred.__class__).is_type_of(Person) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains('to be of type <Person>, but was not') def test_is_instance_of(): assert_that(fred).is_instance_of(Person) assert_that(fred).is_instance_of(object) assert_that(joe).is_instance_of(Developer) assert_that(joe).is_instance_of(Person) assert_that(joe).is_instance_of(object) assert_that(car).is_instance_of(Car) assert_that(car).is_instance_of(AbstractAutomobile) assert_that(car).is_instance_of(object) assert_that(truck).is_instance_of(Truck) assert_that(truck).is_instance_of(AbstractAutomobile) assert_that(truck).is_instance_of(object) def test_is_instance_of_class(): assert_that(fred.__class__).is_instance_of(Person.__class__) def test_is_instance_of_class_failure(): try: assert_that(fred.__class__).is_instance_of(Person) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains('to be instance of class <Person>, but was not') def test_extract_attribute(): assert_that(people).extracting('first_name').is_equal_to(['Fred', 'Joe']) assert_that(people).extracting('first_name').contains('Fred', 'Joe') def test_extract_property(): assert_that(people).extracting('name').contains('Fred Smith', 'Joe Coder') def test_extract_multiple(): assert_that(people).extracting('first_name', 'name').contains(('Fred', 'Fred Smith'), ('Joe', 'Joe Coder')) def test_extract_zero_arg_method(): assert_that(people).extracting('say_hello').contains('Hello, Fred!', 'Joe writes code.')
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,322
assertpy/assertpy
refs/heads/main
/tests/test_expected_exception.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from assertpy import assert_that, fail def test_expected_exception(): assert_that(func_no_arg).raises(RuntimeError).when_called_with() assert_that(func_one_arg).raises(RuntimeError).when_called_with('foo') assert_that(func_multi_args).raises(RuntimeError).when_called_with('foo', 'bar', 'baz') assert_that(func_kwargs).raises(RuntimeError).when_called_with(foo=1, bar=2, baz=3) assert_that(func_all).raises(RuntimeError).when_called_with('a', 'b', 3, 4, foo=1, bar=2, baz='dog') def test_expected_exception_method(): foo = Foo() assert_that(foo.bar).raises(RuntimeError).when_called_with().is_equal_to('method err') def test_expected_exception_chaining(): assert_that(func_no_arg).raises(RuntimeError).when_called_with()\ .is_equal_to('no arg err') assert_that(func_one_arg).raises(RuntimeError).when_called_with('foo')\ .is_equal_to('one arg err') assert_that(func_multi_args).raises(RuntimeError).when_called_with('foo', 'bar', 'baz')\ .is_equal_to('multi args err') assert_that(func_kwargs).raises(RuntimeError).when_called_with(foo=1, bar=2, baz=3)\ .is_equal_to('kwargs err') assert_that(func_all).raises(RuntimeError).when_called_with('a', 'b', 3, 4, foo=1, bar=2, baz='dog')\ .starts_with('all err: arg1=a, arg2=b, args=(3, 4), kwargs=[') def test_expected_exception_no_arg_failure(): try: assert_that(func_noop).raises(RuntimeError).when_called_with() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to( 'Expected <func_noop> to raise <RuntimeError> when called with ().') def test_expected_exception_no_arg_bad_func_failure(): try: assert_that(123).raises(int).when_called_with() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).contains('val must be callable') def test_expected_exception_no_arg_bad_exception_failure(): try: assert_that(func_noop).raises(int).when_called_with() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).contains('given arg must be exception') def test_expected_exception_no_arg_wrong_exception_failure(): try: assert_that(func_no_arg).raises(TypeError).when_called_with() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains('Expected <func_no_arg> to raise <TypeError> when called with (), but raised <RuntimeError>.') def test_expected_exception_no_arg_missing_raises_failure(): try: assert_that(func_noop).when_called_with() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).contains('expected exception not set, raises() must be called first') def test_expected_exception_one_arg_failure(): try: assert_that(func_noop).raises(RuntimeError).when_called_with('foo') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to( "Expected <func_noop> to raise <RuntimeError> when called with ('foo').") def test_expected_exception_multi_args_failure(): try: assert_that(func_noop).raises(RuntimeError).when_called_with('foo', 'bar', 'baz') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <func_noop> to raise <RuntimeError> when called with ('foo', 'bar', 'baz').") def test_expected_exception_kwargs_failure(): try: assert_that(func_noop).raises(RuntimeError).when_called_with(foo=1, bar=2, baz=3) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to( "Expected <func_noop> to raise <RuntimeError> when called with ('bar': 2, 'baz': 3, 'foo': 1).") def test_expected_exception_all_failure(): try: assert_that(func_noop).raises(RuntimeError).when_called_with('a', 'b', 3, 4, foo=1, bar=2, baz='dog') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to( "Expected <func_noop> to raise <RuntimeError> when called with ('a', 'b', 3, 4, 'bar': 2, 'baz': 'dog', 'foo': 1).") def test_expected_exception_arg_passing(): assert_that(func_all).raises(RuntimeError).when_called_with('a', 'b', 3, 4, foo=1, bar=2, baz='dog').is_equal_to( "all err: arg1=a, arg2=b, args=(3, 4), kwargs=[('bar', 2), ('baz', 'dog'), ('foo', 1)]") # helpers def func_noop(*args, **kwargs): pass def func_no_arg(): raise RuntimeError('no arg err') def func_one_arg(arg): raise RuntimeError('one arg err') def func_multi_args(*args): raise RuntimeError('multi args err') def func_kwargs(**kwargs): raise RuntimeError('kwargs err') def func_all(arg1, arg2, *args, **kwargs): raise RuntimeError('all err: arg1=%s, arg2=%s, args=%s, kwargs=%s' % (arg1, arg2, args, [(k, kwargs[k]) for k in sorted(kwargs.keys())])) class Foo(object): def bar(self): raise RuntimeError('method err')
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,323
assertpy/assertpy
refs/heads/main
/tests/test_extensions.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import numbers from assertpy import assert_that, add_extension, remove_extension, fail def is_even(self): if isinstance(self.val, numbers.Integral) is False: raise TypeError('val must be an integer') if self.val % 2 != 0: return self.error('Expected <%s> to be even, but was not.' % (self.val)) return self def is_multiple_of(self, other): if isinstance(self.val, numbers.Integral) is False or self.val <= 0: raise TypeError('val must be a positive integer') if isinstance(other, numbers.Integral) is False or other <= 0: raise TypeError('given arg must be a positive integer') _, rem = divmod(self.val, other) if rem > 0: return self.error('Expected <%s> to be multiple of <%s>, but was not.' % (self.val, other)) return self def is_factor_of(self, other): if isinstance(self.val, numbers.Integral) is False or self.val <= 0: raise TypeError('val must be a positive integer') if isinstance(other, numbers.Integral) is False or other <= 0: raise TypeError('given arg must be a positive integer') _, rem = divmod(other, self.val) if rem > 0: return self.error('Expected <%s> to be factor of <%s>, but was not.' % (self.val, other)) return self add_extension(is_even) add_extension(is_multiple_of) add_extension(is_factor_of) def test_is_even_extension(): assert_that(124).is_even() assert_that(124).is_type_of(int).is_even().is_greater_than(123).is_less_than(125).is_equal_to(124) def test_is_even_extension_failure(): try: assert_that(123).is_even() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <123> to be even, but was not.') def test_is_even_extension_failure_not_callable(): try: add_extension('foo') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('func must be callable') def test_is_even_extension_failure_not_integer(): try: assert_that(124.0).is_even() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val must be an integer') def test_is_multiple_of_extension(): assert_that(24).is_multiple_of(1) assert_that(24).is_multiple_of(2) assert_that(24).is_multiple_of(3) assert_that(24).is_multiple_of(4) assert_that(24).is_multiple_of(6) assert_that(24).is_multiple_of(8) assert_that(24).is_multiple_of(12) assert_that(24).is_multiple_of(24) assert_that(124).is_type_of(int).is_even().is_multiple_of(31).is_equal_to(124) def test_is_multiple_of_extension_failure(): try: assert_that(24).is_multiple_of(5) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <24> to be multiple of <5>, but was not.') def test_is_multiple_of_extension_failure_bad_val(): try: assert_that(24.0).is_multiple_of(5) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val must be a positive integer') def test_is_multiple_of_extension_failure_negative_val(): try: assert_that(-24).is_multiple_of(6) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val must be a positive integer') def test_is_multiple_of_extension_failure_bad_arg(): try: assert_that(24).is_multiple_of('foo') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be a positive integer') def test_is_multiple_of_extension_failure_negative_arg(): try: assert_that(24).is_multiple_of(-6) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be a positive integer') def test_is_factor_of_extension(): assert_that(1).is_factor_of(24) assert_that(2).is_factor_of(24) assert_that(3).is_factor_of(24) assert_that(4).is_factor_of(24) assert_that(6).is_factor_of(24) assert_that(8).is_factor_of(24) assert_that(12).is_factor_of(24) assert_that(24).is_factor_of(24) assert_that(31).is_type_of(int).is_factor_of(124).is_equal_to(31) def test_is_factor_of_extension_failure(): try: assert_that(5).is_factor_of(24) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <5> to be factor of <24>, but was not.') def test_call_missing_extension(): def is_missing(): pass try: remove_extension(is_even) remove_extension(is_multiple_of) remove_extension(is_factor_of) remove_extension(is_missing) assert_that(24).is_multiple_of(6) fail('should have raised error') except AttributeError as ex: assert_that(str(ex)).is_equal_to('assertpy has no assertion <is_multiple_of()>') def test_remove_bad_extension(): try: remove_extension('foo') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('func must be callable') def is_foo(self): if self.val != 'foo': return self.error('Expected <%s> to be foo, but was not.' % (self.val)) return self def dupe1(): add_extension(is_foo) assert_that('foo').is_foo() try: assert_that('FOO').is_foo() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <FOO> to be foo, but was not.') def dupe2(): def is_foo(self): if self.val != 'FOO': return self.error('Expected <%s> to be FOO, but was not.' % (self.val)) return self add_extension(is_foo) assert_that('FOO').is_foo() try: assert_that('foo').is_foo() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <foo> to be FOO, but was not.') def test_dupe_extensions(): dupe1() dupe2() dupe1()
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,324
assertpy/assertpy
refs/heads/main
/assertpy/dict.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. __tracebackhide__ = True class DictMixin(object): """Dict assertions mixin.""" def contains_key(self, *keys): """Asserts the val is a dict and contains the given key or keys. Alias for :meth:`~assertpy.contains.ContainsMixin.contains`. Checks if the dict contains the given key or keys using ``in`` operator. Args: *keys: the key or keys expected to be contained Examples: Usage:: assert_that({'a': 1, 'b': 2}).contains_key('a') assert_that({'a': 1, 'b': 2}).contains_key('a', 'b') Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val does **not** contain the key or keys """ self._check_dict_like(self.val, check_values=False, check_getitem=False) return self.contains(*keys) def does_not_contain_key(self, *keys): """Asserts the val is a dict and does not contain the given key or keys. Alias for :meth:`~assertpy.contains.ContainsMixin.does_not_contain`. Checks if the dict excludes the given key or keys using ``in`` operator. Args: *keys: the key or keys expected to be excluded Examples: Usage:: assert_that({'a': 1, 'b': 2}).does_not_contain_key('x') assert_that({'a': 1, 'b': 2}).does_not_contain_key('x', 'y') Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val **does** contain the key or keys """ self._check_dict_like(self.val, check_values=False, check_getitem=False) return self.does_not_contain(*keys) def contains_value(self, *values): """Asserts that val is a dict and contains the given value or values. Checks if the dict contains the given value or values in *any* key. Args: *values: the value or values expected to be contained Examples: Usage:: assert_that({'a': 1, 'b': 2}).contains_value(1) assert_that({'a': 1, 'b': 2}).contains_value(1, 2) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val does **not** contain the value or values """ self._check_dict_like(self.val, check_getitem=False) if len(values) == 0: raise ValueError('one or more value args must be given') missing = [] for v in values: if v not in self.val.values(): missing.append(v) if missing: return self.error('Expected <%s> to contain values %s, but did not contain %s.' % (self.val, self._fmt_items(values), self._fmt_items(missing))) return self def does_not_contain_value(self, *values): """Asserts that val is a dict and does not contain the given value or values. Checks if the dict excludes the given value or values across *all* keys. Args: *values: the value or values expected to be excluded Examples: Usage:: assert_that({'a': 1, 'b': 2}).does_not_contain_value(3) assert_that({'a': 1, 'b': 2}).does_not_contain_value(3, 4) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val **does** contain the value or values """ self._check_dict_like(self.val, check_getitem=False) if len(values) == 0: raise ValueError('one or more value args must be given') else: found = [] for v in values: if v in self.val.values(): found.append(v) if found: return self.error('Expected <%s> to not contain values %s, but did contain %s.' % (self.val, self._fmt_items(values), self._fmt_items(found))) return self def contains_entry(self, *args, **kwargs): """Asserts that val is a dict and contains the given entry or entries. Checks if the dict contains the given key-value pair or pairs. Args: *args: the entry or entries expected to be contained (as ``{k: v}`` args) **kwargs: the entry or entries expected to be contained (as ``k=v`` kwargs) Examples: Usage:: # using args assert_that({'a': 1, 'b': 2, 'c': 3}).contains_entry({'a': 1}) assert_that({'a': 1, 'b': 2, 'c': 3}).contains_entry({'a': 1}, {'b': 2}) assert_that({'a': 1, 'b': 2, 'c': 3}).contains_entry({'a': 1}, {'b': 2}, {'c': 3}) # using kwargs assert_that({'a': 1, 'b': 2, 'c': 3}).contains_entry(a=1) assert_that({'a': 1, 'b': 2, 'c': 3}).contains_entry(a=1, b=2) assert_that({'a': 1, 'b': 2, 'c': 3}).contains_entry(a=1, b=2, c=3) # or args and kwargs assert_that({'a': 1, 'b': 2, 'c': 3}).contains_entry({'c': 3}, a=1, b=2) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val does **not** contain the entry or entries """ self._check_dict_like(self.val, check_values=False) entries = list(args) + [{k: v} for k, v in kwargs.items()] if len(entries) == 0: raise ValueError('one or more entry args must be given') missing = [] for e in entries: if type(e) is not dict: raise TypeError('given entry arg must be a dict') if len(e) != 1: raise ValueError('given entry args must contain exactly one key-value pair') k = next(iter(e)) if k not in self.val: missing.append(e) # bad key elif self.val[k] != e[k]: missing.append(e) # bad val if missing: return self.error('Expected <%s> to contain entries %s, but did not contain %s.' % (self.val, self._fmt_items(entries), self._fmt_items(missing))) return self def does_not_contain_entry(self, *args, **kwargs): """Asserts that val is a dict and does not contain the given entry or entries. Checks if the dict excludes the given key-value pair or pairs. Args: *args: the entry or entries expected to be excluded (as ``{k: v}`` args) **kwargs: the entry or entries expected to be excluded (as ``k=v`` kwargs) Examples: Usage:: # using args assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain_entry({'a': 2}) assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain_entry({'a': 2}, {'x': 4}) # using kwargs assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain_entry(a=2) assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain_entry(a=2, x=4) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val **does** contain the entry or entries """ self._check_dict_like(self.val, check_values=False) entries = list(args) + [{k: v} for k, v in kwargs.items()] if len(entries) == 0: raise ValueError('one or more entry args must be given') found = [] for e in entries: if type(e) is not dict: raise TypeError('given entry arg must be a dict') if len(e) != 1: raise ValueError('given entry args must contain exactly one key-value pair') k = next(iter(e)) if k in self.val and e[k] == self.val[k]: found.append(e) if found: return self.error('Expected <%s> to not contain entries %s, but did contain %s.' % (self.val, self._fmt_items(entries), self._fmt_items(found))) return self
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,325
assertpy/assertpy
refs/heads/main
/assertpy/string.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import re import collections if sys.version_info[0] == 3: str_types = (str,) unicode = str Iterable = collections.abc.Iterable else: str_types = (basestring,) unicode = unicode Iterable = collections.Iterable __tracebackhide__ = True class StringMixin(object): """String assertions mixin.""" def is_equal_to_ignoring_case(self, other): """Asserts that val is a string and is case-insensitive equal to other. Checks actual is equal to expected using the ``==`` operator and ``str.lower()``. Args: other: the expected value Examples: Usage:: assert_that('foo').is_equal_to_ignoring_case('FOO') assert_that('FOO').is_equal_to_ignoring_case('foo') assert_that('fOo').is_equal_to_ignoring_case('FoO') Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if actual is **not** case-insensitive equal to expected """ if not isinstance(self.val, str_types): raise TypeError('val is not a string') if not isinstance(other, str_types): raise TypeError('given arg must be a string') if self.val.lower() != other.lower(): return self.error('Expected <%s> to be case-insensitive equal to <%s>, but was not.' % (self.val, other)) return self def contains_ignoring_case(self, *items): """Asserts that val is string and contains the given item or items. Walks val and checks for item or items using the ``==`` operator and ``str.lower()``. Args: *items: the item or items expected to be contained Examples: Usage:: assert_that('foo').contains_ignoring_case('F', 'oO') assert_that(['a', 'B']).contains_ignoring_case('A', 'b') assert_that({'a': 1, 'B': 2}).contains_ignoring_case('A', 'b') assert_that({'a', 'B'}).contains_ignoring_case('A', 'b') Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val does **not** contain the case-insensitive item or items """ if len(items) == 0: raise ValueError('one or more args must be given') if isinstance(self.val, str_types): if len(items) == 1: if not isinstance(items[0], str_types): raise TypeError('given arg must be a string') if items[0].lower() not in self.val.lower(): return self.error('Expected <%s> to case-insensitive contain item <%s>, but did not.' % (self.val, items[0])) else: missing = [] for i in items: if not isinstance(i, str_types): raise TypeError('given args must all be strings') if i.lower() not in self.val.lower(): missing.append(i) if missing: return self.error('Expected <%s> to case-insensitive contain items %s, but did not contain %s.' % ( self.val, self._fmt_items(items), self._fmt_items(missing))) elif isinstance(self.val, Iterable): missing = [] for i in items: if not isinstance(i, str_types): raise TypeError('given args must all be strings') found = False for v in self.val: if not isinstance(v, str_types): raise TypeError('val items must all be strings') if i.lower() == v.lower(): found = True break if not found: missing.append(i) if missing: return self.error('Expected <%s> to case-insensitive contain items %s, but did not contain %s.' % ( self.val, self._fmt_items(items), self._fmt_items(missing))) else: raise TypeError('val is not a string or iterable') return self def starts_with(self, prefix): """Asserts that val is string or iterable and starts with prefix. Args: prefix: the prefix Examples: Usage:: assert_that('foo').starts_with('fo') assert_that(['a', 'b', 'c']).starts_with('a') assert_that((1, 2, 3)).starts_with(1) assert_that(((1, 2), (3, 4), (5, 6))).starts_with((1, 2)) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val does **not** start with prefix """ if prefix is None: raise TypeError('given prefix arg must not be none') if isinstance(self.val, str_types): if not isinstance(prefix, str_types): raise TypeError('given prefix arg must be a string') if len(prefix) == 0: raise ValueError('given prefix arg must not be empty') if not self.val.startswith(prefix): return self.error('Expected <%s> to start with <%s>, but did not.' % (self.val, prefix)) elif isinstance(self.val, Iterable): if len(self.val) == 0: raise ValueError('val must not be empty') first = next(iter(self.val)) if first != prefix: return self.error('Expected %s to start with <%s>, but did not.' % (self.val, prefix)) else: raise TypeError('val is not a string or iterable') return self def ends_with(self, suffix): """Asserts that val is string or iterable and ends with suffix. Args: suffix: the suffix Examples: Usage:: assert_that('foo').ends_with('oo') assert_that(['a', 'b', 'c']).ends_with('c') assert_that((1, 2, 3)).ends_with(3) assert_that(((1, 2), (3, 4), (5, 6))).ends_with((5, 6)) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val does **not** end with suffix """ if suffix is None: raise TypeError('given suffix arg must not be none') if isinstance(self.val, str_types): if not isinstance(suffix, str_types): raise TypeError('given suffix arg must be a string') if len(suffix) == 0: raise ValueError('given suffix arg must not be empty') if not self.val.endswith(suffix): return self.error('Expected <%s> to end with <%s>, but did not.' % (self.val, suffix)) elif isinstance(self.val, Iterable): if len(self.val) == 0: raise ValueError('val must not be empty') last = None for last in self.val: pass if last != suffix: return self.error('Expected %s to end with <%s>, but did not.' % (self.val, suffix)) else: raise TypeError('val is not a string or iterable') return self def matches(self, pattern): """Asserts that val is string and matches the given regex pattern. Args: pattern (str): the regular expression pattern, as raw string (aka prefixed with ``r``) Examples: Usage:: assert_that('foo').matches(r'\\w') assert_that('123-456-7890').matches(r'\\d{3}-\\d{3}-\\d{4}') Match is partial unless anchored, so these assertion pass:: assert_that('foo').matches(r'\\w') assert_that('foo').matches(r'oo') assert_that('foo').matches(r'\\w{2}') To match the entire string, just use an anchored regex pattern where ``^`` and ``$`` match the start and end of line and ``\\A`` and ``\\Z`` match the start and end of string:: assert_that('foo').matches(r'^\\w{3}$') assert_that('foo').matches(r'\\A\\w{3}\\Z') And regex flags, such as ``re.MULTILINE`` and ``re.DOTALL``, can only be applied via *inline modifiers*, such as ``(?m)`` and ``(?s)``:: s = '''bar foo baz''' # using multiline (?m) assert_that(s).matches(r'(?m)^foo$') # using dotall (?s) assert_that(s).matches(r'(?s)b(.*)z') Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val does **not** match pattern Tip: Regular expressions are tricky. Be sure to use raw strings (aka prefixed with ``r``). Also, note that the :meth:`matches` assertion passes for partial matches (as does the underlying ``re.match`` method). So, if you need to match the entire string, you must include anchors in the regex pattern. """ if not isinstance(self.val, str_types): raise TypeError('val is not a string') if not isinstance(pattern, str_types): raise TypeError('given pattern arg must be a string') if len(pattern) == 0: raise ValueError('given pattern arg must not be empty') if re.search(pattern, self.val) is None: return self.error('Expected <%s> to match pattern <%s>, but did not.' % (self.val, pattern)) return self def does_not_match(self, pattern): """Asserts that val is string and does not match the given regex pattern. Args: pattern (str): the regular expression pattern, as raw string (aka prefixed with ``r``) Examples: Usage:: assert_that('foo').does_not_match(r'\\d+') assert_that('123').does_not_match(r'\\w+') Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val **does** match pattern See Also: :meth:`matches` - for more about regex patterns """ if not isinstance(self.val, str_types): raise TypeError('val is not a string') if not isinstance(pattern, str_types): raise TypeError('given pattern arg must be a string') if len(pattern) == 0: raise ValueError('given pattern arg must not be empty') if re.search(pattern, self.val) is not None: return self.error('Expected <%s> to not match pattern <%s>, but did.' % (self.val, pattern)) return self def is_alpha(self): """Asserts that val is non-empty string and all characters are alphabetic (using ``str.isalpha()``). Examples: Usage:: assert_that('foo').is_alpha() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** alphabetic """ if not isinstance(self.val, str_types): raise TypeError('val is not a string') if len(self.val) == 0: raise ValueError('val is empty') if not self.val.isalpha(): return self.error('Expected <%s> to contain only alphabetic chars, but did not.' % self.val) return self def is_digit(self): """Asserts that val is non-empty string and all characters are digits (using ``str.isdigit()``). Examples: Usage:: assert_that('1234567890').is_digit() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** digits """ if not isinstance(self.val, str_types): raise TypeError('val is not a string') if len(self.val) == 0: raise ValueError('val is empty') if not self.val.isdigit(): return self.error('Expected <%s> to contain only digits, but did not.' % self.val) return self def is_lower(self): """Asserts that val is non-empty string and all characters are lowercase (using ``str.lower()``). Examples: Usage:: assert_that('foo').is_lower() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** lowercase """ if not isinstance(self.val, str_types): raise TypeError('val is not a string') if len(self.val) == 0: raise ValueError('val is empty') if self.val != self.val.lower(): return self.error('Expected <%s> to contain only lowercase chars, but did not.' % self.val) return self def is_upper(self): """Asserts that val is non-empty string and all characters are uppercase (using ``str.upper()``). Examples: Usage:: assert_that('FOO').is_upper() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** uppercase """ if not isinstance(self.val, str_types): raise TypeError('val is not a string') if len(self.val) == 0: raise ValueError('val is empty') if self.val != self.val.upper(): return self.error('Expected <%s> to contain only uppercase chars, but did not.' % self.val) return self def is_unicode(self): """Asserts that val is a unicode string. Examples: Usage:: assert_that(u'foo').is_unicode() # python 2 assert_that('foo').is_unicode() # python 3 Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** a unicode string """ if type(self.val) is not unicode: return self.error('Expected <%s> to be unicode, but was <%s>.' % (self.val, type(self.val).__name__)) return self
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,326
assertpy/assertpy
refs/heads/main
/docs/conf.py
# fixup path import os import sys sys.path.insert(0, os.path.abspath('..')) print('SYS.PATH=', sys.path) # proj info project = 'assertpy' copyright = '2015-2019 Activision Publishing, Inc.' author = 'Activision' # extensions (for Google-style doc strings) extensions = [ 'sphinx.ext.autodoc', 'sphinxcontrib.napoleon' ] templates_path = ['templates'] exclude_patterns = ['build', '.DS_Store'] # html_theme = 'sphinx_rtd_theme' add_module_names = False
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,327
assertpy/assertpy
refs/heads/main
/tests/test_namedtuple.py
# Copyright (c) 2015-2021, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import collections from assertpy import assert_that, fail Foo = collections.namedtuple('Foo', ['bar', 'baz']) foo = Foo(bar='abc', baz=123) foos = [foo, Foo(bar='xyz', baz=456)] def test_namedtuple_equals(): assert_that(foo).is_instance_of(Foo) assert_that(foo).is_instance_of(tuple) assert_that(foo).is_instance_of(object) assert_that(foo).is_type_of(Foo) assert_that(foo).is_equal_to(('abc', 123)) assert_that(foo).is_equal_to(Foo(bar='abc', baz=123)) assert_that(foo).is_not_equal_to(Foo(bar='abc', baz=124)) assert_that(foo.bar).is_equal_to('abc') assert_that(foo[0]).is_equal_to('abc') assert_that(foo.baz).is_equal_to(123) assert_that(foo[1]).is_equal_to(123) assert_that(foo._fields).is_equal_to(('bar', 'baz')) def test_namedtuple_equals_failure(): try: assert_that(foo).is_equal_to(Foo(bar='abc', baz=124)) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <Foo(bar='abc', baz=123)> to be equal to <Foo(bar='abc', baz=124)>, but was not.") def test_namedtuple_has(): assert_that(foo).has_bar('abc') assert_that(foo).has_baz(123) def test_namedtuple_has_failure(): try: assert_that(foo).has_missing('x') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected attribute <missing>, but val has no attribute <missing>.") def test_namedtuple_extracting_by_index(): assert_that(foos).extracting(0).is_equal_to(['abc', 'xyz']) assert_that(foos).extracting(1).is_equal_to([123, 456]) def test_namedtuple_extracting_by_name(): assert_that(foos).extracting('bar').is_equal_to(['abc', 'xyz']) assert_that(foos).extracting('baz').is_equal_to([123, 456]) def test_namedtuple_extracting_by_name_failure(): try: assert_that(foos).extracting('missing').is_equal_to('x') fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to("item attributes ('bar', 'baz') did no contain attribute <missing>")
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,328
assertpy/assertpy
refs/heads/main
/tests/test_snapshots.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import sys import shutil import datetime import collections import pytest from assertpy import assert_that, fail if sys.version_info[0] < 3: def test_snapshot_v2(): try: assert_that(None).snapshot() fail('should have raised error') except NotImplementedError as ex: assert_that(str(ex)).is_equal_to('snapshot testing requires Python 3') if sys.version_info[0] == 3: @pytest.mark.parametrize('count', [1, 2]) def test_snapshot_v3(count): # test runs twice if count == 1: # on first pass, delete old snapshots...so they are re-created and saved if os.path.exists('__snapshots'): shutil.rmtree('__snapshots') if count == 2: # on second pass, snapshots are loaded and checked assert_that('__snapshots').exists().is_directory() assert_that(None).snapshot() assert_that(True).snapshot() assert_that(False).snapshot() assert_that(123).snapshot() assert_that(-456).snapshot() assert_that(123.456).snapshot() assert_that(-987.654).snapshot() assert_that('').snapshot() assert_that('foo').snapshot() assert_that([1, 2, 3]).snapshot() assert_that(['a', 'b', 'c']).snapshot() assert_that([[1, 2, 3], ['a', 'b', 'c']]).snapshot() assert_that(set(['a', 'b', 'c', 'a'])).snapshot() assert_that({'a': 1, 'b': 2, 'c': 3}).snapshot() assert_that({'a': {'x': 1}, 'b': {'y': 2}, 'c': {'z': 3}}).snapshot() assert_that({'a': [1, 2], 'b': [3, 4], 'c': [5, 6]}).snapshot() assert_that({'a': set([1, 2]), 'b': set([3, 4]), 'c': set([5, 6])}).snapshot() assert_that({'a': {'b': {'c': {'x': {'y': {'z': 1}}}}}}).snapshot() assert_that(collections.OrderedDict([('a', 1), ('c', 3), ('b', 2)])).snapshot() assert_that(datetime.datetime(2000, 11, 22, 3, 44, 55)).snapshot() assert_that(1 + 2j).snapshot() # tuples are always converted to lists...can this be fixed? # assert_that((1, 2, 3)).snapshot() # assert_that({'a': (1,2), 'b': (3,4), 'c': (5,6)}).snapshot() assert_that({'custom': 'id'}).snapshot(id='mycustomid') assert_that({'custom': 'path'}).snapshot(path='mycustompath') foo = Foo() foo2 = Foo({ 'a': 1, 'b': [1, 2, 3], 'c': {'x': 1, 'y': 2, 'z': 3}, 'd': set([-1, 2, -3]), 'e': datetime.datetime(2000, 11, 22, 3, 44, 55), 'f': -1 - 2j }) bar = Bar() assert_that(foo.x).is_equal_to(0) assert_that(foo.y).is_equal_to(1) assert_that(foo2.x['a']).is_equal_to(1) assert_that(foo2.x['b']).is_equal_to([1, 2, 3]) assert_that(foo2.y).is_equal_to(1) assert_that(bar.x).is_equal_to(0) assert_that(bar.y).is_equal_to(1) assert_that(foo).snapshot() assert_that(foo2).snapshot() try: assert_that(bar).snapshot() if count == 2: fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).contains('Expected ').contains(' to be equal to ').contains('test_snapshots.Bar').contains(', but was not.') assert_that({ 'none': None, 'truthy': True, 'falsy': False, 'int': 123, 'intneg': -456, 'float': 123.456, 'floatneg': -987.654, 'empty': '', 'str': 'foo', 'list': [1, 2, 3], 'liststr': ['a', 'b', 'c'], 'listmix': [1, 'a', [2, 4, 6], set([1, 2, 3]), 3+6j], 'set': set([1, 2, 3]), 'dict': {'a': 1, 'b': 2, 'c': 3}, 'time': datetime.datetime(2000, 11, 22, 3, 44, 55), 'complex': 1 + 2j, 'foo': foo, 'foo2': foo2 }).snapshot() assert_that({'__type__': 'foo', '__data__': 'bar'}).snapshot() # def test_snapshot_not_serializable(): # try: # assert_that(range(5)).snapshot() # fail('should have raised error') # except TypeError as ex: # assert_that(str(ex)).ends_with('is not JSON serializable') def test_snapshot_custom_id_int(): try: assert_that('foo').snapshot(id=123) fail('should have raised error') except ValueError as ex: assert_that(str(ex)).starts_with('failed to create snapshot filename') def test_snapshot_custom_path_none(): try: assert_that('foo').snapshot(path=None) fail('should have raised error') except ValueError as ex: assert_that(str(ex)).starts_with('failed to create snapshot filename') class Foo(object): def __init__(self, x=0): self.x = x self.y = 1 def __eq__(self, other): if isinstance(self, other.__class__): return self.__dict__ == other.__dict__ return NotImplemented class Bar(Foo): def __eq__(self, other): return NotImplemented
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,329
assertpy/assertpy
refs/heads/main
/assertpy/exception.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import collections if sys.version_info[0] == 3: Iterable = collections.abc.Iterable else: Iterable = collections.Iterable __tracebackhide__ = True class ExceptionMixin(object): """Expected exception mixin.""" def raises(self, ex): """Asserts that val is callable and set the expected exception. Just sets the expected exception, but never calls val, and therefore never failes. You must chain to :meth:`~when_called_with` to invoke ``val()``. Args: ex: the expected exception Examples: Usage:: assert_that(some_func).raises(RuntimeError).when_called_with('foo') Returns: AssertionBuilder: returns a new instance (now with the given expected exception) to chain to the next assertion """ if not callable(self.val): raise TypeError('val must be callable') if not issubclass(ex, BaseException): raise TypeError('given arg must be exception') # chain on with ex as the expected exception return self.builder(self.val, self.description, self.kind, ex) def when_called_with(self, *some_args, **some_kwargs): """Asserts that val, when invoked with the given args and kwargs, raises the expected exception. Invokes ``val()`` with the given args and kwargs. You must first set the expected exception with :meth:`~raises`. Args: *some_args: the args to call ``val()`` **some_kwargs: the kwargs to call ``val()`` Examples: Usage:: def some_func(a): raise RuntimeError('some error!') assert_that(some_func).raises(RuntimeError).when_called_with('foo') Returns: AssertionBuilder: returns a new instance (now with the captured exception error message as the val) to chain to the next assertion Raises: AssertionError: if val does **not** raise the expected exception TypeError: if expected exception not set via :meth:`raises` """ if not self.expected: raise TypeError('expected exception not set, raises() must be called first') try: self.val(*some_args, **some_kwargs) except BaseException as e: if issubclass(type(e), self.expected): # chain on with error message return self.builder(str(e), self.description, self.kind) else: # got exception, but wrong type, so raise return self.error('Expected <%s> to raise <%s> when called with (%s), but raised <%s>.' % ( self.val.__name__, self.expected.__name__, self._fmt_args_kwargs(*some_args, **some_kwargs), type(e).__name__)) # didn't fail as expected, so raise return self.error('Expected <%s> to raise <%s> when called with (%s).' % ( self.val.__name__, self.expected.__name__, self._fmt_args_kwargs(*some_args, **some_kwargs)))
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,330
assertpy/assertpy
refs/heads/main
/tests/test_core.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from assertpy import assert_that def test_fmt_items_empty(): ab = assert_that(None) assert_that(ab._fmt_items([])).is_equal_to('<>') def test_fmt_items_single(): ab = assert_that(None) assert_that(ab._fmt_items([1])).is_equal_to('<1>') assert_that(ab._fmt_items(['foo'])).is_equal_to('<foo>') assert_that(ab._fmt_items([('bar', 'baz')])).is_equal_to('<(\'bar\', \'baz\')>') def test_fmt_items_multiple(): ab = assert_that(None) assert_that(ab._fmt_items([1, 2, 3])).is_equal_to('<1, 2, 3>') assert_that(ab._fmt_items(['a', 'b', 'c'])).is_equal_to("<'a', 'b', 'c'>") def test_fmt_args_kwargs_empty(): ab = assert_that(None) assert_that(ab._fmt_args_kwargs()).is_equal_to('') def test_fmt_args_kwargs_single_arg(): ab = assert_that(None) assert_that(ab._fmt_args_kwargs(1)).is_equal_to('1') assert_that(ab._fmt_args_kwargs('foo')).is_equal_to("'foo'") def test_fmt_args_kwargs_multiple_args(): ab = assert_that(None) assert_that(ab._fmt_args_kwargs(1, 2, 3)).is_equal_to('1, 2, 3') assert_that(ab._fmt_args_kwargs('a', 'b', 'c')).is_equal_to("'a', 'b', 'c'") def test_fmt_args_kwargs_single_kwarg(): ab = assert_that(None) assert_that(ab._fmt_args_kwargs(a=1)).is_equal_to("'a': 1") assert_that(ab._fmt_args_kwargs(f='foo')).is_equal_to("'f': 'foo'") def test_fmt_args_kwargs_multiple_kwargs(): ab = assert_that(None) assert_that(ab._fmt_args_kwargs(a=1, b=2, c=3)).is_equal_to("'a': 1, 'b': 2, 'c': 3") assert_that(ab._fmt_args_kwargs(a='a', b='b', c='c')).is_equal_to("'a': 'a', 'b': 'b', 'c': 'c'") def test_fmt_args_kwargs_multiple_both(): ab = assert_that(None) assert_that(ab._fmt_args_kwargs(1, 2, 3, a=4, b=5, c=6)).is_equal_to("1, 2, 3, 'a': 4, 'b': 5, 'c': 6") assert_that(ab._fmt_args_kwargs('a', 'b', 'c', d='g', e='h', f='i')).is_equal_to("'a', 'b', 'c', 'd': 'g', 'e': 'h', 'f': 'i'") def test_check_dict_like_empty_dict(): ab = assert_that(None) assert_that(ab._check_dict_like({})) def test_check_dict_like_not_iterable(): ab = assert_that(None) assert_that(ab._check_dict_like).raises(TypeError).when_called_with(123)\ .is_equal_to('val <int> is not dict-like: not iterable') def test_check_dict_like_missing_keys(): ab = assert_that(None) assert_that(ab._check_dict_like).raises(TypeError).when_called_with('foo')\ .is_equal_to('val <str> is not dict-like: missing keys()') def test_check_dict_like_bool(): ab = assert_that(None) assert_that(ab._check_dict_like({}, return_as_bool=True)).is_true() assert_that(ab._check_dict_like(123, return_as_bool=True)).is_false() assert_that(ab._check_dict_like('foo', return_as_bool=True)).is_false()
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,331
assertpy/assertpy
refs/heads/main
/tests/test_string.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from assertpy import assert_that, fail import sys if sys.version_info[0] == 3: unicode = str else: unicode = unicode def test_is_length(): assert_that('foo').is_length(3) def test_is_length_failure(): try: assert_that('foo').is_length(4) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <foo> to be of length <4>, but was <3>.') def test_contains(): assert_that('foo').contains('f') assert_that('foo').contains('o') assert_that('foo').contains('fo', 'o') assert_that('fred').contains('d') assert_that('fred').contains('fr', 'e', 'd') def test_contains_single_item_failure(): try: assert_that('foo').contains('x') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <foo> to contain item <x>, but did not.') def test_contains_multi_item_failure(): try: assert_that('foo').contains('f', 'x', 'z') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <foo> to contain items <'f', 'x', 'z'>, but did not contain <'x', 'z'>.") def test_contains_multi_item_single_failure(): try: assert_that('foo').contains('f', 'o', 'x') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <foo> to contain items <'f', 'o', 'x'>, but did not contain <x>.") def test_contains_ignoring_case(): assert_that('foo').contains_ignoring_case('f') assert_that('foo').contains_ignoring_case('F') assert_that('foo').contains_ignoring_case('Oo') assert_that('foo').contains_ignoring_case('f', 'o', 'F', 'O', 'Fo', 'Oo', 'FoO') def test_contains_ignoring_case_type_failure(): try: assert_that(123).contains_ignoring_case('f') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not a string or iterable') def test_contains_ignoring_case_missinge_item_failure(): try: assert_that('foo').contains_ignoring_case() fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('one or more args must be given') def test_contains_ignoring_case_single_item_failure(): try: assert_that('foo').contains_ignoring_case('X') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <foo> to case-insensitive contain item <X>, but did not.') def test_contains_ignoring_case_single_item_type_failure(): try: assert_that('foo').contains_ignoring_case(12) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be a string') def test_contains_ignoring_case_multi_item_failure(): try: assert_that('foo').contains_ignoring_case('F', 'X', 'Z') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <foo> to case-insensitive contain items <'F', 'X', 'Z'>, but did not contain <'X', 'Z'>.") def test_contains_ignoring_case_multi_item_type_failure(): try: assert_that('foo').contains_ignoring_case('F', 12) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given args must all be strings') def test_contains_ignoring_case_list(): assert_that(['foo']).contains_ignoring_case('Foo') assert_that(['foo', 'bar', 'baz']).contains_ignoring_case('Foo') assert_that(['foo', 'bar', 'baz']).contains_ignoring_case('Foo', 'bAr') assert_that(['foo', 'bar', 'baz']).contains_ignoring_case('Foo', 'bAr', 'baZ') def test_contains_ignoring_case_list_elem_type_failure(): try: assert_that([123]).contains_ignoring_case('f') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val items must all be strings') def test_contains_ignoring_case_list_multi_elem_type_failure(): try: assert_that(['foo', 123]).contains_ignoring_case('f') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val items must all be strings') def test_contains_ignoring_case_list_missinge_item_failure(): try: assert_that(['foo']).contains_ignoring_case() fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('one or more args must be given') def test_contains_ignoring_case_list_single_item_failure(): try: assert_that(['foo']).contains_ignoring_case('X') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <['foo']> to case-insensitive contain items <X>, but did not contain <X>.") def test_contains_ignoring_case_list_single_item_type_failure(): try: assert_that(['foo']).contains_ignoring_case(12) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given args must all be strings') def test_contains_ignoring_case_list_multi_item_failure(): try: assert_that(['foo', 'bar']).contains_ignoring_case('Foo', 'X', 'Y') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <['foo', 'bar']> to case-insensitive contain items <'Foo', 'X', 'Y'>, but did not contain <'X', 'Y'>.") def test_contains_ignoring_case_list_multi_item_type_failure(): try: assert_that(['foo', 'bar']).contains_ignoring_case('F', 12) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given args must all be strings') def test_does_not_contain(): assert_that('foo').does_not_contain('x') assert_that('foo').does_not_contain('x', 'y') def test_does_not_contain_single_item_failure(): try: assert_that('foo').does_not_contain('f') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <foo> to not contain item <f>, but did.') def test_does_not_contain_list_item_failure(): try: assert_that('foo').does_not_contain('x', 'y', 'f') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <foo> to not contain items <'x', 'y', 'f'>, but did contain <f>.") def test_does_not_contain_list_multi_item_failure(): try: assert_that('foo').does_not_contain('x', 'f', 'o') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <foo> to not contain items <'x', 'f', 'o'>, but did contain <'f', 'o'>.") def test_is_empty(): assert_that('').is_empty() def test_is_empty_failure(): try: assert_that('foo').is_empty() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <foo> to be empty string, but was not.') def test_is_not_empty(): assert_that('foo').is_not_empty() def test_is_not_empty_failure(): try: assert_that('').is_not_empty() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected not empty string, but was empty.') def test_is_equal_ignoring_case(): assert_that('FOO').is_equal_to_ignoring_case('foo') assert_that('foo').is_equal_to_ignoring_case('FOO') assert_that('fOO').is_equal_to_ignoring_case('foo') def test_is_equal_ignoring_case_failure(): try: assert_that('foo').is_equal_to_ignoring_case('bar') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <foo> to be case-insensitive equal to <bar>, but was not.') def test_is_equal_ignoring_case_bad_value_type_failure(): try: assert_that(123).is_equal_to_ignoring_case(12) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not a string') def test_is_equal_ignoring_case_bad_arg_type_failure(): try: assert_that('fred').is_equal_to_ignoring_case(12) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be a string') def test_starts_with(): assert_that('fred').starts_with('f') assert_that('fred').starts_with('fr') assert_that('fred').starts_with('fred') def test_starts_with_failure(): try: assert_that('fred').starts_with('bar') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <fred> to start with <bar>, but did not.') def test_starts_with_bad_value_type_failure(): try: assert_that(123).starts_with(12) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not a string or iterable') def test_starts_with_bad_arg_none_failure(): try: assert_that('fred').starts_with(None) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given prefix arg must not be none') def test_starts_with_bad_arg_type_failure(): try: assert_that('fred').starts_with(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given prefix arg must be a string') def test_starts_with_bad_arg_empty_failure(): try: assert_that('fred').starts_with('') fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('given prefix arg must not be empty') def test_ends_with(): assert_that('fred').ends_with('d') assert_that('fred').ends_with('ed') assert_that('fred').ends_with('fred') def test_ends_with_failure(): try: assert_that('fred').ends_with('bar') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <fred> to end with <bar>, but did not.') def test_ends_with_bad_value_type_failure(): try: assert_that(123).ends_with(12) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not a string or iterable') def test_ends_with_bad_arg_none_failure(): try: assert_that('fred').ends_with(None) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given suffix arg must not be none') def test_ends_with_bad_arg_type_failure(): try: assert_that('fred').ends_with(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given suffix arg must be a string') def test_ends_with_bad_arg_empty_failure(): try: assert_that('fred').ends_with('') fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('given suffix arg must not be empty') def test_matches(): assert_that('fred').matches(r'\w') assert_that('fred').matches(r'\w{2}') assert_that('fred').matches(r'\w+') assert_that('fred').matches(r'^\w{4}$') assert_that('fred').matches(r'^.*?$') assert_that('123-456-7890').matches(r'\d{3}-\d{3}-\d{4}') def test_matches_failure(): try: assert_that('fred').matches(r'\d+') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <fred> to match pattern <\\d+>, but did not.') def test_matches_bad_value_type_failure(): try: assert_that(123).matches(12) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not a string') def test_matches_bad_arg_type_failure(): try: assert_that('fred').matches(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given pattern arg must be a string') def test_matches_bad_arg_empty_failure(): try: assert_that('fred').matches('') fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('given pattern arg must not be empty') def test_does_not_match(): assert_that('fred').does_not_match(r'\d+') assert_that('fred').does_not_match(r'\w{5}') assert_that('123-456-7890').does_not_match(r'^\d+$') def test_does_not_match_failure(): try: assert_that('fred').does_not_match(r'\w+') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <fred> to not match pattern <\\w+>, but did.') def test_does_not_match_bad_value_type_failure(): try: assert_that(123).does_not_match(12) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not a string') def test_does_not_match_bad_arg_type_failure(): try: assert_that('fred').does_not_match(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given pattern arg must be a string') def test_does_not_match_bad_arg_empty_failure(): try: assert_that('fred').does_not_match('') fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('given pattern arg must not be empty') def test_is_alpha(): assert_that('foo').is_alpha() def test_is_alpha_digit_failure(): try: assert_that('foo123').is_alpha() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <foo123> to contain only alphabetic chars, but did not.') def test_is_alpha_space_failure(): try: assert_that('foo bar').is_alpha() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <foo bar> to contain only alphabetic chars, but did not.') def test_is_alpha_punctuation_failure(): try: assert_that('foo,bar').is_alpha() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <foo,bar> to contain only alphabetic chars, but did not.') def test_is_alpha_bad_value_type_failure(): try: assert_that(123).is_alpha() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not a string') def test_is_alpha_empty_value_failure(): try: assert_that('').is_alpha() fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('val is empty') def test_is_digit(): assert_that('123').is_digit() def test_is_digit_alpha_failure(): try: assert_that('foo123').is_digit() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <foo123> to contain only digits, but did not.') def test_is_digit_space_failure(): try: assert_that('1 000 000').is_digit() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <1 000 000> to contain only digits, but did not.') def test_is_digit_punctuation_failure(): try: assert_that('-123').is_digit() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <-123> to contain only digits, but did not.') def test_is_digit_bad_value_type_failure(): try: assert_that(123).is_digit() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not a string') def test_is_digit_empty_value_failure(): try: assert_that('').is_digit() fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('val is empty') def test_is_lower(): assert_that('foo').is_lower() assert_that('foo 123').is_lower() assert_that('123 456').is_lower() def test_is_lower_failure(): try: assert_that('FOO').is_lower() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <FOO> to contain only lowercase chars, but did not.') def test_is_lower_bad_value_type_failure(): try: assert_that(123).is_lower() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not a string') def test_is_lower_empty_value_failure(): try: assert_that('').is_lower() fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('val is empty') def test_is_upper(): assert_that('FOO').is_upper() assert_that('FOO 123').is_upper() assert_that('123 456').is_upper() def test_is_upper_failure(): try: assert_that('foo').is_upper() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <foo> to contain only uppercase chars, but did not.') def test_is_upper_bad_value_type_failure(): try: assert_that(123).is_upper() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not a string') def test_is_upper_empty_value_failure(): try: assert_that('').is_upper() fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('val is empty') def test_is_unicode(): assert_that(unicode('unicorn')).is_unicode() assert_that(unicode('unicorn 123')).is_unicode() assert_that(unicode('unicorn')).is_unicode() def test_is_unicode_failure(): try: assert_that(123).is_unicode() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <123> to be unicode, but was <int>.') def test_chaining(): assert_that('foo').is_type_of(str).is_length(3).contains('f').does_not_contain('x') assert_that('fred').starts_with('f').ends_with('d').matches(r'^f.*?d$').does_not_match(r'\d')
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,332
assertpy/assertpy
refs/heads/main
/tests/test_soft_fail.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from assertpy import assert_that, fail, soft_fail, soft_assertions def test_soft_fail_without_context(): try: soft_fail() fail('should have raised error') except AssertionError as e: out = str(e) assert_that(out).is_equal_to('Fail!') assert_that(out).does_not_contain('should have raised error') def test_soft_fail_with_msg_without_context(): try: soft_fail('some msg') fail('should have raised error') except AssertionError as e: out = str(e) assert_that(out).is_equal_to('Fail: some msg!') assert_that(out).does_not_contain('should have raised error') def test_soft_fail(): try: with soft_assertions(): soft_fail() fail('should have raised error') except AssertionError as e: out = str(e) assert_that(out).contains('Fail!') assert_that(out).does_not_contain('should have raised error') def test_soft_fail_with_msg(): try: with soft_assertions(): soft_fail('foobar') fail('should have raised error') except AssertionError as e: out = str(e) assert_that(out).contains('Fail: foobar!') assert_that(out).does_not_contain('should have raised error') def test_soft_fail_with_soft_failing_asserts(): try: with soft_assertions(): assert_that('foo').is_length(4) assert_that('foo').is_empty() soft_fail('foobar') assert_that('foo').is_not_equal_to('foo') assert_that('foo').is_equal_to_ignoring_case('BAR') fail('should have raised error') except AssertionError as e: out = str(e) assert_that(out).contains('Expected <foo> to be of length <4>, but was <3>.') assert_that(out).contains('Expected <foo> to be empty string, but was not.') assert_that(out).contains('Fail: foobar!') assert_that(out).contains('Expected <foo> to be not equal to <foo>, but was.') assert_that(out).contains('Expected <foo> to be case-insensitive equal to <BAR>, but was not.') assert_that(out).does_not_contain('should have raised error') def test_double_soft_fail(): try: with soft_assertions(): soft_fail() soft_fail('foobar') fail('should have raised error') except AssertionError as e: out = str(e) assert_that(out).contains('Fail!') assert_that(out).contains('Fail: foobar!') assert_that(out).does_not_contain('should have raised error')
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,333
assertpy/assertpy
refs/heads/main
/assertpy/snapshot.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import sys import datetime import inspect import json __tracebackhide__ = True class SnapshotMixin(object): """Snapshot mixin. Take a snapshot of a python data structure, store it on disk in JSON format, and automatically compare the latest data to the stored data on every test run. Functional testing (which snapshot testing falls under) is very much blackbox testing. When something goes wrong, it's hard to pinpoint the issue, because functional tests typically provide minimal *isolation* as compared to unit tests. On the plus side, snapshots typically do provide enormous *leverage* as a few well-placed snapshot tests can strongly verify that an application is working. Similar coverage would otherwise require dozens if not hundreds of unit tests. **On-disk Format** Snapshots are stored in a readable JSON format. For example:: assert_that({'a': 1, 'b': 2, 'c': 3}).snapshot() Would be stored as:: { "a": 1, "b": 2, "c": 3 } The JSON formatting support most python data structures (dict, list, object, etc), but not custom binary data. **Updating** It's easy to update your snapshots...just delete them all and re-run the test suite to regenerate all snapshots. Note: Snapshots require Python 3.x """ def snapshot(self, id=None, path='__snapshots'): """Asserts that val is identical to the on-disk snapshot stored previously. On the first run of a test before the snapshot file has been saved, a snapshot is created, stored to disk, and the test *always* passes. But on all subsequent runs, val is compared to the on-disk snapshot, and the test fails if they don't match. Snapshot artifacts are stored in the ``__snapshots`` directory by default, and should be committed to source control alongside any code changes. Snapshots are identified by test filename plus line number by default. Args: id: the item or items expected to be contained path: the item or items expected to be contained Examples: Usage:: assert_that(None).snapshot() assert_that(True).snapshot() assert_that(1).snapshot() assert_that(123.4).snapshot() assert_that('foo').snapshot() assert_that([1, 2, 3]).snapshot() assert_that({'a': 1, 'b': 2, 'c': 3}).snapshot() assert_that({'a', 'b', 'c'}).snapshot() assert_that(1 + 2j).snapshot() assert_that(someobj).snapshot() By default, snapshots are identified by test filename plus line number. Alternately, you can specify a custom identifier using the ``id`` arg:: assert_that({'a': 1, 'b': 2, 'c': 3}).snapshot(id='foo-id') By default, snapshots are stored in the ``__snapshots`` directory. Alternately, you can specify a custom path using the ``path`` arg:: assert_that({'a': 1, 'b': 2, 'c': 3}).snapshot(path='my-custom-folder') Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val does **not** equal to on-disk snapshot """ if sys.version_info[0] < 3: raise NotImplementedError('snapshot testing requires Python 3') class _Encoder(json.JSONEncoder): def default(self, o): if isinstance(o, set): return {'__type__': 'set', '__data__': list(o)} elif isinstance(o, complex): return {'__type__': 'complex', '__data__': [o.real, o.imag]} elif isinstance(o, datetime.datetime): return {'__type__': 'datetime', '__data__': o.strftime('%Y-%m-%d %H:%M:%S')} elif '__dict__' in dir(o) and type(o) is not type: return { '__type__': 'instance', '__class__': o.__class__.__name__, '__module__': o.__class__.__module__, '__data__': o.__dict__ } return json.JSONEncoder.default(self, o) class _Decoder(json.JSONDecoder): def __init__(self): json.JSONDecoder.__init__(self, object_hook=self.object_hook) def object_hook(self, d): if '__type__' in d and '__data__' in d: if d['__type__'] == 'set': return set(d['__data__']) elif d['__type__'] == 'complex': return complex(d['__data__'][0], d['__data__'][1]) elif d['__type__'] == 'datetime': return datetime.datetime.strptime(d['__data__'], '%Y-%m-%d %H:%M:%S') elif d['__type__'] == 'instance': mod = __import__(d['__module__'], fromlist=[d['__class__']]) klass = getattr(mod, d['__class__']) inst = klass.__new__(klass) inst.__dict__ = d['__data__'] return inst return d def _save(name, val): with open(name, 'w') as fp: json.dump(val, fp, indent=2, separators=(',', ': '), sort_keys=True, cls=_Encoder) def _load(name): with open(name, 'r') as fp: return json.load(fp, cls=_Decoder) def _name(path, name): try: return os.path.join(path, 'snap-%s.json' % name.replace(' ', '_').lower()) except Exception: raise ValueError('failed to create snapshot filename, either bad path or bad name') if id: # custom id snapname = _name(path, id) else: # make id from filename and line number f = inspect.currentframe() fpath = os.path.basename(f.f_back.f_code.co_filename) fname = os.path.splitext(fpath)[0] lineno = str(f.f_back.f_lineno) snapname = _name(path, fname) if not os.path.exists(path): os.makedirs(path) if os.path.isfile(snapname): # snap exists, so load snap = _load(snapname) if id: # custom id, so test return self.is_equal_to(snap) else: if lineno in snap: # found sub-snap, so test return self.is_equal_to(snap[lineno]) else: # lineno not in snap, so create sub-snap and pass snap[lineno] = self.val _save(snapname, snap) else: # no snap, so create and pass _save(snapname, self.val if id else {lineno: self.val}) return self
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,334
assertpy/assertpy
refs/heads/main
/assertpy/assertpy.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Assertion library for python unit testing with a fluent API""" from __future__ import print_function import os import contextlib import inspect import logging import sys import types from .base import BaseMixin from .collection import CollectionMixin from .contains import ContainsMixin from .date import DateMixin from .dict import DictMixin from .dynamic import DynamicMixin from .extracting import ExtractingMixin from .exception import ExceptionMixin from .file import FileMixin from .helpers import HelpersMixin from .numeric import NumericMixin from .snapshot import SnapshotMixin from .string import StringMixin __version__ = '1.1' __tracebackhide__ = True # clean tracebacks via py.test integration contextlib.__tracebackhide__ = True # monkey patch contextlib with clean py.test tracebacks # assertpy files ASSERTPY_FILES = [os.path.join('assertpy', file) for file in [ 'assertpy.py', 'base.py', 'collection.py', 'contains.py', 'date.py', 'dict.py', 'dynamic.py', 'exception.py', 'extracting.py', 'file.py', 'helpers.py', 'numeric.py', 'snapshot.py', 'string.py' ]] # soft assertions _soft_ctx = 0 _soft_err = [] @contextlib.contextmanager def soft_assertions(): """Create a soft assertion context. Normally, any assertion failure will halt test execution immediately by raising an error. Soft assertions are way to collect assertion failures (and failure messages) together, to be raised all at once at the end, without halting your test. Examples: Create a soft assertion context, and some failing tests:: from assertpy import assert_that, soft_assertions with soft_assertions(): assert_that('foo').is_length(4) assert_that('foo').is_empty() assert_that('foo').is_false() assert_that('foo').is_digit() assert_that('123').is_alpha() When the context ends, any assertion failures are collected together and a single ``AssertionError`` is raised:: AssertionError: soft assertion failures: 1. Expected <foo> to be of length <4>, but was <3>. 2. Expected <foo> to be empty string, but was not. 3. Expected <False>, but was not. 4. Expected <foo> to contain only digits, but did not. 5. Expected <123> to contain only alphabetic chars, but did not. Note: The soft assertion context only collects *assertion* failures, other errors such as ``TypeError`` or ``ValueError`` are always raised immediately. Triggering an explicit test failure with :meth:`fail` will similarly halt execution immediately. If you need more forgiving behavior, use :meth:`soft_fail` to add a failure message without halting test execution. """ global _soft_ctx global _soft_err # init ctx if _soft_ctx == 0: _soft_err = [] _soft_ctx += 1 try: yield finally: # reset ctx _soft_ctx -= 1 if _soft_err and _soft_ctx == 0: out = 'soft assertion failures:' for i, msg in enumerate(_soft_err): out += '\n%d. %s' % (i+1, msg) # reset msg, then raise _soft_err = [] raise AssertionError(out) # factory methods def assert_that(val, description=''): """Set the value to be tested, plus an optional description, and allow assertions to be called. This is a factory method for the :class:`AssertionBuilder`, and the single most important method in all of assertpy. Args: val: the value to be tested (aka the actual value) description (str, optional): the extra error message description. Defaults to ``''`` (aka empty string) Examples: Just import it once at the top of your test file, and away you go...:: from assertpy import assert_that def test_something(): assert_that(1 + 2).is_equal_to(3) assert_that('foobar').is_length(6).starts_with('foo').ends_with('bar') assert_that(['a', 'b', 'c']).contains('a').does_not_contain('x') """ global _soft_ctx if _soft_ctx: return _builder(val, description, 'soft') return _builder(val, description) def assert_warn(val, description='', logger=None): """Set the value to be tested, and optional description and logger, and allow assertions to be called, but never fail, only log warnings. This is a factory method for the :class:`AssertionBuilder`, but unlike :meth:`assert_that` an `AssertionError` is never raised, and execution is never halted. Instead, any assertion failures results in a warning message being logged. Uses the given logger, or defaults to a simple logger that prints warnings to ``stdout``. Args: val: the value to be tested (aka the actual value) description (str, optional): the extra error message description. Defaults to ``''`` (aka empty string) logger (Logger, optional): the logger for warning message on assertion failure. Defaults to ``None`` (aka use the default simple logger that prints warnings to ``stdout``) Examples: Usage:: from assertpy import assert_warn assert_warn('foo').is_length(4) assert_warn('foo').is_empty() assert_warn('foo').is_false() assert_warn('foo').is_digit() assert_warn('123').is_alpha() Even though all of the above assertions fail, ``AssertionError`` is never raised and test execution is never halted. Instead, the failed assertions merely log the following warning messages to ``stdout``:: 2019-10-27 20:00:35 WARNING [test_foo.py:23]: Expected <foo> to be of length <4>, but was <3>. 2019-10-27 20:00:35 WARNING [test_foo.py:24]: Expected <foo> to be empty string, but was not. 2019-10-27 20:00:35 WARNING [test_foo.py:25]: Expected <False>, but was not. 2019-10-27 20:00:35 WARNING [test_foo.py:26]: Expected <foo> to contain only digits, but did not. 2019-10-27 20:00:35 WARNING [test_foo.py:27]: Expected <123> to contain only alphabetic chars, but did not. Tip: Use :meth:`assert_warn` if and only if you have a *really* good reason to log assertion failures instead of failing. """ return _builder(val, description, 'warn', logger=logger) def fail(msg=''): """Force immediate test failure with the given message. Args: msg (str, optional): the failure message. Defaults to ``''`` Examples: Fail a test:: from assertpy import assert_that, fail def test_fail(): fail('forced fail!') If you wanted to test for a known failure, here is a useful pattern:: import operator def test_adder_bad_arg(): try: operator.add(1, 'bad arg') fail('should have raised error') except TypeError as e: assert_that(str(e)).contains('unsupported operand') """ raise AssertionError('Fail: %s!' % msg if msg else 'Fail!') def soft_fail(msg=''): """Within a :meth:`soft_assertions` context, append the failure message to the soft error list, but do not halt test execution. Otherwise, outside the context, acts identical to :meth:`fail` and forces immediate test failure with the given message. Args: msg (str, optional): the failure message. Defaults to ``''`` Examples: Failing soft assertions:: from assertpy import assert_that, soft_assertions, soft_fail with soft_assertions(): assert_that(1).is_equal_to(2) soft_fail('my message') assert_that('foo').is_equal_to('bar') Fails, and outputs the following soft error list:: AssertionError: soft assertion failures: 1. Expected <1> to be equal to <2>, but was not. 2. Fail: my message! 3. Expected <foo> to be equal to <bar>, but was not. """ global _soft_ctx if _soft_ctx: global _soft_err _soft_err.append('Fail: %s!' % msg if msg else 'Fail!') return fail(msg) # assertion extensions _extensions = {} def add_extension(func): """Add a new user-defined custom assertion to assertpy. Once the assertion is registered with assertpy, use it like any other assertion. Pass val to :meth:`assert_that`, and then call it. Args: func: the assertion function (to be added) Examples: Usage:: from assertpy import add_extension def is_5(self): if self.val != 5: return self.error(f'{self.val} is NOT 5!') return self add_extension(is_5) def test_5(): assert_that(5).is_5() def test_6(): assert_that(6).is_5() # fails # 6 is NOT 5! """ if not callable(func): raise TypeError('func must be callable') _extensions[func.__name__] = func def remove_extension(func): """Remove a user-defined custom assertion. Args: func: the assertion function (to be removed) Examples: Usage:: from assertpy import remove_extension remove_extension(is_5) """ if not callable(func): raise TypeError('func must be callable') if func.__name__ in _extensions: del _extensions[func.__name__] def _builder(val, description='', kind=None, expected=None, logger=None): """Internal helper to build a new :class:`AssertionBuilder` instance and glue on any extension methods.""" ab = AssertionBuilder(val, description, kind, expected, logger) if _extensions: # glue extension method onto new builder instance for name, func in _extensions.items(): meth = types.MethodType(func, ab) setattr(ab, name, meth) return ab # warnings class WarningLoggingAdapter(logging.LoggerAdapter): """Logging adapter to unwind the stack to get the correct callee filename and line number.""" def process(self, msg, kwargs): def _unwind(frame): # walk all the frames frames = [] while frame: frames.append((frame.f_code.co_filename, frame.f_lineno)) frame = frame.f_back # in reverse, find the first assertpy frame (and return the previous one) prev = None for frame in reversed(frames): for f in ASSERTPY_FILES: if frame[0].endswith(f): return prev prev = frame filename, lineno = _unwind(inspect.currentframe()) return '[%s:%d]: %s' % (os.path.basename(filename), lineno, msg), kwargs _logger = logging.getLogger('assertpy') _handler = logging.StreamHandler(sys.stdout) _handler.setLevel(logging.WARNING) _format = logging.Formatter('%(asctime)s %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S') _handler.setFormatter(_format) _logger.addHandler(_handler) _default_logger = WarningLoggingAdapter(_logger, None) class AssertionBuilder( StringMixin, SnapshotMixin, NumericMixin, HelpersMixin, FileMixin, ExtractingMixin, ExceptionMixin, DynamicMixin, DictMixin, DateMixin, ContainsMixin, CollectionMixin, BaseMixin, object ): """The main assertion class. Never call the constructor directly, always use the :meth:`assert_that` helper instead. Or if you just want warning messages, use the :meth:`assert_warn` helper. Args: val: the value to be tested (aka the actual value) description (str, optional): the extra error message description. Defaults to ``''`` (aka empty string) kind (str, optional): the kind of assertions, one of ``None``, ``soft``, or ``warn``. Defaults to ``None`` expected (Error, optional): the expected exception. Defaults to ``None`` logger (Logger, optional): the logger for warning messages. Defaults to ``None`` """ def __init__(self, val, description='', kind=None, expected=None, logger=None): """Never call this constructor directly.""" self.val = val self.description = description self.kind = kind self.expected = expected self.logger = logger if logger else _default_logger def builder(self, val, description='', kind=None, expected=None, logger=None): """Helper to build a new :class:`AssertionBuilder` instance. Use this only if not chaining to ``self``. Args: val: the value to be tested (aka the actual value) description (str, optional): the extra error message description. Defaults to ``''`` (aka empty string) kind (str, optional): the kind of assertions, one of ``None``, ``soft``, or ``warn``. Defaults to ``None`` expected (Error, optional): the expected exception. Defaults to ``None`` logger (Logger, optional): the logger for warning messages. Defaults to ``None`` """ return _builder(val, description, kind, expected, logger) def error(self, msg): """Helper to raise an ``AssertionError`` with the given message. If an error description is set by :meth:`~assertpy.base.BaseMixin.described_as`, then that description is prepended to the error message. Args: msg: the error message Examples: Used to fail an assertion:: if self.val != other: return self.error('Expected <%s> to be equal to <%s>, but was not.' % (self.val, other)) Raises: AssertionError: always raised unless ``kind`` is ``warn`` (as set when using an :meth:`assert_warn` assertion) or ``kind`` is ``soft`` (as set when inside a :meth:`soft_assertions` context). Returns: AssertionBuilder: returns this instance to chain to the next assertion, but only when ``AssertionError`` is not raised, as is the case when ``kind`` is ``warn`` or ``soft``. """ out = '%s%s' % ('[%s] ' % self.description if len(self.description) > 0 else '', msg) if self.kind == 'warn': self.logger.warning(out) return self elif self.kind == 'soft': global _soft_err _soft_err.append(out) return self else: raise AssertionError(out)
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,335
assertpy/assertpy
refs/heads/main
/tests/test_file.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import os import pytest from assertpy import assert_that, contents_of, fail @pytest.fixture() def tmpfile(tmpdir): tmp = tmpdir.join('test.txt') tmp.write('foobar'.encode('utf-8')) with tmp.open('rb') as f: yield f def test_contents_of_path(tmpfile): contents = contents_of(tmpfile.name) assert_that(contents).is_equal_to('foobar').starts_with('foo').ends_with('bar') def test_contents_of_path_ascii(tmpfile): contents = contents_of(tmpfile.name, 'ascii') assert_that(contents).is_equal_to('foobar').starts_with('foo').ends_with('bar') def test_contents_of_return_type(tmpfile): if sys.version_info[0] == 3: contents = contents_of(tmpfile.name) assert_that(contents).is_type_of(str) else: contents = contents_of(tmpfile.name) assert_that(contents).is_type_of(unicode) def test_contents_of_return_type_ascii(tmpfile): if sys.version_info[0] == 3: contents = contents_of(tmpfile.name, 'ascii') assert_that(contents).is_type_of(str) else: contents = contents_of(tmpfile.name, 'ascii') assert_that(contents).is_type_of(str) def test_contents_of_file(tmpfile): contents = contents_of(tmpfile) assert_that(contents).is_equal_to('foobar').starts_with('foo').ends_with('bar') def test_contents_of_file_ascii(tmpfile): contents = contents_of(tmpfile, 'ascii') assert_that(contents).is_equal_to('foobar').starts_with('foo').ends_with('bar') def test_contains_of_bad_type_failure(tmpfile): try: contents_of(123) fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('val must be file or path, but was type <int>') def test_contains_of_missing_file_failure(tmpfile): try: contents_of('missing.txt') fail('should have raised error') except IOError as ex: assert_that(str(ex)).contains_ignoring_case('no such file') def test_exists(tmpfile): assert_that(tmpfile.name).exists() assert_that(os.path.dirname(tmpfile.name)).exists() def test_exists_failure(tmpfile): try: assert_that('missing.txt').exists() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <missing.txt> to exist, but was not found.') def test_exists_bad_val_failure(tmpfile): try: assert_that(123).exists() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not a path') def test_does_not_exist(): assert_that('missing.txt').does_not_exist() def test_does_not_exist_failure(tmpfile): try: assert_that(tmpfile.name).does_not_exist() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <{}> to not exist, but was found.'.format(tmpfile.name)) def test_does_not_exist_bad_val_failure(tmpfile): try: assert_that(123).does_not_exist() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not a path') def test_is_file(tmpfile): assert_that(tmpfile.name).is_file() def test_is_file_exists_failure(): try: assert_that('missing.txt').is_file() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <missing.txt> to exist, but was not found.') def test_is_file_directory_failure(tmpfile): try: dirname = os.path.dirname(tmpfile.name) assert_that(dirname).is_file() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches('Expected <.*> to be a file, but was not.') def test_is_directory(tmpfile): dirname = os.path.dirname(tmpfile.name) assert_that(dirname).is_directory() def test_is_directory_exists_failure(): try: assert_that('missing_dir').is_directory() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <missing_dir> to exist, but was not found.') def test_is_directory_file_failure(tmpfile): try: assert_that(tmpfile.name).is_directory() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches('Expected <.*> to be a directory, but was not.') def test_is_named(tmpfile): basename = os.path.basename(tmpfile.name) assert_that(tmpfile.name).is_named(basename) def test_is_named_failure(tmpfile): try: assert_that(tmpfile.name).is_named('foo.txt') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches('Expected filename <.*> to be equal to <foo.txt>, but was not.') def test_is_named_bad_arg_type_failure(tmpfile): try: assert_that(tmpfile.name).is_named(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).matches('given filename arg must be a path') def test_is_child_of(tmpfile): dirname = os.path.dirname(tmpfile.name) assert_that(tmpfile.name).is_child_of(dirname) def test_is_child_of_failure(tmpfile): try: assert_that(tmpfile.name).is_child_of('foo_dir') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches(r'Expected file <.*> to be a child of <.*[\\/]foo_dir>, but was not.') def test_is_child_of_bad_arg_type_failure(tmpfile): try: assert_that(tmpfile.name).is_child_of(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).matches('given parent directory arg must be a path')
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,336
assertpy/assertpy
refs/heads/main
/assertpy/base.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. __tracebackhide__ = True class BaseMixin(object): """Base mixin.""" def described_as(self, description): """Describes the assertion. On failure, the description is included in the error message. This is not an assertion itself. But if the any of the following chained assertions fail, the description will be included in addition to the regular error message. Args: description: the error message description Examples: Usage:: assert_that(1).described_as('error msg desc').is_equal_to(2) # fails # [error msg desc] Expected <1> to be equal to <2>, but was not. Returns: AssertionBuilder: returns this instance to chain to the next assertion """ self.description = str(description) return self def is_equal_to(self, other, **kwargs): """Asserts that val is equal to other. Checks actual is equal to expected using the ``==`` operator. When val is *dict-like*, optionally ignore or include keys when checking equality. Args: other: the expected value **kwargs: see below Keyword Args: ignore: the dict key (or list of keys) to ignore include: the dict key (of list of keys) to include Examples: Usage:: assert_that(1 + 2).is_equal_to(3) assert_that('foo').is_equal_to('foo') assert_that(123).is_equal_to(123) assert_that(123.4).is_equal_to(123.4) assert_that(['a', 'b']).is_equal_to(['a', 'b']) assert_that((1, 2, 3)).is_equal_to((1, 2, 3)) assert_that({'a': 1, 'b': 2}).is_equal_to({'a': 1, 'b': 2}) assert_that({'a', 'b'}).is_equal_to({'a', 'b'}) When the val is *dict-like*, keys can optionally be *ignored* when checking equality:: # ignore a single key assert_that({'a': 1, 'b': 2}).is_equal_to({'a': 1}, ignore='b') # ignore multiple keys assert_that({'a': 1, 'b': 2, 'c': 3}).is_equal_to({'a': 1}, ignore=['b', 'c']) # ignore nested keys assert_that({'a': {'b': 2, 'c': 3, 'd': 4}}).is_equal_to({'a': {'d': 4}}, ignore=[('a', 'b'), ('a', 'c')]) When the val is *dict-like*, only certain keys can be *included* when checking equality:: # include a single key assert_that({'a': 1, 'b': 2}).is_equal_to({'a': 1}, include='a') # include multiple keys assert_that({'a': 1, 'b': 2, 'c': 3}).is_equal_to({'a': 1, 'b': 2}, include=['a', 'b']) Failure produces a nice error message:: assert_that(1).is_equal_to(2) # fails # Expected <1> to be equal to <2>, but was not. Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if actual is **not** equal to expected Tip: Using :meth:`is_equal_to` with a ``float`` val is just asking for trouble. Instead, you'll always want to use *fuzzy* numeric assertions like :meth:`~assertpy.numeric.NumericMixin.is_close_to` or :meth:`~assertpy.numeric.NumericMixin.is_between`. See Also: :meth:`~assertpy.string.StringMixin.is_equal_to_ignoring_case` - for case-insensitive string equality """ if self._check_dict_like(self.val, check_values=False, return_as_bool=True) and \ self._check_dict_like(other, check_values=False, return_as_bool=True): if self._dict_not_equal(self.val, other, ignore=kwargs.get('ignore'), include=kwargs.get('include')): self._dict_err(self.val, other, ignore=kwargs.get('ignore'), include=kwargs.get('include')) else: if self.val != other: return self.error('Expected <%s> to be equal to <%s>, but was not.' % (self.val, other)) return self def is_not_equal_to(self, other): """Asserts that val is not equal to other. Checks actual is not equal to expected using the ``!=`` operator. Args: other: the expected value Examples: Usage:: assert_that(1 + 2).is_not_equal_to(4) assert_that('foo').is_not_equal_to('bar') assert_that(123).is_not_equal_to(456) assert_that(123.4).is_not_equal_to(567.8) assert_that(['a', 'b']).is_not_equal_to(['c', 'd']) assert_that((1, 2, 3)).is_not_equal_to((1, 2, 4)) assert_that({'a': 1, 'b': 2}).is_not_equal_to({'a': 1, 'b': 3}) assert_that({'a', 'b'}).is_not_equal_to({'a', 'x'}) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if actual **is** equal to expected """ if self.val == other: return self.error('Expected <%s> to be not equal to <%s>, but was.' % (self.val, other)) return self def is_same_as(self, other): """Asserts that val is identical to other. Checks actual is identical to expected using the ``is`` operator. Args: other: the expected value Examples: Basic types are identical:: assert_that(1).is_same_as(1) assert_that('foo').is_same_as('foo') assert_that(123.4).is_same_as(123.4) As are immutables like ``tuple``:: assert_that((1, 2, 3)).is_same_as((1, 2, 3)) But mutable collections like ``list``, ``dict``, and ``set`` are not:: # these all fail... assert_that(['a', 'b']).is_same_as(['a', 'b']) # fails assert_that({'a': 1, 'b': 2}).is_same_as({'a': 1, 'b': 2}) # fails assert_that({'a', 'b'}).is_same_as({'a', 'b'}) # fails Unless they are the same object:: x = {'a': 1, 'b': 2} y = x assert_that(x).is_same_as(y) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if actual is **not** identical to expected """ if self.val is not other: return self.error('Expected <%s> to be identical to <%s>, but was not.' % (self.val, other)) return self def is_not_same_as(self, other): """Asserts that val is not identical to other. Checks actual is not identical to expected using the ``is`` operator. Args: other: the expected value Examples: Usage:: assert_that(1).is_not_same_as(2) assert_that('foo').is_not_same_as('bar') assert_that(123.4).is_not_same_as(567.8) assert_that((1, 2, 3)).is_not_same_as((1, 2, 4)) # mutable collections, even if equal, are not identical... assert_that(['a', 'b']).is_not_same_as(['a', 'b']) assert_that({'a': 1, 'b': 2}).is_not_same_as({'a': 1, 'b': 2}) assert_that({'a', 'b'}).is_not_same_as({'a', 'b'}) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if actual **is** identical to expected """ if self.val is other: return self.error('Expected <%s> to be not identical to <%s>, but was.' % (self.val, other)) return self def is_true(self): """Asserts that val is true. Examples: Usage:: assert_that(True).is_true() assert_that(1).is_true() assert_that('foo').is_true() assert_that(1.0).is_true() assert_that(['a', 'b']).is_true() assert_that((1, 2, 3)).is_true() assert_that({'a': 1, 'b': 2}).is_true() assert_that({'a', 'b'}).is_true() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val **is** false """ if not self.val: return self.error('Expected <True>, but was not.') return self def is_false(self): """Asserts that val is false. Examples: Usage:: assert_that(False).is_false() assert_that(0).is_false() assert_that('').is_false() assert_that(0.0).is_false() assert_that([]).is_false() assert_that(()).is_false() assert_that({}).is_false() assert_that(set()).is_false() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val **is** true """ if self.val: return self.error('Expected <False>, but was not.') return self def is_none(self): """Asserts that val is none. Examples: Usage:: assert_that(None).is_none() assert_that(print('hello world')).is_none() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** none """ if self.val is not None: return self.error('Expected <%s> to be <None>, but was not.' % self.val) return self def is_not_none(self): """Asserts that val is not none. Examples: Usage:: assert_that(0).is_not_none() assert_that('foo').is_not_none() assert_that(False).is_not_none() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val **is** none """ if self.val is None: return self.error('Expected not <None>, but was.') return self def _type(self, val): if hasattr(val, '__name__'): return val.__name__ elif hasattr(val, '__class__'): return val.__class__.__name__ return 'unknown' def is_type_of(self, some_type): """Asserts that val is of the given type. Args: some_type (type): the expected type Examples: Usage:: assert_that(1).is_type_of(int) assert_that('foo').is_type_of(str) assert_that(123.4).is_type_of(float) assert_that(['a', 'b']).is_type_of(list) assert_that((1, 2, 3)).is_type_of(tuple) assert_that({'a': 1, 'b': 2}).is_type_of(dict) assert_that({'a', 'b'}).is_type_of(set) assert_that(True).is_type_of(bool) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** of the given type """ if type(some_type) is not type and not issubclass(type(some_type), type): raise TypeError('given arg must be a type') if type(self.val) is not some_type: t = self._type(self.val) return self.error('Expected <%s:%s> to be of type <%s>, but was not.' % (self.val, t, some_type.__name__)) return self def is_instance_of(self, some_class): """Asserts that val is an instance of the given class. Args: some_class: the expected class Examples: Usage:: assert_that(1).is_instance_of(int) assert_that('foo').is_instance_of(str) assert_that(123.4).is_instance_of(float) assert_that(['a', 'b']).is_instance_of(list) assert_that((1, 2, 3)).is_instance_of(tuple) assert_that({'a': 1, 'b': 2}).is_instance_of(dict) assert_that({'a', 'b'}).is_instance_of(set) assert_that(True).is_instance_of(bool) With a user-defined class:: class Foo: pass f = Foo() assert_that(f).is_instance_of(Foo) assert_that(f).is_instance_of(object) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** an instance of the given class """ try: if not isinstance(self.val, some_class): t = self._type(self.val) return self.error('Expected <%s:%s> to be instance of class <%s>, but was not.' % (self.val, t, some_class.__name__)) except TypeError: raise TypeError('given arg must be a class') return self def is_length(self, length): """Asserts that val is the given length. Checks val is the given length using the ``len()`` built-in. Args: length (int): the expected length Examples: Usage:: assert_that('foo').is_length(3) assert_that(['a', 'b']).is_length(2) assert_that((1, 2, 3)).is_length(3) assert_that({'a': 1, 'b': 2}).is_length(2) assert_that({'a', 'b'}).is_length(2) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** the given length """ if type(length) is not int: raise TypeError('given arg must be an int') if length < 0: raise ValueError('given arg must be a positive int') if len(self.val) != length: return self.error('Expected <%s> to be of length <%d>, but was <%d>.' % (self.val, length, len(self.val))) return self
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,337
assertpy/assertpy
refs/heads/main
/tests/test_equals.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from assertpy import assert_that, fail def test_is_equal(): assert_that('foo').is_equal_to('foo') assert_that(123).is_equal_to(123) assert_that(0.11).is_equal_to(0.11) assert_that(['a', 'b']).is_equal_to(['a', 'b']) assert_that((1, 2, 3)).is_equal_to((1, 2, 3)) assert_that(1 == 1).is_equal_to(True) assert_that(1 == 2).is_equal_to(False) assert_that(set(['a', 'b'])).is_equal_to(set(['b', 'a'])) assert_that({'a': 1, 'b': 2}).is_equal_to({'b': 2, 'a': 1}) def test_is_equal_failure(): try: assert_that('foo').is_equal_to('bar') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <foo> to be equal to <bar>, but was not.') def test_is_equal_int_failure(): try: assert_that(123).is_equal_to(234) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <123> to be equal to <234>, but was not.') def test_is_equal_list_failure(): try: assert_that(['a', 'b']).is_equal_to(['a', 'b', 'c']) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <['a', 'b']> to be equal to <['a', 'b', 'c']>, but was not.") def test_is_not_equal(): assert_that('foo').is_not_equal_to('bar') assert_that(123).is_not_equal_to(234) assert_that(0.11).is_not_equal_to(0.12) assert_that(['a', 'b']).is_not_equal_to(['a', 'x']) assert_that(['a', 'b']).is_not_equal_to(['a']) assert_that(['a', 'b']).is_not_equal_to(['a', 'b', 'c']) assert_that((1, 2, 3)).is_not_equal_to((1, 2)) assert_that(1 == 1).is_not_equal_to(False) assert_that(1 == 2).is_not_equal_to(True) assert_that(set(['a', 'b'])).is_not_equal_to(set(['a'])) assert_that({'a': 1, 'b': 2}).is_not_equal_to({'a': 1, 'b': 3}) assert_that({'a': 1, 'b': 2}).is_not_equal_to({'a': 1, 'c': 2}) def test_is_not_equal_failure(): try: assert_that('foo').is_not_equal_to('foo') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <foo> to be not equal to <foo>, but was.') def test_is_not_equal_int_failure(): try: assert_that(123).is_not_equal_to(123) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <123> to be not equal to <123>, but was.') def test_is_not_equal_list_failure(): try: assert_that(['a', 'b']).is_not_equal_to(['a', 'b']) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <['a', 'b']> to be not equal to <['a', 'b']>, but was.")
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,338
assertpy/assertpy
refs/heads/main
/tests/test_soft.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from assertpy import assert_that, soft_assertions, fail def test_success(): with soft_assertions(): assert_that('foo').is_length(3) assert_that('foo').is_not_empty() assert_that('foo').is_true() assert_that('foo').is_alpha() assert_that('123').is_digit() assert_that('foo').is_lower() assert_that('FOO').is_upper() assert_that('foo').is_equal_to('foo') assert_that('foo').is_not_equal_to('bar') assert_that('foo').is_equal_to_ignoring_case('FOO') assert_that({'a': 1}).has_a(1) def test_failure(): try: with soft_assertions(): assert_that('foo').is_length(4) assert_that('foo').is_empty() assert_that('foo').is_false() assert_that('foo').is_digit() assert_that('123').is_alpha() assert_that('foo').is_upper() assert_that('FOO').is_lower() assert_that('foo').is_equal_to('bar') assert_that('foo').is_not_equal_to('foo') assert_that('foo').is_equal_to_ignoring_case('BAR') assert_that({'a': 1}).has_a(2) assert_that({'a': 1}).has_foo(1) fail('should have raised error') except AssertionError as e: out = str(e) assert_that(out).contains('Expected <foo> to be of length <4>, but was <3>.') assert_that(out).contains('Expected <foo> to be empty string, but was not.') assert_that(out).contains('Expected <False>, but was not.') assert_that(out).contains('Expected <foo> to contain only digits, but did not.') assert_that(out).contains('Expected <123> to contain only alphabetic chars, but did not.') assert_that(out).contains('Expected <foo> to contain only uppercase chars, but did not.') assert_that(out).contains('Expected <FOO> to contain only lowercase chars, but did not.') assert_that(out).contains('Expected <foo> to be equal to <bar>, but was not.') assert_that(out).contains('Expected <foo> to be not equal to <foo>, but was.') assert_that(out).contains('Expected <foo> to be case-insensitive equal to <BAR>, but was not.') assert_that(out).contains('Expected <1> to be equal to <2> on key <a>, but was not.') assert_that(out).contains('Expected key <foo>, but val has no key <foo>.') def test_failure_chain(): try: with soft_assertions(): assert_that('foo').is_length(4).is_empty().is_false().is_digit().is_upper() \ .is_equal_to('bar').is_not_equal_to('foo').is_equal_to_ignoring_case('BAR') fail('should have raised error') except AssertionError as e: out = str(e) assert_that(out).contains('Expected <foo> to be of length <4>, but was <3>.') assert_that(out).contains('Expected <foo> to be empty string, but was not.') assert_that(out).contains('Expected <False>, but was not.') assert_that(out).contains('Expected <foo> to contain only digits, but did not.') assert_that(out).contains('Expected <foo> to contain only uppercase chars, but did not.') assert_that(out).contains('Expected <foo> to be equal to <bar>, but was not.') assert_that(out).contains('Expected <foo> to be not equal to <foo>, but was.') assert_that(out).contains('Expected <foo> to be case-insensitive equal to <BAR>, but was not.') def test_expected_exception_success(): with soft_assertions(): assert_that(func_err).raises(RuntimeError).when_called_with('foo').is_equal_to('err') def test_expected_exception_failure(): try: with soft_assertions(): assert_that(func_err).raises(RuntimeError).when_called_with('foo').is_equal_to('bar') assert_that(func_ok).raises(RuntimeError).when_called_with('baz') fail('should have raised error') except AssertionError as e: out = str(e) assert_that(out).contains('Expected <err> to be equal to <bar>, but was not.') assert_that(out).contains("Expected <func_ok> to raise <RuntimeError> when called with ('baz').") def func_ok(arg): pass def func_err(arg): raise RuntimeError('err') def test_fail(): try: with soft_assertions(): fail() fail('should have raised error') except AssertionError as e: out = str(e) assert_that(out).is_equal_to('Fail!') def test_fail_with_msg(): try: with soft_assertions(): fail('foobar') fail('should have raised error') except AssertionError as e: out = str(e) assert_that(out).is_equal_to('Fail: foobar!') def test_fail_with_soft_failing_asserts(): try: with soft_assertions(): assert_that('foo').is_length(4) assert_that('foo').is_empty() fail('foobar') assert_that('foo').is_not_equal_to('foo') assert_that('foo').is_equal_to_ignoring_case('BAR') fail('should have raised error') except AssertionError as e: out = str(e) assert_that(out).is_equal_to('Fail: foobar!') assert_that(out).does_not_contain('Expected <foo> to be of length <4>, but was <3>.') assert_that(out).does_not_contain('Expected <foo> to be empty string, but was not.') assert_that(out).does_not_contain('Expected <foo> to be not equal to <foo>, but was.') assert_that(out).does_not_contain('Expected <foo> to be case-insensitive equal to <BAR>, but was not.') def test_double_fail(): try: with soft_assertions(): fail() fail('foobar') fail('should have raised error') except AssertionError as e: out = str(e) assert_that(out).is_equal_to('Fail!') def test_nested(): try: with soft_assertions(): assert_that('a').is_equal_to('A') with soft_assertions(): assert_that('b').is_equal_to('B') with soft_assertions(): assert_that('c').is_equal_to('C') assert_that('b').is_equal_to('B2') assert_that('a').is_equal_to('A2') fail('should have raised error') except AssertionError as e: out = str(e) assert_that(out).contains('1. Expected <a> to be equal to <A>, but was not.') assert_that(out).contains('2. Expected <b> to be equal to <B>, but was not.') assert_that(out).contains('3. Expected <c> to be equal to <C>, but was not.') assert_that(out).contains('4. Expected <b> to be equal to <B2>, but was not.') assert_that(out).contains('5. Expected <a> to be equal to <A2>, but was not.') def test_recursive_nesting(): def recurs(i): if i <= 0: return with soft_assertions(): recurs(i-1) assert_that(i).is_equal_to(7) try: recurs(10) except AssertionError as e: out = str(e) assert_that(out).contains('1. Expected <1> to be equal to <7>, but was not.') assert_that(out).contains('2. Expected <2> to be equal to <7>, but was not.') assert_that(out).contains('3. Expected <3> to be equal to <7>, but was not.') assert_that(out).contains('4. Expected <4> to be equal to <7>, but was not.') assert_that(out).contains('5. Expected <5> to be equal to <7>, but was not.') assert_that(out).contains('6. Expected <6> to be equal to <7>, but was not.')
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,339
assertpy/assertpy
refs/heads/main
/tests/test_datetime.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import datetime from assertpy import assert_that, fail d1 = datetime.datetime.today() def test_is_before(): d2 = datetime.datetime.today() assert_that(d1).is_before(d2) def test_is_before_failure(): try: d2 = datetime.datetime.today() assert_that(d2).is_before(d1) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches(r'Expected <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}> to be before <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}>, but was not.') def test_is_before_bad_val_type_failure(): try: assert_that(123).is_before(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val must be datetime, but was type <int>') def test_is_before_bad_arg_type_failure(): try: assert_that(d1).is_before(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be datetime, but was type <int>') def test_is_after(): d2 = datetime.datetime.today() assert_that(d2).is_after(d1) def test_is_after_failure(): try: d2 = datetime.datetime.today() assert_that(d1).is_after(d2) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches(r'Expected <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}> to be after <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}>, but was not.') def test_is_after_bad_val_type_failure(): try: assert_that(123).is_after(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val must be datetime, but was type <int>') def test_is_after_bad_arg_type_failure(): try: assert_that(d1).is_after(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be datetime, but was type <int>') def test_is_equal_to_ignoring_milliseconds(): assert_that(d1).is_equal_to_ignoring_milliseconds(d1) def test_is_equal_to_ignoring_milliseconds_failure(): try: d2 = datetime.datetime.today() + datetime.timedelta(days=1) assert_that(d1).is_equal_to_ignoring_milliseconds(d2) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches(r'Expected <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}> to be equal to <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}>, but was not.') def test_is_equal_to_ignoring_milliseconds_bad_val_type_failure(): try: assert_that(123).is_equal_to_ignoring_milliseconds(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val must be datetime, but was type <int>') def test_is_equal_to_ignoring_milliseconds_bad_arg_type_failure(): try: assert_that(d1).is_equal_to_ignoring_milliseconds(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be datetime, but was type <int>') def test_is_equal_to_ignoring_seconds(): assert_that(d1).is_equal_to_ignoring_seconds(d1) def test_is_equal_to_ignoring_seconds_failure(): try: d2 = datetime.datetime.today() + datetime.timedelta(days=1) assert_that(d1).is_equal_to_ignoring_seconds(d2) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches(r'Expected <\d{4}-\d{2}-\d{2} \d{2}:\d{2}> to be equal to <\d{4}-\d{2}-\d{2} \d{2}:\d{2}>, but was not.') def test_is_equal_to_ignoring_seconds_bad_val_type_failure(): try: assert_that(123).is_equal_to_ignoring_seconds(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val must be datetime, but was type <int>') def test_is_equal_to_ignoring_seconds_bad_arg_type_failure(): try: assert_that(d1).is_equal_to_ignoring_seconds(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be datetime, but was type <int>') def test_is_equal_to_ignoring_time(): assert_that(d1).is_equal_to_ignoring_time(d1) def test_is_equal_to_ignoring_time_failure(): try: d2 = datetime.datetime.today() + datetime.timedelta(days=1) assert_that(d1).is_equal_to_ignoring_time(d2) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches(r'Expected <\d{4}-\d{2}-\d{2}> to be equal to <\d{4}-\d{2}-\d{2}>, but was not.') def test_is_equal_to_ignoring_time_bad_val_type_failure(): try: assert_that(123).is_equal_to_ignoring_time(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val must be datetime, but was type <int>') def test_is_equal_to_ignoring_time_bad_arg_type_failure(): try: assert_that(d1).is_equal_to_ignoring_time(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be datetime, but was type <int>') def test_is_greater_than(): d2 = datetime.datetime.today() assert_that(d2).is_greater_than(d1) def test_is_greater_than_failure(): try: d2 = datetime.datetime.today() assert_that(d1).is_greater_than(d2) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches(r'Expected <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}> to be greater than <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}>, but was not.') def test_is_greater_than_bad_arg_type_failure(): try: assert_that(d1).is_greater_than(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be <datetime>, but was <int>') def test_is_greater_than_or_equal_to(): assert_that(d1).is_greater_than_or_equal_to(d1) def test_is_greater_than_or_equal_to_failure(): try: d2 = datetime.datetime.today() assert_that(d1).is_greater_than_or_equal_to(d2) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches( r'Expected <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}> to be greater than or equal to <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}>, but was not.') def test_is_greater_than_or_equal_to_bad_arg_type_failure(): try: assert_that(d1).is_greater_than_or_equal_to(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be <datetime>, but was <int>') def test_is_less_than(): d2 = datetime.datetime.today() assert_that(d1).is_less_than(d2) def test_is_less_than_failure(): try: d2 = datetime.datetime.today() assert_that(d2).is_less_than(d1) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches( r'Expected <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}> to be less than <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}>, but was not.') def test_is_less_than_bad_arg_type_failure(): try: assert_that(d1).is_less_than(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be <datetime>, but was <int>') def test_is_less_than_or_equal_to(): assert_that(d1).is_less_than_or_equal_to(d1) def test_is_less_than_or_equal_to_failure(): try: d2 = datetime.datetime.today() assert_that(d2).is_less_than_or_equal_to(d1) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches( r'Expected <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}> to be less than or equal to <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}>, but was not.') def test_is_less_than_or_equal_to_bad_arg_type_failure(): try: assert_that(d1).is_less_than_or_equal_to(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be <datetime>, but was <int>') def test_is_between(): d2 = datetime.datetime.today() d3 = datetime.datetime.today() assert_that(d2).is_between(d1, d3) def test_is_between_failure(): try: d2 = datetime.datetime.today() d3 = datetime.datetime.today() assert_that(d1).is_between(d2, d3) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches( r'Expected <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}> to be between ' + r'<\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}> and <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}>, but was not.') def test_is_between_bad_arg1_type_failure(): try: assert_that(d1).is_between(123, 456) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given low arg must be <datetime>, but was <int>') def test_is_between_bad_arg2_type_failure(): try: d2 = datetime.datetime.today() assert_that(d1).is_between(d2, 123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given high arg must be <datetime>, but was <datetime>') def test_is_not_between(): d2 = d1 + datetime.timedelta(minutes=5) d3 = d1 + datetime.timedelta(minutes=10) assert_that(d1).is_not_between(d2, d3) def test_is_not_between_failure(): try: d2 = d1 + datetime.timedelta(minutes=5) d3 = d1 + datetime.timedelta(minutes=10) assert_that(d2).is_not_between(d1, d3) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches( r'Expected <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}> to not be between ' + r'<\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}> and <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}>, but was.') def test_is_not_between_bad_arg1_type_failure(): try: assert_that(d1).is_not_between(123, 456) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given low arg must be <datetime>, but was <int>') def test_is_not_between_bad_arg2_type_failure(): try: d2 = datetime.datetime.today() assert_that(d1).is_not_between(d2, 123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given high arg must be <datetime>, but was <datetime>') def test_is_close_to(): d2 = datetime.datetime.today() assert_that(d1).is_close_to(d2, datetime.timedelta(minutes=5)) def test_is_close_to_failure(): try: d2 = d1 + datetime.timedelta(minutes=5) assert_that(d1).is_close_to(d2, datetime.timedelta(minutes=1)) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches( r'Expected <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}> to be close to ' + r'<\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}> within tolerance <\d+:\d+:\d+>, but was not.') def test_is_close_to_bad_arg_type_failure(): try: assert_that(d1).is_close_to(123, 456) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be datetime, but was <int>') def test_is_close_to_bad_tolerance_arg_type_failure(): try: d2 = datetime.datetime.today() assert_that(d1).is_close_to(d2, 123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given tolerance arg must be timedelta, but was <int>') def test_is_not_close_to(): d2 = d1 + datetime.timedelta(minutes=5) assert_that(d1).is_not_close_to(d2, datetime.timedelta(minutes=4)) def test_is_not_close_to_failure(): try: d2 = datetime.datetime.today() assert_that(d1).is_not_close_to(d2, datetime.timedelta(minutes=5)) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches( r'Expected <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}> to not be close to <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}> within tolerance <\d+:\d+:\d+>, but was.') def test_is_not_close_to_bad_arg_type_failure(): try: assert_that(d1).is_not_close_to(123, 456) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be datetime, but was <int>') def test_is_not_close_to_bad_tolerance_arg_type_failure(): try: d2 = datetime.datetime.today() assert_that(d1).is_not_close_to(d2, 123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given tolerance arg must be timedelta, but was <int>') t1 = datetime.timedelta(seconds=60) def test_is_greater_than_timedelta(): d2 = datetime.timedelta(seconds=120) assert_that(d2).is_greater_than(t1) def test_is_greater_than_timedelta_failure(): try: t2 = datetime.timedelta(seconds=90) assert_that(t1).is_greater_than(t2) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches( r'Expected <\d{1,2}:\d{2}:\d{2}> to be greater than <\d{1,2}:\d{2}:\d{2}>, but was not.') def test_is_greater_than_timedelta_bad_arg_type_failure(): try: assert_that(t1).is_greater_than(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be <timedelta>, but was <int>') def test_is_greater_than_or_equal_to_timedelta(): assert_that(t1).is_greater_than_or_equal_to(t1) def test_is_greater_than_or_equal_to_timedelta_failure(): try: t2 = datetime.timedelta(seconds=90) assert_that(t1).is_greater_than_or_equal_to(t2) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches( r'Expected <\d{1,2}:\d{2}:\d{2}> to be greater than or equal to <\d{1,2}:\d{2}:\d{2}>, but was not.') def test_is_greater_than_or_equal_to_timedelta_bad_arg_type_failure(): try: assert_that(t1).is_greater_than_or_equal_to(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be <timedelta>, but was <int>') def test_is_less_than_timedelta(): t2 = datetime.timedelta(seconds=90) assert_that(t1).is_less_than(t2) def test_is_less_than_timedelta_failure(): try: t2 = datetime.timedelta(seconds=90) assert_that(t2).is_less_than(t1) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches( r'Expected <\d{1,2}:\d{2}:\d{2}> to be less than <\d{1,2}:\d{2}:\d{2}>, but was not.') def test_is_less_than_timedelta_bad_arg_type_failure(): try: assert_that(t1).is_less_than(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be <timedelta>, but was <int>') def test_is_less_than_or_equal_to_timedelta(): assert_that(t1).is_less_than_or_equal_to(t1) def test_is_less_than_or_equal_to_timedelta_failure(): try: t2 = datetime.timedelta(seconds=90) assert_that(t2).is_less_than_or_equal_to(t1) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches( r'Expected <\d{1,2}:\d{2}:\d{2}> to be less than or equal to <\d{1,2}:\d{2}:\d{2}>, but was not.') def test_is_less_than_or_equal_to_timedelta_bad_arg_type_failure(): try: assert_that(t1).is_less_than_or_equal_to(123) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be <timedelta>, but was <int>') def test_is_between_timedelta(): d2 = datetime.timedelta(seconds=90) d3 = datetime.timedelta(seconds=120) assert_that(d2).is_between(t1, d3) def test_is_between_timedelta_failure(): try: d2 = datetime.timedelta(seconds=30) d3 = datetime.timedelta(seconds=40) assert_that(t1).is_between(d2, d3) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches( r'Expected <\d{1,2}:\d{2}:\d{2}> to be between <\d{1,2}:\d{2}:\d{2}> and <\d{1,2}:\d{2}:\d{2}>, but was not.') def test_is_not_between_timedelta(): d2 = datetime.timedelta(seconds=90) d3 = datetime.timedelta(seconds=120) assert_that(t1).is_not_between(d2, d3) def test_is_not_between_timedelta_failure(): try: d2 = datetime.timedelta(seconds=90) d3 = datetime.timedelta(seconds=120) assert_that(d2).is_not_between(t1, d3) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).matches( r'Expected <\d{1,2}:\d{2}:\d{2}> to not be between <\d{1,2}:\d{2}:\d{2}> and <\d{1,2}:\d{2}:\d{2}>, but was.')
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,340
assertpy/assertpy
refs/heads/main
/assertpy/numeric.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from __future__ import division import sys import math import numbers import datetime __tracebackhide__ = True class NumericMixin(object): """Numeric assertions mixin.""" _NUMERIC_COMPAREABLE = set([datetime.datetime, datetime.timedelta, datetime.date, datetime.time]) _NUMERIC_NON_COMPAREABLE = set([complex]) def _validate_compareable(self, other): self_type = type(self.val) other_type = type(other) if self_type in self._NUMERIC_NON_COMPAREABLE: raise TypeError('ordering is not defined for type <%s>' % self_type.__name__) if self_type in self._NUMERIC_COMPAREABLE: if other_type is not self_type: raise TypeError('given arg must be <%s>, but was <%s>' % (self_type.__name__, other_type.__name__)) return if isinstance(self.val, numbers.Number): if not isinstance(other, numbers.Number): raise TypeError('given arg must be a number, but was <%s>' % other_type.__name__) return raise TypeError('ordering is not defined for type <%s>' % self_type.__name__) def _validate_number(self): """Raise TypeError if val is not numeric.""" if isinstance(self.val, numbers.Number) is False: raise TypeError('val is not numeric') def _validate_real(self): """Raise TypeError if val is not real number.""" if isinstance(self.val, numbers.Real) is False: raise TypeError('val is not real number') def is_zero(self): """Asserts that val is numeric and is zero. Examples: Usage:: assert_that(0).is_zero() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** zero """ self._validate_number() return self.is_equal_to(0) def is_not_zero(self): """Asserts that val is numeric and is *not* zero. Examples: Usage:: assert_that(1).is_not_zero() assert_that(123.4).is_not_zero() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val **is** zero """ self._validate_number() return self.is_not_equal_to(0) def is_nan(self): """Asserts that val is real number and is ``NaN`` (not a number). Examples: Usage:: assert_that(float('nan')).is_nan() assert_that(float('inf') * 0).is_nan() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** NaN """ self._validate_number() self._validate_real() if not math.isnan(self.val): return self.error('Expected <%s> to be <NaN>, but was not.' % self.val) return self def is_not_nan(self): """Asserts that val is real number and is *not* ``NaN`` (not a number). Examples: Usage:: assert_that(0).is_not_nan() assert_that(123.4).is_not_nan() assert_that(float('inf')).is_not_nan() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val **is** NaN """ self._validate_number() self._validate_real() if math.isnan(self.val): return self.error('Expected not <NaN>, but was.') return self def is_inf(self): """Asserts that val is real number and is ``Inf`` (infinity). Examples: Usage:: assert_that(float('inf')).is_inf() assert_that(float('inf') * 1).is_inf() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** Inf """ self._validate_number() self._validate_real() if not math.isinf(self.val): return self.error('Expected <%s> to be <Inf>, but was not.' % self.val) return self def is_not_inf(self): """Asserts that val is real number and is *not* ``Inf`` (infinity). Examples: Usage:: assert_that(0).is_not_inf() assert_that(123.4).is_not_inf() assert_that(float('nan')).is_not_inf() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val **is** Inf """ self._validate_number() self._validate_real() if math.isinf(self.val): return self.error('Expected not <Inf>, but was.') return self def is_greater_than(self, other): """Asserts that val is numeric and is greater than other. Args: other: the other date, expected to be less than val Examples: Usage:: assert_that(1).is_greater_than(0) assert_that(123.4).is_greater_than(111.1) For dates, behavior is identical to :meth:`~assertpy.date.DateMixin.is_after`:: import datetime today = datetime.datetime.now() yesterday = today - datetime.timedelta(days=1) assert_that(today).is_greater_than(yesterday) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** greater than other """ self._validate_compareable(other) if self.val <= other: if type(self.val) is datetime.datetime: return self.error('Expected <%s> to be greater than <%s>, but was not.' % ( self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'))) else: return self.error('Expected <%s> to be greater than <%s>, but was not.' % (self.val, other)) return self def is_greater_than_or_equal_to(self, other): """Asserts that val is numeric and is greater than or equal to other. Args: other: the other date, expected to be less than or equal to val Examples: Usage:: assert_that(1).is_greater_than_or_equal_to(0) assert_that(1).is_greater_than_or_equal_to(1) assert_that(123.4).is_greater_than_or_equal_to(111.1) For dates, behavior is identical to :meth:`~assertpy.date.DateMixin.is_after` *except* when equal:: import datetime today = datetime.datetime.now() yesterday = today - datetime.timedelta(days=1) assert_that(today).is_greater_than_or_equal_to(yesterday) assert_that(today).is_greater_than_or_equal_to(today) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** greater than or equal to other """ self._validate_compareable(other) if self.val < other: if type(self.val) is datetime.datetime: return self.error('Expected <%s> to be greater than or equal to <%s>, but was not.' % ( self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'))) else: return self.error('Expected <%s> to be greater than or equal to <%s>, but was not.' % (self.val, other)) return self def is_less_than(self, other): """Asserts that val is numeric and is less than other. Args: other: the other date, expected to be greater than val Examples: Usage:: assert_that(0).is_less_than(1) assert_that(123.4).is_less_than(555.5) For dates, behavior is identical to :meth:`~assertpy.date.DateMixin.is_before`:: import datetime today = datetime.datetime.now() yesterday = today - datetime.timedelta(days=1) assert_that(yesterday).is_less_than(today) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** less than other """ self._validate_compareable(other) if self.val >= other: if type(self.val) is datetime.datetime: return self.error('Expected <%s> to be less than <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'))) else: return self.error('Expected <%s> to be less than <%s>, but was not.' % (self.val, other)) return self def is_less_than_or_equal_to(self, other): """Asserts that val is numeric and is less than or equal to other. Args: other: the other date, expected to be greater than or equal to val Examples: Usage:: assert_that(1).is_less_than_or_equal_to(0) assert_that(1).is_less_than_or_equal_to(1) assert_that(123.4).is_less_than_or_equal_to(100.0) For dates, behavior is identical to :meth:`~assertpy.date.DateMixin.is_before` *except* when equal:: import datetime today = datetime.datetime.now() yesterday = today - datetime.timedelta(days=1) assert_that(yesterday).is_less_than_or_equal_to(today) assert_that(today).is_less_than_or_equal_to(today) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** less than or equal to other """ self._validate_compareable(other) if self.val > other: if type(self.val) is datetime.datetime: return self.error('Expected <%s> to be less than or equal to <%s>, but was not.' % ( self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'))) else: return self.error('Expected <%s> to be less than or equal to <%s>, but was not.' % (self.val, other)) return self def is_positive(self): """Asserts that val is numeric and is greater than zero. Examples: Usage:: assert_that(1).is_positive() assert_that(123.4).is_positive() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** positive """ return self.is_greater_than(0) def is_negative(self): """Asserts that val is numeric and is less than zero. Examples: Usage:: assert_that(-1).is_negative() assert_that(-123.4).is_negative() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** negative """ return self.is_less_than(0) def is_between(self, low, high): """Asserts that val is numeric and is between low and high. Args: low: the low value high: the high value Examples: Usage:: assert_that(1).is_between(0, 2) assert_that(123.4).is_between(111.1, 222.2) For dates, works as expected:: import datetime today = datetime.datetime.now() middle = today - datetime.timedelta(hours=12) yesterday = today - datetime.timedelta(days=1) assert_that(middle).is_between(yesterday, today) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** between low and high """ val_type = type(self.val) self._validate_between_args(val_type, low, high) if self.val < low or self.val > high: if val_type is datetime.datetime: return self.error('Expected <%s> to be between <%s> and <%s>, but was not.' % ( self.val.strftime('%Y-%m-%d %H:%M:%S'), low.strftime('%Y-%m-%d %H:%M:%S'), high.strftime('%Y-%m-%d %H:%M:%S'))) else: return self.error('Expected <%s> to be between <%s> and <%s>, but was not.' % (self.val, low, high)) return self def is_not_between(self, low, high): """Asserts that val is numeric and is *not* between low and high. Args: low: the low value high: the high value Examples: Usage:: assert_that(1).is_not_between(2, 3) assert_that(1.1).is_not_between(2.2, 3.3) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val **is** between low and high """ val_type = type(self.val) self._validate_between_args(val_type, low, high) if self.val >= low and self.val <= high: if val_type is datetime.datetime: return self.error('Expected <%s> to not be between <%s> and <%s>, but was.' % ( self.val.strftime('%Y-%m-%d %H:%M:%S'), low.strftime('%Y-%m-%d %H:%M:%S'), high.strftime('%Y-%m-%d %H:%M:%S'))) else: return self.error('Expected <%s> to not be between <%s> and <%s>, but was.' % (self.val, low, high)) return self def is_close_to(self, other, tolerance): """Asserts that val is numeric and is close to other within tolerance. Args: other: the other value, expected to be close to val within tolerance tolerance: the tolerance Examples: Usage:: assert_that(123).is_close_to(100, 25) assert_that(123.4).is_close_to(123, 0.5) For dates, works as expected:: import datetime today = datetime.datetime.now() yesterday = today - datetime.timedelta(days=1) assert_that(today).is_close_to(yesterday, datetime.timedelta(hours=36)) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** close to other within tolerance """ self._validate_close_to_args(self.val, other, tolerance) if self.val < (other-tolerance) or self.val > (other+tolerance): if type(self.val) is datetime.datetime: tolerance_seconds = tolerance.days * 86400 + tolerance.seconds + tolerance.microseconds / 1000000 h, rem = divmod(tolerance_seconds, 3600) m, s = divmod(rem, 60) return self.error('Expected <%s> to be close to <%s> within tolerance <%d:%02d:%02d>, but was not.' % ( self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'), h, m, s)) else: return self.error('Expected <%s> to be close to <%s> within tolerance <%s>, but was not.' % (self.val, other, tolerance)) return self def is_not_close_to(self, other, tolerance): """Asserts that val is numeric and is *not* close to other within tolerance. Args: other: the other value tolerance: the tolerance Examples: Usage:: assert_that(123).is_not_close_to(100, 22) assert_that(123.4).is_not_close_to(123, 0.1) Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val **is** close to other within tolerance """ self._validate_close_to_args(self.val, other, tolerance) if self.val >= (other-tolerance) and self.val <= (other+tolerance): if type(self.val) is datetime.datetime: tolerance_seconds = tolerance.days * 86400 + tolerance.seconds + tolerance.microseconds / 1000000 h, rem = divmod(tolerance_seconds, 3600) m, s = divmod(rem, 60) return self.error('Expected <%s> to not be close to <%s> within tolerance <%d:%02d:%02d>, but was.' % ( self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'), h, m, s)) else: return self.error('Expected <%s> to not be close to <%s> within tolerance <%s>, but was.' % (self.val, other, tolerance)) return self
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,341
assertpy/assertpy
refs/heads/main
/assertpy/collection.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import collections if sys.version_info[0] == 3: Iterable = collections.abc.Iterable else: Iterable = collections.Iterable __tracebackhide__ = True class CollectionMixin(object): """Collection assertions mixin.""" def is_iterable(self): """Asserts that val is iterable collection. Examples: Usage:: assert_that('foo').is_iterable() assert_that(['a', 'b']).is_iterable() assert_that((1, 2, 3)).is_iterable() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** iterable """ if not isinstance(self.val, Iterable): return self.error('Expected iterable, but was not.') return self def is_not_iterable(self): """Asserts that val is not iterable collection. Examples: Usage:: assert_that(1).is_not_iterable() assert_that(123.4).is_not_iterable() assert_that(True).is_not_iterable() assert_that(None).is_not_iterable() Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val **is** iterable """ if isinstance(self.val, Iterable): return self.error('Expected not iterable, but was.') return self def is_subset_of(self, *supersets): """Asserts that val is iterable and a subset of the given superset (or supersets). Args: *supersets: the expected superset (or supersets) Examples: Usage:: assert_that('foo').is_subset_of('abcdefghijklmnopqrstuvwxyz') assert_that(['a', 'b']).is_subset_of(['a', 'b', 'c']) assert_that((1, 2, 3)).is_subset_of([1, 2, 3, 4]) assert_that({'a': 1, 'b': 2}).is_subset_of({'a': 1, 'b': 2, 'c': 3}) assert_that({'a', 'b'}).is_subset_of({'a', 'b', 'c'}) # or multiple supersets (as comma-separated args) assert_that('aBc').is_subset_of('abc', 'ABC') assert_that((1, 2, 3)).is_subset_of([1, 3, 5], [2, 4, 6]) assert_that({'a': 1, 'b': 2}).is_subset_of({'a': 1, 'c': 3}) # fails # Expected <{'a': 1, 'b': 2}> to be subset of <{'a': 1, 'c': 3}>, but <{'b': 2}> was missing. Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** subset of given superset (or supersets) """ if not isinstance(self.val, Iterable): raise TypeError('val is not iterable') if len(supersets) == 0: raise ValueError('one or more superset args must be given') missing = [] if hasattr(self.val, 'keys') and callable(getattr(self.val, 'keys')) and hasattr(self.val, '__getitem__'): # flatten superset dicts superdict = {} for l, j in enumerate(supersets): self._check_dict_like(j, check_values=False, name='arg #%d' % (l+1)) for k in j.keys(): superdict.update({k: j[k]}) for i in self.val.keys(): if i not in superdict: missing.append({i: self.val[i]}) # bad key elif self.val[i] != superdict[i]: missing.append({i: self.val[i]}) # bad val if missing: return self.error('Expected <%s> to be subset of %s, but %s %s missing.' % ( self.val, self._fmt_items(superdict), self._fmt_items(missing), 'was' if len(missing) == 1 else 'were')) else: # flatten supersets superset = set() for j in supersets: try: for k in j: superset.add(k) except Exception: superset.add(j) for i in self.val: if i not in superset: missing.append(i) if missing: return self.error('Expected <%s> to be subset of %s, but %s %s missing.' % ( self.val, self._fmt_items(superset), self._fmt_items(missing), 'was' if len(missing) == 1 else 'were')) return self def is_sorted(self, key=lambda x: x, reverse=False): """Asserts that val is iterable and is sorted. Args: key (function): the one-arg function to extract the sort comparison key. Defaults to ``lambda x: x`` to just compare items directly. reverse (bool): if ``True``, then comparison key is reversed. Defaults to ``False``. Examples: Usage:: assert_that(['a', 'b', 'c']).is_sorted() assert_that((1, 2, 3)).is_sorted() # with a key function assert_that('aBc').is_sorted(key=str.lower) # reverse order assert_that(['c', 'b', 'a']).is_sorted(reverse=True) assert_that((3, 2, 1)).is_sorted(reverse=True) assert_that((1, 2, 3, 4, -5, 6)).is_sorted() # fails # Expected <(1, 2, 3, 4, -5, 6)> to be sorted, but subset <4, -5> at index 3 is not. Returns: AssertionBuilder: returns this instance to chain to the next assertion Raises: AssertionError: if val is **not** sorted """ if not isinstance(self.val, Iterable): raise TypeError('val is not iterable') for i, x in enumerate(self.val): if i > 0: if reverse: if key(x) > key(prev): return self.error('Expected <%s> to be sorted reverse, but subset %s at index %s is not.' % (self.val, self._fmt_items([prev, x]), i-1)) else: if key(x) < key(prev): return self.error('Expected <%s> to be sorted, but subset %s at index %s is not.' % (self.val, self._fmt_items([prev, x]), i-1)) prev = x return self
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,342
assertpy/assertpy
refs/heads/main
/assertpy/__init__.py
from __future__ import absolute_import from .assertpy import assert_that, assert_warn, soft_assertions, fail, soft_fail, add_extension, remove_extension, WarningLoggingAdapter, __version__ from .file import contents_of
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,343
assertpy/assertpy
refs/heads/main
/tests/test_warn.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import logging from assertpy import assert_that, assert_warn, fail, WarningLoggingAdapter if sys.version_info[0] == 3: from io import StringIO else: from StringIO import StringIO def test_success(): assert_warn('foo').is_length(3) assert_warn('foo').is_not_empty() assert_warn('foo').is_true() assert_warn('foo').is_alpha() assert_warn('123').is_digit() assert_warn('foo').is_lower() assert_warn('FOO').is_upper() assert_warn('foo').is_equal_to('foo') assert_warn('foo').is_not_equal_to('bar') assert_warn('foo').is_equal_to_ignoring_case('FOO') def test_failures(): # capture log capture = StringIO() logger = logging.getLogger('capture') handler = logging.StreamHandler(capture) logger.addHandler(handler) adapted = WarningLoggingAdapter(logger, None) assert_warn('foo', logger=adapted).is_length(4) assert_warn('foo', logger=adapted).is_empty() assert_warn('foo', logger=adapted).is_false() assert_warn('foo', logger=adapted).is_digit() assert_warn('123', logger=adapted).is_alpha() assert_warn('foo', logger=adapted).is_upper() assert_warn('FOO', logger=adapted).is_lower() assert_warn('foo', logger=adapted).is_equal_to('bar') assert_warn('foo', logger=adapted).is_not_equal_to('foo') assert_warn('foo', logger=adapted).is_equal_to_ignoring_case('BAR') # dump log to string out = capture.getvalue() capture.close() assert_that(out).contains('[test_warn.py:61]: Expected <foo> to be of length <4>, but was <3>.') assert_that(out).contains('[test_warn.py:62]: Expected <foo> to be empty string, but was not.') assert_that(out).contains('[test_warn.py:63]: Expected <False>, but was not.') assert_that(out).contains('[test_warn.py:64]: Expected <foo> to contain only digits, but did not.') assert_that(out).contains('[test_warn.py:65]: Expected <123> to contain only alphabetic chars, but did not.') assert_that(out).contains('[test_warn.py:66]: Expected <foo> to contain only uppercase chars, but did not.') assert_that(out).contains('[test_warn.py:67]: Expected <FOO> to contain only lowercase chars, but did not.') assert_that(out).contains('[test_warn.py:68]: Expected <foo> to be equal to <bar>, but was not.') assert_that(out).contains('[test_warn.py:69]: Expected <foo> to be not equal to <foo>, but was.') assert_that(out).contains('[test_warn.py:70]: Expected <foo> to be case-insensitive equal to <BAR>, but was not.') def test_chained_failure(): # capture log capture2 = StringIO() logger = logging.getLogger('capture2') handler = logging.StreamHandler(capture2) logger.addHandler(handler) adapted = WarningLoggingAdapter(logger, None) assert_warn('foo', logger=adapted).is_length(4).is_in('bar').does_not_contain_duplicates() # dump log to string out = capture2.getvalue() capture2.close() assert_that(out).contains('[test_warn.py:96]: Expected <foo> to be of length <4>, but was <3>.') assert_that(out).contains('[test_warn.py:96]: Expected <foo> to be in <bar>, but was not.') assert_that(out).contains('[test_warn.py:96]: Expected <foo> to not contain duplicates, but did.') def test_failures_with_renamed_import(): from assertpy import assert_warn as warn # capture log capture3 = StringIO() logger = logging.getLogger('capture3') handler = logging.StreamHandler(capture3) logger.addHandler(handler) adapted = WarningLoggingAdapter(logger, None) warn('foo', logger=adapted).is_length(4) warn('foo', logger=adapted).is_empty() warn('foo', logger=adapted).is_false() warn('foo', logger=adapted).is_digit() warn('123', logger=adapted).is_alpha() warn('foo', logger=adapted).is_upper() warn('FOO', logger=adapted).is_lower() warn('foo', logger=adapted).is_equal_to('bar') warn('foo', logger=adapted).is_not_equal_to('foo') warn('foo', logger=adapted).is_equal_to_ignoring_case('BAR') # dump log to string out = capture3.getvalue() capture3.close() assert_that(out).contains('[test_warn.py:117]: Expected <foo> to be of length <4>, but was <3>.') assert_that(out).contains('[test_warn.py:118]: Expected <foo> to be empty string, but was not.') assert_that(out).contains('[test_warn.py:119]: Expected <False>, but was not.') assert_that(out).contains('[test_warn.py:120]: Expected <foo> to contain only digits, but did not.') assert_that(out).contains('[test_warn.py:121]: Expected <123> to contain only alphabetic chars, but did not.') assert_that(out).contains('[test_warn.py:122]: Expected <foo> to contain only uppercase chars, but did not.') assert_that(out).contains('[test_warn.py:123]: Expected <FOO> to contain only lowercase chars, but did not.') assert_that(out).contains('[test_warn.py:124]: Expected <foo> to be equal to <bar>, but was not.') assert_that(out).contains('[test_warn.py:125]: Expected <foo> to be not equal to <foo>, but was.') assert_that(out).contains('[test_warn.py:126]: Expected <foo> to be case-insensitive equal to <BAR>, but was not.')
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,344
assertpy/assertpy
refs/heads/main
/tests/test_list.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import collections from assertpy import assert_that, fail def test_is_length(): assert_that(['a', 'b', 'c']).is_length(3) assert_that((1, 2, 3, 4)).is_length(4) assert_that({'a': 1, 'b': 2}).is_length(2) assert_that(set(['a', 'b'])).is_length(2) def test_is_length_failure(): try: assert_that(['a', 'b', 'c']).is_length(4) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <['a', 'b', 'c']> to be of length <4>, but was <3>.") def test_is_length_bad_arg_failure(): try: assert_that(['a', 'b', 'c']).is_length('bar') fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('given arg must be an int') def test_is_length_negative_arg_failure(): try: assert_that(['a', 'b', 'c']).is_length(-1) fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('given arg must be a positive int') def test_contains(): assert_that(['a', 'b', 'c']).contains('a') assert_that(['a', 'b', 'c']).contains('c', 'b', 'a') assert_that((1, 2, 3, 4)).contains(1, 2, 3) assert_that((1, 2, 3, 4)).contains(4) assert_that({'a': 1, 'b': 2, 'c': 3}).contains('a') assert_that({'a': 1, 'b': 2, 'c': 3}).contains('a', 'b') assert_that(set(['a', 'b', 'c'])).contains('a') assert_that(set(['a', 'b', 'c'])).contains('c', 'b') fred = Person('fred') joe = Person('joe') bob = Person('bob') assert_that([fred, joe, bob]).contains(joe) def test_contains_single_item_failure(): try: assert_that(['a', 'b', 'c']).contains('x') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <['a', 'b', 'c']> to contain item <x>, but did not.") def test_contains_multi_item_failure(): try: assert_that(['a', 'b', 'c']).contains('a', 'x', 'z') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <['a', 'b', 'c']> to contain items <'a', 'x', 'z'>, but did not contain <'x', 'z'>.") def test_contains_multi_item_single_failure(): try: assert_that(['a', 'b', 'c']).contains('a', 'b', 'z') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <['a', 'b', 'c']> to contain items <'a', 'b', 'z'>, but did not contain <z>.") def test_does_not_contain(): assert_that(['a', 'b', 'c']).does_not_contain('x') assert_that(['a', 'b', 'c']).does_not_contain('x', 'y') assert_that((1, 2, 3, 4)).does_not_contain(5) assert_that((1, 2, 3, 4)).does_not_contain(5, 6) assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain('x') assert_that({'a': 1, 'b': 2, 'c': 3}).does_not_contain('x', 'y') assert_that(set(['a', 'b', 'c'])).does_not_contain('x') assert_that(set(['a', 'b', 'c'])).does_not_contain('x', 'y') fred = Person('fred') joe = Person('joe') bob = Person('bob') assert_that([fred, joe]).does_not_contain(bob) def test_does_not_contain_single_item_failure(): try: assert_that(['a', 'b', 'c']).does_not_contain('a') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <['a', 'b', 'c']> to not contain item <a>, but did.") def test_does_not_contain_list_item_failure(): try: assert_that(['a', 'b', 'c']).does_not_contain('x', 'y', 'a') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <['a', 'b', 'c']> to not contain items <'x', 'y', 'a'>, but did contain <a>.") def test_does_not_contain_list_multi_item_failure(): try: assert_that(['a', 'b', 'c']).does_not_contain('x', 'a', 'b') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <['a', 'b', 'c']> to not contain items <'x', 'a', 'b'>, but did contain <'a', 'b'>.") def test_contains_only(): assert_that(['a', 'b', 'c']).contains_only('a', 'b', 'c') assert_that(['a', 'b', 'c']).contains_only('c', 'b', 'a') assert_that(['a', 'a', 'b']).contains_only('a', 'b') assert_that(['a', 'a', 'a']).contains_only('a') assert_that((1, 2, 3, 4)).contains_only(1, 2, 3, 4) assert_that((1, 2, 3, 1)).contains_only(1, 2, 3) assert_that((1, 2, 2, 1)).contains_only(1, 2) assert_that((1, 1, 1, 1)).contains_only(1) assert_that('foobar').contains_only('f', 'o', 'b', 'a', 'r') def test_contains_only_no_args_failure(): try: assert_that([1, 2, 3]).contains_only() fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('one or more args must be given') def test_contains_only_failure(): try: assert_that([1, 2, 3]).contains_only(1, 2) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <[1, 2, 3]> to contain only <1, 2>, but did contain <3>.') def test_contains_only_multi_failure(): try: assert_that([1, 2, 3]).contains_only(1, 4) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <[1, 2, 3]> to contain only <1, 4>, but did contain <2, 3>.') def test_contains_only_superlist_failure(): try: assert_that([1, 2, 3]).contains_only(1, 2, 3, 4) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <[1, 2, 3]> to contain only <1, 2, 3, 4>, but did not contain <4>.') def test_contains_sequence(): assert_that(['a', 'b', 'c']).contains_sequence('a') assert_that(['a', 'b', 'c']).contains_sequence('b') assert_that(['a', 'b', 'c']).contains_sequence('c') assert_that(['a', 'b', 'c']).contains_sequence('a', 'b') assert_that(['a', 'b', 'c']).contains_sequence('b', 'c') assert_that(['a', 'b', 'c']).contains_sequence('a', 'b', 'c') assert_that((1, 2, 3, 4)).contains_sequence(1) assert_that((1, 2, 3, 4)).contains_sequence(2) assert_that((1, 2, 3, 4)).contains_sequence(3) assert_that((1, 2, 3, 4)).contains_sequence(4) assert_that((1, 2, 3, 4)).contains_sequence(1, 2) assert_that((1, 2, 3, 4)).contains_sequence(2, 3) assert_that((1, 2, 3, 4)).contains_sequence(3, 4) assert_that((1, 2, 3, 4)).contains_sequence(1, 2, 3) assert_that((1, 2, 3, 4)).contains_sequence(2, 3, 4) assert_that((1, 2, 3, 4)).contains_sequence(1, 2, 3, 4) assert_that('foobar').contains_sequence('o', 'o', 'b') fred = Person('fred') joe = Person('joe') bob = Person('bob') assert_that([fred, joe, bob]).contains_sequence(fred, joe) def test_contains_sequence_failure(): try: assert_that([1, 2, 3]).contains_sequence(4, 5) fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <[1, 2, 3]> to contain sequence <4, 5>, but did not.') def test_contains_sequence_bad_val_failure(): try: assert_that(123).contains_sequence(1, 2) fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not iterable') def test_contains_sequence_no_args_failure(): try: assert_that([1, 2, 3]).contains_sequence() fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('one or more args must be given') def test_contains_duplicates(): assert_that(['a', 'b', 'c', 'a']).contains_duplicates() assert_that(('a', 'b', 'c', 'a')).contains_duplicates() assert_that([1, 2, 3, 3]).contains_duplicates() assert_that((1, 2, 3, 3)).contains_duplicates() assert_that('foobar').contains_duplicates() fred = Person('fred') joe = Person('joe') assert_that([fred, joe, fred]).contains_duplicates() def test_contains_duplicates_failure(): try: assert_that([1, 2, 3]).contains_duplicates() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <[1, 2, 3]> to contain duplicates, but did not.') def test_contains_duplicates_bad_val_failure(): try: assert_that(123).contains_duplicates() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not iterable') def test_does_not_contain_duplicates(): assert_that(['a', 'b', 'c']).does_not_contain_duplicates() assert_that(('a', 'b', 'c')).does_not_contain_duplicates() assert_that(set(['a', 'b', 'c'])).does_not_contain_duplicates() assert_that([1, 2, 3]).does_not_contain_duplicates() assert_that((1, 2, 3)).does_not_contain_duplicates() assert_that(set([1, 2, 3])).does_not_contain_duplicates() assert_that('fobar').does_not_contain_duplicates() fred = Person('fred') joe = Person('joe') assert_that([fred, joe]).does_not_contain_duplicates() def test_does_not_contain_duplicates_failure(): try: assert_that([1, 2, 3, 3]).does_not_contain_duplicates() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <[1, 2, 3, 3]> to not contain duplicates, but did.') def test_does_not_contain_duplicates_bad_val_failure(): try: assert_that(123).does_not_contain_duplicates() fail('should have raised error') except TypeError as ex: assert_that(str(ex)).is_equal_to('val is not iterable') def test_is_empty(): assert_that([]).is_empty() assert_that(()).is_empty() assert_that({}).is_empty() def test_is_empty_failure(): try: assert_that(['a', 'b']).is_empty() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected <['a', 'b']> to be empty, but was not.") def test_is_not_empty(): assert_that(['a', 'b']).is_not_empty() assert_that((1, 2)).is_not_empty() assert_that({'a': 1, 'b': 2}).is_not_empty() assert_that(set(['a', 'b'])).is_not_empty() def test_is_not_empty_failure(): try: assert_that([]).is_not_empty() fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected not empty, but was empty.') def test_starts_with(): assert_that(['a', 'b', 'c']).starts_with('a') assert_that((1, 2, 3)).starts_with(1) if sys.version_info[0] == 3: ordered = collections.OrderedDict([('z', 9), ('x', 7), ('y', 8)]) assert_that(ordered.keys()).starts_with('z') assert_that(ordered.values()).starts_with(9) assert_that(ordered.items()).starts_with(('z', 9)) def test_starts_with_failure(): try: assert_that(['a', 'b', 'c']).starts_with('d') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected ['a', 'b', 'c'] to start with <d>, but did not.") def test_starts_with_bad_val_failure(): try: assert_that([]).starts_with('a') fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('val must not be empty') def test_starts_with_bad_prefix_failure(): try: assert_that(['a', 'b', 'c']).starts_with('a', 'b') fail('should have raised error') except TypeError as ex: if sys.version_info[0] == 3: assert_that(str(ex)).contains('starts_with() takes 2 positional arguments but 3 were given') else: assert_that(str(ex)).contains('starts_with() takes exactly 2 arguments (3 given)') def test_ends_with(): assert_that(['a', 'b', 'c']).ends_with('c') assert_that((1, 2, 3)).ends_with(3) if sys.version_info[0] == 3: ordered = collections.OrderedDict([('z', 9), ('x', 7), ('y', 8)]) assert_that(ordered.keys()).ends_with('y') assert_that(ordered.values()).ends_with(8) assert_that(ordered.items()).ends_with(('y', 8)) def test_ends_with_failure(): try: assert_that(['a', 'b', 'c']).ends_with('d') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to("Expected ['a', 'b', 'c'] to end with <d>, but did not.") def test_ends_with_bad_val_failure(): try: assert_that([]).ends_with('a') fail('should have raised error') except ValueError as ex: assert_that(str(ex)).is_equal_to('val must not be empty') def test_ends_with_bad_prefix_failure(): try: assert_that(['a', 'b', 'c']).ends_with('b', 'c') fail('should have raised error') except TypeError as ex: if sys.version_info[0] == 3: assert_that(str(ex)).contains('ends_with() takes 2 positional arguments but 3 were given') else: assert_that(str(ex)).contains('ends_with() takes exactly 2 arguments (3 given)') def test_chaining(): assert_that(['a', 'b', 'c']).is_type_of(list).is_length(3).contains('a').does_not_contain('x') assert_that(['a', 'b', 'c']).is_type_of(list).is_length(3).contains('a', 'b').does_not_contain('x', 'y') def test_list_of_lists(): l = [[1, 2, 3], ['a', 'b', 'c'], (4, 5, 6)] assert_that(l).is_length(3) assert_that(l).is_equal_to([[1, 2, 3], ['a', 'b', 'c'], (4, 5, 6)]) assert_that(l).contains([1, 2, 3]) assert_that(l).contains(['a', 'b', 'c']) assert_that(l).contains((4, 5, 6)) assert_that(l).starts_with([1, 2, 3]) assert_that(l).ends_with((4, 5, 6)) assert_that(l[0]).is_equal_to([1, 2, 3]) assert_that(l[2]).is_equal_to((4, 5, 6)) assert_that(l[0][0]).is_equal_to(1) assert_that(l[2][2]).is_equal_to(6) def test_list_of_dicts(): l = [{'a': 1}, {'b': 2}, {'c': 3}] assert_that(l).is_length(3) assert_that(l).is_equal_to([{'a': 1}, {'b': 2}, {'c': 3}]) assert_that(l).contains({'a': 1}) assert_that(l).contains({'b': 2}) assert_that(l).contains({'c': 3}) assert_that(l).starts_with({'a': 1}) assert_that(l).ends_with({'c': 3}) assert_that(l[0]).is_equal_to({'a': 1}) assert_that(l[2]).is_equal_to({'c': 3}) assert_that(l[0]['a']).is_equal_to(1) assert_that(l[2]['c']).is_equal_to(3) class Person(object): def __init__(self, name): self.name = name
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}
64,345
assertpy/assertpy
refs/heads/main
/tests/test_traceback.py
# Copyright (c) 2015-2019, Activision Publishing, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import traceback from assertpy import assert_that, fail def test_traceback(): try: assert_that('foo').is_equal_to('bar') fail('should have raised error') except AssertionError as ex: assert_that(str(ex)).is_equal_to('Expected <foo> to be equal to <bar>, but was not.') assert_that(ex).is_type_of(AssertionError) # extract all stack frames from the traceback _, _, tb = sys.exc_info() assert_that(tb).is_not_none() # walk_tb added in 3.5 if sys.version_info[0] == 3 and sys.version_info[1] >= 5: frames = [(f.f_code.co_filename, f.f_code.co_name, lineno) for f, lineno in traceback.walk_tb(tb)] assert_that(frames).is_length(3) assert_that(frames[0][0]).ends_with('test_traceback.py') assert_that(frames[0][1]).is_equal_to('test_traceback') assert_that(frames[0][2]).is_equal_to(36) assert_that(frames[1][0]).ends_with('base.py') assert_that(frames[1][1]).is_equal_to('is_equal_to') assert_that(frames[1][2]).is_greater_than(40) assert_that(frames[2][0]).ends_with('assertpy.py') assert_that(frames[2][1]).is_equal_to('error') assert_that(frames[2][2]).is_greater_than(100)
{"/tests/test_readme.py": ["/assertpy/__init__.py"], "/tests/test_custom_dict.py": ["/assertpy/__init__.py"], "/tests/test_collection.py": ["/assertpy/__init__.py"], "/tests/test_dict.py": ["/assertpy/__init__.py"], "/tests/test_custom_list.py": ["/assertpy/__init__.py"], "/tests/test_same_as.py": ["/assertpy/__init__.py"], "/setup.py": ["/assertpy/__init__.py"], "/tests/test_numbers.py": ["/assertpy/__init__.py"], "/tests/test_dyn.py": ["/assertpy/__init__.py"], "/tests/test_dict_compare.py": ["/assertpy/__init__.py"], "/tests/test_extracting.py": ["/assertpy/__init__.py"], "/tests/test_class.py": ["/assertpy/__init__.py"], "/tests/test_expected_exception.py": ["/assertpy/__init__.py"], "/tests/test_extensions.py": ["/assertpy/__init__.py"], "/tests/test_namedtuple.py": ["/assertpy/__init__.py"], "/tests/test_snapshots.py": ["/assertpy/__init__.py"], "/tests/test_core.py": ["/assertpy/__init__.py"], "/tests/test_string.py": ["/assertpy/__init__.py"], "/tests/test_soft_fail.py": ["/assertpy/__init__.py"], "/assertpy/assertpy.py": ["/assertpy/base.py", "/assertpy/collection.py", "/assertpy/contains.py", "/assertpy/date.py", "/assertpy/dict.py", "/assertpy/dynamic.py", "/assertpy/extracting.py", "/assertpy/exception.py", "/assertpy/file.py", "/assertpy/helpers.py", "/assertpy/numeric.py", "/assertpy/snapshot.py", "/assertpy/string.py"], "/tests/test_file.py": ["/assertpy/__init__.py"], "/tests/test_equals.py": ["/assertpy/__init__.py"], "/tests/test_soft.py": ["/assertpy/__init__.py"], "/tests/test_datetime.py": ["/assertpy/__init__.py"], "/assertpy/__init__.py": ["/assertpy/assertpy.py", "/assertpy/file.py"], "/tests/test_warn.py": ["/assertpy/__init__.py"], "/tests/test_list.py": ["/assertpy/__init__.py"], "/tests/test_traceback.py": ["/assertpy/__init__.py"]}