Skip to content

Commit

Permalink
Merge pull request #56 from iprak/fixed-failing-tests
Browse files Browse the repository at this point in the history
Fixed failing tests
  • Loading branch information
iprak authored Oct 22, 2021
2 parents c4246b2 + 47dbd28 commit 19e60c8
Show file tree
Hide file tree
Showing 20 changed files with 645 additions and 623 deletions.
Binary file modified .coverage
Binary file not shown.
118 changes: 59 additions & 59 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,60 +1,60 @@
repos:
- repo: https://github.com/asottile/pyupgrade
rev: v2.7.2
hooks:
- id: pyupgrade
args: [--py38-plus]
- repo: https://github.com/psf/black
rev: 20.8b1
hooks:
- id: black
args:
- --safe
- --quiet
files: ^((homeassistant|script|tests)/.+)?[^/]+\.py$
- repo: https://github.com/codespell-project/codespell
rev: v2.0.0
hooks:
- id: codespell
args:
- --ignore-words-list=hass,alot,datas,dof,dur,ether,farenheit,hist,iff,ines,ist,lightsensor,mut,nd,pres,referer,ser,serie,te,technik,ue,uint,visability,wan,wanna,withing,iam,incomfort
- --skip="./.*,*.csv,*.json"
- --quiet-level=2
exclude_types: [csv, json]
exclude: ^tests/fixtures/
- repo: https://gitlab.com/pycqa/flake8
rev: 3.8.4
hooks:
- id: flake8
additional_dependencies:
- flake8-docstrings==1.5.0
- pydocstyle==5.1.1
files: ^(homeassistant|script|tests)/.+\.py$
- repo: https://github.com/PyCQA/bandit
rev: 1.7.0
hooks:
- id: bandit
args:
- --quiet
- --format=custom
- --configfile=tests/bandit.yaml
files: ^(homeassistant|script|tests)/.+\.py$
- repo: https://github.com/PyCQA/isort
rev: 5.5.3
hooks:
- id: isort
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0
hooks:
- id: check-executables-have-shebangs
stages: [manual]
- id: check-json
exclude: (.vscode|.devcontainer)
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.790
hooks:
- id: mypy
args:
- --pretty
- --show-error-codes
repos:
- repo: https://github.com/asottile/pyupgrade
rev: v2.7.2
hooks:
- id: pyupgrade
args: [--py38-plus]
- repo: https://github.com/psf/black
rev: 20.8b1
hooks:
- id: black
args:
- --safe
- --quiet
files: ^((homeassistant|script|tests)/.+)?[^/]+\.py$
- repo: https://github.com/codespell-project/codespell
rev: v2.0.0
hooks:
- id: codespell
args:
- --ignore-words-list=hass,alot,datas,dof,dur,ether,farenheit,hist,iff,ines,ist,lightsensor,mut,nd,pres,referer,ser,serie,te,technik,ue,uint,visability,wan,wanna,withing,iam,incomfort
- --skip="./.*,*.csv,*.json"
- --quiet-level=2
exclude_types: [csv, json]
exclude: ^tests/fixtures/
- repo: https://gitlab.com/pycqa/flake8
rev: 3.8.4
hooks:
- id: flake8
additional_dependencies:
- flake8-docstrings==1.5.0
- pydocstyle==5.1.1
files: ^(homeassistant|script|tests)/.+\.py$
- repo: https://github.com/PyCQA/bandit
rev: 1.7.0
hooks:
- id: bandit
args:
- --quiet
- --format=custom
- --configfile=tests/bandit.yaml
files: ^(homeassistant|script|tests)/.+\.py$
- repo: https://github.com/PyCQA/isort
rev: 5.5.3
hooks:
- id: isort
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0
hooks:
- id: check-executables-have-shebangs
stages: [manual]
- id: check-json
exclude: (.vscode|.devcontainer)
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.790
hooks:
- id: mypy
args:
- --pretty
- --show-error-codes
- --show-error-context
12 changes: 6 additions & 6 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"python.formatting.provider": "black",
"editor.formatOnPaste": false,
"editor.formatOnSave": true,
"files.trimTrailingWhitespace": true,
"git.ignoreLimitWarning": true,
{
"python.formatting.provider": "black",
"editor.formatOnPaste": false,
"editor.formatOnSave": true,
"files.trimTrailingWhitespace": true,
"git.ignoreLimitWarning": true,
}
2 changes: 1 addition & 1 deletion custom_components/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
"""Dummy __init__.py to make imports with pytest-homeassistant-custom-component work."""
"""Dummy __init__.py to make imports with pytest-homeassistant-custom-component work."""
62 changes: 47 additions & 15 deletions custom_components/yahoofinance/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@

from datetime import timedelta
import logging
from typing import Union
from typing import Final, Union

from homeassistant.const import CONF_SCAN_INTERVAL
from homeassistant.core import HomeAssistant
from homeassistant.helpers import discovery
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.typing import ConfigType
import voluptuous as vol

