Compare commits
59 Commits
version-up
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6ee6fc8b88 | ||
|
|
7d05b1c42c | ||
|
|
b03c9738f1 | ||
|
|
36f8f1e737 | ||
|
|
2d27cc2a3c | ||
|
|
f81c1b775a | ||
|
|
270f4bbbdb | ||
|
|
7d981684aa | ||
|
|
53be265b23 | ||
|
|
a07b122c39 | ||
|
|
6d54153a24 | ||
|
|
c30a453a6b | ||
|
|
3e87ef3849 | ||
|
|
0f1cc41967 | ||
|
|
7ca7f47e94 | ||
|
|
d8ec2f61aa | ||
|
|
f94d861c64 | ||
|
|
565b714d81 | ||
|
|
e1a9038789 | ||
|
|
b38f99bffe | ||
|
|
4d20bfd79c | ||
|
|
99359aa518 | ||
|
|
ea7d47c5da | ||
|
|
fcdd6ab8dd | ||
|
|
c850e34112 | ||
|
|
ee21957027 | ||
|
|
acb0af24d1 | ||
|
|
31db8017bc | ||
|
|
5d28665fbb | ||
|
|
51771057f5 | ||
|
|
d7e249847a | ||
|
|
b348fe13f3 | ||
|
|
30f9b9b338 | ||
|
|
815bfd8af6 | ||
|
|
2be1a46c1d | ||
|
|
2aac9a20be | ||
|
|
fe4f67c041 | ||
|
|
6c1d9a9e1d | ||
|
|
7ab58533b7 | ||
|
|
dc498679cc | ||
|
|
c49d29620d | ||
|
|
2a3036f039 | ||
|
|
14b2f7a08d | ||
|
|
5c4d0b3aed | ||
|
|
f20fc33349 | ||
|
|
3d2a8def57 | ||
|
|
80c1a17e4b | ||
|
|
b5eda64a05 | ||
|
|
87cf273cd6 | ||
|
|
c5466fd182 | ||
|
|
fe17d3977c | ||
|
|
f93e1cb341 | ||
|
|
2cf6c675e0 | ||
|
|
991cc564dd | ||
|
|
7ebc08356a | ||
|
|
a58ca74362 | ||
|
|
8a73f911e2 | ||
|
|
87891a6331 | ||
|
|
daab45edda |
@ -1,3 +0,0 @@
|
||||
[run]
|
||||
|
||||
include: pydiscourse/*
|
||||
@ -1,3 +1,11 @@
|
||||
c0db7215c95dbd31770ade1fc6ea65aa426d4590
|
||||
0177c46356b9d0fc4b93f09aab7a224643a3685e
|
||||
f6b4c02fc0f144dffc88cdd48b8261a69228d2f0
|
||||
2a3036f0395a810b0941522bfb1ca80b159525ce
|
||||
c49d29620dfb867f73ebb6be84b5e1ba922fadc9
|
||||
dc498679cc6769acafe19cf0083f40154ffdcff8
|
||||
7ab58533b759d1ff879476a5703051b201afd835
|
||||
fe4f67c04160a76948d810848ae082713ea6b5ed
|
||||
2aac9a20beb19a6a052286f73f5d0f5bf76ed758
|
||||
2be1a46c1da497e136818b5ef77708b8c5b69e57
|
||||
31db8017bc90978b879c5caa7f1cd4777d19a27e
|
||||
|
||||
24
.github/workflows/test.yml
vendored
24
.github/workflows/test.yml
vendored
@ -3,13 +3,35 @@ name: Tests
|
||||
on: [ push, pull_request ]
|
||||
|
||||
jobs:
|
||||
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v2
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install ruff
|
||||
|
||||
- name: Lint with Ruff
|
||||
run: ruff .
|
||||
|
||||
test:
|
||||
|
||||
needs: lint
|
||||
|
||||
name: Test on Python ${{ matrix.python-version }}
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
python-version: [ "3.8", "3.9", "3.10", "3.11" ]
|
||||
python-version: [ "3.8", "3.9", "3.10", "3.11", "3.12" ]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
|
||||
19
.pre-commit-config.yaml
Normal file
19
.pre-commit-config.yaml
Normal file
@ -0,0 +1,19 @@
|
||||
exclude: "docs|.git|.tox"
|
||||
default_stages: [ commit ]
|
||||
fail_fast: true
|
||||
|
||||
repos:
|
||||
|
||||
- repo: https://github.com/charliermarsh/ruff-pre-commit
|
||||
rev: "v0.0.286"
|
||||
hooks:
|
||||
- id: ruff
|
||||
|
||||
- repo: https://github.com/psf/black
|
||||
rev: 23.7.0
|
||||
hooks:
|
||||
- id: black
|
||||
args:
|
||||
- --config=pyproject.toml
|
||||
- src/pydiscourse
|
||||
- tests
|
||||
@ -19,9 +19,9 @@ Reviewing and merging pull requests is work, so whatever you can do to make this
|
||||
easier for the package maintainer not only speed up the process of getting your
|
||||
changes merged but also ensure they are. These few guidelines help significantly.
|
||||
If they are confusing or you need help understanding how to accomplish them,
|
||||
please ask for help in an issue.
|
||||
please ask for help in an issue.
|
||||
|
||||
- Please do make sure your chnageset represents a *discrete update*. If you would like to fix formatting, by all means, but don't mix that up with a bug fix. Those are separate PRs.
|
||||
- Please do make sure your changeset represents a *discrete update*. If you would like to fix formatting, by all means, but don't mix that up with a bug fix. Those are separate PRs.
|
||||
- Please do make sure that both your pull request description and your commits are meaningful and descriptive. Rebase first, if need be.
|
||||
- Please do make sure your changeset does not include more commits than necessary. Rebase first, if need be.
|
||||
- Please do make sure the changeset is not very big. If you have a large change propose it in an issue first.
|
||||
@ -30,10 +30,27 @@ please ask for help in an issue.
|
||||
Testing
|
||||
=======
|
||||
|
||||
The best way to run the tests is with `tox <http://tox.readthedocs.org/en/latest/>`_::
|
||||
Running tests
|
||||
-------------
|
||||
|
||||
The simplest way to quickly and repeatedly run tests while developing a feature or fix
|
||||
is to use `pytest` in your current Python environment.
|
||||
|
||||
After installing the test dependencies::
|
||||
|
||||
pip install -r requirements.txt
|
||||
pip install -e .
|
||||
|
||||
Your can run the tests with `pytest`::
|
||||
|
||||
pytest --cov=src/pydiscourse
|
||||
|
||||
This will ensure you get coverage reporting.
|
||||
|
||||
The most comprehensive way to run the tests is with `tox <http://tox.readthedocs.org/en/latest/>`_::
|
||||
|
||||
pip install tox
|
||||
detox
|
||||
tox
|
||||
|
||||
Or it's slightly faster cousin `detox
|
||||
<https://pypi.python.org/pypi/detox>`_ which will parallelize test runs::
|
||||
@ -41,16 +58,29 @@ Or it's slightly faster cousin `detox
|
||||
pip install detox
|
||||
detox
|
||||
|
||||
Alternatively, you can run the self test with the following commands::
|
||||
Writing tests
|
||||
-------------
|
||||
|
||||
pip install -r requirements.txt
|
||||
pip install -e .
|
||||
python setup.py test
|
||||
The primary modules of the library have coverage requirements, so you should
|
||||
write a test or tests when you add a new feature.
|
||||
|
||||
**At a bare minimum a test should show which Discourse API endpoint is called,
|
||||
using which HTTP method, and returning any necessary data for the new function/method.**
|
||||
|
||||
In most cases this can be accomplished quite simply by using the `discourse_request`
|
||||
fixture, which allows for mocking the HTTP request in the `requests` library. In some cases
|
||||
this may be insufficient, and you may want to directly use the `requests_mock` mocking
|
||||
fixture.
|
||||
|
||||
If in the course of writing your test you see a `requests_mock.NoMockAddress` exception
|
||||
raised then either the *method* or the *path* (including querystring) - or both! - in
|
||||
either your mock OR your new API client method is incorrect.
|
||||
|
||||
Live Testing
|
||||
============
|
||||
|
||||
You can test against a Discourse instance by following the [Official Discourse developement instructions][discoursedev].
|
||||
|
||||
For the impatient here is the quick and dirty version::
|
||||
|
||||
git clone git@github.com:discourse/discourse.git
|
||||
|
||||
24
HISTORY.rst
24
HISTORY.rst
@ -3,6 +3,30 @@
|
||||
Release history
|
||||
===============
|
||||
|
||||
|
||||
1.7.0
|
||||
-----
|
||||
|
||||
- Possible breaking change: Change `search()` term paramater from `term` to `q`,
|
||||
fixes search. Thanks @weber-s
|
||||
- Add support for Python 3.12
|
||||
|
||||
1.6.1
|
||||
-----
|
||||
|
||||
- Adds `posts_by_number` endpoint from @Dettorer
|
||||
|
||||
1.6.0
|
||||
-----
|
||||
|
||||
- Breaking: `toggle_gravatar`, `pick_avatar`, `create_group` now *require*
|
||||
keyword arguments where keyword arguments were used. This *may* break existing
|
||||
code if you have not referenced these by keyword!
|
||||
- Introduced `ruff` and `black` into pre-commit hook
|
||||
- Added `lint` job to GitHub Actions, tests will run if and only if lint job
|
||||
passes.
|
||||
- Sundry code cleanup
|
||||
|
||||
1.5.0
|
||||
-----
|
||||
|
||||
|
||||
70
README.rst
70
README.rst
@ -2,9 +2,13 @@
|
||||
pydiscourse
|
||||
===========
|
||||
|
||||
.. image:: https://github.com/bennylope/pydiscourse/workflows/Tests/badge.svg
|
||||
.. image:: https://img.shields.io/pypi/v/pydiscourse?color=blue
|
||||
:alt: PyPI
|
||||
:target: https://pypi.org/project/pydiscourse/
|
||||
|
||||
.. image:: https://github.com/pydiscourse/pydiscourse/workflows/Tests/badge.svg
|
||||
:alt: Build Status
|
||||
:target: https://github.com/bennylope/pydiscourse/actions
|
||||
:target: https://github.com/pydiscourse/pydiscourse/actions
|
||||
|
||||
.. image:: https://img.shields.io/badge/Check%20out%20the-Docs-blue.svg
|
||||
:alt: Check out the Docs
|
||||
@ -37,42 +41,52 @@ Installation
|
||||
Examples
|
||||
========
|
||||
|
||||
Create a client connection to a Discourse server::
|
||||
Create a client connection to a Discourse server:
|
||||
|
||||
from pydiscourse import DiscourseClient
|
||||
client = DiscourseClient(
|
||||
'http://example.com',
|
||||
api_username='username',
|
||||
api_key='areallylongstringfromdiscourse')
|
||||
.. code:: python
|
||||
|
||||
Get info about a user::
|
||||
from pydiscourse import DiscourseClient
|
||||
client = DiscourseClient(
|
||||
'http://example.com',
|
||||
api_username='username',
|
||||
api_key='areallylongstringfromdiscourse')
|
||||
|
||||
user = client.user('eviltrout')
|
||||
print user
|
||||
Get info about a user:
|
||||
|
||||
user_topics = client.topics_by('johnsmith')
|
||||
print user_topics
|
||||
.. code:: python
|
||||
|
||||
Create a new user::
|
||||
user = client.user('eviltrout')
|
||||
print user
|
||||
|
||||
user = client.create_user('The Black Knight', 'blacknight', 'knight@python.org', 'justafleshwound')
|
||||
user_topics = client.topics_by('johnsmith')
|
||||
print user_topics
|
||||
|
||||
Implement SSO for Discourse with your Python server::
|
||||
Create a new user:
|
||||
|
||||
@login_required
|
||||
def discourse_sso_view(request):
|
||||
payload = request.GET.get('sso')
|
||||
signature = request.GET.get('sig')
|
||||
nonce = sso_validate(payload, signature, SECRET)
|
||||
url = sso_redirect_url(nonce, SECRET, request.user.email, request.user.id, request.user.username)
|
||||
return redirect('http://discuss.example.com' + url)
|
||||
.. code:: python
|
||||
|
||||
user = client.create_user('The Black Knight', 'blacknight', 'knight@python.org', 'justafleshwound')
|
||||
|
||||
Implement SSO for Discourse with your Python server:
|
||||
|
||||
.. code:: python
|
||||
|
||||
@login_required
|
||||
def discourse_sso_view(request):
|
||||
payload = request.GET.get('sso')
|
||||
signature = request.GET.get('sig')
|
||||
nonce = sso_validate(payload, signature, SECRET)
|
||||
url = sso_redirect_url(nonce, SECRET, request.user.email, request.user.id, request.user.username)
|
||||
return redirect('http://discuss.example.com' + url)
|
||||
|
||||
Command line
|
||||
============
|
||||
|
||||
To help experiment with the Discourse API, pydiscourse provides a simple command line client::
|
||||
To help experiment with the Discourse API, pydiscourse provides a simple command line client:
|
||||
|
||||
export DISCOURSE_API_KEY=your_master_key
|
||||
pydiscoursecli --host-http://yourhost --api-user-system latest_topics
|
||||
pydiscoursecli --host-http://yourhost --api-user-system topics_by johnsmith
|
||||
pydiscoursecli --host-http://yourhost --api-user-system user eviltrout
|
||||
.. code:: bash
|
||||
|
||||
export DISCOURSE_API_KEY=your_master_key
|
||||
pydiscoursecli --host-http://yourhost --api-user-system latest_topics
|
||||
pydiscoursecli --host-http://yourhost --api-user-system topics_by johnsmith
|
||||
pydiscoursecli --host-http://yourhost --api-user-system user eviltrout
|
||||
|
||||
@ -51,9 +51,9 @@ copyright = u'2014, Marc Sibson'
|
||||
# built documents.
|
||||
#
|
||||
# The short X.Y version.
|
||||
version = '1.5'
|
||||
version = '1.7'
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = '1.5.0'
|
||||
release = '1.7.0'
|
||||
|
||||
# The language for content autogenerated by Sphinx. Refer to documentation
|
||||
# for a list of supported languages.
|
||||
|
||||
49
pyproject.toml
Normal file
49
pyproject.toml
Normal file
@ -0,0 +1,49 @@
|
||||
[tool.black]
|
||||
line-length=120
|
||||
target-version = ["py311"]
|
||||
|
||||
[tool.ruff]
|
||||
exclude = [
|
||||
".tox",
|
||||
".git",
|
||||
"build",
|
||||
"dist",
|
||||
"docs",
|
||||
".ropeproject",
|
||||
]
|
||||
ignore = [
|
||||
"S101", # Assertions good, actually
|
||||
"TRY003", # For now not worth back tracking
|
||||
]
|
||||
line-length = 240
|
||||
select = [
|
||||
"S", # Security (formerly B when using Bandit directly)
|
||||
"E",
|
||||
"F",
|
||||
"N",
|
||||
"W",
|
||||
"COM", # commas
|
||||
"PT", # pytest
|
||||
"UP", # Upgrade Python syntax
|
||||
"T",
|
||||
"A", # built-in shadowing
|
||||
"FBT", # Boolean traps
|
||||
"BLE", # Blind exceptions
|
||||
"PIE",
|
||||
"TRY",
|
||||
"ERA", # eradicate commented out code
|
||||
]
|
||||
|
||||
[tool.ruff.flake8-pytest-style]
|
||||
fixture-parentheses = false
|
||||
mark-parentheses = true
|
||||
parametrize-names-type = "tuple"
|
||||
parametrize-values-row-type = "tuple"
|
||||
|
||||
[tool.ruff.mccabe]
|
||||
# Unlike Flake8, default to a complexity level of 10.
|
||||
max-complexity = 10
|
||||
|
||||
[tool.coverage.run]
|
||||
include = ["src/pydiscourse/*"]
|
||||
|
||||
@ -1,2 +1,9 @@
|
||||
pytest==6.2.5
|
||||
pytest-cov==3.0.0
|
||||
pre-commit==3.3.3
|
||||
ruff==0.0.286
|
||||
pytest==7.4.0
|
||||
pytest-cov==4.1.0
|
||||
pytest-mock==3.11.1 # https://github.com/pytest-dev/pytest-mock/
|
||||
pytest-socket==0.6.0 # https://github.com/miketheman/pytest-socket
|
||||
requests-mock==1.11.0 # https://github.com/jamielennox/requests-mock
|
||||
pytest-subtests==0.11.0 # https://github.com/pytest-dev/pytest-subtests
|
||||
pytest-icdiff==0.6 # https://pypi.org/project/pytest-icdiff/
|
||||
|
||||
@ -18,7 +18,6 @@ package_dir =
|
||||
=src
|
||||
install_requires =
|
||||
requests>=2.4.2
|
||||
typing; python_version<"3.6"
|
||||
classifiers =
|
||||
Development Status :: 5 - Production/Stable
|
||||
Environment :: Web Environment
|
||||
@ -30,6 +29,7 @@ classifiers =
|
||||
Programming Language :: Python :: 3.9
|
||||
Programming Language :: Python :: 3.10
|
||||
Programming Language :: Python :: 3.11
|
||||
Programming Language :: Python :: 3.12
|
||||
|
||||
[options.packages.find]
|
||||
where=src
|
||||
|
||||
1
setup.py
1
setup.py
@ -1,4 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
See setup.cfg for packaging settings
|
||||
"""
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
"""Python client for the Discourse API."""
|
||||
|
||||
__version__ = "1.5.0"
|
||||
__version__ = "1.7.0"
|
||||
|
||||
from pydiscourse.client import DiscourseClient
|
||||
|
||||
|
||||
@ -27,7 +27,15 @@ POST = "POST"
|
||||
PUT = "PUT"
|
||||
|
||||
|
||||
class DiscourseClient(object):
|
||||
def now() -> datetime:
|
||||
"""Returns the current UTC time.
|
||||
|
||||
This function enables simple mocking for freezing time.
|
||||
"""
|
||||
return datetime.utcnow()
|
||||
|
||||
|
||||
class DiscourseClient:
|
||||
"""Discourse API client"""
|
||||
|
||||
def __init__(self, host, api_username, api_key, timeout=None):
|
||||
@ -62,16 +70,16 @@ class DiscourseClient(object):
|
||||
dict of user information
|
||||
|
||||
"""
|
||||
return self._get("/users/{0}.json".format(username))["user"]
|
||||
return self._get(f"/users/{username}.json")["user"]
|
||||
|
||||
def approve(self, user_id):
|
||||
return self._get("/admin/users/{0}/approve.json".format(user_id))
|
||||
return self._get(f"/admin/users/{user_id}/approve.json")
|
||||
|
||||
def activate(self, user_id):
|
||||
return self._put("/admin/users/{0}/activate.json".format(user_id))
|
||||
return self._put(f"/admin/users/{user_id}/activate.json")
|
||||
|
||||
def deactivate(self, user_id):
|
||||
return self._put("/admin/users/{0}/deactivate.json".format(user_id))
|
||||
return self._put(f"/admin/users/{user_id}/deactivate.json")
|
||||
|
||||
def user_all(self, user_id):
|
||||
"""
|
||||
@ -82,7 +90,7 @@ class DiscourseClient(object):
|
||||
Returns:
|
||||
dict of user information
|
||||
"""
|
||||
return self._get("/admin/users/{0}.json".format(user_id))
|
||||
return self._get(f"/admin/users/{user_id}.json")
|
||||
|
||||
def invite(self, email, group_names, custom_message, **kwargs):
|
||||
"""
|
||||
@ -103,7 +111,7 @@ class DiscourseClient(object):
|
||||
email=email,
|
||||
group_names=group_names,
|
||||
custom_message=custom_message,
|
||||
**kwargs
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def invite_link(self, email, group_names, custom_message, **kwargs):
|
||||
@ -125,7 +133,7 @@ class DiscourseClient(object):
|
||||
email=email,
|
||||
group_names=group_names,
|
||||
custom_message=custom_message,
|
||||
**kwargs
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def user_by_id(self, pk):
|
||||
@ -138,7 +146,7 @@ class DiscourseClient(object):
|
||||
Returns:
|
||||
user
|
||||
"""
|
||||
return self._get("/admin/users/{0}.json".format(pk))
|
||||
return self._get(f"/admin/users/{pk}.json")
|
||||
|
||||
def user_by_email(self, email):
|
||||
"""
|
||||
@ -150,7 +158,7 @@ class DiscourseClient(object):
|
||||
Returns:
|
||||
user
|
||||
"""
|
||||
return self._get("/admin/users/list/all.json?email={0}".format(email))
|
||||
return self._get(f"/admin/users/list/all.json?email={email}")
|
||||
|
||||
def create_user(self, name, username, email, password, **kwargs):
|
||||
"""
|
||||
@ -182,7 +190,7 @@ class DiscourseClient(object):
|
||||
password=password,
|
||||
password_confirmation=confirmations,
|
||||
challenge=challenge,
|
||||
**kwargs
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def user_by_external_id(self, external_id):
|
||||
@ -194,7 +202,7 @@ class DiscourseClient(object):
|
||||
Returns:
|
||||
|
||||
"""
|
||||
response = self._get("/users/by-external/{0}".format(external_id))
|
||||
response = self._get(f"/users/by-external/{external_id}")
|
||||
return response["user"]
|
||||
|
||||
by_external_id = user_by_external_id
|
||||
@ -208,7 +216,7 @@ class DiscourseClient(object):
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._post("/admin/users/{0}/log_out".format(userid))
|
||||
return self._post(f"/admin/users/{userid}/log_out")
|
||||
|
||||
def trust_level(self, userid, level):
|
||||
"""
|
||||
@ -220,7 +228,18 @@ class DiscourseClient(object):
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._put("/admin/users/{0}/trust_level".format(userid), level=level)
|
||||
return self._put(f"/admin/users/{userid}/trust_level", level=level)
|
||||
|
||||
def anonymize(self, userid):
|
||||
"""
|
||||
|
||||
Args:
|
||||
userid: the Discourse user ID
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._put(f"/admin/users/{userid}/anonymize")
|
||||
|
||||
def suspend(self, userid, duration, reason):
|
||||
"""
|
||||
@ -236,9 +255,9 @@ class DiscourseClient(object):
|
||||
????
|
||||
|
||||
"""
|
||||
suspend_until = (datetime.now() + timedelta(days=duration)).isoformat()
|
||||
suspend_until = (now() + timedelta(days=duration)).isoformat()
|
||||
return self._put(
|
||||
"/admin/users/{0}/suspend".format(userid),
|
||||
f"/admin/users/{userid}/suspend",
|
||||
suspend_until=suspend_until,
|
||||
reason=reason,
|
||||
)
|
||||
@ -253,21 +272,21 @@ class DiscourseClient(object):
|
||||
Returns:
|
||||
None???
|
||||
"""
|
||||
return self._put("/admin/users/{0}/unsuspend".format(userid))
|
||||
return self._put(f"/admin/users/{userid}/unsuspend")
|
||||
|
||||
def list_users(self, type, **kwargs):
|
||||
def list_users(self, user_type, **kwargs):
|
||||
"""
|
||||
|
||||
optional user search: filter='test@example.com' or filter='scott'
|
||||
|
||||
Args:
|
||||
type:
|
||||
user_type:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._get("/admin/users/list/{0}.json".format(type), **kwargs)
|
||||
return self._get(f"/admin/users/list/{user_type}.json", **kwargs)
|
||||
|
||||
def update_avatar_from_url(self, username, url, **kwargs):
|
||||
"""
|
||||
@ -281,7 +300,9 @@ class DiscourseClient(object):
|
||||
|
||||
"""
|
||||
return self._post(
|
||||
"/users/{0}/preferences/avatar".format(username), file=url, **kwargs
|
||||
f"/users/{username}/preferences/avatar",
|
||||
file=url,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def update_avatar_image(self, username, img, **kwargs):
|
||||
@ -299,10 +320,12 @@ class DiscourseClient(object):
|
||||
"""
|
||||
files = {"file": img}
|
||||
return self._post(
|
||||
"/users/{0}/preferences/avatar".format(username), files=files, **kwargs
|
||||
f"/users/{username}/preferences/avatar",
|
||||
files=files,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def toggle_gravatar(self, username, state=True, **kwargs):
|
||||
def toggle_gravatar(self, username, *, state=True, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
@ -313,14 +336,14 @@ class DiscourseClient(object):
|
||||
Returns:
|
||||
|
||||
"""
|
||||
url = "/users/{0}/preferences/avatar/toggle".format(username)
|
||||
url = f"/users/{username}/preferences/avatar/toggle"
|
||||
if bool(state):
|
||||
kwargs["use_uploaded_avatar"] = "true"
|
||||
else:
|
||||
kwargs["use_uploaded_avatar"] = "false"
|
||||
return self._put(url, **kwargs)
|
||||
|
||||
def pick_avatar(self, username, gravatar=True, generated=False, **kwargs):
|
||||
def pick_avatar(self, username, *, gravatar=True, generated=False, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
@ -332,7 +355,7 @@ class DiscourseClient(object):
|
||||
Returns:
|
||||
|
||||
"""
|
||||
url = "/users/{0}/preferences/avatar/pick".format(username)
|
||||
url = f"/users/{username}/preferences/avatar/pick"
|
||||
return self._put(url, **kwargs)
|
||||
|
||||
def update_avatar(self, username, url, **kwargs):
|
||||
@ -350,9 +373,9 @@ class DiscourseClient(object):
|
||||
kwargs["synchronous"] = "true"
|
||||
upload_response = self._post("/uploads", url=url, **kwargs)
|
||||
return self._put(
|
||||
"/users/{0}/preferences/avatar/pick".format(username),
|
||||
f"/users/{username}/preferences/avatar/pick",
|
||||
upload_id=upload_response["id"],
|
||||
**kwargs
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def update_email(self, username, email, **kwargs):
|
||||
@ -367,7 +390,9 @@ class DiscourseClient(object):
|
||||
|
||||
"""
|
||||
return self._put(
|
||||
"/users/{0}/preferences/email".format(username), email=email, **kwargs
|
||||
f"/users/{username}/preferences/email",
|
||||
email=email,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def update_user(self, username, **kwargs):
|
||||
@ -380,7 +405,7 @@ class DiscourseClient(object):
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._put("/users/{0}".format(username), json=True, **kwargs)
|
||||
return self._put(f"/users/{username}", json=True, **kwargs)
|
||||
|
||||
def update_username(self, username, new_username, **kwargs):
|
||||
"""
|
||||
@ -394,9 +419,9 @@ class DiscourseClient(object):
|
||||
|
||||
"""
|
||||
return self._put(
|
||||
"/users/{0}/preferences/username".format(username),
|
||||
f"/users/{username}/preferences/username",
|
||||
new_username=new_username,
|
||||
**kwargs
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def set_preference(self, username=None, **kwargs):
|
||||
@ -411,7 +436,7 @@ class DiscourseClient(object):
|
||||
"""
|
||||
if username is None:
|
||||
username = self.api_username
|
||||
return self._put(u"/users/{0}".format(username), **kwargs)
|
||||
return self._put(f"/users/{username}", **kwargs)
|
||||
|
||||
def sync_sso(self, **kwargs):
|
||||
"""
|
||||
@ -427,7 +452,7 @@ class DiscourseClient(object):
|
||||
"""
|
||||
sso_secret = kwargs.pop("sso_secret")
|
||||
payload = sso_payload(sso_secret, **kwargs)
|
||||
return self._post("/admin/users/sync_sso?{0}".format(payload), **kwargs)
|
||||
return self._post(f"/admin/users/sync_sso?{payload}", **kwargs)
|
||||
|
||||
def generate_api_key(self, userid, **kwargs):
|
||||
"""
|
||||
@ -439,7 +464,7 @@ class DiscourseClient(object):
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._post("/admin/users/{0}/generate_api_key".format(userid), **kwargs)
|
||||
return self._post(f"/admin/users/{userid}/generate_api_key", **kwargs)
|
||||
|
||||
def delete_user(self, userid, **kwargs):
|
||||
"""
|
||||
@ -455,22 +480,22 @@ class DiscourseClient(object):
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._delete("/admin/users/{0}.json".format(userid), **kwargs)
|
||||
return self._delete(f"/admin/users/{userid}.json", **kwargs)
|
||||
|
||||
def users(self, filter=None, **kwargs):
|
||||
def users(self, filter_name=None, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
filter:
|
||||
filter_name:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
if filter is None:
|
||||
filter = "active"
|
||||
if filter_name is None:
|
||||
filter_name = "active"
|
||||
|
||||
return self._get("/admin/users/list/{0}.json".format(filter), **kwargs)
|
||||
return self._get(f"/admin/users/list/{filter_name}.json", **kwargs)
|
||||
|
||||
def private_messages(self, username=None, **kwargs):
|
||||
"""
|
||||
@ -484,7 +509,7 @@ class DiscourseClient(object):
|
||||
"""
|
||||
if username is None:
|
||||
username = self.api_username
|
||||
return self._get("/topics/private-messages/{0}.json".format(username), **kwargs)
|
||||
return self._get(f"/topics/private-messages/{username}.json", **kwargs)
|
||||
|
||||
def private_messages_unread(self, username=None, **kwargs):
|
||||
"""
|
||||
@ -499,7 +524,8 @@ class DiscourseClient(object):
|
||||
if username is None:
|
||||
username = self.api_username
|
||||
return self._get(
|
||||
"/topics/private-messages-unread/{0}.json".format(username), **kwargs
|
||||
f"/topics/private-messages-unread/{username}.json",
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def category_topics(self, category_id, **kwargs):
|
||||
@ -514,9 +540,9 @@ class DiscourseClient(object):
|
||||
|
||||
"""
|
||||
return self._get(
|
||||
"/c/{0}.json".format(category_id),
|
||||
f"/c/{category_id}.json",
|
||||
override_request_kwargs={"allow_redirects": True},
|
||||
**kwargs
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
# Doesn't work on recent Discourse versions (2014+)
|
||||
@ -574,7 +600,7 @@ class DiscourseClient(object):
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._get("/t/{0}/{1}.json".format(slug, topic_id), **kwargs)
|
||||
return self._get(f"/t/{slug}/{topic_id}.json", **kwargs)
|
||||
|
||||
def delete_topic(self, topic_id, **kwargs):
|
||||
"""
|
||||
@ -588,7 +614,7 @@ class DiscourseClient(object):
|
||||
JSON API response
|
||||
|
||||
"""
|
||||
return self._delete(u"/t/{0}".format(topic_id), **kwargs)
|
||||
return self._delete(f"/t/{topic_id}", **kwargs)
|
||||
|
||||
def post(self, topic_id, post_id, **kwargs):
|
||||
"""
|
||||
@ -601,7 +627,7 @@ class DiscourseClient(object):
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._get("/t/{0}/{1}.json".format(topic_id, post_id), **kwargs)
|
||||
return self._get(f"/t/{topic_id}/{post_id}.json", **kwargs)
|
||||
|
||||
def post_action_users(self, post_id, post_action_type_id=None, **kwargs):
|
||||
"""
|
||||
@ -631,7 +657,20 @@ class DiscourseClient(object):
|
||||
Returns:
|
||||
post
|
||||
"""
|
||||
return self._get("/posts/{0}.json".format(post_id), **kwargs)
|
||||
return self._get(f"/posts/{post_id}.json", **kwargs)
|
||||
|
||||
def post_by_number(self, topic_id, post_number, **kwargs):
|
||||
"""
|
||||
Get a post from its number inside a specific topic
|
||||
Args:
|
||||
topic_id: the topic the post belongs to
|
||||
post_number: the number of the post inside the topic
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
post
|
||||
"""
|
||||
return self._get(f"/posts/by_number/{topic_id}/{post_number}", **kwargs)
|
||||
|
||||
def posts(self, topic_id, post_ids=None, **kwargs):
|
||||
"""
|
||||
@ -647,7 +686,7 @@ class DiscourseClient(object):
|
||||
"""
|
||||
if post_ids:
|
||||
kwargs["post_ids[]"] = post_ids
|
||||
return self._get("/t/{0}/posts.json".format(topic_id), **kwargs)
|
||||
return self._get(f"/t/{topic_id}/posts.json", **kwargs)
|
||||
|
||||
def latest_posts(self, before=None, **kwargs):
|
||||
"""
|
||||
@ -682,7 +721,7 @@ class DiscourseClient(object):
|
||||
kwargs["topic_id"] = topic_id
|
||||
kwargs["topic_time"] = time
|
||||
for post_num, timing in timings.items():
|
||||
kwargs["timings[{0}]".format(post_num)] = timing
|
||||
kwargs[f"timings[{post_num}]"] = timing
|
||||
|
||||
return self._post("/topics/timings", **kwargs)
|
||||
|
||||
@ -696,7 +735,7 @@ class DiscourseClient(object):
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._get("/t/{0}/posts.json".format(topic_id), **kwargs)
|
||||
return self._get(f"/t/{topic_id}/posts.json", **kwargs)
|
||||
|
||||
def update_topic(self, topic_url, title, **kwargs):
|
||||
"""
|
||||
@ -711,10 +750,16 @@ class DiscourseClient(object):
|
||||
|
||||
"""
|
||||
kwargs["title"] = title
|
||||
return self._put("{}".format(topic_url), **kwargs)
|
||||
return self._put(f"{topic_url}", **kwargs)
|
||||
|
||||
def create_post(
|
||||
self, content, category_id=None, topic_id=None, title=None, tags=[], **kwargs
|
||||
self,
|
||||
content,
|
||||
category_id=None,
|
||||
topic_id=None,
|
||||
title=None,
|
||||
tags=[],
|
||||
**kwargs,
|
||||
):
|
||||
"""
|
||||
|
||||
@ -737,7 +782,7 @@ class DiscourseClient(object):
|
||||
title=title,
|
||||
raw=content,
|
||||
topic_id=topic_id,
|
||||
**kwargs
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def update_topic_status(self, topic_id, status, enabled, **kwargs):
|
||||
@ -758,7 +803,7 @@ class DiscourseClient(object):
|
||||
kwargs["enabled"] = "true"
|
||||
else:
|
||||
kwargs["enabled"] = "false"
|
||||
return self._put("/t/{0}/status".format(topic_id), **kwargs)
|
||||
return self._put(f"/t/{topic_id}/status", **kwargs)
|
||||
|
||||
def update_post(self, post_id, content, edit_reason="", **kwargs):
|
||||
"""
|
||||
@ -774,7 +819,7 @@ class DiscourseClient(object):
|
||||
"""
|
||||
kwargs["post[raw]"] = content
|
||||
kwargs["post[edit_reason]"] = edit_reason
|
||||
return self._put("/posts/{0}".format(post_id), **kwargs)
|
||||
return self._put(f"/posts/{post_id}", **kwargs)
|
||||
|
||||
def reset_bump_date(self, topic_id, **kwargs):
|
||||
"""
|
||||
@ -782,7 +827,7 @@ class DiscourseClient(object):
|
||||
|
||||
See https://meta.discourse.org/t/what-is-a-bump/105562
|
||||
"""
|
||||
return self._put("/t/{0}/reset-bump-date".format(topic_id), **kwargs)
|
||||
return self._put(f"/t/{topic_id}/reset-bump-date", **kwargs)
|
||||
|
||||
def topics_by(self, username, **kwargs):
|
||||
"""
|
||||
@ -794,7 +839,7 @@ class DiscourseClient(object):
|
||||
Returns:
|
||||
|
||||
"""
|
||||
url = "/topics/created-by/{0}.json".format(username)
|
||||
url = f"/topics/created-by/{username}.json"
|
||||
return self._get(url, **kwargs)["topic_list"]["topics"]
|
||||
|
||||
def invite_user_to_topic(self, user_email, topic_id):
|
||||
@ -808,19 +853,19 @@ class DiscourseClient(object):
|
||||
|
||||
"""
|
||||
kwargs = {"email": user_email, "topic_id": topic_id}
|
||||
return self._post("/t/{0}/invite.json".format(topic_id), **kwargs)
|
||||
return self._post(f"/t/{topic_id}/invite.json", **kwargs)
|
||||
|
||||
def search(self, term, **kwargs):
|
||||
def search(self, q, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
term:
|
||||
q:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
kwargs["term"] = term
|
||||
kwargs["q"] = q
|
||||
return self._get("/search.json", **kwargs)
|
||||
|
||||
def badges(self, **kwargs):
|
||||
@ -846,7 +891,10 @@ class DiscourseClient(object):
|
||||
|
||||
"""
|
||||
return self._post(
|
||||
"/user_badges", username=username, badge_id=badge_id, **kwargs
|
||||
"/user_badges",
|
||||
username=username,
|
||||
badge_id=badge_id,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def user_badges(self, username, **kwargs):
|
||||
@ -858,7 +906,7 @@ class DiscourseClient(object):
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._get("/user-badges/{}.json".format(username))
|
||||
return self._get(f"/user-badges/{username}.json")
|
||||
|
||||
def user_emails(self, username, **kwargs):
|
||||
"""
|
||||
@ -870,10 +918,16 @@ class DiscourseClient(object):
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._get("/u/{}/emails.json".format(username))
|
||||
return self._get(f"/u/{username}/emails.json")
|
||||
|
||||
def create_category(
|
||||
self, name, color, text_color="FFFFFF", permissions=None, parent=None, **kwargs
|
||||
self,
|
||||
name,
|
||||
color,
|
||||
text_color="FFFFFF",
|
||||
permissions=None,
|
||||
parent=None,
|
||||
**kwargs,
|
||||
):
|
||||
"""
|
||||
|
||||
@ -897,7 +951,7 @@ class DiscourseClient(object):
|
||||
permissions = {"everyone": "1"}
|
||||
|
||||
for key, value in permissions.items():
|
||||
kwargs["permissions[{0}]".format(key)] = value
|
||||
kwargs[f"permissions[{key}]"] = value
|
||||
|
||||
if parent:
|
||||
parent_id = None
|
||||
@ -907,7 +961,7 @@ class DiscourseClient(object):
|
||||
continue
|
||||
|
||||
if not parent_id:
|
||||
raise DiscourseClientError(u"{0} not found".format(parent))
|
||||
raise DiscourseClientError(f"{parent} not found")
|
||||
|
||||
kwargs["parent_category_id"] = parent_id
|
||||
|
||||
@ -935,7 +989,7 @@ class DiscourseClient(object):
|
||||
|
||||
"""
|
||||
|
||||
return self._get(u"/c/{0}/show.json".format(category_id), **kwargs)
|
||||
return self._get(f"/c/{category_id}/show.json", **kwargs)
|
||||
|
||||
def update_category(self, category_id, **kwargs):
|
||||
"""
|
||||
@ -947,7 +1001,7 @@ class DiscourseClient(object):
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._put("/categories/{0}".format(category_id), json=True, **kwargs)
|
||||
return self._put(f"/categories/{category_id}", json=True, **kwargs)
|
||||
|
||||
def delete_category(self, category_id, **kwargs):
|
||||
"""
|
||||
@ -960,7 +1014,7 @@ class DiscourseClient(object):
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._delete(u"/categories/{0}".format(category_id), **kwargs)
|
||||
return self._delete(f"/categories/{category_id}", **kwargs)
|
||||
|
||||
def get_site_info(self):
|
||||
"""
|
||||
@ -979,8 +1033,8 @@ class DiscourseClient(object):
|
||||
Get latest topics from a category
|
||||
"""
|
||||
if parent:
|
||||
name = u"{0}/{1}".format(parent, name)
|
||||
return self._get(u"/c/{0}/l/latest.json".format(name), **kwargs)
|
||||
name = f"{parent}/{name}"
|
||||
return self._get(f"/c/{name}/l/latest.json", **kwargs)
|
||||
|
||||
def site_settings(self, **kwargs):
|
||||
"""
|
||||
@ -995,7 +1049,9 @@ class DiscourseClient(object):
|
||||
for setting, value in kwargs.items():
|
||||
setting = setting.replace(" ", "_")
|
||||
self._request(
|
||||
PUT, "/admin/site_settings/{0}".format(setting), {setting: value}
|
||||
PUT,
|
||||
f"/admin/site_settings/{setting}",
|
||||
{setting: value},
|
||||
)
|
||||
|
||||
def customize_site_texts(self, site_texts, **kwargs):
|
||||
@ -1012,7 +1068,9 @@ class DiscourseClient(object):
|
||||
for site_text, value in site_texts.items():
|
||||
kwargs = {"site_text": {"value": value}}
|
||||
self._put(
|
||||
"/admin/customize/site_texts/{0}".format(site_text), json=True, **kwargs
|
||||
f"/admin/customize/site_texts/{site_text}",
|
||||
json=True,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def groups(self, **kwargs):
|
||||
@ -1066,11 +1124,12 @@ class DiscourseClient(object):
|
||||
"""
|
||||
Get all infos of a group by group name
|
||||
"""
|
||||
return self._get("/groups/{0}.json".format(group_name))
|
||||
return self._get(f"/groups/{group_name}.json")
|
||||
|
||||
def create_group(
|
||||
self,
|
||||
name,
|
||||
*,
|
||||
title="",
|
||||
visible=True,
|
||||
alias_level=0,
|
||||
@ -1082,7 +1141,7 @@ class DiscourseClient(object):
|
||||
flair_url=None,
|
||||
flair_bg_color=None,
|
||||
flair_color=None,
|
||||
**kwargs
|
||||
**kwargs,
|
||||
):
|
||||
"""
|
||||
Args:
|
||||
@ -1108,9 +1167,7 @@ class DiscourseClient(object):
|
||||
kwargs["automatic_membership_retroactive"] = automatic_membership_retroactive
|
||||
kwargs["primary_group"] = primary_group
|
||||
kwargs["automatic"] = automatic
|
||||
kwargs[
|
||||
"automatic_membership_email_domains"
|
||||
] = automatic_membership_email_domains
|
||||
kwargs["automatic_membership_email_domains"] = automatic_membership_email_domains
|
||||
kwargs["grant_trust_level"] = grant_trust_level
|
||||
kwargs["flair_url"] = flair_url
|
||||
kwargs["flair_bg_color"] = flair_bg_color
|
||||
@ -1131,7 +1188,7 @@ class DiscourseClient(object):
|
||||
JSON API response
|
||||
|
||||
"""
|
||||
return self._delete("/admin/groups/{0}.json".format(groupid))
|
||||
return self._delete(f"/admin/groups/{groupid}.json")
|
||||
|
||||
def add_group_owner(self, groupid, username):
|
||||
"""
|
||||
@ -1161,7 +1218,8 @@ class DiscourseClient(object):
|
||||
"""
|
||||
usernames = ",".join(usernames)
|
||||
return self._put(
|
||||
"/groups/{0}/owners.json".format(groupid), **{"usernames": usernames}
|
||||
f"/groups/{groupid}/owners.json",
|
||||
usernames=usernames,
|
||||
)
|
||||
|
||||
def delete_group_owner(self, groupid, userid):
|
||||
@ -1179,14 +1237,15 @@ class DiscourseClient(object):
|
||||
|
||||
"""
|
||||
return self._delete(
|
||||
"/admin/groups/{0}/owners.json".format(groupid), user_id=userid
|
||||
f"/admin/groups/{groupid}/owners.json",
|
||||
user_id=userid,
|
||||
)
|
||||
|
||||
def group_owners(self, group_name):
|
||||
"""
|
||||
Get all owners of a group by group name
|
||||
"""
|
||||
group = self._get("/groups/{0}/members.json".format(group_name))
|
||||
group = self._get(f"/groups/{group_name}/members.json")
|
||||
return group["owners"]
|
||||
|
||||
def _get_paginated_list(self, url, name, offset, **kwargs):
|
||||
@ -1208,9 +1267,7 @@ class DiscourseClient(object):
|
||||
"""
|
||||
Get all members of a group by group name
|
||||
"""
|
||||
return self._get_paginated_list(
|
||||
"/groups/{0}/members.json".format(group_name),
|
||||
"members", offset, **kwargs)
|
||||
return self._get_paginated_list(f"/groups/{group_name}/members.json", "members", offset, **kwargs)
|
||||
|
||||
def add_group_member(self, groupid, username):
|
||||
"""
|
||||
@ -1228,7 +1285,8 @@ class DiscourseClient(object):
|
||||
|
||||
"""
|
||||
return self._put(
|
||||
"/groups/{0}/members.json".format(groupid), usernames=username
|
||||
f"/groups/{groupid}/members.json",
|
||||
usernames=username,
|
||||
)
|
||||
|
||||
def add_group_members(self, groupid, usernames):
|
||||
@ -1248,7 +1306,8 @@ class DiscourseClient(object):
|
||||
"""
|
||||
usernames = ",".join(usernames)
|
||||
return self._put(
|
||||
"/groups/{0}/members.json".format(groupid), usernames=usernames,
|
||||
f"/groups/{groupid}/members.json",
|
||||
usernames=usernames,
|
||||
json=True,
|
||||
)
|
||||
|
||||
@ -1267,7 +1326,7 @@ class DiscourseClient(object):
|
||||
DiscourseError if user is already member of group
|
||||
|
||||
"""
|
||||
return self._post("/admin/users/{0}/groups".format(userid), group_id=groupid)
|
||||
return self._post(f"/admin/users/{userid}/groups", group_id=groupid)
|
||||
|
||||
def delete_group_member(self, groupid, username):
|
||||
"""
|
||||
@ -1283,10 +1342,7 @@ class DiscourseClient(object):
|
||||
JSON API response
|
||||
|
||||
"""
|
||||
return self._request(
|
||||
DELETE, "/groups/{0}/members.json".format(groupid),
|
||||
json={"usernames": username})
|
||||
|
||||
return self._request(DELETE, f"/groups/{groupid}/members.json", json={"usernames": username})
|
||||
|
||||
def color_schemes(self, **kwargs):
|
||||
"""
|
||||
@ -1318,9 +1374,7 @@ class DiscourseClient(object):
|
||||
kwargs["enabled"] = "true"
|
||||
else:
|
||||
kwargs["enabled"] = "false"
|
||||
kwargs["colors"] = [
|
||||
{"name": name, "hex": color} for name, color in colors.items()
|
||||
]
|
||||
kwargs["colors"] = [{"name": name, "hex": color} for name, color in colors.items()]
|
||||
kwargs = {"color_scheme": kwargs}
|
||||
return self._post("/admin/color_schemes.json", json=True, **kwargs)
|
||||
|
||||
@ -1362,7 +1416,7 @@ class DiscourseClient(object):
|
||||
kwargs["locked"] = "true"
|
||||
else:
|
||||
kwargs["locked"] = "false"
|
||||
return self._put("/admin/users/{}/trust_level_lock".format(user_id), **kwargs)
|
||||
return self._put(f"/admin/users/{user_id}/trust_level_lock", **kwargs)
|
||||
|
||||
def block(self, user_id, **kwargs):
|
||||
"""
|
||||
@ -1375,23 +1429,23 @@ class DiscourseClient(object):
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._put("/admin/users/{}/block".format(user_id), **kwargs)
|
||||
return self._put(f"/admin/users/{user_id}/block", **kwargs)
|
||||
|
||||
def upload_image(self, image, type, synchronous, **kwargs):
|
||||
def upload_image(self, image, upload_type, synchronous, **kwargs):
|
||||
"""
|
||||
Upload image or avatar
|
||||
|
||||
Args:
|
||||
name:
|
||||
file:
|
||||
type:
|
||||
upload_type: one of "avatar" "profile_background" "card_background" "custom_emoji" "composer"
|
||||
synchronous:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
kwargs["type"] = type
|
||||
kwargs["type"] = upload_type
|
||||
if bool(synchronous):
|
||||
kwargs["synchronous"] = "true"
|
||||
else:
|
||||
@ -1399,20 +1453,20 @@ class DiscourseClient(object):
|
||||
files = {"file": open(image, "rb")}
|
||||
return self._post("/uploads.json", files=files, **kwargs)
|
||||
|
||||
def user_actions(self, username, filter, offset=0, **kwargs):
|
||||
def user_actions(self, username, actions_filter, offset=0, **kwargs):
|
||||
"""
|
||||
List all possible user actions
|
||||
|
||||
Args:
|
||||
username:
|
||||
filter:
|
||||
actions_filter:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
kwargs["username"] = username
|
||||
kwargs["filter"] = filter
|
||||
kwargs["filter"] = actions_filter
|
||||
kwargs["offset"] = offset
|
||||
return self._get("/user_actions.json", **kwargs)["user_actions"]
|
||||
|
||||
@ -1441,7 +1495,8 @@ class DiscourseClient(object):
|
||||
https://github.com/discourse/discourse-data-explorer
|
||||
"""
|
||||
return self._post(
|
||||
"/admin/plugins/explorer/queries/{}/run".format(query_id), **kwargs
|
||||
f"/admin/plugins/explorer/queries/{query_id}/run",
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def notifications(self, category_id, **kwargs):
|
||||
@ -1454,7 +1509,13 @@ class DiscourseClient(object):
|
||||
notification_level=(int)
|
||||
|
||||
"""
|
||||
return self._post("/category/{}/notifications".format(category_id), **kwargs)
|
||||
return self._post(f"/category/{category_id}/notifications", **kwargs)
|
||||
|
||||
def about(self):
|
||||
"""
|
||||
Get site info
|
||||
"""
|
||||
return self._get("/about.json")
|
||||
|
||||
def _get(self, path, override_request_kwargs=None, **kwargs):
|
||||
"""
|
||||
@ -1467,10 +1528,13 @@ class DiscourseClient(object):
|
||||
|
||||
"""
|
||||
return self._request(
|
||||
GET, path, params=kwargs, override_request_kwargs=override_request_kwargs
|
||||
GET,
|
||||
path,
|
||||
params=kwargs,
|
||||
override_request_kwargs=override_request_kwargs,
|
||||
)
|
||||
|
||||
def _put(self, path, json=False, override_request_kwargs=None, **kwargs):
|
||||
def _put(self, path, *, json=False, override_request_kwargs=None, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
@ -1482,16 +1546,28 @@ class DiscourseClient(object):
|
||||
"""
|
||||
if not json:
|
||||
return self._request(
|
||||
PUT, path, data=kwargs, override_request_kwargs=override_request_kwargs
|
||||
PUT,
|
||||
path,
|
||||
data=kwargs,
|
||||
override_request_kwargs=override_request_kwargs,
|
||||
)
|
||||
|
||||
else:
|
||||
return self._request(
|
||||
PUT, path, json=kwargs, override_request_kwargs=override_request_kwargs
|
||||
PUT,
|
||||
path,
|
||||
json=kwargs,
|
||||
override_request_kwargs=override_request_kwargs,
|
||||
)
|
||||
|
||||
def _post(
|
||||
self, path, files=None, json=False, override_request_kwargs=None, **kwargs
|
||||
self,
|
||||
path,
|
||||
*,
|
||||
files=None,
|
||||
json=False,
|
||||
override_request_kwargs=None,
|
||||
**kwargs,
|
||||
):
|
||||
"""
|
||||
|
||||
@ -1531,7 +1607,10 @@ class DiscourseClient(object):
|
||||
|
||||
"""
|
||||
return self._request(
|
||||
DELETE, path, params=kwargs, override_request_kwargs=override_request_kwargs
|
||||
DELETE,
|
||||
path,
|
||||
params=kwargs,
|
||||
override_request_kwargs=override_request_kwargs,
|
||||
)
|
||||
|
||||
def _request(
|
||||
@ -1593,12 +1672,12 @@ class DiscourseClient(object):
|
||||
break
|
||||
if not response.ok:
|
||||
try:
|
||||
msg = u",".join(response.json()["errors"])
|
||||
msg = ",".join(response.json()["errors"])
|
||||
except (ValueError, TypeError, KeyError):
|
||||
if response.reason:
|
||||
msg = response.reason
|
||||
else:
|
||||
msg = u"{0}: {1}".format(response.status_code, response.text)
|
||||
msg = f"{response.status_code}: {response.text}"
|
||||
|
||||
if 400 <= response.status_code < 500:
|
||||
if 429 == response.status_code:
|
||||
@ -1606,26 +1685,21 @@ class DiscourseClient(object):
|
||||
content_type = response.headers.get("Content-Type")
|
||||
if content_type is not None and "application/json" in content_type:
|
||||
ret = response.json()
|
||||
wait_delay = (
|
||||
retry_backoff + ret["extras"]["wait_seconds"]
|
||||
) # how long to back off for.
|
||||
wait_delay = retry_backoff + ret["extras"]["wait_seconds"] # how long to back off for.
|
||||
else:
|
||||
# We got an early 429 error without a proper JSON body
|
||||
ret = response.content
|
||||
wait_delay = retry_backoff + 10
|
||||
|
||||
limit_name = response.headers.get(
|
||||
"Discourse-Rate-Limit-Error-Code", "<unknown>")
|
||||
limit_name = response.headers.get("Discourse-Rate-Limit-Error-Code", "<unknown>")
|
||||
|
||||
log.info(
|
||||
"We have been rate limited (limit: {2}) and will wait {0} seconds ({1} retries left)".format(
|
||||
wait_delay, retry_count, limit_name
|
||||
)
|
||||
f"We have been rate limited (limit: {limit_name}) and will wait {wait_delay} seconds ({retry_count} retries left)",
|
||||
)
|
||||
if retry_count > 1:
|
||||
time.sleep(wait_delay)
|
||||
retry_count -= 1
|
||||
log.debug("API returned {0}".format(ret))
|
||||
log.debug(f"API returned {ret}")
|
||||
continue
|
||||
else:
|
||||
raise DiscourseClientError(msg, response=response)
|
||||
@ -1641,7 +1715,8 @@ class DiscourseClient(object):
|
||||
|
||||
if response.status_code == 302:
|
||||
raise DiscourseError(
|
||||
"Unexpected Redirect, invalid api key or host?", response=response
|
||||
"Unexpected Redirect, invalid api key or host?",
|
||||
response=response,
|
||||
)
|
||||
|
||||
json_content = "application/json; charset=utf-8"
|
||||
@ -1652,24 +1727,22 @@ class DiscourseClient(object):
|
||||
return None
|
||||
|
||||
raise DiscourseError(
|
||||
'Invalid Response, expecting "{0}" got "{1}"'.format(
|
||||
json_content, content_type
|
||||
),
|
||||
f'Invalid Response, expecting "{json_content}" got "{content_type}"',
|
||||
response=response,
|
||||
)
|
||||
|
||||
try:
|
||||
decoded = response.json()
|
||||
except ValueError:
|
||||
raise DiscourseError("failed to decode response", response=response)
|
||||
except ValueError as err:
|
||||
raise DiscourseError("failed to decode response", response=response) from err
|
||||
|
||||
# Checking "errors" length because
|
||||
# data-explorer (e.g. POST /admin/plugins/explorer/queries/{}/run)
|
||||
# data-explorer (e.g. POST /admin/plugins/explorer/queries/{}/run) # noqa: ERA001
|
||||
# sends an empty errors array
|
||||
if "errors" in decoded and len(decoded["errors"]) > 0:
|
||||
message = decoded.get("message")
|
||||
if not message:
|
||||
message = u",".join(decoded["errors"])
|
||||
message = ",".join(decoded["errors"])
|
||||
raise DiscourseError(message, response=response)
|
||||
|
||||
return decoded
|
||||
|
||||
@ -38,7 +38,7 @@ class DiscourseCmd(cmd.Cmd):
|
||||
return method(*args, **kwargs)
|
||||
|
||||
except DiscourseError as e:
|
||||
print(e, e.response.text)
|
||||
sys.stderr.write(f"{e}, {e.response.text}\n")
|
||||
return e.response
|
||||
|
||||
return wrapper
|
||||
@ -57,7 +57,11 @@ class DiscourseCmd(cmd.Cmd):
|
||||
"""Writes output of the command to console"""
|
||||
try:
|
||||
json.dump(
|
||||
result, self.output, sort_keys=True, indent=4, separators=(",", ": ")
|
||||
result,
|
||||
self.output,
|
||||
sort_keys=True,
|
||||
indent=4,
|
||||
separators=(",", ": "),
|
||||
)
|
||||
except TypeError:
|
||||
self.output.write(result.text)
|
||||
|
||||
@ -43,18 +43,20 @@ def sso_validate(payload, signature, secret):
|
||||
raise DiscourseError("No SSO payload or signature.")
|
||||
|
||||
if not secret:
|
||||
raise DiscourseError("Invalid secret..")
|
||||
raise DiscourseError("Invalid secret.")
|
||||
|
||||
payload = unquote(payload)
|
||||
if not payload:
|
||||
raise DiscourseError("Invalid payload..")
|
||||
raise DiscourseError("Invalid payload.")
|
||||
|
||||
decoded = b64decode(payload.encode("utf-8")).decode("utf-8")
|
||||
if "nonce" not in decoded:
|
||||
raise DiscourseError("Invalid payload..")
|
||||
raise DiscourseError("Invalid payload.")
|
||||
|
||||
h = hmac.new(
|
||||
secret.encode("utf-8"), payload.encode("utf-8"), digestmod=hashlib.sha256
|
||||
secret.encode("utf-8"),
|
||||
payload.encode("utf-8"),
|
||||
digestmod=hashlib.sha256,
|
||||
)
|
||||
this_signature = h.hexdigest()
|
||||
|
||||
@ -92,7 +94,7 @@ def sso_redirect_url(nonce, secret, email, external_id, username, **kwargs):
|
||||
"email": email,
|
||||
"external_id": external_id,
|
||||
"username": username,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
return "/session/sso_login?%s" % sso_payload(secret, **kwargs)
|
||||
|
||||
136
tests/conftest.py
Normal file
136
tests/conftest.py
Normal file
@ -0,0 +1,136 @@
|
||||
"""Test fixtures."""
|
||||
|
||||
import datetime
|
||||
|
||||
import pytest
|
||||
from pydiscourse import client
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def sso_secret():
|
||||
return "d836444a9e4084d5b224a60c208dce14"
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def sso_nonce():
|
||||
return "cb68251eefb5211e58c00ff1395f0c0b"
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def sso_payload():
|
||||
return "bm9uY2U9Y2I2ODI1MWVlZmI1MjExZTU4YzAwZmYxMzk1ZjBjMGI%3D%0A"
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def sso_signature():
|
||||
return "2828aa29899722b35a2f191d34ef9b3ce695e0e6eeec47deb46d588d70c7cb56"
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def name():
|
||||
return "sam"
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def username():
|
||||
return "samsam"
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def external_id():
|
||||
return "hello123"
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def email():
|
||||
return "test@test.com"
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def redirect_url(sso_payload):
|
||||
return f"/session/sso_login?sso={sso_payload}YW0mdXNlcm5hbWU9c2Ftc2FtJmVtYWlsPXRlc3QlNDB0ZXN0LmNvbSZleHRl%0Acm5hbF9pZD1oZWxsbzEyMw%3D%3D%0A&sig=1c884222282f3feacd76802a9dd94e8bc8deba5d619b292bed75d63eb3152c0b"
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def discourse_host():
|
||||
return "http://testhost"
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def discourse_api_username():
|
||||
return "testuser"
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def discourse_api_key():
|
||||
return "testkey"
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def discourse_client(discourse_host, discourse_api_username, discourse_api_key):
|
||||
return client.DiscourseClient(
|
||||
discourse_host,
|
||||
discourse_api_username,
|
||||
discourse_api_key,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def _frozen_time(mocker):
|
||||
now = mocker.patch("pydiscourse.client.now")
|
||||
now.return_value = datetime.datetime(
|
||||
2023,
|
||||
8,
|
||||
13,
|
||||
12,
|
||||
30,
|
||||
15,
|
||||
tzinfo=datetime.timezone.utc,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def discourse_request(discourse_host, discourse_client, requests_mock):
|
||||
"""Fixture for mocking Discourse API requests.
|
||||
|
||||
The only request arguments are the method and the path.
|
||||
|
||||
Example:
|
||||
|
||||
>>> def test_something(discourse_request):
|
||||
>>> request = discourse_request(
|
||||
>>> "put", # the method, case-insensitive
|
||||
>>> "/the-path.json?q=4", # the absolute path with query, NO host
|
||||
>>> headers={'content-type': 'text/plain'}, # override default headers
|
||||
>>> content=b"ERROR", # override bytestring response
|
||||
>>> )
|
||||
|
||||
If `content` is provided, that will be used as the response body.
|
||||
If `json` is provided, then the body will return the given JSON-
|
||||
compatable Python structure (e.g. dictionary).
|
||||
If neither is given then the return `json` will be an empty
|
||||
dictionary (`{}`).
|
||||
|
||||
Returns a function for inserting sensible default values.
|
||||
"""
|
||||
|
||||
def inner(method, path, headers=None, json=None, content=None):
|
||||
full_path = f"{discourse_host}{path}"
|
||||
if not headers:
|
||||
headers = {
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
"Api-Key": discourse_client.api_key,
|
||||
"Api-Username": discourse_client.api_username,
|
||||
}
|
||||
|
||||
kwargs = {}
|
||||
if content:
|
||||
kwargs["content"] = content
|
||||
elif json:
|
||||
kwargs["json"] = json
|
||||
else:
|
||||
kwargs["json"] = {}
|
||||
|
||||
return requests_mock.request(method, full_path, headers=headers, **kwargs)
|
||||
|
||||
return inner
|
||||
@ -1,221 +1,220 @@
|
||||
import sys
|
||||
import unittest
|
||||
"""Tests for the client methods."""
|
||||
|
||||
from unittest import mock
|
||||
import urllib.parse
|
||||
|
||||
from pydiscourse import client
|
||||
import pytest
|
||||
|
||||
|
||||
if sys.version_info < (3,):
|
||||
def test_empty_content_http_ok(discourse_host, discourse_client, discourse_request):
|
||||
"""Empty content should not raise error
|
||||
|
||||
def b(x):
|
||||
return x
|
||||
|
||||
|
||||
else:
|
||||
import codecs
|
||||
|
||||
def b(x):
|
||||
return codecs.latin_1_encode(x)[0]
|
||||
|
||||
|
||||
def prepare_response(request):
|
||||
# we need to mocked response to look a little more real
|
||||
request.return_value = mock.MagicMock(
|
||||
headers={"content-type": "application/json; charset=utf-8"}
|
||||
Critical to test against *bytestrings* rather than unicode
|
||||
"""
|
||||
discourse_request(
|
||||
"get",
|
||||
"/users/admin/1/unsuspend",
|
||||
headers={"Content-Type": "text/plain; charset=utf-8"},
|
||||
content=b" ",
|
||||
)
|
||||
|
||||
resp = discourse_client._request("GET", "/users/admin/1/unsuspend", {})
|
||||
|
||||
class ClientBaseTestCase(unittest.TestCase):
|
||||
"""
|
||||
|
||||
"""
|
||||
|
||||
def setUp(self):
|
||||
self.host = "http://testhost"
|
||||
self.api_username = "testuser"
|
||||
self.api_key = "testkey"
|
||||
|
||||
self.client = client.DiscourseClient(self.host, self.api_username, self.api_key)
|
||||
|
||||
def assertRequestCalled(self, request, verb, url, **params):
|
||||
self.assertTrue(request.called)
|
||||
|
||||
args, kwargs = request.call_args
|
||||
|
||||
self.assertEqual(args[0], verb)
|
||||
self.assertEqual(args[1], self.host + url)
|
||||
|
||||
headers = kwargs["headers"]
|
||||
self.assertEqual(headers.pop("Api-Username"), self.api_username)
|
||||
self.assertEqual(headers.pop("Api-Key"), self.api_key)
|
||||
|
||||
if verb == "GET":
|
||||
self.assertEqual(kwargs["params"], params)
|
||||
assert resp is None
|
||||
|
||||
|
||||
class TestClientRequests(ClientBaseTestCase):
|
||||
"""
|
||||
Tests for common request handling
|
||||
"""
|
||||
|
||||
@mock.patch("pydiscourse.client.requests")
|
||||
def test_empty_content_http_ok(self, mocked_requests):
|
||||
"""Empty content should not raise error
|
||||
|
||||
Critical to test against *bytestrings* rather than unicode
|
||||
"""
|
||||
mocked_response = mock.MagicMock()
|
||||
mocked_response.content = b(" ")
|
||||
mocked_response.status_code = 200
|
||||
mocked_response.headers = {"content-type": "text/plain; charset=utf-8"}
|
||||
|
||||
assert "content-type" in mocked_response.headers
|
||||
|
||||
mocked_requests.request = mock.MagicMock()
|
||||
mocked_requests.request.return_value = mocked_response
|
||||
|
||||
resp = self.client._request("GET", "/users/admin/1/unsuspend", {})
|
||||
self.assertIsNone(resp)
|
||||
|
||||
|
||||
@mock.patch("requests.request")
|
||||
class TestUser(ClientBaseTestCase):
|
||||
|
||||
def test_user(self, request):
|
||||
prepare_response(request)
|
||||
self.client.user("someuser")
|
||||
self.assertRequestCalled(request, "GET", "/users/someuser.json")
|
||||
|
||||
def test_create_user(self, request):
|
||||
prepare_response(request)
|
||||
self.client.create_user(
|
||||
"Test User", "testuser", "test@example.com", "notapassword"
|
||||
class TestUserManagement:
|
||||
def test_get_user(self, discourse_host, discourse_client, discourse_request):
|
||||
request = discourse_request(
|
||||
"get",
|
||||
"/users/someuser.json",
|
||||
json={"user": "someuser"},
|
||||
)
|
||||
self.assertEqual(request.call_count, 2)
|
||||
discourse_client.user("someuser")
|
||||
|
||||
# XXX incomplete
|
||||
assert request.called_once
|
||||
|
||||
def test_update_email(self, request):
|
||||
prepare_response(request)
|
||||
email = "test@example.com"
|
||||
self.client.update_email("someuser", email)
|
||||
self.assertRequestCalled(
|
||||
request, "PUT", "/users/someuser/preferences/email", email=email
|
||||
def test_users(self, discourse_client, discourse_request):
|
||||
request = discourse_request("get", "/admin/users/list/active.json")
|
||||
discourse_client.users()
|
||||
assert request.called_once
|
||||
|
||||
def test_create_user(self, discourse_host, discourse_client, discourse_request):
|
||||
session_request = discourse_request(
|
||||
"get",
|
||||
"/session/hp.json",
|
||||
json={"challenge": "challenge", "value": "value"},
|
||||
)
|
||||
user_request = discourse_request("post", "/users")
|
||||
discourse_client.create_user(
|
||||
"Test User",
|
||||
"testuser",
|
||||
"test@example.com",
|
||||
"notapassword",
|
||||
)
|
||||
|
||||
def test_update_user(self, request):
|
||||
prepare_response(request)
|
||||
self.client.update_user("someuser", a="a", b="b")
|
||||
self.assertRequestCalled(request, "PUT", "/users/someuser", a="a", b="b")
|
||||
assert session_request.called_once
|
||||
assert user_request.called_once
|
||||
|
||||
def test_update_username(self, request):
|
||||
prepare_response(request)
|
||||
self.client.update_username("someuser", "newname")
|
||||
self.assertRequestCalled(
|
||||
request, "PUT", "/users/someuser/preferences/username", username="newname"
|
||||
def test_update_email(self, discourse_host, discourse_client, discourse_request):
|
||||
request = discourse_request("put", "/users/someuser/preferences/email")
|
||||
discourse_client.update_email("someuser", "newmeail@example.com")
|
||||
|
||||
assert request.called_once
|
||||
|
||||
def test_update_user(self, discourse_client, discourse_request):
|
||||
request = discourse_request("put", "/users/someuser")
|
||||
discourse_client.update_user("someuser", a="a", b="b")
|
||||
|
||||
assert request.called_once
|
||||
|
||||
def test_update_username(self, discourse_client, discourse_request):
|
||||
request = discourse_request("put", "/users/someuser/preferences/username")
|
||||
discourse_client.update_username("someuser", "newname")
|
||||
|
||||
assert request.called_once
|
||||
|
||||
def test_by_external_id(self, discourse_client, discourse_request):
|
||||
request = discourse_request(
|
||||
"get",
|
||||
"/users/by-external/123",
|
||||
json={"user": "123"},
|
||||
)
|
||||
discourse_client.by_external_id(123)
|
||||
|
||||
def test_by_external_id(self, request):
|
||||
prepare_response(request)
|
||||
self.client.by_external_id(123)
|
||||
self.assertRequestCalled(request, "GET", "/users/by-external/123")
|
||||
assert request.called_once
|
||||
|
||||
def test_suspend_user(self, request):
|
||||
prepare_response(request)
|
||||
self.client.suspend(123, 1, "Testing")
|
||||
self.assertRequestCalled(
|
||||
request, "PUT", "/admin/users/123/suspend", duration=1, reason="Testing"
|
||||
def test_anonymize(self, discourse_client, discourse_request):
|
||||
request = discourse_request("put", "/admin/users/123/anonymize")
|
||||
discourse_client.anonymize(123)
|
||||
|
||||
assert request.called_once
|
||||
|
||||
@pytest.mark.usefixtures("_frozen_time")
|
||||
def test_suspend_user(self, discourse_client, discourse_request):
|
||||
request = discourse_request("put", "/admin/users/123/suspend")
|
||||
discourse_client.suspend(123, 1, "Testing")
|
||||
|
||||
assert request.called_once
|
||||
assert request.last_request.method == "PUT"
|
||||
|
||||
request_payload = urllib.parse.parse_qs(request.last_request.text)
|
||||
|
||||
assert request_payload["reason"] == ["Testing"]
|
||||
assert request_payload["suspend_until"] == ["2023-08-14T12:30:15+00:00"]
|
||||
|
||||
def test_unsuspend_user(self, discourse_client, discourse_request):
|
||||
request = discourse_request("put", "/admin/users/123/unsuspend")
|
||||
discourse_client.unsuspend(123)
|
||||
|
||||
assert request.called_once
|
||||
|
||||
def test_user_bagdes(self, discourse_client, discourse_request):
|
||||
request = discourse_request("get", "/user-badges/myusername.json")
|
||||
discourse_client.user_badges("myusername")
|
||||
|
||||
assert request.called_once
|
||||
|
||||
|
||||
class TestTopics:
|
||||
def test_hot_topics(self, discourse_client, discourse_request):
|
||||
request = discourse_request("get", "/hot.json")
|
||||
discourse_client.hot_topics()
|
||||
assert request.called_once
|
||||
|
||||
def test_latest_topics(self, discourse_client, discourse_request):
|
||||
request = discourse_request("get", "/latest.json")
|
||||
discourse_client.latest_topics()
|
||||
|
||||
assert request.called_once
|
||||
|
||||
def test_new_topics(self, discourse_client, discourse_request):
|
||||
request = discourse_request("get", "/new.json")
|
||||
discourse_client.new_topics()
|
||||
assert request.called_once
|
||||
|
||||
def test_topic(self, discourse_client, discourse_request):
|
||||
request = discourse_request("get", "/t/some-test-slug/22.json")
|
||||
discourse_client.topic("some-test-slug", 22)
|
||||
assert request.called_once
|
||||
|
||||
def test_topics_by(self, discourse_client, discourse_request):
|
||||
request = discourse_request(
|
||||
"get",
|
||||
"/topics/created-by/someuser.json",
|
||||
json={"topic_list": {"topics": []}},
|
||||
)
|
||||
discourse_client.topics_by("someuser")
|
||||
|
||||
def test_unsuspend_user(self, request):
|
||||
prepare_response(request)
|
||||
self.client.unsuspend(123)
|
||||
self.assertRequestCalled(request, "PUT", "/admin/users/123/unsuspend")
|
||||
assert request.called_once
|
||||
|
||||
def test_user_bagdes(self, request):
|
||||
prepare_response(request)
|
||||
self.client.user_badges("username")
|
||||
self.assertRequestCalled(
|
||||
request, "GET", "/user-badges/{}.json".format("username")
|
||||
def test_invite_user_to_topic(self, discourse_client, discourse_request):
|
||||
request = discourse_request("post", "/t/22/invite.json")
|
||||
discourse_client.invite_user_to_topic("test@example.com", 22)
|
||||
assert request.called_once
|
||||
|
||||
request_payload = urllib.parse.parse_qs(request.last_request.text)
|
||||
|
||||
assert request_payload["email"] == ["test@example.com"]
|
||||
assert request_payload["topic_id"] == ["22"]
|
||||
|
||||
|
||||
class TestPosts:
|
||||
def test_latest_posts(self, discourse_client, discourse_request):
|
||||
request = discourse_request("get", "/posts.json?before=54321")
|
||||
discourse_client.latest_posts(before=54321)
|
||||
assert request.called_once
|
||||
|
||||
def test_post_by_number(self, discourse_client, discourse_request):
|
||||
request = discourse_request("get", "/posts/by_number/8796/5")
|
||||
discourse_client.post_by_number(8796, 5)
|
||||
assert request.called_once
|
||||
|
||||
|
||||
class TestSearch:
|
||||
def test_search(self, discourse_client, discourse_request):
|
||||
request = discourse_request("get", "/search.json?q=needle")
|
||||
discourse_client.search(q="needle")
|
||||
assert request.called_once
|
||||
|
||||
|
||||
class TestCategories:
|
||||
def test_categories(self, discourse_client, discourse_request):
|
||||
request = discourse_request(
|
||||
"get",
|
||||
"/categories.json",
|
||||
json={"category_list": {"categories": []}},
|
||||
)
|
||||
discourse_client.categories()
|
||||
assert request.called_once
|
||||
|
||||
def test_update_category(self, discourse_client, discourse_request):
|
||||
request = discourse_request("put", "/categories/123")
|
||||
discourse_client.update_category(123, a="a", b="b")
|
||||
|
||||
request_payload = request.last_request.json()
|
||||
|
||||
assert request_payload["a"] == "a"
|
||||
assert request_payload["b"] == "b"
|
||||
|
||||
|
||||
@mock.patch("requests.request")
|
||||
class TestTopics(ClientBaseTestCase):
|
||||
class TestBadges:
|
||||
def test_badges(self, discourse_client, discourse_request):
|
||||
request = discourse_request("get", "/admin/badges.json")
|
||||
discourse_client.badges()
|
||||
assert request.called_once
|
||||
|
||||
def test_hot_topics(self, request):
|
||||
prepare_response(request)
|
||||
self.client.hot_topics()
|
||||
self.assertRequestCalled(request, "GET", "/hot.json")
|
||||
def test_grant_badge_to(self, discourse_client, discourse_request):
|
||||
request = discourse_request("post", "/user_badges")
|
||||
discourse_client.grant_badge_to("username", 1)
|
||||
|
||||
def test_latest_topics(self, request):
|
||||
prepare_response(request)
|
||||
self.client.latest_topics()
|
||||
self.assertRequestCalled(request, "GET", "/latest.json")
|
||||
request_payload = urllib.parse.parse_qs(request.last_request.text)
|
||||
|
||||
def test_new_topics(self, request):
|
||||
prepare_response(request)
|
||||
self.client.new_topics()
|
||||
self.assertRequestCalled(request, "GET", "/new.json")
|
||||
|
||||
def test_topic(self, request):
|
||||
prepare_response(request)
|
||||
self.client.topic("some-test-slug", 22)
|
||||
self.assertRequestCalled(request, "GET", "/t/some-test-slug/22.json")
|
||||
|
||||
def test_topics_by(self, request):
|
||||
prepare_response(request)
|
||||
r = self.client.topics_by("someuser")
|
||||
self.assertRequestCalled(request, "GET", "/topics/created-by/someuser.json")
|
||||
self.assertEqual(r, request().json()["topic_list"]["topics"])
|
||||
|
||||
def invite_user_to_topic(self, request):
|
||||
prepare_response(request)
|
||||
email = "test@example.com"
|
||||
self.client.invite_user_to_topic(email, 22)
|
||||
self.assertRequestCalled(
|
||||
request, "POST", "/t/22/invite.json", email=email, topic_id=22
|
||||
)
|
||||
assert request_payload["username"] == ["username"]
|
||||
assert request_payload["badge_id"] == ["1"]
|
||||
|
||||
|
||||
@mock.patch("pydiscourse.client.requests.request")
|
||||
class MiscellaneousTests(ClientBaseTestCase):
|
||||
|
||||
def test_latest_posts(self, request):
|
||||
prepare_response(request)
|
||||
r = self.client.latest_posts(before=54321)
|
||||
self.assertRequestCalled(request, "GET", "/posts.json", before=54321)
|
||||
|
||||
def test_search(self, request):
|
||||
prepare_response(request)
|
||||
self.client.search("needle")
|
||||
self.assertRequestCalled(request, "GET", "/search.json", term="needle")
|
||||
|
||||
def test_categories(self, request):
|
||||
prepare_response(request)
|
||||
r = self.client.categories()
|
||||
self.assertRequestCalled(request, "GET", "/categories.json")
|
||||
self.assertEqual(r, request().json()["category_list"]["categories"])
|
||||
|
||||
def test_update_category(self, request):
|
||||
prepare_response(request)
|
||||
self.client.update_category(123, a="a", b="b")
|
||||
self.assertRequestCalled(request, "PUT", "/categories/123", a="a", b="b")
|
||||
|
||||
def test_users(self, request):
|
||||
prepare_response(request)
|
||||
self.client.users()
|
||||
self.assertRequestCalled(request, "GET", "/admin/users/list/active.json")
|
||||
|
||||
def test_badges(self, request):
|
||||
prepare_response(request)
|
||||
self.client.badges()
|
||||
self.assertRequestCalled(request, "GET", "/admin/badges.json")
|
||||
|
||||
def test_grant_badge_to(self, request):
|
||||
prepare_response(request)
|
||||
self.client.grant_badge_to("username", 1)
|
||||
self.assertRequestCalled(
|
||||
request, "POST", "/user_badges", username="username", badge_id=1
|
||||
)
|
||||
class TestAbout:
|
||||
def test_about(self, discourse_client, discourse_request):
|
||||
request = discourse_request("get", "/about.json")
|
||||
discourse_client.about()
|
||||
assert request.called_once
|
||||
|
||||
@ -1,76 +1,95 @@
|
||||
from base64 import b64decode
|
||||
|
||||
import unittest
|
||||
|
||||
from urllib.parse import unquote
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
|
||||
import pytest
|
||||
|
||||
from pydiscourse import sso
|
||||
from pydiscourse.exceptions import DiscourseError
|
||||
|
||||
|
||||
class SSOTestCase(unittest.TestCase):
|
||||
def test_sso_validate_missing_payload():
|
||||
with pytest.raises(DiscourseError) as excinfo:
|
||||
sso.sso_validate(None, "abc", "123")
|
||||
|
||||
def setUp(self):
|
||||
# values from https://meta.discourse.org/t/official-single-sign-on-for-discourse/13045
|
||||
self.secret = "d836444a9e4084d5b224a60c208dce14"
|
||||
self.nonce = "cb68251eefb5211e58c00ff1395f0c0b"
|
||||
self.payload = "bm9uY2U9Y2I2ODI1MWVlZmI1MjExZTU4YzAwZmYxMzk1ZjBjMGI%3D%0A"
|
||||
self.signature = "2828aa29899722b35a2f191d34ef9b3ce695e0e6eeec47deb46d588d70c7cb56"
|
||||
assert excinfo.value.args[0] == "No SSO payload or signature."
|
||||
|
||||
self.name = u"sam"
|
||||
self.username = u"samsam"
|
||||
self.external_id = u"hello123"
|
||||
self.email = u"test@test.com"
|
||||
self.redirect_url = u"/session/sso_login?sso=bm9uY2U9Y2I2ODI1MWVlZmI1MjExZTU4YzAwZmYxMzk1ZjBjMGImbmFtZT1z%0AYW0mdXNlcm5hbWU9c2Ftc2FtJmVtYWlsPXRlc3QlNDB0ZXN0LmNvbSZleHRl%0Acm5hbF9pZD1oZWxsbzEyMw%3D%3D%0A&sig=1c884222282f3feacd76802a9dd94e8bc8deba5d619b292bed75d63eb3152c0b"
|
||||
|
||||
def test_missing_args(self):
|
||||
with self.assertRaises(DiscourseError):
|
||||
sso.sso_validate(None, self.signature, self.secret)
|
||||
def test_sso_validate_empty_payload():
|
||||
with pytest.raises(DiscourseError) as excinfo:
|
||||
sso.sso_validate("", "abc", "123")
|
||||
|
||||
with self.assertRaises(DiscourseError):
|
||||
sso.sso_validate("", self.signature, self.secret)
|
||||
assert excinfo.value.args[0] == "Invalid payload."
|
||||
|
||||
with self.assertRaises(DiscourseError):
|
||||
sso.sso_validate(self.payload, None, self.secret)
|
||||
|
||||
def test_invalid_signature(self):
|
||||
with self.assertRaises(DiscourseError):
|
||||
sso.sso_validate(self.payload, "notavalidsignature", self.secret)
|
||||
def test_sso_validate_missing_signature():
|
||||
with pytest.raises(DiscourseError) as excinfo:
|
||||
sso.sso_validate("sig", None, "123")
|
||||
|
||||
def test_valid_nonce(self):
|
||||
nonce = sso.sso_validate(self.payload, self.signature, self.secret)
|
||||
self.assertEqual(nonce, self.nonce)
|
||||
assert excinfo.value.args[0] == "No SSO payload or signature."
|
||||
|
||||
def test_valid_redirect_url(self):
|
||||
url = sso.sso_redirect_url(
|
||||
self.nonce,
|
||||
self.secret,
|
||||
self.email,
|
||||
self.external_id,
|
||||
self.username,
|
||||
name="sam",
|
||||
)
|
||||
|
||||
self.assertIn("/session/sso_login", url[:20])
|
||||
@pytest.mark.parametrize("bad_secret", [None, ""])
|
||||
def test_sso_validate_missing_secret(bad_secret):
|
||||
with pytest.raises(DiscourseError) as excinfo:
|
||||
sso.sso_validate("payload", "signature", bad_secret)
|
||||
|
||||
# check its valid, using our own handy validator
|
||||
params = parse_qs(urlparse(url).query)
|
||||
payload = params["sso"][0]
|
||||
sso.sso_validate(payload, params["sig"][0], self.secret)
|
||||
assert excinfo.value.args[0] == "Invalid secret."
|
||||
|
||||
# check the params have all the data we expect
|
||||
payload = b64decode(payload.encode("utf-8")).decode("utf-8")
|
||||
payload = unquote(payload)
|
||||
payload = dict((p.split("=") for p in payload.split("&")))
|
||||
|
||||
self.assertEqual(
|
||||
payload,
|
||||
{
|
||||
"username": self.username,
|
||||
"nonce": self.nonce,
|
||||
"external_id": self.external_id,
|
||||
"name": self.name,
|
||||
"email": self.email,
|
||||
},
|
||||
)
|
||||
def test_sso_validate_invalid_signature(sso_payload, sso_signature, sso_secret):
|
||||
with pytest.raises(DiscourseError) as excinfo:
|
||||
sso.sso_validate("Ym9i", sso_signature, sso_secret)
|
||||
|
||||
assert excinfo.value.args[0] == "Invalid payload."
|
||||
|
||||
|
||||
def test_sso_validate_invalid_payload_nonce(sso_payload, sso_secret):
|
||||
with pytest.raises(DiscourseError) as excinfo:
|
||||
sso.sso_validate(sso_payload, "notavalidsignature", sso_secret)
|
||||
|
||||
assert excinfo.value.args[0] == "Payload does not match signature."
|
||||
|
||||
|
||||
def test_valid_nonce(sso_payload, sso_signature, sso_secret, sso_nonce):
|
||||
generated_nonce = sso.sso_validate(sso_payload, sso_signature, sso_secret)
|
||||
assert generated_nonce == sso_nonce
|
||||
|
||||
|
||||
def test_valid_redirect_url(
|
||||
sso_secret,
|
||||
sso_nonce,
|
||||
name,
|
||||
email,
|
||||
username,
|
||||
external_id,
|
||||
redirect_url,
|
||||
):
|
||||
url = sso.sso_redirect_url(
|
||||
sso_nonce,
|
||||
sso_secret,
|
||||
email,
|
||||
external_id,
|
||||
username,
|
||||
name="sam",
|
||||
)
|
||||
|
||||
assert "/session/sso_login" in url[:20]
|
||||
|
||||
# check its valid, using our own handy validator
|
||||
params = parse_qs(urlparse(url).query)
|
||||
payload = params["sso"][0]
|
||||
sso.sso_validate(payload, params["sig"][0], sso_secret)
|
||||
|
||||
# check the params have all the data we expect
|
||||
payload = b64decode(payload.encode("utf-8")).decode("utf-8")
|
||||
payload = unquote(payload)
|
||||
payload = dict(p.split("=") for p in payload.split("&"))
|
||||
|
||||
assert payload == {
|
||||
"username": username,
|
||||
"nonce": sso_nonce,
|
||||
"external_id": external_id,
|
||||
"name": name,
|
||||
"email": email,
|
||||
}
|
||||
|
||||
22
tox.ini
22
tox.ini
@ -1,5 +1,5 @@
|
||||
[tox]
|
||||
envlist = py37, py38, py39, py310, py311
|
||||
envlist = py38, py39, py310, py311
|
||||
|
||||
[gh-actions]
|
||||
python =
|
||||
@ -7,24 +7,22 @@ python =
|
||||
3.9: py39
|
||||
3.10: py310
|
||||
3.11: py311
|
||||
3.12: py312
|
||||
|
||||
[testenv]
|
||||
setenv =
|
||||
PYTHONPATH = {toxinidir}:{toxinidir}/pydiscourse
|
||||
commands = pytest {posargs} --cov=pydiscourse
|
||||
commands =
|
||||
pytest {posargs} --cov=pydiscourse
|
||||
coverage report -m --include='**/pydiscourse/client.py' --fail-under=46
|
||||
coverage report -m --include='**/pydiscourse/sso.py' --fail-under=100
|
||||
deps =
|
||||
-r{toxinidir}/requirements.txt
|
||||
|
||||
[testenv:flake8]
|
||||
[testenv:ruff]
|
||||
basepython=python
|
||||
skip_install=true
|
||||
deps=
|
||||
flake8
|
||||
flake8_docstrings
|
||||
ruff
|
||||
commands=
|
||||
flake8 src/pydiscourse --docstring-convention google --ignore D415
|
||||
|
||||
[flake8]
|
||||
ignore = E126,E128
|
||||
max-line-length = 119
|
||||
exclude = .ropeproject
|
||||
max-complexity = 10
|
||||
ruff .
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user