27 Commits

Author SHA1 Message Date
d83594760c remove fail-on-missing 2026-03-28 22:12:56 +00:00
46a85f2904 remove env-include 2026-03-28 08:38:57 +00:00
fe9f305afe update examples to work with modified req client
examples now expect env variables
2026-03-27 16:29:16 +00:00
7126a2efe0 Merge branch 'aatikturk:main' into autogen-reqclient 2026-03-27 15:51:12 +00:00
3d312c18ed upd .gitignore 2026-03-26 07:39:20 +00:00
9d99ea0aea add autogenerated reqclient methods
update tests so they pass

add Taskfile

add hatch-dotenv plugin
2026-03-26 07:05:34 +00:00
4e9fb934be fix payload key 2025-07-05 15:42:40 +01:00
f70583d7ca Merge pull request #58 from onyx-and-iris/add-v5.4-v5.5-reqs
add v5.4, v5.5 methods
2025-07-01 09:20:00 +01:00
82baa40e79 reqclient rework initial commit
position arguments removed.

keyword-only argument enforced.

type annotations added

this is a breaking change and would required a major version bump.
2025-06-28 14:24:50 +01:00
3bce50701e add v5.4, v5.5 methods
v5.4:
- get_source_filter_kind_list
- get_scene_item_source

v5.5:
- split_record_file
- create_record_chapter

minor bump
2025-06-23 06:25:31 +01:00
8e8062d5c8 Merge pull request #57 from onyx-and-iris/dev
Return response class for toggle_record
2025-05-14 20:19:49 +01:00
6f64e884d8 md fix 2025-05-07 22:00:19 +01:00
90abc4f9ee upd test_get_hot_key_list
- check hotkey list is not empty
- check it has at least one OBSBasic. hotkey.
2025-05-07 19:13:09 +01:00
f564f53c69 return response class for toggle_record()
patch bump
2025-05-07 18:42:29 +01:00
4d9dfa9d11 Merge pull request #55 from onyx-and-iris/dev
Update tests
2025-02-11 14:19:27 +00:00
9e361f0f8a fix hatch link 2025-02-11 10:16:56 +00:00
797161a6f2 import Callable, Iterable from collections.abs instead of typing.
update tests to reflect changes in the API.

reorganise hatch envs

add black,isort configs to pyproject.toml

add pre-commit config
2025-02-11 09:51:00 +00:00
0fe78197fc Merge branch 'aatikturk:main' into dev 2025-02-10 12:27:07 +00:00
Adem
9c4c5a1df9 Merge pull request #53 from Zynthasius39/dev-zynt
Fix Trigger Hotkey Methods
2025-02-10 15:02:36 +03:00
f52ac163b8 patch bump version 2025-02-10 09:12:09 +00:00
Zynthasius39
197a60a7cd Fix trigger_hot_key_by_key_sequence() method 2025-02-08 18:31:12 +04:00
Zynthasius39
633093ead4 Fix trigger_hot_key_by_name() method 2025-02-08 17:59:45 +04:00
935392a0b6 Merge branch 'aatikturk:main' into dev 2025-01-25 22:34:36 +00:00
d2f2926334 Merge pull request #51 from marzeq/patch-1
Fix project.license field in pyproject.toml so that setup.py doesn't fail
2025-01-25 21:48:55 +00:00
marzeq
58cd50dd6c Fix project.license field in pyproject.toml so that setup.py doesn't fail 2025-01-25 21:34:27 +01:00
7614cdfe4a add py12 to test matrix 2024-02-21 14:15:40 +00:00
Adem
9402f2e472 Merge pull request #43 from onyx-and-iris/fix-disconnect
Add disconnect() methods. Default ws timeout to None for event thread.
2024-01-21 15:45:06 +03:00
18 changed files with 2718 additions and 1559 deletions

179
.gitignore vendored
View File

