code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def test_empty_result_from_get_bbox_dict(self):
"""Test handling of empty results from get_bbox_dict_yolox_table."""
# Mock get_bbox_dict_yolox_table to return empty dict
self.mock_get_bbox_dict.return_value = {}
# Save original transform_normalized_coordinates_to_original method
... | Test handling of empty results from get_bbox_dict_yolox_table. | test_empty_result_from_get_bbox_dict | python | NVIDIA/nv-ingest | api/api_tests/primitives/nim/model_interface/test_yolox_interface_table_structure.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/nim/model_interface/test_yolox_interface_table_structure.py | Apache-2.0 |
def test_single_detection(self):
"""Test with a single detection that passes thresholds."""
# Create a prediction with one detection
# Format: [batch, detections, values]
# Values: [x, y, width, height, objectness, class1_conf, class2_conf]
prediction = np.zeros((1, 1, 7))
... | Test with a single detection that passes thresholds. | test_single_detection | python | NVIDIA/nv-ingest | api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | Apache-2.0 |
def test_multiple_detections(self):
"""Test with multiple detections that pass thresholds."""
# Create a prediction with multiple detections
prediction = np.zeros((1, 3, 7))
prediction[0, 0, :] = [0.3, 0.3, 0.2, 0.2, 0.9, 0.8, 0.2] # Detection 1
prediction[0, 1, :] = [0.6, 0.6, ... | Test with multiple detections that pass thresholds. | test_multiple_detections | python | NVIDIA/nv-ingest | api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | Apache-2.0 |
def test_multiple_images(self):
"""Test with multiple images in the batch."""
# Create predictions for multiple images
prediction = np.zeros((2, 2, 7))
# Image 1, two detections
prediction[0, 0, :] = [0.3, 0.3, 0.2, 0.2, 0.9, 0.8, 0.2]
prediction[0, 1, :] = [0.6, 0.6, 0.2... | Test with multiple images in the batch. | test_multiple_images | python | NVIDIA/nv-ingest | api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | Apache-2.0 |
def test_confidence_threshold(self):
"""Test with detections above and below confidence threshold."""
# Create a prediction with detections of varying confidence
prediction = np.zeros((1, 3, 7))
prediction[0, 0, :] = [0.3, 0.3, 0.2, 0.2, 0.9, 0.8, 0.2] # High confidence
predicti... | Test with detections above and below confidence threshold. | test_confidence_threshold | python | NVIDIA/nv-ingest | api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | Apache-2.0 |
def test_no_detections_after_confidence_filter(self):
"""Test with detections that all fail the confidence threshold."""
# Create a prediction with low confidence detections
prediction = np.zeros((1, 2, 7))
prediction[0, 0, :] = [0.3, 0.3, 0.2, 0.2, 0.4, 0.3, 0.2] # Low confidence
... | Test with detections that all fail the confidence threshold. | test_no_detections_after_confidence_filter | python | NVIDIA/nv-ingest | api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | Apache-2.0 |
def test_corner_conversion(self):
"""Test that box coordinates are properly converted from center format to corner format."""
# Create a prediction with one detection
# Format: [x_center, y_center, width, height, objectness, class1_conf, class2_conf]
prediction = np.zeros((1, 1, 7))
... | Test that box coordinates are properly converted from center format to corner format. | test_corner_conversion | python | NVIDIA/nv-ingest | api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | Apache-2.0 |
def test_handle_1d_image_pred(self):
"""Test handling of 1D image predictions (edge case)."""
# This is a rare edge case where an image might have a single detection that gets reduced to 1D
# Create a prediction array that could lead to a 1D tensor
prediction = np.zeros((1, 1, 7))
... | Test handling of 1D image predictions (edge case). | test_handle_1d_image_pred | python | NVIDIA/nv-ingest | api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | Apache-2.0 |
def test_postprocess_results_rounding(self):
"""Test that postprocess_results rounds coordinates to 4 decimal places."""
# Create a result with coordinates that will produce many decimal places when normalized
result = torch.tensor(
[
[123, 456, 789, 987, 0.9, 0.8, 0]... | Test that postprocess_results rounds coordinates to 4 decimal places. | test_postprocess_results_rounding | python | NVIDIA/nv-ingest | api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | Apache-2.0 |
def test_resize_image_without_target_size(self):
"""Test resize_image without a target size (should return original image)."""
with patch(f"{MODULE_UNDER_TEST}.np.pad") as mock_pad:
result = resize_image(self.sample_image, None)
# Check that cv2.resize was not called
... | Test resize_image without a target size (should return original image). | test_resize_image_without_target_size | python | NVIDIA/nv-ingest | api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | Apache-2.0 |
def test_resize_image_padding(self):
"""Test that resize_image correctly pads the image to target size."""
# For this test, we need to bypass the mock of cv2.resize to check padding
self.cv2_resize_patcher.stop()
# Create a small image
small_image = np.ones((50, 100, 3), dtype=n... | Test that resize_image correctly pads the image to target size. | test_resize_image_padding | python | NVIDIA/nv-ingest | api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | Apache-2.0 |
def test_expand_table_bboxes_clipping(self):
"""Test that expanded table boundaries are clipped to [0, 1]."""
# Create a table near the top of the image so expansion would go beyond 0
annotations = {"table": [[0.1, 0.05, 0.3, 0.15, 0.9]], "figure": []} # y1 is very small
result = expan... | Test that expanded table boundaries are clipped to [0, 1]. | test_expand_table_bboxes_clipping | python | NVIDIA/nv-ingest | api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | Apache-2.0 |
def test_expand_table_bboxes_rounding(self):
"""Test that expanded table coordinates are rounded to 4 decimal places."""
annotations = {"table": [[0.1, 0.2, 0.3, 0.4, 0.9]], "figure": []}
result = expand_table_bboxes(annotations)
# Check that all values are rounded to 4 decimal places
... | Test that expanded table coordinates are rounded to 4 decimal places. | test_expand_table_bboxes_rounding | python | NVIDIA/nv-ingest | api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | Apache-2.0 |
def test_weighted_boxes_fusion_empty_result(self):
"""Test weighted_boxes_fusion when prefilter returns empty result."""
# Setup prefilter to return empty dict
self.mock_prefilter.return_value = {}
boxes, scores, labels = weighted_boxes_fusion(self.boxes, self.scores, self.labels)
... | Test weighted_boxes_fusion when prefilter returns empty result. | test_weighted_boxes_fusion_empty_result | python | NVIDIA/nv-ingest | api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | Apache-2.0 |
def test_weighted_boxes_fusion_with_matching_boxes(self):
"""Test weighted_boxes_fusion when boxes match (should form clusters)."""
# This test is problematic because we're mocking an internal function
# that is expected to return a specific index, but we don't control
# how many boxes a... | Test weighted_boxes_fusion when boxes match (should form clusters). | test_weighted_boxes_fusion_with_matching_boxes | python | NVIDIA/nv-ingest | api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | Apache-2.0 |
def test_prefilter_boxes_warnings(self):
"""Test that prefilter_boxes issues warnings for invalid boxes."""
_ = prefilter_boxes(self.boxes, self.scores, self.labels, self.weights, thr=0.0)
# Check that warnings were issued for the invalid boxes
self.assertTrue(self.mock_warnings.warn.ca... | Test that prefilter_boxes issues warnings for invalid boxes. | test_prefilter_boxes_warnings | python | NVIDIA/nv-ingest | api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | Apache-2.0 |
def find_matching_box_fast(boxes_list, new_box, match_iou):
"""
Reimplementation of find_matching_box with numpy instead of loops. Gives significant speed up for larger arrays
(~100x). This was previously the bottleneck since the function is called for every entry in the array.
"""
... |
Reimplementation of find_matching_box with numpy instead of loops. Gives significant speed up for larger arrays
(~100x). This was previously the bottleneck since the function is called for every entry in the array.
| find_matching_box_fast | python | NVIDIA/nv-ingest | api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | Apache-2.0 |
def test_find_matching_box_fast_no_match(self):
"""Test finding a matching box with no good match."""
# Use a high IOU threshold that won't be met
index, iou = find_matching_box_fast(self.boxes, self.new_box, match_iou=0.9)
# No box should match
self.assertEqual(index, -1)
... | Test finding a matching box with no good match. | test_find_matching_box_fast_no_match | python | NVIDIA/nv-ingest | api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | Apache-2.0 |
def test_find_matching_box_fast_empty_boxes(self):
"""Test finding a matching box with empty boxes."""
empty_boxes = np.zeros((0, 8))
index, iou = find_matching_box_fast(empty_boxes, self.new_box, match_iou=0.5)
# No box should match
self.assertEqual(index, -1)
# The r... | Test finding a matching box with empty boxes. | test_find_matching_box_fast_empty_boxes | python | NVIDIA/nv-ingest | api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | Apache-2.0 |
def test_find_matching_box_fast_multiple_candidates(self):
"""Test finding a matching box with multiple candidates."""
# Create boxes with multiple overlapping candidates
boxes = np.array(
[
[0, 0.9, 1.0, 0, 0.1, 0.2, 0.3, 0.4], # Box 1 (moderate overlap)
... | Test finding a matching box with multiple candidates. | test_find_matching_box_fast_multiple_candidates | python | NVIDIA/nv-ingest | api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | Apache-2.0 |
def test_find_matching_box_fast_identical_box(self):
"""Test finding a matching box that is identical."""
# Create a box identical to the new box
identical_box = self.new_box.copy()
boxes = np.array([identical_box])
index, iou = find_matching_box_fast(boxes, self.new_box, match_... | Test finding a matching box that is identical. | test_find_matching_box_fast_identical_box | python | NVIDIA/nv-ingest | api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | Apache-2.0 |
def test_find_matching_box_fast_no_overlap(self):
"""Test finding a matching box with no overlap."""
# Create boxes with no overlap
boxes = np.array(
[
[0, 0.9, 1.0, 0, 0.6, 0.7, 0.8, 0.9], # No overlap with new_box
[1, 0.8, 1.0, 0, 0.7, 0.8, 0.9, 1.0... | Test finding a matching box with no overlap. | test_find_matching_box_fast_no_overlap | python | NVIDIA/nv-ingest | api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/nim/model_interface/test_yolox_utilities.py | Apache-2.0 |
def test_traceable_func_without_trace_name():
"""
Test that the traceable_func logs entry and exit times using the function name when no trace_name is provided.
"""
trace_info = {}
result = simple_func("sample_value", trace_info=trace_info)
assert result == "Processed sample_value"
assert "... |
Test that the traceable_func logs entry and exit times using the function name when no trace_name is provided.
| test_traceable_func_without_trace_name | python | NVIDIA/nv-ingest | api/api_tests/primitives/tracing/test_tagging.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/tracing/test_tagging.py | Apache-2.0 |
def test_traceable_func_with_trace_name_formatting():
"""
Test that the traceable_func logs entry and exit times using the formatted trace_name with argument values.
"""
trace_info = {}
result = simple_func("formatted_value", trace_info=trace_info)
assert result == "Processed formatted_value"
... |
Test that the traceable_func logs entry and exit times using the formatted trace_name with argument values.
| test_traceable_func_with_trace_name_formatting | python | NVIDIA/nv-ingest | api/api_tests/primitives/tracing/test_tagging.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/tracing/test_tagging.py | Apache-2.0 |
def test_traceable_func_dedupe():
"""
Test that the traceable_func deduplicates trace keys by appending an index when dedupe=True.
"""
trace_info = {}
result1 = simple_func("dedupe_test", trace_info=trace_info)
result2 = simple_func("dedupe_test", trace_info=trace_info)
assert result1 == "P... |
Test that the traceable_func deduplicates trace keys by appending an index when dedupe=True.
| test_traceable_func_dedupe | python | NVIDIA/nv-ingest | api/api_tests/primitives/tracing/test_tagging.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/tracing/test_tagging.py | Apache-2.0 |
def test_traceable_func_without_trace_info():
"""
Test that traceable_func creates a new trace_info dictionary if one is not passed.
"""
result = simple_func("no_trace_info")
assert result == "Processed no_trace_info" |
Test that traceable_func creates a new trace_info dictionary if one is not passed.
| test_traceable_func_without_trace_info | python | NVIDIA/nv-ingest | api/api_tests/primitives/tracing/test_tagging.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/tracing/test_tagging.py | Apache-2.0 |
def test_traceable_func_with_multiple_args():
"""
Test that traceable_func handles functions with multiple arguments and formats trace_name accordingly.
"""
@traceable_func(trace_name="multi_args_func::{arg1}::{arg2}")
def multi_args_func(arg1, arg2, **kwargs):
return f"Processed {arg1} and... |
Test that traceable_func handles functions with multiple arguments and formats trace_name accordingly.
| test_traceable_func_with_multiple_args | python | NVIDIA/nv-ingest | api/api_tests/primitives/tracing/test_tagging.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/tracing/test_tagging.py | Apache-2.0 |
def test_traceable_func_dedupe_disabled():
"""
Test that the traceable_func does not deduplicate trace keys when dedupe=False.
"""
@traceable_func(trace_name="no_dedupe_test", dedupe=False)
def no_dedupe_test(param, **kwargs):
return f"Processed {param}"
trace_info = {}
result1 = n... |
Test that the traceable_func does not deduplicate trace keys when dedupe=False.
| test_traceable_func_dedupe_disabled | python | NVIDIA/nv-ingest | api/api_tests/primitives/tracing/test_tagging.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/primitives/tracing/test_tagging.py | Apache-2.0 |
def test_doc_type_to_content_type_valid(doc_type, expected_content_type):
"""
Test doc_type_to_content_type function with valid document types.
"""
assert (
doc_type_to_content_type(doc_type) == expected_content_type
), f"doc_type {doc_type} should map to content type {expected_content_type}... |
Test doc_type_to_content_type function with valid document types.
| test_doc_type_to_content_type_valid | python | NVIDIA/nv-ingest | api/api_tests/util/converters/test_type_mappings.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/converters/test_type_mappings.py | Apache-2.0 |
def test_doc_type_to_content_type_invalid():
"""
Test doc_type_to_content_type function with an invalid document type.
"""
invalid_doc_type = "invalid_doc_type" # Assume this is not a valid DocumentTypeEnum value
with pytest.raises(KeyError):
doc_type_to_content_type(invalid_doc_type) |
Test doc_type_to_content_type function with an invalid document type.
| test_doc_type_to_content_type_invalid | python | NVIDIA/nv-ingest | api/api_tests/util/converters/test_type_mappings.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/converters/test_type_mappings.py | Apache-2.0 |
def test_detect_language_unknown_language():
"""
Test detect_language function with text in an unknown language or not covered by LanguageEnum.
"""
unknown_text = "1234" # Assuming Japanese is not in LanguageEnum
assert detect_language(unknown_text) == LanguageEnum.UNKNOWN |
Test detect_language function with text in an unknown language or not covered by LanguageEnum.
| test_detect_language_unknown_language | python | NVIDIA/nv-ingest | api/api_tests/util/detectors/test_language.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/detectors/test_language.py | Apache-2.0 |
def test_datetools_exception_handler_with_exception():
"""
Test the decorator with a function that raises an exception,
checking that the returned date is within a few minutes of the current time.
"""
start_time = remove_tz(datetime.now(timezone.utc))
result = test_func_raises_exception()
... |
Test the decorator with a function that raises an exception,
checking that the returned date is within a few minutes of the current time.
| test_datetools_exception_handler_with_exception | python | NVIDIA/nv-ingest | api/api_tests/util/exception_handlers/test_converters.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/exception_handlers/test_converters.py | Apache-2.0 |
def test_datetools_exception_handler_without_exception():
"""
Test the decorator with a function that does not raise an exception.
"""
result = test_func_success()
assert result == "Success", "Decorator should not interfere with the function's normal execution" |
Test the decorator with a function that does not raise an exception.
| test_datetools_exception_handler_without_exception | python | NVIDIA/nv-ingest | api/api_tests/util/exception_handlers/test_converters.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/exception_handlers/test_converters.py | Apache-2.0 |
def test_langdetect_exception_handler_success():
"""
Test that the decorator correctly passes through the return value of the function when no exception is raised.
"""
result = decorated_sample_func("Test text")
assert result == "detected_language", "The function should return the detected language.... |
Test that the decorator correctly passes through the return value of the function when no exception is raised.
| test_langdetect_exception_handler_success | python | NVIDIA/nv-ingest | api/api_tests/util/exception_handlers/test_detectors.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/exception_handlers/test_detectors.py | Apache-2.0 |
def test_schema_exception_handler_success():
"""
Test that the decorator does not interfere with the normal execution of a function.
"""
result = function_success()
assert result == "Success", "The function should successfully return 'Success'." |
Test that the decorator does not interfere with the normal execution of a function.
| test_schema_exception_handler_success | python | NVIDIA/nv-ingest | api/api_tests/util/exception_handlers/test_schemas.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/exception_handlers/test_schemas.py | Apache-2.0 |
def test_schema_exception_handler_with_validation_error(mock_logger):
"""
Test that the decorator correctly handles a ValidationError and logs the expected message.
"""
with pytest.raises(ValueError) as exc_info:
function_fail()
# Verify the correct error message was logged
expected_err... |
Test that the decorator correctly handles a ValidationError and logs the expected message.
| test_schema_exception_handler_with_validation_error | python | NVIDIA/nv-ingest | api/api_tests/util/exception_handlers/test_schemas.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/exception_handlers/test_schemas.py | Apache-2.0 |
def generate_base64_image(size: Tuple[int, int]) -> str:
"""Helper function to generate a base64-encoded PNG image of a specific size."""
img = Image.new("RGB", size, color="blue") # Create a simple blue image
buffered = io.BytesIO()
img.save(buffered, format="PNG")
return base64.b64encode(buffered... | Helper function to generate a base64-encoded PNG image of a specific size. | generate_base64_image | python | NVIDIA/nv-ingest | api/api_tests/util/image_processing/test_transforms.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/image_processing/test_transforms.py | Apache-2.0 |
def generate_base64_image_with_format(format: str = "PNG", size: Tuple[int, int] = (100, 100)) -> str:
"""Helper function to generate a base64-encoded image of a specified format and size."""
img = Image.new("RGB", size, color="blue") # Simple blue image
buffered = io.BytesIO()
img.save(buffered, forma... | Helper function to generate a base64-encoded image of a specified format and size. | generate_base64_image_with_format | python | NVIDIA/nv-ingest | api/api_tests/util/image_processing/test_transforms.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/image_processing/test_transforms.py | Apache-2.0 |
def test_valid_log_levels(caplog):
"""
Test that the logger is correctly configured for each valid log level.
"""
for level in LogLevel:
logger = logging.getLogger("test")
configure_logging(logger, level.value)
logger.log(getattr(logging, level.value), f"Test message for {level.v... |
Test that the logger is correctly configured for each valid log level.
| test_valid_log_levels | python | NVIDIA/nv-ingest | api/api_tests/util/logging/test_configuration.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/logging/test_configuration.py | Apache-2.0 |
def test_invalid_log_level():
"""
Test that configuring the logger with an invalid log level raises ValueError.
"""
logger = logging.getLogger("test_invalid")
with pytest.raises(ValueError):
configure_logging(logger, "INVALID_LEVEL") |
Test that configuring the logger with an invalid log level raises ValueError.
| test_invalid_log_level | python | NVIDIA/nv-ingest | api/api_tests/util/logging/test_configuration.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/logging/test_configuration.py | Apache-2.0 |
def test_logger_level_set_correctly(logger):
"""
Test that the logger level is set correctly when a valid level is provided.
"""
for level in LogLevel:
configure_logging(logger, level.value)
assert logger.level == getattr(logging, level.value), "Logger level did not match expected level" |
Test that the logger level is set correctly when a valid level is provided.
| test_logger_level_set_correctly | python | NVIDIA/nv-ingest | api/api_tests/util/logging/test_configuration.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/logging/test_configuration.py | Apache-2.0 |
def test_logger_raises_for_invalid_level(logger):
"""
Test that the logger raises a ValueError for invalid log levels.
"""
with pytest.raises(ValueError) as exc_info:
configure_logging(logger, "NO_LEVEL")
assert "Invalid log level: NO_LEVEL" in str(exc_info.value), "Expected specific error m... |
Test that the logger raises a ValueError for invalid log levels.
| test_logger_raises_for_invalid_level | python | NVIDIA/nv-ingest | api/api_tests/util/logging/test_configuration.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/logging/test_configuration.py | Apache-2.0 |
def test_get_client_with_successful_ping(mock_redis_client, mock_redis):
"""
Test get_client method when the ping is successful.
Expect that ping() is called exactly once.
"""
client = mock_redis_client.get_client()
assert client == mock_redis
client.ping()
mock_redis.ping.assert_called_... |
Test get_client method when the ping is successful.
Expect that ping() is called exactly once.
| test_get_client_with_successful_ping | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/redis/test_redis_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/redis/test_redis_client.py | Apache-2.0 |
def test_fetch_message_successful(mock_redis_client, mock_redis):
"""
Test fetch_message method successfully returns a complete (non-fragmented) message.
"""
job_payload = mock_redis_client.fetch_message("queue")
expected = json.loads(TEST_PAYLOAD)
assert job_payload == expected |
Test fetch_message method successfully returns a complete (non-fragmented) message.
| test_fetch_message_successful | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/redis/test_redis_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/redis/test_redis_client.py | Apache-2.0 |
def test_fetch_message_with_retries(mock_time, mock_redis_client, mock_redis):
"""
Test that fetch_message retries when a temporary error (RedisError) occurs and then succeeds.
"""
# Set BLPOP to raise a RedisError on the first call and then succeed.
mock_redis.blpop.side_effect = [RedisError("Tempo... |
Test that fetch_message retries when a temporary error (RedisError) occurs and then succeeds.
| test_fetch_message_with_retries | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/redis/test_redis_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/redis/test_redis_client.py | Apache-2.0 |
def test_can_push_full_queue(queue):
"""Test can_push when the queue is full."""
queue.push("Message 1")
queue.push("Message 2")
queue.push("Message 3")
assert queue.can_push() is False | Test can_push when the queue is full. | test_can_push_full_queue | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | Apache-2.0 |
def test_can_push_in_flight_not_counted(queue):
"""Test can_push when in-flight messages don't count towards maxsize."""
queue.push("Message 1")
transaction_id = str(uuid4())
queue.pop(transaction_id)
assert queue.can_push() is True | Test can_push when in-flight messages don't count towards maxsize. | test_can_push_in_flight_not_counted | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | Apache-2.0 |
def test_push(queue):
"""Test push adds messages and maintains order."""
queue.push("Message 1")
queue.push("Message 2")
assert queue.qsize() == 2 | Test push adds messages and maintains order. | test_push | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | Apache-2.0 |
def test_push_order(queue):
"""Test that pushed messages maintain insertion order."""
index1 = queue.push("Message 1")
index2 = queue.push("Message 2")
assert index1 < index2 | Test that pushed messages maintain insertion order. | test_push_order | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | Apache-2.0 |
def test_pop(queue):
"""Test pop retrieves messages in order."""
queue.push("Message 1")
queue.push("Message 2")
transaction_id = str(uuid4())
message = queue.pop(transaction_id)
assert message == "Message 1"
assert queue.qsize() == 1 | Test pop retrieves messages in order. | test_pop | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | Apache-2.0 |
def test_pop_blocks_until_message_available():
"""Test pop blocks until a message is available."""
queue = OrderedMessageQueue()
transaction_id = str(uuid4())
def delayed_push():
threading.Event().wait(1) # Wait 1 second before pushing
queue.push("Delayed Message")
threading.Threa... | Test pop blocks until a message is available. | test_pop_blocks_until_message_available | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | Apache-2.0 |
def test_acknowledge_removes_in_flight(queue):
"""Test acknowledge removes in-flight message."""
queue.push("Message 1")
transaction_id = str(uuid4())
queue.pop(transaction_id)
assert transaction_id in queue.in_flight
queue.acknowledge(transaction_id)
assert transaction_id not in queue.in_fl... | Test acknowledge removes in-flight message. | test_acknowledge_removes_in_flight | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | Apache-2.0 |
def test_qsize(queue):
"""Test qsize returns the correct number of messages in the queue."""
queue.push("Message 1")
queue.push("Message 2")
assert queue.qsize() == 2 | Test qsize returns the correct number of messages in the queue. | test_qsize | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | Apache-2.0 |
def test_empty(queue):
"""Test empty returns True for an empty queue."""
assert queue.empty() is True
queue.push("Message 1")
assert queue.empty() is False | Test empty returns True for an empty queue. | test_empty | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | Apache-2.0 |
def test_full(queue):
"""Test full returns True when the queue is full."""
queue.push("Message 1")
queue.push("Message 2")
queue.push("Message 3")
assert queue.full() is True | Test full returns True when the queue is full. | test_full | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | Apache-2.0 |
def test_full_with_in_flight(queue):
"""Test full considers both queued and in-flight messages."""
queue.push("Message 1")
transaction_id = str(uuid4())
queue.pop(transaction_id)
queue.push("Message 2")
queue.push("Message 3")
queue.push("Message 4")
assert queue.full() is True | Test full considers both queued and in-flight messages. | test_full_with_in_flight | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | Apache-2.0 |
def test_return_message_order(queue):
"""Test that return_message retains original message order."""
queue.push("Message 1")
queue.push("Message 2")
transaction_id = str(uuid4())
queue.pop(transaction_id)
queue.push("Message 3")
queue.return_message(transaction_id)
assert queue.pop(str(... | Test that return_message retains original message order. | test_return_message_order | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_ordered_message_queue.py | Apache-2.0 |
def broker_server():
"""Fixture to start and stop the SimpleMessageBroker server."""
server = SimpleMessageBroker(HOST, PORT, MAX_QUEUE_SIZE)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True # Allows program to exit even if thread is running
server_thread.st... | Fixture to start and stop the SimpleMessageBroker server. | broker_server | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_client.py | Apache-2.0 |
def test_message_ordering():
"""Test that messages are popped in the same order they were pushed (FIFO)."""
client = SimpleClient(HOST, PORT)
queue_name = f"test_queue_{uuid4()}"
messages = [f"Message {i}" for i in range(5)]
# Push messages in order
for msg in messages:
response = clien... | Test that messages are popped in the same order they were pushed (FIFO). | test_message_ordering | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_client.py | Apache-2.0 |
def test_push_to_full_queue():
"""Test pushing messages to a full queue."""
client = SimpleClient(HOST, PORT)
queue_name = f"test_queue_{uuid4()}"
messages = [f"Message {i}" for i in range(MAX_QUEUE_SIZE)]
# Push messages until the queue is full
for msg in messages:
response = client.su... | Test pushing messages to a full queue. | test_push_to_full_queue | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_client.py | Apache-2.0 |
def test_invalid_inputs():
"""Test that the client handles invalid inputs properly."""
client = SimpleClient(HOST, PORT)
# Test with empty queue name
response = client.submit_message("", "Test Message")
assert response.response_code == 1
assert response.response_reason == "Invalid queue name."
... | Test that the client handles invalid inputs properly. | test_invalid_inputs | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_client.py | Apache-2.0 |
def test_server_unavailable():
"""Test client's behavior when the server is unavailable."""
client = SimpleClient(HOST, 9991)
queue_name = f"test_queue_{uuid4()}"
# Do not start the broker_server fixture to simulate server unavailability
response = client.submit_message(queue_name, "Test Message",... | Test client's behavior when the server is unavailable. | test_server_unavailable | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_client.py | Apache-2.0 |
def test_client_retry_logic():
"""Test that the client retries the specified number of times on connection failure."""
invalid_port = 9998 # Assume this port is closed
client = SimpleClient(HOST, invalid_port, max_retries=2)
queue_name = f"test_queue_{uuid4()}"
start_time = time.time()
respons... | Test that the client retries the specified number of times on connection failure. | test_client_retry_logic | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_client.py | Apache-2.0 |
def test_operation_timeout():
"""Test client's behavior when an operation times out."""
client = SimpleClient(HOST, PORT, connection_timeout=0.001) # Set a very short timeout
queue_name = f"test_queue_{uuid4()}"
response = client.submit_message(queue_name, "Test Message", timeout=(1, None))
assert... | Test client's behavior when an operation times out. | test_operation_timeout | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_client.py | Apache-2.0 |
def test_pop_empty_queue(client):
"""Test popping from an empty queue."""
queue_name = f"test_queue_{uuid4()}"
response = client.fetch_message(queue_name, timeout=(1, None))
assert response.response_code == 1
assert response.response_reason == POP_TIMEOUT_MSG | Test popping from an empty queue. | test_pop_empty_queue | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_client.py | Apache-2.0 |
def test_multiple_clients(client):
"""Test multiple clients interacting with the server."""
queue_name = f"test_queue_{uuid4()}"
messages = [f"Message {i}" for i in range(5)]
clients = [SimpleClient(HOST, PORT) for _ in range(5)]
# Each client pushes a message
for i, c in enumerate(clients):
... | Test multiple clients interacting with the server. | test_multiple_clients | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_client.py | Apache-2.0 |
def test_concurrent_push_pop(client):
"""Test concurrent PUSH and POP operations."""
queue_name = f"test_queue_{uuid4()}"
messages = [f"Message {i}" for i in range(10)]
results = []
lock = threading.Lock()
def push(msg):
response = client.submit_message(queue_name, msg)
with loc... | Test concurrent PUSH and POP operations. | test_concurrent_push_pop | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_client.py | Apache-2.0 |
def send_request(request_data):
"""Helper method to send a request to the server and receive a response."""
sock = socket.create_connection((HOST, PORT))
try:
# Send request
request_json = json.dumps(request_data).encode("utf-8")
sock.sendall(len(request_json).to_bytes(8, "big") + re... | Helper method to send a request to the server and receive a response. | send_request | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | Apache-2.0 |
def recv_exact(sock, num_bytes):
"""Helper method to receive an exact number of bytes."""
data = bytearray()
while len(data) < num_bytes:
packet = sock.recv(num_bytes - len(data))
if not packet:
return None
data.extend(packet)
return bytes(data) | Helper method to receive an exact number of bytes. | recv_exact | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | Apache-2.0 |
def send_ack(sock, transaction_id, ack=True):
"""Helper method to send an ACK to the server."""
ack_data = json.dumps({"transaction_id": transaction_id, "ack": ack}).encode("utf-8")
sock.sendall(len(ack_data).to_bytes(8, "big") + ack_data) | Helper method to send an ACK to the server. | send_ack | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | Apache-2.0 |
def _push_message(queue_name, message):
"""Helper method to push a message into the queue without testing ACK behavior."""
request_data = {"command": "PUSH", "queue_name": queue_name, "message": message, "timeout": 5}
sock, response = send_request(request_data)
transaction_id = response["transaction_id"... | Helper method to push a message into the queue without testing ACK behavior. | _push_message | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | Apache-2.0 |
def test_push_without_ack():
"""Test PUSH operation without acknowledgment (should not store the message)."""
queue_name = f"test_queue_{uuid4()}"
message = "Test Message"
# Send PUSH request
request_data = {
"command": "PUSH",
"queue_name": queue_name,
"message": message,
... | Test PUSH operation without acknowledgment (should not store the message). | test_push_without_ack | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | Apache-2.0 |
def test_pop_without_ack():
"""Test POP operation without acknowledgment (should return data to queue)."""
queue_name = f"test_queue_{uuid4()}"
message = "Test Message"
# Pre-populate the queue
_push_message(queue_name, message)
# Send POP request
request_data = {"command": "POP", "queue_n... | Test POP operation without acknowledgment (should return data to queue). | test_pop_without_ack | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | Apache-2.0 |
def test_size_command():
"""Test SIZE command to get the number of items in a queue."""
queue_name = f"test_queue_{uuid4()}"
messages = ["Message 1", "Message 2", "Message 3"]
# Push messages into the queue
for msg in messages:
_push_message(queue_name, msg)
# Send SIZE request
req... | Test SIZE command to get the number of items in a queue. | test_size_command | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | Apache-2.0 |
def test_invalid_command():
"""Test handling of an invalid command."""
request_data = {"command": "INVALID", "queue_name": "test_queue"}
sock, response = send_request(request_data)
assert response["response_code"] == 1
assert response["response_reason"] == "Unknown command"
sock.close() | Test handling of an invalid command. | test_invalid_command | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | Apache-2.0 |
def test_queue_not_exist():
"""Test POP from a non-existent queue."""
queue_name = f"non_existent_queue_{uuid4()}"
# Send POP request
request_data = {"command": "POP", "queue_name": queue_name, "timeout": 1}
sock, response = send_request(request_data)
assert response["response_code"] == 1
... | Test POP from a non-existent queue. | test_queue_not_exist | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | Apache-2.0 |
def test_queue_full():
"""Test PUSH operation when the queue is full."""
queue_name = f"test_queue_{uuid4()}"
message = "Test Message"
# Fill the queue to its maximum size
for _ in range(MAX_QUEUE_SIZE):
request_data = {"command": "PUSH", "queue_name": queue_name, "message": message, "timeo... | Test PUSH operation when the queue is full. | test_queue_full | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | Apache-2.0 |
def test_ack_with_wrong_transaction_id():
"""Test sending ACK with incorrect transaction ID."""
queue_name = f"test_queue_{uuid4()}"
message = "Test Message"
# Send PUSH request
request_data = {"command": "PUSH", "queue_name": queue_name, "message": message, "timeout": 5}
sock, response = send_... | Test sending ACK with incorrect transaction ID. | test_ack_with_wrong_transaction_id | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | Apache-2.0 |
def test_push_with_large_message():
"""Test pushing a large message to the queue."""
queue_name = f"test_queue_{uuid4()}"
message = "A" * (1024 * 1024 * 5) # 5MB message
# Send PUSH request
request_data = {"command": "PUSH", "queue_name": queue_name, "message": message, "timeout": 5}
sock, res... | Test pushing a large message to the queue. | test_push_with_large_message | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | Apache-2.0 |
def test_pop_from_empty_queue():
"""Test POP operation from an empty queue."""
queue_name = f"test_queue_{uuid4()}"
# Send POP request
request_data = {"command": "POP", "queue_name": queue_name, "timeout": 5}
sock, response = send_request(request_data)
assert response["response_code"] == 1
... | Test POP operation from an empty queue. | test_pop_from_empty_queue | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | Apache-2.0 |
def test_ack_timeout():
"""Test that the server times out waiting for ACK."""
queue_name = f"test_queue_{uuid4()}"
message = "Test Message"
# Send PUSH request with a short timeout
request_data = {"command": "PUSH", "queue_name": queue_name, "message": message, "timeout": 1} # 1-second timeout
... | Test that the server times out waiting for ACK. | test_ack_timeout | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | Apache-2.0 |
def test_multiple_clients():
"""Test multiple clients interacting with the server simultaneously."""
queue_name = f"test_queue_{uuid4()}"
messages = [f"Client {i} Message" for i in range(5)]
lock = threading.Lock()
results = []
def client_thread(message):
# Push message
_push_me... | Test multiple clients interacting with the server simultaneously. | test_multiple_clients | python | NVIDIA/nv-ingest | api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/message_brokers/simple_message_broker/test_simple_message_broker.py | Apache-2.0 |
def test_validate_schema_success():
"""Test validating metadata with a correct structure."""
user_metadata = {"name": "John Doe", "age": 30}
validated_user = validate_schema(user_metadata, UserSchema)
assert validated_user.name == "John Doe"
assert validated_user.age == 30 | Test validating metadata with a correct structure. | test_validate_schema_success | python | NVIDIA/nv-ingest | api/api_tests/util/schema/test_schema_validator.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/schema/test_schema_validator.py | Apache-2.0 |
def test_validate_schema_failure():
"""Test validating metadata that does not conform to the schema."""
incorrect_metadata = {"name": "John Doe", "age": -5} # Invalid age
with pytest.raises(ValueError):
validate_schema(incorrect_metadata, UserSchema) | Test validating metadata that does not conform to the schema. | test_validate_schema_failure | python | NVIDIA/nv-ingest | api/api_tests/util/schema/test_schema_validator.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/schema/test_schema_validator.py | Apache-2.0 |
def test_validate_schema_optional_and_default():
"""Test schema validation with optional fields and fields with default values."""
# Assuming the UserSchema has optional fields or fields with default values
partial_metadata = {"name": "Jane Doe"} # 'age' is intentionally omitted
with pytest.raises(Valu... | Test schema validation with optional fields and fields with default values. | test_validate_schema_optional_and_default | python | NVIDIA/nv-ingest | api/api_tests/util/schema/test_schema_validator.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/schema/test_schema_validator.py | Apache-2.0 |
def test_validate_schema_with_extra_fields():
"""Test schema validation with extra fields not defined in the schema."""
extra_metadata = {"name": "John Doe", "age": 30, "title": "sir"}
# Depending on schema configuration, this might either pass or fail
# Assuming extra fields are ignored
validated_u... | Test schema validation with extra fields not defined in the schema. | test_validate_schema_with_extra_fields | python | NVIDIA/nv-ingest | api/api_tests/util/schema/test_schema_validator.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/util/schema/test_schema_validator.py | Apache-2.0 |
def extract_chart_data_from_image(
*,
df_ledger: pd.DataFrame,
yolox_endpoints: Tuple[str, str],
paddle_endpoints: Tuple[str, str],
yolox_protocol: str = "grpc",
paddle_protocol: str = "grpc",
auth_token: str = "",
) -> DataFrame:
"""
Public interface to extract chart data from ledge... |
Public interface to extract chart data from ledger DataFrame.
Parameters
----------
df_ledger : pd.DataFrame
DataFrame containing metadata required for chart extraction.
yolox_endpoints : Tuple[str, str]
YOLOX inference server endpoints.
paddle_endpoints : Tuple[str, str]
... | extract_chart_data_from_image | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/interface/extract.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/interface/extract.py | Apache-2.0 |
def extract_table_data_from_image(
*,
df_ledger: pd.DataFrame,
yolox_endpoints: Optional[Tuple[str, str]] = None,
paddle_endpoints: Optional[Tuple[str, str]] = None,
yolox_protocol: Optional[str] = None,
paddle_protocol: Optional[str] = None,
auth_token: Optional[str] = None,
) -> pd.DataFra... |
Public interface to extract chart data from a ledger DataFrame.
Parameters
----------
df_ledger : pd.DataFrame
DataFrame containing metadata required for chart extraction.
yolox_endpoints : Optional[Tuple[str, str]], default=None
YOLOX inference server endpoints. If None, the defau... | extract_table_data_from_image | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/interface/extract.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/interface/extract.py | Apache-2.0 |
def extract_infographic_data_from_image(
*,
df_ledger: pd.DataFrame,
paddle_endpoints: Optional[Tuple[str, str]] = None,
paddle_protocol: Optional[str] = None,
auth_token: Optional[str] = None,
) -> pd.DataFrame:
"""
Extract infographic data from a DataFrame using the configured infographic ... |
Extract infographic data from a DataFrame using the configured infographic extraction pipeline.
This function creates a task configuration for infographic extraction, builds the extraction
configuration from the provided PaddleOCR endpoints, protocol, and authentication token (or uses
the default valu... | extract_infographic_data_from_image | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/interface/extract.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/interface/extract.py | Apache-2.0 |
def filter_images(
*,
df_ledger: pd.DataFrame,
min_size: int = 128,
max_aspect_ratio: Union[float, int] = 5.0,
min_aspect_ratio: Union[float, int] = 2.0,
) -> pd.DataFrame:
"""
Apply an image filter to the ledger DataFrame based on size and aspect ratio criteria.
This function builds a ... |
Apply an image filter to the ledger DataFrame based on size and aspect ratio criteria.
This function builds a set of task parameters and then delegates the filtering work to
`filter_images_internal`. If an exception occurs during filtering, the error is logged
and re-raised with additional context.
... | filter_images | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/interface/mutate.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/interface/mutate.py | Apache-2.0 |
def deduplicate_images(
*,
df_ledger: pd.DataFrame,
hash_algorithm: str = "md5",
) -> pd.DataFrame:
"""
Deduplicate images in the DataFrame based on content hashes.
This function constructs a task configuration using the specified hashing algorithm
and delegates the deduplication process to... |
Deduplicate images in the DataFrame based on content hashes.
This function constructs a task configuration using the specified hashing algorithm
and delegates the deduplication process to the internal function
``deduplicate_images_internal``. The deduplication is performed by computing content
has... | deduplicate_images | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/interface/mutate.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/interface/mutate.py | Apache-2.0 |
def store_images_to_minio(
*,
df_ledger: pd.DataFrame,
store_structured: bool = True,
store_unstructured: bool = False,
minio_access_key: Optional[str] = None,
minio_bucket_name: Optional[str] = None,
minio_endpoint: Optional[str] = None,
minio_region: Optional[str] = None,
minio_sec... |
Store images to a Minio storage backend.
This function prepares a flat configuration dictionary for storing images and structured
data to a Minio storage system. It determines which content types to store based on the
provided flags and delegates the storage operation to the internal function
`sto... | store_images_to_minio | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/interface/store.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/interface/store.py | Apache-2.0 |
def transform_text_create_embeddings(
*,
inputs: pd.DataFrame,
api_key: str,
batch_size: Optional[int] = 8192,
embedding_model: Optional[str] = None,
embedding_nim_endpoint: Optional[str] = None,
encoding_format: Optional[str] = None,
input_type: Optional[str] = None,
truncate: Optio... |
Creates text embeddings using the provided configuration.
Parameters provided as None will use the default values from EmbedExtractionsSchema.
| transform_text_create_embeddings | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/interface/transform.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/interface/transform.py | Apache-2.0 |
def transform_image_create_vlm_caption(
*,
inputs: Union[pd.DataFrame, tuple, List[tuple]],
api_key: Optional[str] = None,
prompt: Optional[str] = None,
endpoint_url: Optional[str] = None,
model_name: Optional[str] = None,
) -> pd.DataFrame:
"""
Extract captions for image content using t... |
Extract captions for image content using the VLM model API.
This function processes image content for caption generation. It accepts input in one
of three forms:
1. A pandas DataFrame with the following required structure:
- Columns:
- ``source_name`` (str): Identifier for the source ... | transform_image_create_vlm_caption | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/interface/transform.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/interface/transform.py | Apache-2.0 |
def transform_text_split_and_tokenize(
*,
inputs: Union[pd.DataFrame, str, List[str]],
tokenizer: str,
chunk_size: int,
chunk_overlap: int,
split_source_types: Optional[List[str]] = None,
hugging_face_access_token: Optional[str] = None,
) -> pd.DataFrame:
"""
Transform and tokenize t... |
Transform and tokenize text documents by splitting them into smaller chunks.
This function prepares the configuration parameters for text splitting and tokenization,
and then delegates the splitting and asynchronous tokenization to an internal function.
The function accepts input in one of two forms:... | transform_text_split_and_tokenize | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/interface/transform.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/interface/transform.py | Apache-2.0 |
def read_file_as_base64(file_path: str) -> str:
"""
Reads the file at file_path in binary mode and returns its base64-encoded string.
"""
with open(file_path, "rb") as f:
file_bytes = f.read()
return base64.b64encode(file_bytes).decode("utf-8") |
Reads the file at file_path in binary mode and returns its base64-encoded string.
| read_file_as_base64 | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/interface/utility.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/interface/utility.py | Apache-2.0 |
def create_source_metadata(source_name: str, source_id: str, document_type: str) -> dict:
"""
Creates a source metadata dictionary for a file.
The source_type is set to the provided document_type.
The date_created and last_modified fields are set to the current ISO timestamp.
"""
now_iso = date... |
Creates a source metadata dictionary for a file.
The source_type is set to the provided document_type.
The date_created and last_modified fields are set to the current ISO timestamp.
| create_source_metadata | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/interface/utility.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/interface/utility.py | Apache-2.0 |
def create_content_metadata(document_type: str) -> dict:
"""
Creates a content metadata dictionary for a file based on its document type.
It maps the document type to the corresponding content type.
"""
# Use the mapping; if document_type is not found, fallback to "unknown".
content_type = DOCU... |
Creates a content metadata dictionary for a file based on its document type.
It maps the document type to the corresponding content type.
| create_content_metadata | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/interface/utility.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/interface/utility.py | Apache-2.0 |
def build_dataframe_from_files(
file_paths: List[Union[str, BytesIO]],
source_names: List[str],
source_ids: List[str],
document_types: List[str],
) -> pd.DataFrame:
"""
Given lists of file paths (or BytesIO objects), source names, source IDs, and document types,
reads each file (base64-encod... |
Given lists of file paths (or BytesIO objects), source names, source IDs, and document types,
reads each file (base64-encoding its contents) and constructs a DataFrame.
For image content, 'image_metadata' is initialized as an empty dict, so it can later be updated.
| build_dataframe_from_files | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/interface/utility.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/interface/utility.py | Apache-2.0 |
def _build_config_from_schema(schema_class: type[BaseModel], args: Dict[str, Any]) -> Dict[str, Any]:
"""
Build and validate a configuration dictionary from the provided arguments using a Pydantic schema.
This function filters the supplied arguments to include only those keys defined in the given
Pydan... |
Build and validate a configuration dictionary from the provided arguments using a Pydantic schema.
This function filters the supplied arguments to include only those keys defined in the given
Pydantic schema (using Pydantic v2's `model_fields`), instantiates the schema for validation,
and returns the ... | _build_config_from_schema | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/interface/__init__.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/interface/__init__.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.