from custom_components.yahoofinance.coordinator import YahooSymbolUpdateCoordinator
Expand All @@ -35,11 +37,10 @@
HASS_DATA_COORDINATOR,
SERVICE_REFRESH,
)
from .coordinator import YahooSymbolUpdateCoordinator

_LOGGER = logging.getLogger(__name__)
DEFAULT_SCAN_INTERVAL = timedelta(hours=6)
MINIMUM_SCAN_INTERVAL = timedelta(seconds=30)
DEFAULT_SCAN_INTERVAL: Final = timedelta(hours=6)
MINIMUM_SCAN_INTERVAL: Final = timedelta(seconds=30)


BASIC_SYMBOL_SCHEMA = vol.All(cv.string, vol.Upper)
Expand Down Expand Up @@ -94,6 +95,34 @@
)


class SymbolDefinition:
"""Symbol definition."""

symbol: str
target_currency: str

def __init__(self, symbol: str, target_currency: Union[str, None] = None) -> None:
"""Create a new symbol definition."""
self.symbol = symbol
self.target_currency = target_currency

def __repr__(self) -> str:
"""Return the representation."""
return f"{self.symbol},{self.target_currency}"

def __eq__(self, other: any) -> bool:
"""Return the comparison."""
return (
isinstance(other, SymbolDefinition)
and self.symbol == other.symbol
and self.target_currency == other.target_currency
)

def __hash__(self) -> int:
"""Make hashable."""
return hash((self.symbol, self.target_currency))


def parse_scan_interval(scan_interval: Union[timedelta, str]) -> timedelta:
"""Parse and validate scan_interval."""
if isinstance(scan_interval, str):
Expand All @@ -110,31 +139,34 @@ def parse_scan_interval(scan_interval: Union[timedelta, str]) -> timedelta:
return scan_interval


def normalize_input(defined_symbols):
def normalize_input(defined_symbols: list) -> tuple[list[str], list[SymbolDefinition]]:
"""Normalize input and remove duplicates."""
symbols = set()
normalized_symbols = []
symbol_definitions: list[SymbolDefinition] = []

for value in defined_symbols:
if isinstance(value, str):
if value not in symbols:
symbols.add(value)
normalized_symbols.append({"symbol": value})
symbol_definitions.append(SymbolDefinition(value))
else:
if value["symbol"] not in symbols:
symbols.add(value["symbol"])
normalized_symbols.append(value)
symbol = value["symbol"]
if symbol not in symbols:
symbols.add(symbol)
symbol_definitions.append(
SymbolDefinition(symbol, value.get(CONF_TARGET_CURRENCY))
)

return (list(symbols), normalized_symbols)
return (list(symbols), symbol_definitions)


