Ejemplo n.º 1
0
def manager_with_user(opp, store, provider_with_user):
    """Mock manager with trusted user."""
    return auth.AuthManager(
        opp,
        store,
        {(provider_with_user.type, provider_with_user.id): provider_with_user},
        {},
    )
Ejemplo n.º 2
0
def manager_bypass_login(opp, store, provider_bypass_login):
    """Mock manager with allow bypass login."""
    return auth.AuthManager(
        opp,
        store,
        {
            (provider_bypass_login.type, provider_bypass_login.id):
            provider_bypass_login
        },
        {},
    )
Ejemplo n.º 3
0
async def async_test_open_peer_power(loop, load_registries=True):
    """Return a Open Peer Power object pointing at test config dir."""
    opp = ha.OpenPeerPower()
    store = auth_store.AuthStore(opp)
    opp.auth = auth.AuthManager(opp, store, {}, {})
    ensure_auth_manager_loaded(opp.auth)
    INSTANCES.append(opp)

    orig_async_add_job = opp.async_add_job
    orig_async_add_executor_job = opp.async_add_executor_job
    orig_async_create_task = opp.async_create_task

    def async_add_job(target, *args):
        """Add job."""
        check_target = target
        while isinstance(check_target, ft.partial):
            check_target = check_target.func

        if isinstance(check_target,
                      Mock) and not isinstance(target, AsyncMock):
            fut = asyncio.Future()
            fut.set_result(target(*args))
            return fut

        return orig_async_add_job(target, *args)

    def async_add_executor_job(target, *args):
        """Add executor job."""
        check_target = target
        while isinstance(check_target, ft.partial):
            check_target = check_target.func

        if isinstance(check_target, Mock):
            fut = asyncio.Future()
            fut.set_result(target(*args))
            return fut

        return orig_async_add_executor_job(target, *args)

    def async_create_task(coroutine):
        """Create task."""
        if isinstance(coroutine,
                      Mock) and not isinstance(coroutine, AsyncMock):
            fut = asyncio.Future()
            fut.set_result(None)
            return fut

        return orig_async_create_task(coroutine)

    async def async_wait_for_task_count(self,
                                        max_remaining_tasks: int = 0) -> None:
        """Block until at most max_remaining_tasks remain.

        Based on OpenPeerPower.async_block_till_done
        """
        # To flush out any call_soon_threadsafe
        await asyncio.sleep(0)
        start_time: float | None = None

        while len(self._pending_tasks) > max_remaining_tasks:
            pending: Collection[Awaitable[Any]] = [
                task for task in self._pending_tasks if not task.done()
            ]
            self._pending_tasks.clear()
            if len(pending) > max_remaining_tasks:
                remaining_pending = await self._await_count_and_log_pending(
                    pending, max_remaining_tasks=max_remaining_tasks)
                self._pending_tasks.extend(remaining_pending)

                if start_time is None:
                    # Avoid calling monotonic() until we know
                    # we may need to start logging blocked tasks.
                    start_time = 0
                elif start_time == 0:
                    # If we have waited twice then we set the start
                    # time
                    start_time = monotonic()
                elif monotonic() - start_time > BLOCK_LOG_TIMEOUT:
                    # We have waited at least three loops and new tasks
                    # continue to block. At this point we start
                    # logging all waiting tasks.
                    for task in pending:
                        _LOGGER.debug("Waiting for task: %s", task)
            else:
                self._pending_tasks.extend(pending)
                await asyncio.sleep(0)

    async def _await_count_and_log_pending(
            self,
            pending: Collection[Awaitable[Any]],
            max_remaining_tasks: int = 0) -> Collection[Awaitable[Any]]:
        """Block at most max_remaining_tasks remain and log tasks that take a long time.

        Based on OpenPeerPower._await_and_log_pending
        """
        wait_time = 0

        return_when = asyncio.ALL_COMPLETED
        if max_remaining_tasks:
            return_when = asyncio.FIRST_COMPLETED

        while len(pending) > max_remaining_tasks:
            _, pending = await asyncio.wait(pending,
                                            timeout=BLOCK_LOG_TIMEOUT,
                                            return_when=return_when)
            if not pending or max_remaining_tasks:
                return pending
            wait_time += BLOCK_LOG_TIMEOUT
            for task in pending:
                _LOGGER.debug("Waited %s seconds for task: %s", wait_time,
                              task)

        return []

    opp.async_add_job = async_add_job
    opp.async_add_executor_job = async_add_executor_job
    opp.async_create_task = async_create_task
    opp.async_wait_for_task_count = types.MethodType(async_wait_for_task_count,
                                                     opp)
    opp._await_count_and_log_pending = types.MethodType(
        _await_count_and_log_pending, opp)

    opp.data[loader.DATA_CUSTOM_COMPONENTS] = {}

    opp.config.location_name = "test home"
    opp.config.config_dir = get_test_config_dir()
    opp.config.latitude = 32.87336
    opp.config.longitude = -117.22743
    opp.config.elevation = 0
    opp.config.time_zone = "US/Pacific"
    opp.config.units = METRIC_SYSTEM
    opp.config.media_dirs = {"local": get_test_config_dir("media")}
    opp.config.skip_pip = True

    opp.config_entries = config_entries.ConfigEntries(opp, {})
    opp.config_entries._entries = {}
    opp.config_entries._store._async_ensure_stop_listener = lambda: None

    # Load the registries
    if load_registries:
        await asyncio.gather(
            device_registry.async_load(opp),
            entity_registry.async_load(opp),
            area_registry.async_load(opp),
        )
        await opp.async_block_till_done()

    opp.state = ha.CoreState.running

    # Mock async_start
    orig_start = opp.async_start

    async def mock_async_start():
        """Start the mocking."""
        # We only mock time during tests and we want to track tasks
        with patch("openpeerpower.core._async_create_timer"), patch.object(
                opp, "async_stop_track_tasks"):
            await orig_start()

    opp.async_start = mock_async_start

    @ha.callback
    def clear_instance(event):
        """Clear global instance."""
        INSTANCES.remove(opp)

    opp.bus.async_listen_once(EVENT_OPENPEERPOWER_CLOSE, clear_instance)

    return opp
Ejemplo n.º 4
0
def manager(opp, store, provider):
    """Mock manager."""
    return auth.AuthManager(opp, store,
                            {(provider.type, provider.id): provider}, {})