Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add client atexit shutdown hook on process exit #126

Merged
merged 2 commits into from
Sep 10, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/axiom_py/client.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Client provides an easy-to use client library to connect to Axiom."""

import ndjson
import atexit
import gzip
import ujson
import os
Expand Down Expand Up @@ -128,6 +129,7 @@ class Client: # pylint: disable=R0903
datasets: DatasetsClient
users: UsersClient
annotations: AnnotationsClient
is_closed: bool # track if the client has been closed ( for tests )
bahlo marked this conversation as resolved.
Show resolved Hide resolved

def __init__(
self,
Expand Down Expand Up @@ -175,6 +177,14 @@ def __init__(
self.users = UsersClient(self.session)
self.annotations = AnnotationsClient(self.session, self.logger)

# wrap shutdown hook in a lambda passing in self as a ref
atexit.register(lambda: self.shutdown_hook())
self.is_closed = False

def shutdown_hook(self):
self.session.close()
self.is_closed = True

def ingest(
self,
dataset: str,
Expand Down
13 changes: 13 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
"""This module contains the tests for the axiom client."""

import sys
import os
import unittest
from unittest.mock import patch
import gzip
import ujson
import rfc3339
Expand Down Expand Up @@ -224,6 +226,17 @@ def test_step005_complex_query(self):
agg = res.buckets.totals[0].aggregations[0]
self.assertEqual("event_count", agg.op)

@patch("sys.exit")
def test_client_shutdown_atexit(self, mock_exit):
"""Test client shutdown atexit"""
# Use the mock to test the firing mechanism
self.assertEqual(self.client.is_closed, False)
sys.exit()
mock_exit.assert_called_once()
# Use the hook implementation to assert the client is closed closed
self.client.shutdown_hook()
self.assertEqual(self.client.is_closed, True)

@classmethod
def tearDownClass(cls):
"""A teardown that checks if the dataset still exists and deletes it,
Expand Down