async def async_setup(hass, config) -> bool:
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the component."""
domain_config = config.get(DOMAIN, {})
defined_symbols = domain_config.get(CONF_SYMBOLS, [])

symbols, normalized_symbols = normalize_input(defined_symbols)
domain_config[CONF_SYMBOLS] = normalized_symbols
symbols, symbol_definitions = normalize_input(defined_symbols)
domain_config[CONF_SYMBOLS] = symbol_definitions

scan_interval = parse_scan_interval(domain_config.get(CONF_SCAN_INTERVAL))

Expand All @@ -155,7 +187,7 @@ async def async_setup(hass, config) -> bool:
HASS_DATA_CONFIG: domain_config,
}

async def handle_refresh_symbols(_call):
async def handle_refresh_symbols(_call) -> None:
"""Refresh symbol data."""
_LOGGER.info("Processing refresh_symbols")
await coordinator.async_request_refresh()
Expand Down
84 changes: 43 additions & 41 deletions custom_components/yahoofinance/const.py
Original file line number Diff line number Diff line change
@@ -1,49 +1,51 @@
"""Constants for Yahoo Finance sensor."""

from typing import Final

# Additional attributes exposed by the sensor
ATTR_CURRENCY_SYMBOL = "currencySymbol"
ATTR_QUOTE_TYPE = "quoteType"
ATTR_QUOTE_SOURCE_NAME = "quoteSourceName"
ATTR_SYMBOL = "symbol"
ATTR_TRENDING = "trending"
ATTR_MARKET_STATE = "marketState"
ATTR_CURRENCY_SYMBOL: Final = "currencySymbol"
ATTR_QUOTE_TYPE: Final = "quoteType"
ATTR_QUOTE_SOURCE_NAME: Final = "quoteSourceName"
ATTR_SYMBOL: Final = "symbol"
ATTR_TRENDING: Final = "trending"
ATTR_MARKET_STATE: Final = "marketState"

# Hass data
HASS_DATA_CONFIG = "config"
HASS_DATA_COORDINATOR = "coordinator"
HASS_DATA_CONFIG: Final = "config"
HASS_DATA_COORDINATOR: Final = "coordinator"

# JSON data pieces
DATA_CURRENCY_SYMBOL = "currency"
DATA_FINANCIAL_CURRENCY = "financialCurrency"
DATA_QUOTE_TYPE = "quoteType"
DATA_QUOTE_SOURCE_NAME = "quoteSourceName"
DATA_SHORT_NAME = "shortName"
DATA_MARKET_STATE = "marketState"
DATA_CURRENCY_SYMBOL: Final = "currency"
DATA_FINANCIAL_CURRENCY: Final = "financialCurrency"
DATA_QUOTE_TYPE: Final = "quoteType"
DATA_QUOTE_SOURCE_NAME: Final = "quoteSourceName"
DATA_SHORT_NAME: Final = "shortName"
DATA_MARKET_STATE: Final = "marketState"

DATA_REGULAR_MARKET_PREVIOUS_CLOSE = "regularMarketPreviousClose"
DATA_REGULAR_MARKET_PRICE = "regularMarketPrice"
DATA_REGULAR_MARKET_PREVIOUS_CLOSE: Final = "regularMarketPreviousClose"
DATA_REGULAR_MARKET_PRICE: Final = "regularMarketPrice"

CONF_DECIMAL_PLACES = "decimal_places"
CONF_INCLUDE_FIFTY_DAY_VALUES = "include_fifty_day_values"
CONF_INCLUDE_POST_VALUES = "include_post_values"
CONF_INCLUDE_PRE_VALUES = "include_pre_values"
CONF_INCLUDE_TWO_HUNDRED_DAY_VALUES = "include_two_hundred_day_values"
CONF_SHOW_TRENDING_ICON = "show_trending_icon"
CONF_TARGET_CURRENCY = "target_currency"
CONF_DECIMAL_PLACES: Final = "decimal_places"
CONF_INCLUDE_FIFTY_DAY_VALUES: Final = "include_fifty_day_values"
CONF_INCLUDE_POST_VALUES: Final = "include_post_values"
CONF_INCLUDE_PRE_VALUES: Final = "include_pre_values"
CONF_INCLUDE_TWO_HUNDRED_DAY_VALUES: Final = "include_two_hundred_day_values"
CONF_SHOW_TRENDING_ICON: Final = "show_trending_icon"
CONF_TARGET_CURRENCY: Final = "target_currency"

DEFAULT_CONF_DECIMAL_PLACES = 2
DEFAULT_CONF_INCLUDE_FIFTY_DAY_VALUES = True
DEFAULT_CONF_INCLUDE_POST_VALUES = True
DEFAULT_CONF_INCLUDE_PRE_VALUES = True
DEFAULT_CONF_INCLUDE_TWO_HUNDRED_DAY_VALUES = True
DEFAULT_CONF_SHOW_TRENDING_ICON = False
DEFAULT_CONF_DECIMAL_PLACES: Final = 2
DEFAULT_CONF_INCLUDE_FIFTY_DAY_VALUES: Final = True
DEFAULT_CONF_INCLUDE_POST_VALUES: Final = True
DEFAULT_CONF_INCLUDE_PRE_VALUES: Final = True
DEFAULT_CONF_INCLUDE_TWO_HUNDRED_DAY_VALUES: Final = True
DEFAULT_CONF_SHOW_TRENDING_ICON: Final = False

DEFAULT_NUMERIC_DATA_GROUP = "default"
DEFAULT_NUMERIC_DATA_GROUP: Final = "default"

# Data keys grouped into categories. The values for the categories (except for DEFAULT_NUMERIC_DATA_GROUP)
# can be conditionally pulled into attributes. The first value of the set is the key and the second
# boolean value indicates if the attribute is a currency.
NUMERIC_DATA_GROUPS = {
NUMERIC_DATA_GROUPS: Final = {
DEFAULT_NUMERIC_DATA_GROUP: [
("averageDailyVolume10Day", False),
("averageDailyVolume3Month", False),
Expand Down Expand Up @@ -80,7 +82,7 @@
],
}

STRING_DATA_KEYS = [
STRING_DATA_KEYS: Final = [
DATA_CURRENCY_SYMBOL,
DATA_FINANCIAL_CURRENCY,
DATA_QUOTE_TYPE,
Expand All @@ -90,17 +92,17 @@
]


ATTRIBUTION = "Data provided by Yahoo Finance"
BASE = "https://query1.finance.yahoo.com/v7/finance/quote?symbols="
ATTRIBUTION: Final = "Data provided by Yahoo Finance"
BASE: Final = "https://query1.finance.yahoo.com/v7/finance/quote?symbols="

CONF_SYMBOLS = "symbols"
DEFAULT_CURRENCY = "USD"
DEFAULT_CURRENCY_SYMBOL = "$"
DEFAULT_ICON = "mdi:currency-usd"
DOMAIN = "yahoofinance"
SERVICE_REFRESH = "refresh_symbols"
CONF_SYMBOLS: Final = "symbols"
DEFAULT_CURRENCY: Final = "USD"
DEFAULT_CURRENCY_SYMBOL: Final = "$"
DEFAULT_ICON: Final = "mdi:currency-usd"
DOMAIN: Final = "yahoofinance"
SERVICE_REFRESH: Final = "refresh_symbols"

CURRENCY_CODES = {
CURRENCY_CODES: Final = {
"bdt": "৳",
"brl": "R$",
"btc": "₿",
Expand Down
Loading

0 comments on commit 19e60c8

Please sign in to comment.