@@ -1,8 +1,14 @@
# Generated by ignr: github.com/onyx-and-iris/ignr
## Python ##
# Byte-compiled / optimized / DLL files # Byte-compiled / optimized / DLL files
__pycache__/ __pycache__/
*.py[cod] *.py[codz]
*$py.class *$py.class
# C extensions
*.so
# Distribution / packaging # Distribution / packaging
.Python .Python
build/ build/
@@ -17,11 +23,22 @@ parts/
sdist/ sdist/
var/ var/
wheels/ wheels/
share/python-wheels/
*.egg-info/ *.egg-info/
.installed.cfg .installed.cfg
*.egg *.egg
MANIFEST MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports # Unit test / coverage reports
htmlcov/ htmlcov/
.tox/ .tox/
@@ -32,27 +49,169 @@ htmlcov/
nosetests.xml nosetests.xml
coverage.xml coverage.xml
*.cover *.cover
*.py.cover
.hypothesis/ .hypothesis/
.pytest_cache/ .pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# UV
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
#uv.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
#poetry.toml
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
#pdm.lock
#pdm.toml
.pdm-python
.pdm-build/
# pixi
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
#pixi.lock
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
# in the .venv directory. It is recommended not to include this directory in version control.
.pixi
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments # Environments
.env .env
.envrc
.venv .venv
env/ env/
venv/ venv/
ENV/ ENV/
env.bak/ env.bak/
venv.bak/ venv.bak/
.hatch
# pyenv # Spyder project settings
# For a library or package, you might want to ignore these files since the code is .spyderproject
# intended to run in multiple environments; otherwise, check them in: .spyproject
.python-version
# Test/config # Rope project settings
quick.py .ropeproject
config.toml
obsws.log
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
# Abstra
# Abstra is an AI-powered process automation framework.
# Ignore directories containing user credentials, local state, and settings.
# Learn more at https://abstra.io/docs
.abstra/
# Visual Studio Code
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
# and can be added to the global gitignore or merged into this file. However, if you prefer,
# you could uncomment the following to ignore the entire vscode folder
.vscode/ .vscode/
# Ruff stuff:
.ruff_cache/
# PyPI configuration file
.pypirc
# Cursor
# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
# refer to https://docs.cursor.com/context/ignore-files
.cursorignore
.cursorindexingignore
# Marimo
marimo/_static/
marimo/_lsp/
__marimo__/
# End of ignr
tools/
test-*.py
config.toml

10
.pre-commit-config.yaml Normal file
View File

@@ -0,0 +1,10 @@
repos:
- repo: local
hooks:
- id: format
name: format
entry: hatch run style:fmt
language: system
pass_filenames: false
verbose: true
files: \.(py)$

View File

