Black tests and setup.py (#1657)

This commit is contained in:
Will 2018-05-14 19:09:54 -04:00 committed by Tobotimus
parent b88b5a2601
commit e01cdbb091
12 changed files with 149 additions and 150 deletions

View File

@ -7,38 +7,44 @@ import sys
from setuptools import find_packages
IS_TRAVIS = 'TRAVIS' in os.environ
IS_DEPLOYING = 'DEPLOYING' in os.environ
IS_RTD = 'READTHEDOCS' in os.environ
IS_TRAVIS = "TRAVIS" in os.environ
IS_DEPLOYING = "DEPLOYING" in os.environ
IS_RTD = "READTHEDOCS" in os.environ
dep_links = ['https://github.com/Rapptz/discord.py/tarball/rewrite#egg=discord.py-1.0']
dep_links = ["https://github.com/Rapptz/discord.py/tarball/rewrite#egg=discord.py-1.0"]
if IS_TRAVIS:
dep_links = []
def get_package_list():
core = find_packages(include=['redbot', 'redbot.*'])
core = find_packages(include=["redbot", "redbot.*"])
return core
def get_requirements():
with open('requirements.txt') as f:
with open("requirements.txt") as f:
requirements = f.read().splitlines()
try:
requirements.remove('git+https://github.com/Rapptz/discord.py.git@rewrite#egg=discord.py[voice]')
requirements.remove(
"git+https://github.com/Rapptz/discord.py.git@rewrite#egg=discord.py[voice]"
)
except ValueError:
pass
if IS_DEPLOYING or not (IS_TRAVIS or IS_RTD):
requirements.append('discord.py>=1.0.0a0')
requirements.append("discord.py>=1.0.0a0")
if sys.platform.startswith("linux"):
requirements.append("distro")
return requirements
def get_version():
with open('redbot/core/__init__.py') as f:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', f.read(), re.MULTILINE).group(1)
with open("redbot/core/__init__.py") as f:
version = re.search(
r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', f.read(), re.MULTILINE
).group(
1
)
return version
@ -48,6 +54,7 @@ def find_locale_folders():
all you gotta know. Don't fuck with this unless you really know what
you're doing, otherwise we lose all translations.
"""
def glob_locale_files(path: Path):
msgs = path.glob("*.po")
@ -55,62 +62,58 @@ def find_locale_folders():
return [str(m.relative_to(parents[0])) for m in msgs]
ret = {
'redbot.core': glob_locale_files(Path('redbot/core/locales'))
}
ret = {"redbot.core": glob_locale_files(Path("redbot/core/locales"))}
cogs_path = Path('redbot/cogs')
cogs_path = Path("redbot/cogs")
for cog_folder in cogs_path.iterdir():
locales_folder = cog_folder / 'locales'
locales_folder = cog_folder / "locales"
if not locales_folder.is_dir():
continue
pkg_name = str(cog_folder).replace('/', '.')
pkg_name = str(cog_folder).replace("/", ".")
ret[pkg_name] = glob_locale_files(locales_folder)
return ret
setup(
name='Red-DiscordBot',
name="Red-DiscordBot",
version=get_version(),
packages=get_package_list(),
package_data=find_locale_folders(),
include_package_data=True,
url='https://github.com/Cog-Creators/Red-DiscordBot',
license='GPLv3',
author='Cog-Creators',
author_email='',
description='A highly customizable Discord bot',
url="https://github.com/Cog-Creators/Red-DiscordBot",
license="GPLv3",
author="Cog-Creators",
author_email="",
description="A highly customizable Discord bot",
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: AsyncIO',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Communications :: Chat',
'Topic :: Documentation :: Sphinx'
"Development Status :: 4 - Beta",
"Framework :: AsyncIO",
"Intended Audience :: Developers",
"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Topic :: Communications :: Chat",
"Topic :: Documentation :: Sphinx",
],
entry_points={
'console_scripts': [
'redbot=redbot.__main__:main',
'redbot-setup=redbot.setup:main',
'redbot-launcher=redbot.launcher:main'
"console_scripts": [
"redbot=redbot.__main__:main",
"redbot-setup=redbot.setup:main",
"redbot-launcher=redbot.launcher:main",
]
},
python_requires='>=3.5,<3.7',
python_requires=">=3.5,<3.7",
setup_requires=get_requirements(),
install_requires=get_requirements(),
dependency_links=dep_links,
extras_require={
'test': [
'pytest>3', 'pytest-asyncio'
],
'mongo': ['motor'],
'docs': ['sphinx>=1.7', 'sphinxcontrib-asyncio', 'sphinx_rtd_theme'],
'voice': ['red-lavalink>=0.0.4']
}
"test": ["pytest>3", "pytest-asyncio"],
"mongo": ["motor"],
"docs": ["sphinx>=1.7", "sphinxcontrib-asyncio", "sphinx_rtd_theme"],
"voice": ["red-lavalink>=0.0.4"],
},
)

View File

@ -22,6 +22,7 @@ async def fake_run_noprint(*args, **kwargs):
@pytest.fixture(scope="module", autouse=True)
def patch_relative_to(monkeysession):
def fake_relative_to(self, some_path: Path):
return self
@ -38,14 +39,14 @@ def repo_manager(tmpdir_factory, config):
@pytest.fixture
def repo(tmpdir):
repo_folder = Path(str(tmpdir)) / 'repos' / 'squid'
repo_folder = Path(str(tmpdir)) / "repos" / "squid"
repo_folder.mkdir(parents=True, exist_ok=True)
return Repo(
url="https://github.com/tekulvw/Squid-Plugins",
name="squid",
branch="rewrite_cogs",
folder_path=repo_folder
folder_path=repo_folder,
)
@ -63,19 +64,19 @@ def bot_repo(event_loop):
branch="WRONG",
url="https://empty.com/something.git",
folder_path=cwd,
loop=event_loop
loop=event_loop,
)
def test_existing_git_repo(tmpdir):
repo_folder = Path(str(tmpdir)) / 'repos' / 'squid' / '.git'
repo_folder = Path(str(tmpdir)) / "repos" / "squid" / ".git"
repo_folder.mkdir(parents=True, exist_ok=True)
r = Repo(
url="https://github.com/tekulvw/Squid-Plugins",
name="squid",
branch="rewrite_cogs",
folder_path=repo_folder.parent
folder_path=repo_folder.parent,
)
exists, _ = r._existing_git_repo()
@ -89,24 +90,21 @@ async def test_clone_repo(repo_norun, capsys):
clone_cmd, _ = capsys.readouterr()
clone_cmd = clone_cmd.strip('[\']').split('\', \'')
assert clone_cmd[0] == 'git'
assert clone_cmd[1] == 'clone'
assert clone_cmd[2] == '-b'
assert clone_cmd[3] == 'rewrite_cogs'
clone_cmd = clone_cmd.strip("[']").split("', '")
assert clone_cmd[0] == "git"
assert clone_cmd[1] == "clone"
assert clone_cmd[2] == "-b"
assert clone_cmd[3] == "rewrite_cogs"
assert clone_cmd[4] == repo_norun.url
assert 'repos/squid' in clone_cmd[5]
assert "repos/squid" in clone_cmd[5]
@pytest.mark.asyncio
async def test_add_repo(monkeypatch, repo_manager):
monkeypatch.setattr("redbot.cogs.downloader.repo_manager.Repo._run",
fake_run_noprint)
monkeypatch.setattr("redbot.cogs.downloader.repo_manager.Repo._run", fake_run_noprint)
squid = await repo_manager.add_repo(
url="https://github.com/tekulvw/Squid-Plugins",
name="squid",
branch="rewrite_cogs"
url="https://github.com/tekulvw/Squid-Plugins", name="squid", branch="rewrite_cogs"
)
assert squid.available_modules == []

View File

@ -6,23 +6,16 @@ import pytest
from redbot.cogs.downloader.installable import Installable, InstallableType
INFO_JSON = {
"author": (
"tekulvw",
),
"author": ("tekulvw",),
"bot_version": (3, 0, 0),
"description": "A long description",
"hidden": False,
"install_msg": "A post-installation message",
"required_cogs": {},
"requirements": (
"tabulate"
),
"requirements": ("tabulate"),
"short": "A short description",
"tags": (
"tag1",
"tag2"
),
"type": "COG"
"tags": ("tag1", "tag2"),
"type": "COG",
}
@ -30,7 +23,7 @@ INFO_JSON = {
def installable(tmpdir):
cog_path = tmpdir.mkdir("test_repo").mkdir("test_cog")
info_path = cog_path.join("info.json")
info_path.write_text(json.dumps(INFO_JSON), 'utf-8')
info_path.write_text(json.dumps(INFO_JSON), "utf-8")
cog_info = Installable(Path(str(cog_path)))
return cog_info

View File

@ -4,9 +4,11 @@ import pytest
@pytest.fixture()
def bank(config):
from redbot.core import Config
Config.get_conf = lambda *args, **kwargs: config
from redbot.core import bank
bank._register_defaults()
return bank

View File

@ -20,7 +20,7 @@ async def test_modlog_register_casetype(mod, ctx):
"default_setting": True,
"image": ":hammer:",
"case_str": "Ban",
"audit_type": "ban"
"audit_type": "ban",
}
casetype = await mod.register_casetype(**ct)
assert casetype is not None
@ -29,6 +29,7 @@ async def test_modlog_register_casetype(mod, ctx):
@pytest.mark.asyncio
async def test_modlog_case_create(mod, ctx, member_factory):
from datetime import datetime as dt
usr = member_factory.get()
guild = ctx.guild
bot = ctx.bot
@ -36,9 +37,7 @@ async def test_modlog_case_create(mod, ctx, member_factory):
moderator = ctx.author
reason = "Test 12345"
created_at = dt.utcnow()
case = await mod.create_case(
bot, guild, created_at, case_type, usr, moderator, reason
)
case = await mod.create_case(bot, guild, created_at, case_type, usr, moderator, reason)
assert case is not None
assert case.user == usr
assert case.action_type == case_type

View File

@ -20,36 +20,35 @@ def monkeysession(request):
@pytest.fixture(autouse=True)
def override_data_path(tmpdir):
from redbot.core import data_manager
data_manager.basic_config = data_manager.basic_config_default
data_manager.basic_config['DATA_PATH'] = str(tmpdir)
data_manager.basic_config["DATA_PATH"] = str(tmpdir)
@pytest.fixture()
def coroutine():
async def some_coro(*args, **kwargs):
return args, kwargs
return some_coro
@pytest.fixture()
def json_driver(tmpdir_factory):
import uuid
rand = str(uuid.uuid4())
path = Path(str(tmpdir_factory.mktemp(rand)))
driver = red_json.JSON(
"PyTest",
identifier=str(uuid.uuid4()),
data_path_override=path
)
driver = red_json.JSON("PyTest", identifier=str(uuid.uuid4()), data_path_override=path)
return driver
@pytest.fixture()
def config(json_driver):
conf = Config(
cog_name="PyTest",
unique_identifier=json_driver.unique_cog_identifier,
driver=json_driver)
cog_name="PyTest", unique_identifier=json_driver.unique_cog_identifier, driver=json_driver
)
yield conf
conf._defaults = {}
@ -63,7 +62,7 @@ def config_fr(json_driver):
cog_name="PyTest",
unique_identifier=json_driver.unique_cog_identifier,
driver=json_driver,
force_registration=True
force_registration=True,
)
yield conf
conf._defaults = {}
@ -75,6 +74,7 @@ def guild_factory():
mock_guild = namedtuple("Guild", "id members")
class GuildFactory:
def get(self):
return mock_guild(random.randint(1, 999999999), [])
@ -103,11 +103,9 @@ def member_factory(guild_factory):
mock_member = namedtuple("Member", "id guild display_name")
class MemberFactory:
def get(self):
return mock_member(
random.randint(1, 999999999),
guild_factory.get(),
'Testing_Name')
return mock_member(random.randint(1, 999999999), guild_factory.get(), "Testing_Name")
return MemberFactory()
@ -122,9 +120,9 @@ def user_factory():
mock_user = namedtuple("User", "id")
class UserFactory:
def get(self):
return mock_user(
random.randint(1, 999999999))
return mock_user(random.randint(1, 999999999))
return UserFactory()
@ -143,8 +141,9 @@ def empty_message():
@pytest.fixture()
def ctx(empty_member, empty_channel, red):
mock_ctx = namedtuple("Context", "author guild channel message bot")
return mock_ctx(empty_member, empty_member.guild, empty_channel,
empty_message, red)
return mock_ctx(empty_member, empty_member.guild, empty_channel, empty_message, red)
# endregion
@ -152,6 +151,7 @@ def ctx(empty_member, empty_channel, red):
@pytest.fixture()
def red(config_fr):
from redbot.core.cli import parse_cli_flags
cli_flags = parse_cli_flags(["ignore_me"])
description = "Red v3 - Alpha"
@ -163,4 +163,6 @@ def red(config_fr):
yield red
red.http._session.close()
# endregion

View File

@ -18,7 +18,7 @@ def default_dir(red):
@pytest.mark.skip
@pytest.mark.asyncio
async def test_ensure_cogs_in_paths(cog_mgr, default_dir):
cogs_dir = default_dir / 'redbot' / 'cogs'
cogs_dir = default_dir / "redbot" / "cogs"
assert cogs_dir in await cog_mgr.paths()
@ -31,7 +31,7 @@ async def test_install_path_set(cog_mgr: cog_manager.CogManager, tmpdir):
@pytest.mark.asyncio
async def test_install_path_set_bad(cog_mgr):
path = Path('something')
path = Path("something")
with pytest.raises(ValueError):
await cog_mgr.set_install_path(path)

View File

@ -61,6 +61,8 @@ async def test_config_force_register_global(config_fr):
config_fr.register_global(enabled=True)
assert await config_fr.enabled() is True
# endregion
@ -73,7 +75,7 @@ async def test_nested_registration(config):
@pytest.mark.asyncio
async def test_nested_registration_asdict(config):
defaults = {'bar': {'baz': False}}
defaults = {"bar": {"baz": False}}
config.register_global(foo=defaults)
assert await config.foo.bar.baz() is False
@ -81,7 +83,7 @@ async def test_nested_registration_asdict(config):
@pytest.mark.asyncio
async def test_nested_registration_and_changing(config):
defaults = {'bar': {'baz': False}}
defaults = {"bar": {"baz": False}}
config.register_global(foo=defaults)
assert await config.foo.bar.baz() is False
@ -100,14 +102,7 @@ async def test_doubleset_default(config):
@pytest.mark.asyncio
async def test_nested_registration_multidict(config):
defaults = {
"foo": {
"bar": {
"baz": True
}
},
"blah": True
}
defaults = {"foo": {"bar": {"baz": True}}, "blah": True}
config.register_global(**defaults)
assert await config.foo.bar.baz() is True
@ -122,7 +117,7 @@ def test_nested_group_value_badreg(config):
@pytest.mark.asyncio
async def test_nested_toplevel_reg(config):
defaults = {'bar': True, 'baz': False}
defaults = {"bar": True, "baz": False}
config.register_global(foo=defaults)
assert await config.foo.bar() is True
@ -180,6 +175,8 @@ async def test_member_default_override(config, empty_member):
@pytest.mark.asyncio
async def test_user_default_override(config, empty_user):
assert await config.user(empty_user).some_value(True) is True
# endregion
@ -213,6 +210,8 @@ async def test_set_channel(config, empty_channel):
async def test_set_channel_no_register(config, empty_channel):
await config.channel(empty_channel).no_register.set(True)
assert await config.channel(empty_channel).no_register() is True
# endregion
@ -305,7 +304,7 @@ async def test_clear_all(config):
await config.clear_all()
with pytest.raises(KeyError):
await config.get_raw('foo')
await config.get_raw("foo")
@pytest.mark.asyncio
@ -314,16 +313,13 @@ async def test_clear_value(config):
await config.foo.clear()
with pytest.raises(KeyError):
await config.get_raw('foo')
await config.get_raw("foo")
# Get All testing
@pytest.mark.asyncio
async def test_user_get_all_from_kind(config, user_factory):
config.register_user(
foo=False,
bar=True
)
config.register_user(foo=False, bar=True)
for _ in range(5):
user = user_factory.get()
await config.user(user).foo.set(True)
@ -333,17 +329,14 @@ async def test_user_get_all_from_kind(config, user_factory):
assert len(all_data) == 5
for _, v in all_data.items():
assert v['foo'] is True
assert v['bar'] is True
assert v["foo"] is True
assert v["bar"] is True
@pytest.mark.asyncio
async def test_user_getalldata(config, user_factory):
user = user_factory.get()
config.register_user(
foo=True,
bar=False
)
config.register_user(foo=True, bar=False)
await config.user(user).foo.set(False)
all_data = await config.user(user).all()
@ -351,18 +344,19 @@ async def test_user_getalldata(config, user_factory):
assert "foo" in all_data
assert "bar" in all_data
assert config.user(user).defaults['foo'] is True
assert config.user(user).defaults["foo"] is True
@pytest.mark.asyncio
async def test_value_ctxmgr(config):
config.register_global(foo_list=[])
async with config.foo_list() as foo_list:
foo_list.append('foo')
foo_list.append("foo")
foo_list = await config.foo_list()
assert 'foo' in foo_list
assert "foo" in foo_list
@pytest.mark.asyncio
@ -371,14 +365,14 @@ async def test_value_ctxmgr_saves(config):
try:
async with config.bar_list() as bar_list:
bar_list.append('bar')
bar_list.append("bar")
raise RuntimeError()
except RuntimeError:
pass
bar_list = await config.bar_list()
assert 'bar' in bar_list
assert "bar" in bar_list
@pytest.mark.asyncio

View File

@ -15,13 +15,13 @@ def cleanup_datamanager():
@pytest.fixture()
def data_mgr_config(tmpdir):
default = data_manager.basic_config_default.copy()
default['BASE_DIR'] = str(tmpdir)
default["BASE_DIR"] = str(tmpdir)
return default
@pytest.fixture()
def cog_instance():
thing = type('CogTest', (object, ), {})
thing = type("CogTest", (object,), {})
return thing()
@ -35,9 +35,9 @@ def test_no_basic(cog_instance):
@pytest.mark.skip
def test_core_path(data_mgr_config, tmpdir):
conf_path = tmpdir.join('config.json')
conf_path = tmpdir.join("config.json")
conf_path.write(json.dumps(data_mgr_config))
data_manager.load_basic_configuration(Path(str(conf_path)))
assert data_manager.core_data_path().parent == Path(data_mgr_config['BASE_DIR'])
assert data_manager.core_data_path().parent == Path(data_mgr_config["BASE_DIR"])

View File

@ -3,46 +3,54 @@ from redbot.core.utils import chat_formatting
def test_bordered_symmetrical():
expected = textwrap.dedent("""\
expected = textwrap.dedent(
"""\
one four
two five
three six
""")
col1, col2 = ['one', 'two', 'three'], ['four', 'five', 'six']
"""
)
col1, col2 = ["one", "two", "three"], ["four", "five", "six"]
assert chat_formatting.bordered(col1, col2) == expected
def test_bordered_asymmetrical():
expected = textwrap.dedent("""\
expected = textwrap.dedent(
"""\
one four
two five
three six
seven
""")
col1, col2 = ['one', 'two', 'three'], ['four', 'five', 'six', 'seven']
"""
)
col1, col2 = ["one", "two", "three"], ["four", "five", "six", "seven"]
assert chat_formatting.bordered(col1, col2) == expected
def test_bordered_asymmetrical_2():
expected = textwrap.dedent("""\
expected = textwrap.dedent(
"""\
one five
two six
three
four
""")
col1, col2 = ['one', 'two', 'three', 'four'], ['five', 'six']
"""
)
col1, col2 = ["one", "two", "three", "four"], ["five", "six"]
assert chat_formatting.bordered(col1, col2) == expected
def test_bordered_ascii():
expected = textwrap.dedent("""\
expected = textwrap.dedent(
"""\
---------------- ---------------
|one | |four |
|two | |five |
|three | |six |
---------------- ---------------""")
col1, col2 = ['one', 'two', 'three'], ['four', 'five', 'six']
---------------- ---------------"""
)
col1, col2 = ["one", "two", "three"], ["four", "five", "six"]
assert chat_formatting.bordered(col1, col2, ascii_border=True) == expected

View File

@ -2,5 +2,5 @@ from redbot import core
def test_version_working():
assert hasattr(core, '__version__')
assert hasattr(core, "__version__")
assert core.__version__[0] == "3"