Skip to content

Commit

Permalink
Merge pull request #3 from praw-dev/tests
Browse files Browse the repository at this point in the history
  • Loading branch information
LilSpazJoekp committed Jul 16, 2020
2 parents 64fb320 + 75cbcdc commit 4c218ff
Show file tree
Hide file tree
Showing 746 changed files with 81,877 additions and 125,311 deletions.
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ jobs:
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install https://github.com/LilSpazJoekp/vcrpy/archive/asyncpraw.zip
pip install .[test]
- name: Test with pytest
run: pytest
Expand All @@ -121,6 +122,7 @@ jobs:
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install https://github.com/LilSpazJoekp/vcrpy/archive/asyncpraw.zip
pip install .[test]
pip install https://github.com/bboe/coveralls-python/archive/github_actions.zip
- name: Test with pytest
Expand Down Expand Up @@ -154,6 +156,7 @@ jobs:
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install https://github.com/LilSpazJoekp/vcrpy/archive/asyncpraw.zip
pip install .[test]
- name: Run network test
run: pytest tests/integration/test_github_actions.py::test_github_actions
Expand Down
30 changes: 8 additions & 22 deletions asyncpraw/models/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
from json import dumps
from typing import AsyncGenerator, List, Optional, Union

from asyncprawcore import NotFound