@@ -1,5 +1,6 @@
[![PyPI version](https://badge.fury.io/py/obsws-python.svg)](https://badge.fury.io/py/obsws-python) [![PyPI version](https://badge.fury.io/py/obsws-python.svg)](https://badge.fury.io/py/obsws-python)
[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://github.com/aatikturk/obsstudio_sdk/blob/main/LICENSE) [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://github.com/aatikturk/obsstudio_sdk/blob/main/LICENSE)
[![Hatch project](https://img.shields.io/badge/%F0%9F%A5%9A-Hatch-4051b5.svg)](https://github.com/pypa/hatch)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
[![Imports: isort](https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336)](https://pycqa.github.io/isort/) [![Imports: isort](https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336)](https://pycqa.github.io/isort/)
@@ -92,7 +93,7 @@ resp = cl_req.send("GetVersion", raw=True)
print(f"response data: {resp}") print(f"response data: {resp}")
``` ```
For a full list of requests refer to [Requests](https://github.com/obsproject/obs-websocket/blob/master/docs/generated/protocol.md#requests) For a full list of requests refer to [Requests][obsws-reqs]
### Events ### Events
@@ -125,7 +126,7 @@ cl.callback.deregister(on_input_mute_state_changed)
`register(fns)` and `deregister(fns)` accept both single functions and lists of functions. `register(fns)` and `deregister(fns)` accept both single functions and lists of functions.
For a full list of events refer to [Events](https://github.com/obsproject/obs-websocket/blob/master/docs/generated/protocol.md#events) For a full list of events refer to [Events][obsws-events]
### Attributes ### Attributes
@@ -149,7 +150,7 @@ def on_scene_created(data):
- The following attributes are available: - The following attributes are available:
- `req_name`: name of the request. - `req_name`: name of the request.
- `code`: request status code. - `code`: request status code.
- For a full list of status codes refer to [Codes](https://github.com/obsproject/obs-websocket/blob/master/docs/generated/protocol.md#requeststatus) - For a full list of status codes refer to [Codes][obsws-codes]
### Logging ### Logging
@@ -168,18 +169,21 @@ logging.basicConfig(level=logging.DEBUG)
### Tests ### Tests
First install development dependencies: Install [hatch][hatch-install] and then:
`pip install -e .['dev']`
To run all tests:
``` ```
pytest -v hatch test
``` ```
### Official Documentation ### Official Documentation
For the full documentation: For the full documentation:
- [OBS Websocket SDK](https://github.com/obsproject/obs-websocket/blob/master/docs/generated/protocol.md#obs-websocket-501-protocol) - [OBS Websocket SDK][obsws-pro]
[obsws-reqs]: https://github.com/obsproject/obs-websocket/blob/master/docs/generated/protocol.md#requests
[obsws-events]: https://github.com/obsproject/obs-websocket/blob/master/docs/generated/protocol.md#events
[obsws-codes]: https://github.com/obsproject/obs-websocket/blob/master/docs/generated/protocol.md#requeststatus
[obsws-pro]: https://github.com/obsproject/obs-websocket/blob/master/docs/generated/protocol.md#obs-websocket-501-protocol
[hatch-install]: https://hatch.pypa.io/latest/install/

23
Taskfile.yaml Normal file
View File

@@ -0,0 +1,23 @@
version: '3'
tasks:
default:
desc: Generate ReqClient methods from the API spec
deps: [generate]
generate:
desc: Generate ReqClient methods from the API spec
deps: [pull-protocol-json]
cmds:
- python tools/generate.py
- hatch run style:fmt
internal: true
pull-protocol-json:
desc: Pull the latest API spec from the obs-websocket repository
preconditions:
- sh: '[ ! -f tools/protocol.json ] || [ "$(find tools/protocol.json -mmin +1440)" ]'
msg: 'The protocol.json file is up to date (last modified less than 24 hours ago).'
cmds:
- curl -sSfL -o tools/protocol.json "https://raw.githubusercontent.com/obsproject/obs-websocket/refs/heads/master/docs/generated/protocol.json"
internal: true

View File

@@ -1,11 +1,13 @@
import time import os
from threading import Event
import obsws_python as obs import obsws_python as obs
class Observer: class Observer:
def __init__(self): def __init__(self, host, port, password, stop_event):
self._client = obs.EventClient() self._client = obs.EventClient(host=host, port=port, password=password)
self._stop_event = stop_event
self._client.callback.register( self._client.callback.register(
[ [
self.on_current_program_scene_changed, self.on_current_program_scene_changed,
@@ -15,7 +17,6 @@ class Observer:
] ]
) )
print(f"Registered events: {self._client.callback.get()}") print(f"Registered events: {self._client.callback.get()}")
self.running = True
def __enter__(self): def __enter__(self):
return self return self
@@ -38,10 +39,15 @@ class Observer:
def on_exit_started(self, _): def on_exit_started(self, _):
"""OBS has begun the shutdown process.""" """OBS has begun the shutdown process."""
print("OBS closing!") print("OBS closing!")
self.running = False self._stop_event.set()
if __name__ == "__main__": if __name__ == "__main__":
with Observer() as observer: host = os.getenv("OBSWS_HOST", "localhost")
while observer.running: port = int(os.getenv("OBSWS_PORT", 4455))
time.sleep(0.1) password = os.getenv("OBSWS_PASSWORD", "")
stop_event = Event()
with Observer(host, port, password, stop_event) as observer:
stop_event.wait()

View File

@@ -1,13 +1,14 @@
import inspect import inspect
import os
import keyboard import keyboard # type: ignore
import obsws_python as obs import obsws_python as obs
class Observer: class Observer:
def __init__(self): def __init__(self, host, port, password):
self._client = obs.EventClient() self._client = obs.EventClient(host=host, port=port, password=password)
self._client.callback.register(self.on_current_program_scene_changed) self._client.callback.register(self.on_current_program_scene_changed)
print(f"Registered events: {self._client.callback.get()}") print(f"Registered events: {self._client.callback.get()}")
@@ -34,12 +35,16 @@ def version():
def set_scene(scene, *args): def set_scene(scene, *args):
req_client.set_current_program_scene(scene) req_client.set_current_program_scene(scene_name=scene)
if __name__ == "__main__": if __name__ == "__main__":
with obs.ReqClient() as req_client: host = os.getenv("OBSWS_HOST", "localhost")
with Observer() as observer: port = int(os.getenv("OBSWS_PORT", 4455))
password = os.getenv("OBSWS_PASSWORD", "")
with obs.ReqClient(host=host, port=port, password=password) as req_client:
with Observer(host, port, password) as observer:
keyboard.add_hotkey("0", version) keyboard.add_hotkey("0", version)
keyboard.add_hotkey("1", set_scene, args=("START",)) keyboard.add_hotkey("1", set_scene, args=("START",))
keyboard.add_hotkey("2", set_scene, args=("BRB",)) keyboard.add_hotkey("2", set_scene, args=("BRB",))

View File

@@ -1,3 +1,4 @@
import os
from enum import IntEnum from enum import IntEnum
from math import log from math import log
@@ -34,8 +35,15 @@ def on_input_volume_meters(data):
def main(): def main():
host = os.getenv("OBSWS_HOST", "localhost")
port = int(os.getenv("OBSWS_PORT", 4455))
password = os.getenv("OBSWS_PASSWORD", "")
with obs.EventClient( with obs.EventClient(
subs=(obs.Subs.LOW_VOLUME | obs.Subs.INPUTVOLUMEMETERS) host=host,
port=port,
password=password,
subs=(obs.Subs.LOW_VOLUME | obs.Subs.INPUTVOLUMEMETERS),
) as client: ) as client:
client.callback.register([on_input_volume_meters, on_input_mute_state_changed]) client.callback.register([on_input_volume_meters, on_input_mute_state_changed])

View File

@@ -1,16 +1,21 @@
import os
import time import time
import obsws_python as obs import obsws_python as obs
def main(): def main():
with obs.ReqClient() as client: host = os.getenv("OBSWS_HOST", "localhost")
port = int(os.getenv("OBSWS_PORT", 4455))
password = os.getenv("OBSWS_PASSWORD", "")
with obs.ReqClient(host=host, port=port, password=password) as client:
resp = client.get_scene_list() resp = client.get_scene_list()
scenes = [di.get("sceneName") for di in reversed(resp.scenes)] scenes = [di.get("sceneName") for di in reversed(resp.scenes)]
for scene in scenes: for scene in scenes:
print(f"Switching to scene {scene}") print(f"Switching to scene {scene}")
client.set_current_program_scene(scene) client.set_current_program_scene(scene_name=scene)
time.sleep(0.5) time.sleep(0.5)

View File

@@ -96,10 +96,8 @@ class ObsClient:
auth = base64.b64encode( auth = base64.b64encode(
hashlib.sha256( hashlib.sha256(
(
secret secret
+ self.server_hello["d"]["authentication"]["challenge"].encode() + self.server_hello["d"]["authentication"]["challenge"].encode()
)
).digest() ).digest()
).decode() ).decode()

View File

@@ -1,4 +1,5 @@
from typing import Callable, Iterable, Union from collections.abc import Callable, Iterable
from typing import Union
from .util import as_dataclass, to_camel_case, to_snake_case from .util import as_dataclass, to_camel_case, to_snake_case

File diff suppressed because it is too large Load Diff

View File

@@ -1 +1 @@
version = "1.7.0" version = "1.8.0"

View File

@@ -7,23 +7,10 @@ name = "obsws-python"
dynamic = ["version"] dynamic = ["version"]
description = "A Python SDK for OBS Studio WebSocket v5.0" description = "A Python SDK for OBS Studio WebSocket v5.0"
readme = "README.md" readme = "README.md"
license = "GPL-3.0-only" license = { text = "GPL-3.0-only" }
requires-python = ">=3.9" requires-python = ">=3.9"
authors = [ authors = [{ name = "Adem Atikturk", email = "aatikturk@gmail.com" }]
{ name = "Adem Atikturk", email = "aatikturk@gmail.com" }, dependencies = ["tomli >= 2.0.1;python_version < '3.11'", "websocket-client"]
]
dependencies = [
"tomli >= 2.0.1;python_version < '3.11'",
"websocket-client",
]
[project.optional-dependencies]
dev = [
"black",
"isort",
"pytest",
"pytest-randomly",
]
[project.urls] [project.urls]
Homepage = "https://github.com/aatikturk/obsws-python" Homepage = "https://github.com/aatikturk/obsws-python"
@@ -32,23 +19,64 @@ Homepage = "https://github.com/aatikturk/obsws-python"
path = "obsws_python/version.py" path = "obsws_python/version.py"
[tool.hatch.build.targets.sdist] [tool.hatch.build.targets.sdist]
include = [ include = ["/obsws_python"]
"/obsws_python",
] [tool.hatch.env]
requires = ["hatch-dotenv"]
[tool.hatch.env.collectors.dotenv.e]
env-files = [".env"]
# fail-on-missing = true # breaks publish workflow
[tool.hatch.env.collectors.dotenv.hatch-test]
env-files = [".env"]
# fail-on-missing = true # breaks publish workflow
[tool.hatch.envs.default]
dependencies = ["pre-commit"]
[tool.hatch.envs.e]
dependencies = ["keyboard"]
# env-include = ["OBSWS_*"] # causes issues on Windows.
[tool.hatch.envs.e.scripts] [tool.hatch.envs.e.scripts]
events = "python {root}\\examples\\events\\." events = "python -m examples.events"
hotkeys = "python {root}\\examples\\hotkeys\\." hotkeys = "python -m examples.hotkeys"
levels = "python {root}\\examples\\levels\\." levels = "python -m examples.levels"
scene_rotate = "python {root}\\examples\\scene_rotate\\." scene-rotate = "python -m examples.scene_rotate"
[tool.hatch.envs.test] [tool.hatch.envs.hatch-test]
dependencies = [ randomize = true
"pytest", # env-include = ["OBSWS_*"] # causes issues on Windows.
]
[tool.hatch.envs.test.scripts] [tool.hatch.envs.hatch-test.scripts]
run = 'pytest -v' run = "pytest{env:HATCH_TEST_ARGS:} {args}"
[[tool.hatch.envs.test.matrix]] [[tool.hatch.envs.hatch-test.matrix]]
python = ["39", "310", "311"] python = ["313", "312", "311", "310", "39"]
[tool.hatch.envs.style]
detached = true
dependencies = ["black", "isort"]
[tool.hatch.envs.style.scripts]
check = ["black --check --diff .", "isort --check-only --diff ."]
fmt = ["isort .", "black ."]
[tool.black]
line-length = 88
include = '\.pyi?$'
# 'extend-exclude' excludes files or directories in addition to the defaults
extend-exclude = '''
(
^/\.git/ # exclude all files in the .git directory
^/\.hatch/ # exclude all files in the .hatch directory
^/\.pytest_cache/ # exclude all files in the .pytest_cache directory
| .*_pb2.py # exclude autogenerated Protocol Buffer files anywhere in the project
)
'''
[tool.isort]
profile = "black"
skip = [".gitignore", ".dockerignore"]
skip_glob = [".git/*", ".hatch/*", ".pytest_cache/*"]

View File

@@ -1,19 +1,25 @@
import os
import obsws_python as obs import obsws_python as obs
req_cl = obs.ReqClient() req_cl = obs.ReqClient(
host=os.getenv("OBSWS_HOST", "localhost"),
port=int(os.getenv("OBSWS_PORT", 4455)),
password=os.getenv("OBSWS_PASSWORD", ""),
)
def setup_module(): def setup_module():
req_cl.create_scene("START_TEST") req_cl.create_scene(scene_name="START_TEST")
req_cl.create_scene("BRB_TEST") req_cl.create_scene(scene_name="BRB_TEST")
req_cl.create_scene("END_TEST") req_cl.create_scene(scene_name="END_TEST")
def teardown_module(): def teardown_module():
req_cl.remove_scene("START_TEST") req_cl.remove_scene(scene_name="START_TEST")
req_cl.remove_scene("BRB_TEST") req_cl.remove_scene(scene_name="BRB_TEST")
req_cl.remove_scene("END_TEST") req_cl.remove_scene(scene_name="END_TEST")
resp = req_cl.get_studio_mode_enabled() resp = req_cl.get_studio_mode_enabled()
if resp.studio_mode_enabled: if resp.studio_mode_enabled:
req_cl.set_studio_mode_enabled(False) req_cl.set_studio_mode_enabled(studio_mode_enabled=False)
req_cl.base_client.ws.close() req_cl.base_client.ws.close()

View File

@@ -18,7 +18,12 @@ class TestAttrs:
def test_get_current_program_scene_attrs(self): def test_get_current_program_scene_attrs(self):
resp = req_cl.get_current_program_scene() resp = req_cl.get_current_program_scene()
assert resp.attrs() == ["current_program_scene_name"] assert resp.attrs() == [
"current_program_scene_name",
"current_program_scene_uuid",
"scene_name",
"scene_uuid",
]
def test_get_transition_kind_list_attrs(self): def test_get_transition_kind_list_attrs(self):
resp = req_cl.get_transition_kind_list() resp = req_cl.get_transition_kind_list()

View File

@@ -1,4 +1,5 @@
import pytest import pytest
from obsws_python.callback import Callback from obsws_python.callback import Callback

View File

@@ -1,3 +1,5 @@
import os
import pytest import pytest
import obsws_python as obsws import obsws_python as obsws
@@ -8,7 +10,11 @@ class TestErrors:
__test__ = True __test__ = True
def test_it_raises_an_obssdk_error_on_incorrect_password(self): def test_it_raises_an_obssdk_error_on_incorrect_password(self):
bad_conn = {"host": "localhost", "port": 4455, "password": "incorrectpassword"} bad_conn = {
"host": os.getenv("OBSWS_HOST", "localhost"),
"port": int(os.getenv("OBSWS_PORT", 4455)),
"password": "incorrectpassword",
}
with pytest.raises( with pytest.raises(
obsws.error.OBSSDKError, obsws.error.OBSSDKError,
match="failed to identify client with the server, please check connection settings", match="failed to identify client with the server, please check connection settings",
@@ -16,7 +22,11 @@ class TestErrors:
obsws.ReqClient(**bad_conn) obsws.ReqClient(**bad_conn)
def test_it_raises_an_obssdk_error_if_auth_enabled_but_no_password_provided(self): def test_it_raises_an_obssdk_error_if_auth_enabled_but_no_password_provided(self):
bad_conn = {"host": "localhost", "port": 4455, "password": ""} bad_conn = {
"host": os.getenv("OBSWS_HOST", "localhost"),
"port": int(os.getenv("OBSWS_PORT", 4455)),
"password": "",
}
with pytest.raises( with pytest.raises(
obsws.error.OBSSDKError, obsws.error.OBSSDKError,
match="authentication enabled but no password provided", match="authentication enabled but no password provided",
@@ -28,7 +38,7 @@ class TestErrors:
obsws.error.OBSSDKRequestError, obsws.error.OBSSDKRequestError,
match="Request SetCurrentProgramScene returned code 600. With message: No source was found by the name of `invalid`.", match="Request SetCurrentProgramScene returned code 600. With message: No source was found by the name of `invalid`.",
) as exc_info: ) as exc_info:
req_cl.set_current_program_scene("invalid") req_cl.set_current_program_scene(scene_name="invalid")
e = exc_info.value e = exc_info.value
assert e.req_name == "SetCurrentProgramScene" assert e.req_name == "SetCurrentProgramScene"

View File

@@ -11,37 +11,10 @@ class TestRequests:
assert hasattr(resp, "obs_version") assert hasattr(resp, "obs_version")
assert hasattr(resp, "obs_web_socket_version") assert hasattr(resp, "obs_web_socket_version")
def test_get_hot_key_list(self): def test_get_hotkey_list(self):
resp = req_cl.get_hot_key_list() resp = req_cl.get_hotkey_list()
obsbasic_hotkey_list = [ assert resp.hotkeys
"OBSBasic.SelectScene", assert any(x.startswith("OBSBasic.") for x in resp.hotkeys)
"OBSBasic.QuickTransition.1",
"OBSBasic.QuickTransition.2",
"OBSBasic.QuickTransition.3",
"OBSBasic.StartStreaming",
"OBSBasic.StopStreaming",
"OBSBasic.ForceStopStreaming",
"OBSBasic.StartRecording",
"OBSBasic.StopRecording",
"OBSBasic.PauseRecording",
"OBSBasic.UnpauseRecording",
"OBSBasic.SplitFile",
"OBSBasic.StartReplayBuffer",
"OBSBasic.StopReplayBuffer",
"OBSBasic.StartVirtualCam",
"OBSBasic.StopVirtualCam",
"OBSBasic.EnablePreview",
"OBSBasic.DisablePreview",
"OBSBasic.EnablePreviewProgram",
"OBSBasic.DisablePreviewProgram",
"OBSBasic.ShowContextBar",
"OBSBasic.HideContextBar",
"OBSBasic.Transition",
"OBSBasic.ResetStats",
"OBSBasic.Screenshot",
"OBSBasic.SelectedSourceScreenshot",
]
assert all(x in resp.hotkeys for x in obsbasic_hotkey_list)
@pytest.mark.parametrize( @pytest.mark.parametrize(
"name,data", "name,data",
@@ -51,15 +24,20 @@ class TestRequests:
], ],
) )
def test_persistent_data(self, name, data): def test_persistent_data(self, name, data):
req_cl.set_persistent_data("OBS_WEBSOCKET_DATA_REALM_PROFILE", name, data) req_cl.set_persistent_data(
resp = req_cl.get_persistent_data("OBS_WEBSOCKET_DATA_REALM_PROFILE", name) realm="OBS_WEBSOCKET_DATA_REALM_PROFILE", slot_name=name, slot_value=data
)
resp = req_cl.get_persistent_data(
realm="OBS_WEBSOCKET_DATA_REALM_PROFILE", slot_name=name
)
assert resp.slot_value == data assert resp.slot_value == data
@pytest.mark.skip(reason="possible bug in obs-websocket, needs checking")
def test_profile_list(self): def test_profile_list(self):
req_cl.create_profile("test") req_cl.create_profile(profile_name="test")
resp = req_cl.get_profile_list() resp = req_cl.get_profile_list()
assert "test" in resp.profiles assert "test" in resp.profiles
req_cl.remove_profile("test") req_cl.remove_profile(profile_name="test")
resp = req_cl.get_profile_list() resp = req_cl.get_profile_list()
assert "test" not in resp.profiles assert "test" not in resp.profiles
@@ -69,8 +47,8 @@ class TestRequests:
"key": "live_myvery_secretkey", "key": "live_myvery_secretkey",
} }
req_cl.set_stream_service_settings( req_cl.set_stream_service_settings(
"rtmp_common", stream_service_type="rtmp_common",
settings, stream_service_settings=settings,
) )
resp = req_cl.get_stream_service_settings() resp = req_cl.get_stream_service_settings()
assert resp.stream_service_type == "rtmp_common" assert resp.stream_service_type == "rtmp_common"
@@ -88,28 +66,40 @@ class TestRequests:
], ],
) )
def test_current_program_scene(self, scene): def test_current_program_scene(self, scene):
req_cl.set_current_program_scene(scene) req_cl.set_current_program_scene(scene_name=scene)
resp = req_cl.get_current_program_scene() resp = req_cl.get_current_program_scene()
assert resp.current_program_scene_name == scene assert resp.current_program_scene_name == scene
def test_input_list(self): def test_input_list(self):
req_cl.create_input( req_cl.create_input(
"START_TEST", "test", "color_source_v3", {"color": 4294945535}, True scene_name="START_TEST",
input_name="test",
input_kind="color_source_v3",
input_settings={"color": 4294945535},
scene_item_enabled=True,
) )
resp = req_cl.get_input_list() resp = req_cl.get_input_list()
assert { for input_item in resp.inputs:
"inputKind": "color_source_v3", if input_item["inputName"] == "test":
"inputName": "test", assert input_item["inputKind"] == "color_source_v3"
"unversionedInputKind": "color_source", assert input_item["unversionedInputKind"] == "color_source"
} in resp.inputs break
resp = req_cl.get_input_settings("test") else:
# This else block is executed if the for loop completes without finding the input_item with inputName "test"
raise AssertionError("Input with inputName 'test' not found")
resp = req_cl.get_input_settings(input_name="test")
assert resp.input_kind == "color_source_v3" assert resp.input_kind == "color_source_v3"
assert resp.input_settings == {"color": 4294945535} assert resp.input_settings == {"color": 4294945535}
req_cl.remove_input("test") req_cl.remove_input(input_name="test")
def test_source_filter(self): def test_source_filter(self):
req_cl.create_source_filter("START_TEST", "test", "color_key_filter_v2") req_cl.create_source_filter(
resp = req_cl.get_source_filter_list("START_TEST") source_name="START_TEST",
filter_name="test",
filter_kind="color_key_filter_v2",
)
resp = req_cl.get_source_filter_list(source_name="START_TEST")
assert resp.filters == [ assert resp.filters == [
{ {
"filterEnabled": True, "filterEnabled": True,
@@ -119,7 +109,7 @@ class TestRequests:
"filterSettings": {}, "filterSettings": {},
} }
] ]
req_cl.remove_source_filter("START_TEST", "test") req_cl.remove_source_filter(source_name="START_TEST", filter_name="test")
@pytest.mark.parametrize( @pytest.mark.parametrize(
"state", "state",
@@ -129,6 +119,6 @@ class TestRequests:
], ],
) )
def test_studio_mode_enabled(self, state): def test_studio_mode_enabled(self, state):
req_cl.set_studio_mode_enabled(state) req_cl.set_studio_mode_enabled(studio_mode_enabled=state)
resp = req_cl.get_studio_mode_enabled() resp = req_cl.get_studio_mode_enabled()
assert resp.studio_mode_enabled == state assert resp.studio_mode_enabled == state