from ..const import API_PATH
from .base import AsyncPRAWBase
from .reddit.live import LiveThread
Expand Down Expand Up @@ -33,7 +31,7 @@ async def __call__(
await livethread.close()
:param id: A live thread ID, e.g., ``ukaeu1ik4sw5``.
:param fetch: Determines if the object is loaded on call (default: False).
:param fetch: Determines if the object is lazily loaded (default: False).
"""
live_thread = LiveThread(self._reddit, id=id)
if fetch:
Expand Down Expand Up @@ -70,7 +68,7 @@ def info(self, ids: List[str]) -> AsyncGenerator[LiveThread, None]:
if not isinstance(ids, list):
raise TypeError("ids must be a list")

async def generator():
async def generator(): # pragma: no cover; FIXME this endpoint does not work as of 07/12/2020
for position in range(0, len(ids), 100):
ids_chunk = ids[position : position + 100]
url = API_PATH["live_info"].format(ids=",".join(ids_chunk))
Expand Down Expand Up @@ -143,7 +141,7 @@ async def __call__(
:param redditor: A redditor name (e.g., ``"spez"``) or
:class:`~.Redditor` instance who owns the multireddit.
:param name: The name of the multireddit.
:param fetch: Determines if the object is loaded on call (default: False).
:param fetch: Determines if the object is lazily loaded (default: False).
"""
path = "/user/{}/m/{}".format(redditor, name)
multireddit = Multireddit(self._reddit, _data={"name": name, "path": path})
Expand Down Expand Up @@ -213,29 +211,18 @@ async def __call__(self, display_name: str, fetch: bool = False) -> Subreddit:
print(comment.author)
:param display_name: The name of the subreddit.
:param fetch: Determines if the object is loaded on call (default: False).
:param fetch: Determines if the object is lazily loaded (default: False).
"""
lower_name = display_name.lower()

if lower_name == "random":
return await self._reddit.random_subreddit()
if lower_name == "randnsfw":
return await self._reddit.random_subreddit(nsfw=True)
sub = Subreddit(self._reddit, display_name=display_name)
subreddit = Subreddit(self._reddit, display_name=display_name)
if fetch:
sub = await self._determine_fetch(lower_name, sub)
return sub

async def _determine_fetch(self, lower_name, sub):
# if the sub doesn't exist then check to see if it is a special subreddit
# construct and re-raise the exception if it is not
if "+" not in lower_name and lower_name not in ["mod", "all"]:
try:
await sub._fetch()
return sub
except NotFound:
if not lower_name.startswith(("mod", "all")) and "-" not in lower_name:
raise NotFound
await subreddit._fetch()
return subreddit

async def create(
self,
Expand Down Expand Up @@ -276,6 +263,5 @@ async def create(
wikimode=wikimode,
**other_settings
)
subreddit = self(name)
await subreddit._fetch()
subreddit = await self(name, fetch=True)
return subreddit
6 changes: 1 addition & 5 deletions asyncpraw/models/list/base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""Provide the BaseList class."""
from typing import TYPE_CHECKING, Any, Dict, Iterator, AsyncIterator
from typing import TYPE_CHECKING, Any, Dict, Iterator

from ..base import AsyncPRAWBase

Expand Down Expand Up @@ -35,10 +35,6 @@ def __getitem__(self, index: int) -> Any:
"""Return the item at position index in the list."""
return getattr(self, self.CHILD_ATTRIBUTE)[index]

async def __aiter__(self,) -> AsyncIterator[Any]:
"""Return an async iterator to the list."""
return getattr(self, self.CHILD_ATTRIBUTE).__aiter__()

def __iter__(self) -> Iterator[Any]:
"""Return an iterator to the list."""
return getattr(self, self.CHILD_ATTRIBUTE).__iter__()
Expand Down
8 changes: 4 additions & 4 deletions asyncpraw/models/listing/mixins/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,16 +160,16 @@ def top(
reddit.domain("imgur.com").top("week")
multireddit = await reddit.multireddit("samuraisam", "programming", lazy=False)
multireddit = await reddit.multireddit("samuraisam", "programming")
multireddit.top("day")
redditor = await reddit.redditor("spez", lazy=True)
redditor = await reddit.redditor("spez")
redditor.top("month")
redditor = await reddit.redditor("spez", lazy=True)
redditor = await reddit.redditor("spez")
redditor.comments.top("year")
redditor = await reddit.redditor("spez", lazy=True)
redditor = await reddit.redditor("spez")
redditor.submissions.top("all")
subreddit = await reddit.subreddit("all")
Expand Down
4 changes: 2 additions & 2 deletions asyncpraw/models/listing/mixins/subreddit.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def __call__(
.. code-block:: python
subreddit = await reddit.subreddit('redditdev', lazy=True)
subreddit = await reddit.subreddit('redditdev')
async for comment in subreddit.comments(limit=25):
print(comment.author)
Expand All @@ -59,7 +59,7 @@ def comments(self) -> CommentHelper:
.. code-block:: python
subreddit = await reddit.subreddit('redditdev', lazy=True)
subreddit = await reddit.subreddit('redditdev')
async for comment in subreddit.comments(limit=25):
print(comment.author)
Expand Down
18 changes: 11 additions & 7 deletions asyncpraw/models/reddit/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -424,11 +424,11 @@ def mod(self) -> "SubredditCollectionsModeration":
.. code-block:: python
my_sub = await reddit.subreddit("SUBREDDIT")
my_sub = await reddit.subreddit("SUBREDDIT", fetch=True)
new_collection = await my_sub.collections.mod.create("Title", "desc")
"""
return SubredditCollectionsModeration(self._reddit, self.subreddit.fullname)
return SubredditCollectionsModeration(self._reddit, self.subreddit)

async def __call__(
self,
Expand All @@ -440,7 +440,7 @@ async def __call__(
:param collection_id: The ID of a Collection (default: None).
:param permalink: The permalink of a Collection (default: None).
:param lazy: Determines if object is loaded lazily (default: False)
:param lazy: If True, object is loaded lazily (default: False)
:returns: The specified Collection.
Exactly one of ``collection_id`` and ``permalink`` is required.
Expand All @@ -466,7 +466,7 @@ class method) you can do:
.. code-block:: python
subreddit = await reddit.subreddit("SUBREDDIT")
subreddit = await reddit.subreddit("SUBREDDIT", fetch=True)
collection = await subreddit.collections(uuid, lazy=True)
await collection.mod.add("submission_id")
Expand Down Expand Up @@ -504,6 +504,8 @@ async def __aiter__(self):
print(collection.permalink)
"""
if not self.subreddit._fetched:
await self.subreddit._fetch()
request = await self._reddit.get(
API_PATH["collection_subreddit"],
params={"sr_fullname": self.subreddit.fullname},
Expand All @@ -527,12 +529,12 @@ class SubredditCollectionsModeration(AsyncPRAWBase):
def __init__(
self,
reddit: "Reddit",
sub_fullname: str,
subreddit: Subreddit,
_data: Optional[Dict[str, Any]] = None,
):
"""Initialize the SubredditCollectionsModeration instance."""
super().__init__(reddit, _data)
self.subreddit_fullname = sub_fullname
self.subreddit = subreddit

async def create(self, title: str, description: str):
"""Create a new :class:`.Collection`.
Expand All @@ -556,10 +558,12 @@ async def create(self, title: str, description: str):
.. seealso:: :meth:`~CollectionModeration.delete`
"""
if not self.subreddit._fetched:
await self.subreddit._fetch()
return await self._reddit.post(
API_PATH["collection_create"],
data={
"sr_fullname": self.subreddit_fullname,
"sr_fullname": self.subreddit.fullname,
"title": title,
"description": description,
},
Expand Down
8 changes: 2 additions & 6 deletions asyncpraw/models/reddit/comment.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,12 +279,8 @@ async def parent(self) -> Union["Comment", "Submission"]:
"""
# pylint: disable=no-member

if "submission" in self.__dict__:
if not self.submission._fetched:
await self.submission._fetch()
else:
await self._fetch()
await self.submission._fetch()
await self._fetch()
await self.submission._fetch()
if self.parent_id == self.submission.fullname:
return self.submission

Expand Down
16 changes: 14 additions & 2 deletions asyncpraw/models/reddit/emoji.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,10 +145,11 @@ async def update(
class SubredditEmoji:
"""Provides a set of functions to a Subreddit for emoji."""

async def get_emoji(self, name: str) -> Emoji:
async def get_emoji(self, name: str, lazy: bool = False) -> Emoji:
"""Return the Emoji for the subreddit named ``name``.
:param name: The name of the emoji
:param lazy: If True, object is loaded lazily (default: False)
This method is to be used to fetch a specific emoji url, like so:
Expand All @@ -158,9 +159,20 @@ async def get_emoji(self, name: str) -> Emoji:
emoji = await subreddit.emoji.get_emoji("test")
print(emoji)
If you don't need the object fetched right away (e.g., to utilize a
class method) you can do:
.. code-block:: python
subreddit = await reddit.subreddit("praw_test")
emoji = await subreddit.emoji.get_emoji("test", lazy=True)
await emoji.delete()
"""
emoji = Emoji(self._reddit, self.subreddit, name)
await emoji._fetch()
if not lazy:
await emoji._fetch()
return emoji

def __init__(self, subreddit: "Subreddit"):
Expand Down
41 changes: 21 additions & 20 deletions asyncpraw/models/reddit/live.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ def _handle_permissions(permissions):
permissions = set(permissions)
return ",".join("+{}".format(x) for x in permissions)

# TODO: this is implemented differently than in praw
def __call__(self,) -> AsyncGenerator: # noqa: D202
"""Return a :class:`.RedditorList` for live threads' contributors.
Expand Down Expand Up @@ -357,11 +356,11 @@ def __eq__(self, other: Union[str, "LiveThread"]) -> bool:
return other == str(self)
return isinstance(other, self.__class__) and str(self) == str(other)

async def get_update(self, update_id: str) -> "LiveUpdate":
async def get_update(self, update_id: str, lazy: bool = False) -> "LiveUpdate":
"""Return a :class:`.LiveUpdate` instance.
:param update_id: A live update ID, e.g.,
``"7827987a-c998-11e4-a0b9-22000b6a88d2"``.
:param update_id: A live update ID, e.g., ``"7827987a-c998-11e4-a0b9-22000b6a88d2"``.
:param lazy: If True, object is loaded lazily (default: False).
Usage:
Expand All @@ -372,9 +371,19 @@ async def get_update(self, update_id: str) -> "LiveUpdate":
update.thread # LiveThread(id="ukaeu1ik4sw5")
update.id # "7827987a-c998-11e4-a0b9-22000b6a88d2"
update.author # "umbrae"
If you don't need the object fetched right away (e.g., to utilize a
class method) you can do:
.. code-block:: python
thread = await reddit.live("ukaeu1ik4sw5")
update = await thread.get_update("7827987a-c998-11e4-a0b9-22000b6a88d2", lazy=True)
update.contrib # LiveUpdateContribution instance
"""
update = LiveUpdate(self._reddit, self.id, update_id)
await update._fetch()
if not lazy:
await update._fetch()
return update

def __hash__(self) -> int:
Expand Down Expand Up @@ -595,9 +604,9 @@ async def update(
}

url = API_PATH["live_update_thread"].format(id=self.thread.id)
# asyncprawcore (0.7.0) Session.request() modifies `data` kwarg
# prawcore (0.7.0) Session.request() modifies `data` kwarg
await self.thread._reddit.post(url, data=data.copy())
self.thread._reset_attributes(*data.keys()) # TODO: see if this is necessary
self.thread._reset_attributes(*data.keys())


class LiveThreadStream:
Expand Down Expand Up @@ -694,7 +703,7 @@ def contrib(self) -> "LiveUpdateContribution":
.. code-block:: python
thread = await reddit.live("ukaeu1ik4sw5")
update = await thread.get_update("7827987a-c998-11e4-a0b9-22000b6a88d2")
update = await thread.get_update("7827987a-c998-11e4-a0b9-22000b6a88d2", lazy=True)
update.contrib # LiveUpdateContribution instance
"""
Expand All @@ -705,12 +714,6 @@ def thread(self) -> LiveThread:
"""Return :class:`.LiveThread` object the update object belongs to."""
return self._thread

# TODO: this will need implemented differently; possibly changed to async
# for example:
# async def __ainit__(..):
# ...
# __init__ = __ainit__

def __init__(
self,
reddit: "Reddit",
Expand All @@ -720,20 +723,18 @@ def __init__(
):
"""Initialize a lazy :class:`.LiveUpdate` instance.
Either ``thread_id`` and ``update_id``, or ``_data`` must be
provided.
Either ``thread_id`` and ``update_id``, or ``_data`` must be provided.
:param reddit: An instance of :class:`.Reddit`.
:param thread_id: A live thread ID, e.g., ``"ukaeu1ik4sw5"``.
:param update_id: A live update ID, e.g.,
``"7827987a-c998-11e4-a0b9-22000b6a88d2"``.
:param update_id: A live update ID, e.g., ``"7827987a-c998-11e4-a0b9-22000b6a88d2"``.
Usage:
.. code-block:: python
update = LiveUpdate(reddit, "ukaeu1ik4sw5",
"7827987a-c998-11e4-a0b9-22000b6a88d2")
update = LiveUpdate(reddit, "ukaeu1ik4sw5", "7827987a-c998-11e4-a0b9-22000b6a88d2")
await update.load()
update.thread # LiveThread(id="ukaeu1ik4sw5")
update.id # "7827987a-c998-11e4-a0b9-22000b6a88d2"
update.author # "umbrae"
Expand Down
1 change: 1 addition & 0 deletions asyncpraw/models/reddit/mixins/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ async def distinguish(self, how="yes", sticky=False):
"""
data = {"how": how, "id": self.thing.fullname}
await self.thing._fetch()
if sticky and getattr(self.thing, "is_root", False):
data["sticky"] = True
await self.thing._reddit.post(API_PATH["distinguish"], data=data)
Expand Down
2 changes: 1 addition & 1 deletion asyncpraw/models/reddit/mixins/replyable.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,5 @@ async def reply(self, body: str):
comments = await self._reddit.post(API_PATH["comment"], data=data)
try:
return comments[0]
except IndexError:
except IndexError: # pragma: no cover; I haven't been able to make this happen again
return None

0 comments on commit 4c218ff

Please sign in to comment.