language
stringclasses
4 values
source_code
stringlengths
2
986k
test_code
stringlengths
125
758k
repo_name
stringclasses
97 values
python
# Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import List, Optional, Set, TYPE_CHECKING import weakref from rcl_interfaces.msg import SetParametersResult from rclpy.clock import ROSClock from rclpy.clock_type import ClockType from rclpy.parameter import Parameter from rclpy.qos import QoSProfile from rclpy.qos import ReliabilityPolicy from rclpy.time import Time import rosgraph_msgs.msg if TYPE_CHECKING: from rclpy.node import Node from rclpy.subscription import Subscription CLOCK_TOPIC = '/clock' USE_SIM_TIME_NAME = 'use_sim_time' class TimeSource: def __init__(self, *, node: Optional['Node'] = None): self._clock_sub: Optional['Subscription[rosgraph_msgs.msg.Clock]'] = None self._node_weak_ref: Optional[weakref.ReferenceType['Node']] = None self._associated_clocks: Set[ROSClock] = set() # Zero time is a special value that means time is uninitialzied self._last_time_set = Time(clock_type=ClockType.ROS_TIME) self._ros_time_is_active = False if node is not None: self.attach_node(node) @property def ros_time_is_active(self) -> bool: return self._ros_time_is_active @ros_time_is_active.setter def ros_time_is_active(self, enabled: bool) -> None: if self._ros_time_is_active == enabled: return self._ros_time_is_active = enabled for clock in self._associated_clocks: clock._set_ros_time_is_active(enabled) if enabled: self._subscribe_to_clock_topic() else: if self._clock_sub is not None: node = self._get_node() if node is not None: node.destroy_subscription(self._clock_sub) self._clock_sub = None def _subscribe_to_clock_topic(self) -> None: if self._clock_sub is None: node = self._get_node() if node is not None: self._clock_sub = node.create_subscription( rosgraph_msgs.msg.Clock, CLOCK_TOPIC, self.clock_callback, QoSProfile(depth=1, reliability=ReliabilityPolicy.BEST_EFFORT) ) def attach_node(self, node: 'Node') -> None: from rclpy.node import Node if not isinstance(node, Node): raise TypeError('Node must be of type rclpy.node.Node') # Remove an existing node. if self._node_weak_ref is not None: self.detach_node() self._node_weak_ref = weakref.ref(node) if not node.has_parameter(USE_SIM_TIME_NAME): node.declare_parameter(USE_SIM_TIME_NAME, False) use_sim_time_param = node.get_parameter(USE_SIM_TIME_NAME) if use_sim_time_param.type_ != Parameter.Type.NOT_SET: if use_sim_time_param.type_ == Parameter.Type.BOOL: self.ros_time_is_active = use_sim_time_param.value else: node.get_logger().error( "Invalid type for parameter '{}' {!r} should be bool" .format(USE_SIM_TIME_NAME, use_sim_time_param.type_)) else: node.get_logger().debug( "'{}' parameter not set, using wall time by default" .format(USE_SIM_TIME_NAME)) node.add_on_set_parameters_callback(self._on_parameter_event) def detach_node(self) -> None: # Remove the subscription to the clock topic. if self._clock_sub is not None: node = self._get_node() if node is None: raise RuntimeError('Unable to destroy previously created clock subscription') node.destroy_subscription(self._clock_sub) self._clock_sub = None self._node_weak_ref = None def attach_clock(self, clock: ROSClock) -> None: if not isinstance(clock, ROSClock): raise ValueError('Only clocks with type ROS_TIME can be attached.') clock.set_ros_time_override(self._last_time_set) clock._set_ros_time_is_active(self.ros_time_is_active) self._associated_clocks.add(clock) def clock_callback(self, msg: rosgraph_msgs.msg.Clock) -> None: # Cache the last message in case a new clock is attached. time_from_msg = Time.from_msg(msg.clock) self._last_time_set = time_from_msg for clock in self._associated_clocks: clock.set_ros_time_override(time_from_msg) def _on_parameter_event(self, parameter_list: List[Parameter[bool]]) -> SetParametersResult: successful = True reason = '' for parameter in parameter_list: if parameter.name == USE_SIM_TIME_NAME: if parameter.type_ == Parameter.Type.BOOL: self.ros_time_is_active = parameter.value else: successful = False reason = '{} parameter set to something besides a bool'.format( USE_SIM_TIME_NAME) node = self._get_node() if node: node.get_logger().error(reason) break return SetParametersResult(successful=successful, reason=reason) def _get_node(self) -> Optional['Node']: if self._node_weak_ref is not None: return self._node_weak_ref() return None
# Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import unittest from unittest.mock import Mock import rclpy from rclpy.clock import Clock from rclpy.clock import ClockChange from rclpy.clock import JumpThreshold from rclpy.clock import ROSClock from rclpy.clock_type import ClockType from rclpy.duration import Duration from rclpy.parameter import Parameter from rclpy.time import Time from rclpy.time_source import CLOCK_TOPIC from rclpy.time_source import TimeSource import rosgraph_msgs.msg class TestTimeSource(unittest.TestCase): def setUp(self) -> None: self.context = rclpy.context.Context() rclpy.init(context=self.context) self.node = rclpy.create_node( 'TestTimeSource', namespace='/rclpy', context=self.context, allow_undeclared_parameters=True) def tearDown(self) -> None: self.node.destroy_node() rclpy.shutdown(context=self.context) def publish_clock_messages(self) -> None: clock_pub = self.node.create_publisher(rosgraph_msgs.msg.Clock, CLOCK_TOPIC, 1) cycle_count = 0 time_msg = rosgraph_msgs.msg.Clock() while rclpy.ok(context=self.context) and cycle_count < 5: time_msg.clock.sec = cycle_count clock_pub.publish(time_msg) cycle_count += 1 executor = rclpy.executors.SingleThreadedExecutor(context=self.context) rclpy.spin_once(self.node, timeout_sec=1, executor=executor) # TODO(dhood): use rate once available time.sleep(1) def publish_reversed_clock_messages(self) -> None: clock_pub = self.node.create_publisher(rosgraph_msgs.msg.Clock, CLOCK_TOPIC, 1) cycle_count = 0 time_msg = rosgraph_msgs.msg.Clock() while rclpy.ok(context=self.context) and cycle_count < 5: time_msg.clock.sec = 6 - cycle_count clock_pub.publish(time_msg) cycle_count += 1 executor = rclpy.executors.SingleThreadedExecutor(context=self.context) rclpy.spin_once(self.node, timeout_sec=1, executor=executor) time.sleep(1) def set_use_sim_time_parameter(self, value: bool) -> bool: self.node.set_parameters( [Parameter('use_sim_time', Parameter.Type.BOOL, value)]) executor = rclpy.executors.SingleThreadedExecutor(context=self.context) cycle_count = 0 while rclpy.ok(context=self.context) and cycle_count < 5: use_sim_time_param: Parameter[bool] = self.node.get_parameter('use_sim_time') cycle_count += 1 if use_sim_time_param.type_ == Parameter.Type.BOOL: break rclpy.spin_once(self.node, timeout_sec=1, executor=executor) time.sleep(1) return use_sim_time_param.value == value def test_time_source_attach_clock(self) -> None: time_source = TimeSource(node=self.node) # ROSClock is a specialization of Clock with ROS time methods. time_source.attach_clock(ROSClock()) # Other clock types are not supported. with self.assertRaises(ValueError): time_source.attach_clock( Clock(clock_type=ClockType.SYSTEM_TIME)) # type: ignore[arg-type] with self.assertRaises(ValueError): time_source.attach_clock( Clock(clock_type=ClockType.STEADY_TIME)) # type: ignore[arg-type] def test_time_source_not_using_sim_time(self) -> None: time_source = TimeSource(node=self.node) clock = ROSClock() time_source.attach_clock(clock) # When not using sim time, ROS time should look like system time now = clock.now() system_now = Clock(clock_type=ClockType.SYSTEM_TIME).now() assert (system_now.nanoseconds - now.nanoseconds) < 1e9 # Presence of clock publisher should not affect the clock self.publish_clock_messages() self.assertFalse(clock.ros_time_is_active) now = clock.now() system_now = Clock(clock_type=ClockType.SYSTEM_TIME).now() assert (system_now.nanoseconds - now.nanoseconds) < 1e9 # Whether or not an attached clock is using ROS time should be determined by the time # source managing it. self.assertFalse(time_source.ros_time_is_active) clock2 = ROSClock() clock2._set_ros_time_is_active(True) time_source.attach_clock(clock2) self.assertFalse(clock2.ros_time_is_active) assert time_source._clock_sub is None def test_time_source_using_sim_time(self) -> None: time_source = TimeSource(node=self.node) clock = ROSClock() time_source.attach_clock(clock) # Setting ROS time active on a time source should also cause attached clocks' use of ROS # time to be set to active. self.assertFalse(time_source.ros_time_is_active) self.assertFalse(clock.ros_time_is_active) assert self.set_use_sim_time_parameter(True) self.assertTrue(time_source.ros_time_is_active) self.assertTrue(clock.ros_time_is_active) # A subscriber should have been created assert time_source._clock_sub is not None # Before any messages have been received on the /clock topic, now() should return 0 assert clock.now() == Time(seconds=0, clock_type=ClockType.ROS_TIME) # When using sim time, ROS time should look like the messages received on /clock self.publish_clock_messages() assert clock.now() > Time(seconds=0, clock_type=ClockType.ROS_TIME) assert clock.now() <= Time(seconds=5, clock_type=ClockType.ROS_TIME) # Check that attached clocks get the cached message clock2 = Clock(clock_type=ClockType.ROS_TIME) time_source.attach_clock(clock2) assert clock2.now() > Time(seconds=0, clock_type=ClockType.ROS_TIME) assert clock2.now() <= Time(seconds=5, clock_type=ClockType.ROS_TIME) # Check detaching the node time_source.detach_node() node2 = rclpy.create_node('TestTimeSource2', namespace='/rclpy', context=self.context) time_source.attach_node(node2) node2.destroy_node() assert time_source._get_node() == node2 assert time_source._clock_sub is None def test_forwards_jump(self) -> None: time_source = TimeSource(node=self.node) clock = ROSClock() time_source.attach_clock(clock) assert self.set_use_sim_time_parameter(True) pre_cb = Mock() post_cb = Mock() threshold = JumpThreshold( min_forward=Duration(seconds=0.5), min_backward=None, on_clock_change=False) handler = clock.create_jump_callback( threshold, pre_callback=pre_cb, post_callback=post_cb) self.publish_clock_messages() pre_cb.assert_called() post_cb.assert_called() assert post_cb.call_args[0][0].clock_change == ClockChange.ROS_TIME_NO_CHANGE handler.unregister() def test_backwards_jump(self) -> None: time_source = TimeSource(node=self.node) clock = ROSClock() time_source.attach_clock(clock) assert self.set_use_sim_time_parameter(True) pre_cb = Mock() post_cb = Mock() threshold = JumpThreshold( min_forward=None, min_backward=Duration(seconds=-0.5), on_clock_change=False) handler = clock.create_jump_callback( threshold, pre_callback=pre_cb, post_callback=post_cb) self.publish_reversed_clock_messages() pre_cb.assert_called() post_cb.assert_called() assert post_cb.call_args[0][0].clock_change == ClockChange.ROS_TIME_NO_CHANGE handler.unregister() def test_clock_change(self) -> None: time_source = TimeSource(node=self.node) clock = ROSClock() time_source.attach_clock(clock) assert self.set_use_sim_time_parameter(True) pre_cb = Mock() post_cb = Mock() threshold = JumpThreshold(min_forward=None, min_backward=None, on_clock_change=True) handler = clock.create_jump_callback( threshold, pre_callback=pre_cb, post_callback=post_cb) assert self.set_use_sim_time_parameter(False) pre_cb.assert_called() post_cb.assert_called() assert post_cb.call_args[0][0].clock_change == ClockChange.ROS_TIME_DEACTIVATED pre_cb.reset_mock() post_cb.reset_mock() assert self.set_use_sim_time_parameter(True) pre_cb.assert_called() post_cb.assert_called() assert post_cb.call_args[0][0].clock_change == ClockChange.ROS_TIME_ACTIVATED handler.unregister() def test_no_pre_callback(self) -> None: time_source = TimeSource(node=self.node) clock = ROSClock() time_source.attach_clock(clock) assert self.set_use_sim_time_parameter(True) post_cb = Mock() threshold = JumpThreshold(min_forward=None, min_backward=None, on_clock_change=True) handler = clock.create_jump_callback( threshold, pre_callback=None, post_callback=post_cb) assert self.set_use_sim_time_parameter(False) post_cb.assert_called_once() assert post_cb.call_args[0][0].clock_change == ClockChange.ROS_TIME_DEACTIVATED handler.unregister() def test_no_post_callback(self) -> None: time_source = TimeSource(node=self.node) clock = ROSClock() time_source.attach_clock(clock) assert self.set_use_sim_time_parameter(True) pre_cb = Mock() threshold = JumpThreshold(min_forward=None, min_backward=None, on_clock_change=True) handler = clock.create_jump_callback( threshold, pre_callback=pre_cb, post_callback=None) assert self.set_use_sim_time_parameter(False) pre_cb.assert_called_once() handler.unregister() if __name__ == '__main__': unittest.main()
rclpy
python
# Copyright 2024-2025 Brad Martin # Copyright 2024 Merlin Labs, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import faulthandler import typing import rclpy.executors from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy # Try to look like we inherit from the rclpy Executor for type checking purposes without # getting any of the code from the base class. def EventsExecutor(*, context: typing.Optional[rclpy.Context] = None) -> rclpy.executors.Executor: if context is None: context = rclpy.get_default_context() # For debugging purposes, if anything goes wrong in C++ make sure we also get a # Python backtrace dumped with the crash. faulthandler.enable() ex = typing.cast(rclpy.executors.Executor, _rclpy.EventsExecutor(context)) # rclpy.Executor does this too. Note, the context itself is smart enough to check # for bound methods, and check whether the instances they're bound to still exist at # callback time, so we don't have to worry about tearing down this stale callback at # destruction time. # TODO(bmartin427) This should really be done inside of the EventsExecutor # implementation itself, but I'm unable to figure out a pybind11 incantation that # allows me to pass this bound method call from C++. context.on_shutdown(ex.wake) return ex
# Copyright 2024-2025 Brad Martin # Copyright 2024 Merlin Labs, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import typing import unittest import action_msgs.msg import rclpy.action from rclpy.action.client import ClientGoalHandle from rclpy.action.server import ServerGoalHandle import rclpy.clock_type import rclpy.duration import rclpy.event_handler import rclpy.executors import rclpy.experimental import rclpy.node import rclpy.parameter import rclpy.qos import rclpy.time import rclpy.timer import rosgraph_msgs.msg import test_msgs.action import test_msgs.msg import test_msgs.srv from typing_extensions import TypeAlias FibonacciServerGoalHandle: TypeAlias = ServerGoalHandle[test_msgs.action.Fibonacci.Goal, test_msgs.action.Fibonacci.Result, test_msgs.action.Fibonacci.Feedback] FibonacciClientGoalHandle: TypeAlias = ClientGoalHandle[test_msgs.action.Fibonacci.Goal, test_msgs.action.Fibonacci.Result, test_msgs.action.Fibonacci.Feedback] def _get_pub_sub_qos(transient_local: bool) -> rclpy.qos.QoSProfile: if not transient_local: return rclpy.qos.QoSProfile(history=rclpy.qos.HistoryPolicy.KEEP_ALL) # For test purposes we deliberately want a TRANSIENT_LOCAL QoS with KEEP_ALL # history. return rclpy.qos.QoSProfile( history=rclpy.qos.HistoryPolicy.KEEP_ALL, durability=rclpy.qos.DurabilityPolicy.TRANSIENT_LOCAL, ) class SubTestNode(rclpy.node.Node): """Node to test subscriptions and subscription-related events.""" def __init__(self, *, transient_local: bool = False, use_async_handler: bool = False) -> None: super().__init__('test_sub_node') self._new_pub_future: typing.Optional[ rclpy.Future[rclpy.event_handler.QoSSubscriptionMatchedInfo] ] = None self._received_future: typing.Optional[rclpy.Future[test_msgs.msg.BasicTypes]] = None self._sub = self.create_subscription( test_msgs.msg.BasicTypes, # This node seems to get stale discovery data and then complain about QoS # changes if we reuse the same topic name. 'test_topic' + ('_transient_local' if transient_local else ''), self._async_handle_sub if use_async_handler else self._handle_sub, _get_pub_sub_qos(transient_local), event_callbacks=rclpy.event_handler.SubscriptionEventCallbacks( matched=self._handle_matched_sub ), ) def drop_subscription(self) -> None: self.destroy_subscription(self._sub) def expect_pub_info( self, ) -> rclpy.Future[rclpy.event_handler.QoSSubscriptionMatchedInfo]: self._new_pub_future = rclpy.Future() return self._new_pub_future def expect_message(self) -> rclpy.Future[test_msgs.msg.BasicTypes]: self._received_future = rclpy.Future() return self._received_future def _handle_sub(self, msg: test_msgs.msg.BasicTypes) -> None: if self._received_future is not None: future = self._received_future self._received_future = None future.set_result(msg) async def _async_handle_sub(self, msg: test_msgs.msg.BasicTypes) -> None: # Don't bother to actually delay at all for this test return self._handle_sub(msg) def _handle_matched_sub(self, info: rclpy.event_handler.QoSSubscriptionMatchedInfo) -> None: """Handle a new publisher being matched to our subscription.""" if self._new_pub_future is not None: self._new_pub_future.set_result(info) self._new_pub_future = None class PubTestNode(rclpy.node.Node): """Node to test publications and publication-related events.""" def __init__(self, *, transient_local: bool = False) -> None: super().__init__('test_pub_node') self._new_sub_future: typing.Optional[ rclpy.Future[rclpy.event_handler.QoSPublisherMatchedInfo] ] = None self._pub = self.create_publisher( test_msgs.msg.BasicTypes, 'test_topic' + ('_transient_local' if transient_local else ''), _get_pub_sub_qos(transient_local), event_callbacks=rclpy.event_handler.PublisherEventCallbacks( matched=self._handle_matched_pub ), ) def expect_sub_info( self, ) -> rclpy.Future[rclpy.event_handler.QoSPublisherMatchedInfo]: self._new_sub_future = rclpy.Future() return self._new_sub_future def publish(self, value: float) -> None: self._pub.publish(test_msgs.msg.BasicTypes(float32_value=value)) def _handle_matched_pub(self, info: rclpy.event_handler.QoSPublisherMatchedInfo) -> None: """Handle a new subscriber being matched to our publication.""" if self._new_sub_future is not None: self._new_sub_future.set_result(info) self._new_sub_future = None class ServiceServerTestNode(rclpy.node.Node): """Node to test service server-side operation.""" def __init__( self, *, use_async_handler: bool = False, parameter_overrides: typing.Optional[list[rclpy.parameter.Parameter[bool]]] = None, ) -> None: super().__init__('test_service_server_node', parameter_overrides=parameter_overrides) self._got_request_future: typing.Optional[ rclpy.Future[test_msgs.srv.BasicTypes.Request] ] = None self._pending_response: typing.Optional[test_msgs.srv.BasicTypes.Response] = None self.create_service( test_msgs.srv.BasicTypes, 'test_service', self._async_handle_service if use_async_handler else self._handle_service, ) def expect_request( self, success: bool, error_msg: str ) -> rclpy.Future[test_msgs.srv.BasicTypes.Request]: """ Expect an incoming request. The arguments are used to compose the response. """ self._got_request_future = rclpy.Future() self._pending_response = test_msgs.srv.BasicTypes.Response( bool_value=success, string_value=error_msg ) return self._got_request_future def _handle_service( self, req: test_msgs.srv.BasicTypes.Request, res: test_msgs.srv.BasicTypes.Response, ) -> test_msgs.srv.BasicTypes.Response: self._handle_request(req) return self._get_response(res) def _handle_request(self, req: test_msgs.srv.BasicTypes.Request) -> None: if self._got_request_future is not None: self._got_request_future.set_result(req) self._got_request_future = None def _get_response( self, res: test_msgs.srv.BasicTypes.Response ) -> test_msgs.srv.BasicTypes.Response: if self._pending_response is not None: res = self._pending_response self._pending_response = None return res async def _async_handle_service( self, req: test_msgs.srv.BasicTypes.Request, res: test_msgs.srv.BasicTypes.Response ) -> test_msgs.srv.BasicTypes.Response: self._handle_request(req) # Create and await a timer before replying, to represent other work. timer_future = rclpy.Future[None]() timer = self.create_timer( 1.0, lambda: timer_future.set_result(None), # NOTE: As of this writing, the callback_group is entirely ignored by EventsExecutor; # however, it would be needed for SingleThreadedExecutor to pass this same test, so # we'll include it anyway. callback_group=rclpy.callback_groups.ReentrantCallbackGroup(), ) await timer_future self.destroy_timer(timer) return self._get_response(res) class ServiceClientTestNode(rclpy.node.Node): """Node to test service client-side operation.""" def __init__(self) -> None: super().__init__('test_service_client_node') self._client: rclpy.client.Client[ test_msgs.srv.BasicTypes.Request, test_msgs.srv.BasicTypes.Response ] = self.create_client(test_msgs.srv.BasicTypes, 'test_service') def issue_request(self, value: float) -> rclpy.Future[test_msgs.srv.BasicTypes.Response]: req = test_msgs.srv.BasicTypes.Request(float32_value=value) return self._client.call_async(req) class TimerTestNode(rclpy.node.Node): """Node to test timer operation.""" def __init__( self, index: int = 0, parameter_overrides: typing.Optional[list[rclpy.parameter.Parameter[bool]]] = None, ) -> None: super().__init__(f'test_timer{index}', parameter_overrides=parameter_overrides) self._timer_events = 0 self._tick_future: typing.Optional[rclpy.Future[rclpy.timer.TimerInfo]] = None self._timer = self.create_timer(0.1, self._handle_timer) @property def timer_events(self) -> int: return self._timer_events def expect_tick(self) -> rclpy.Future[rclpy.timer.TimerInfo]: """Get future on TimerInfo for an anticipated timer tick.""" self._tick_future = rclpy.Future() return self._tick_future def _handle_timer(self, info: rclpy.timer.TimerInfo) -> None: self._timer_events += 1 if self._tick_future is not None: self._tick_future.set_result(info) self._tick_future = None class ClockPublisherNode(rclpy.node.Node): """Node to publish rostime clock updates.""" def __init__(self) -> None: super().__init__('clock_node') self._now = rclpy.time.Time(clock_type=rclpy.clock_type.ClockType.ROS_TIME) self._pub = self.create_publisher( rosgraph_msgs.msg.Clock, '/clock', rclpy.qos.QoSProfile(depth=1, reliability=rclpy.qos.ReliabilityPolicy.BEST_EFFORT), ) def advance_time(self, millisec: int) -> None: self._now += rclpy.duration.Duration(nanoseconds=millisec * 1000000) self._pub.publish(rosgraph_msgs.msg.Clock(clock=self._now.to_msg())) @property def now(self) -> rclpy.time.Time: return self._now class ActionServerTestNode(rclpy.node.Node): """Node to test action server-side operation.""" def __init__(self) -> None: super().__init__( 'test_action_server_node', parameter_overrides=[rclpy.parameter.Parameter('use_sim_time', value=True)], ) self._got_goal_future: typing.Optional[rclpy.Future[test_msgs.action.Fibonacci.Goal]] = ( None ) self._srv = rclpy.action.ActionServer( self, test_msgs.action.Fibonacci, 'test_action', self._handle_execute, handle_accepted_callback=self._handle_accepted, result_timeout=10, ) self._goal_handle: typing.Optional[FibonacciServerGoalHandle] = None self._sequence: list[int] = [] def expect_goal(self) -> rclpy.Future[test_msgs.action.Fibonacci.Goal]: self._goal_handle = None self._got_goal_future = rclpy.Future() return self._got_goal_future def _handle_accepted(self, goal_handle: FibonacciServerGoalHandle) -> None: self._goal_handle = goal_handle self._sequence = [0, 1] if self._got_goal_future is not None: self._got_goal_future.set_result(goal_handle.request) self._got_goal_future = None # Wait to finish until instructed by test def advance_feedback(self) -> typing.Optional[list[int]]: """ Add an entry to the result in progress and sends a feedback message. Returns the current sequence in progress if incomplete, or None if the sequence is complete and it's time to complete the operation instead. """ assert self._goal_handle is not None n = self._goal_handle.request.order + 1 if len(self._sequence) < n: self._sequence.append(self._sequence[-2] + self._sequence[-1]) if len(self._sequence) >= n: return None # FYI normally feedbacks would be sent from the execute handler, but we've tied # it to its own public method for testing fb = test_msgs.action.Fibonacci.Feedback() fb.sequence = self._sequence self._goal_handle.publish_feedback(fb) return self._sequence def execute(self) -> FibonacciServerGoalHandle: """ Completes the action in progress. Returns the handle to the goal executed. """ handle = self._goal_handle self._goal_handle = None assert handle is not None handle.execute() return handle def _handle_execute( self, goal_handle: FibonacciServerGoalHandle ) -> test_msgs.action.Fibonacci.Result: goal_handle.succeed() result = test_msgs.action.Fibonacci.Result() result.sequence = self._sequence return result class ActionClientTestNode(rclpy.node.Node): """Node to test action client-side operation.""" def __init__(self) -> None: super().__init__('test_action_client_node') self._client = rclpy.action.ActionClient[ test_msgs.action.Fibonacci.Goal, test_msgs.action.Fibonacci.Result, test_msgs.action.Fibonacci.Feedback, ](self, test_msgs.action.Fibonacci, 'test_action') self._feedback_future: typing.Optional[ rclpy.Future[test_msgs.action.Fibonacci.Feedback] ] = None self._result_future: typing.Optional[rclpy.Future[test_msgs.action.Fibonacci.Result]] = ( None ) def send_goal(self, order: int) -> rclpy.Future[FibonacciClientGoalHandle]: """ Send a new goal. The future will contain the goal handle when the goal submission response has been received. """ self._client.wait_for_server() goal_ack_future = self._client.send_goal_async( test_msgs.action.Fibonacci.Goal(order=order), feedback_callback=self._handle_feedback, ) goal_ack_future.add_done_callback(self._handle_goal_ack) return goal_ack_future def _handle_goal_ack(self, future: rclpy.Future[FibonacciClientGoalHandle]) -> None: handle = future.result() assert handle is not None result_future = handle.get_result_async() result_future.add_done_callback(self._handle_result_response) def expect_feedback(self) -> rclpy.Future[test_msgs.action.Fibonacci.Feedback]: self._feedback_future = rclpy.Future() return self._feedback_future def _handle_feedback( self, # If this is a private 'Impl' detail, why is rclpy handing this out?? fb_msg: test_msgs.action.Fibonacci.Impl.FeedbackMessage, ) -> None: if self._feedback_future is not None: self._feedback_future.set_result(fb_msg.feedback) self._feedback_future = None def expect_result( self, ) -> rclpy.Future[test_msgs.action.Fibonacci.Result]: self._result_future = rclpy.Future() return self._result_future def _handle_result_response( self, future: rclpy.Future[test_msgs.action.Fibonacci_GetResult_Response] ) -> None: response: typing.Optional[test_msgs.action.Fibonacci_GetResult_Response] = future.result() assert response is not None assert self._result_future is not None result: test_msgs.action.Fibonacci.Result = response.result self._result_future.set_result(result) self._result_future = None # These two python types are both actually rmw_matched_status_t rmw_matched_status_t = typing.Union[ rclpy.event_handler.QoSSubscriptionMatchedInfo, rclpy.event_handler.QoSPublisherMatchedInfo ] class TestEventsExecutor(unittest.TestCase): def setUp(self, *args: typing.Any, **kwargs: typing.Any) -> None: super().__init__(*args, **kwargs) # Prevent nodes under test from discovering other random stuff to talk to os.environ['ROS_AUTOMATIC_DISCOVERY_RANGE'] = 'OFF' rclpy.init() self.executor = rclpy.experimental.EventsExecutor() def tearDown(self) -> None: # Clean up all nodes still in the executor before shutdown for node in self.executor.get_nodes(): self.executor.remove_node(node) node.destroy_node() self.executor.shutdown() rclpy.shutdown() def _expect_future_done(self, future: rclpy.Future[typing.Any]) -> None: # Use a moderately long timeout with the expectation that we shouldn't often # need the whole duration. self.executor.spin_until_future_complete(future, 1.0) self.assertTrue(future.done()) def _expect_future_not_done(self, future: rclpy.Future[typing.Any]) -> None: # Use a short timeout to give the future some time to complete if we are going # to fail, but not very long because we'll be waiting the full duration every # time during successful tests. It's ok if the timeout is a bit short and the # failure isn't 100% deterministic. self.executor.spin_until_future_complete(future, 0.2) self.assertFalse(future.done()) def _spin_for(self, sec: float) -> None: """Spins the executor for the given number of realtime seconds.""" # Note that this roundabout approach of waiting on a future that will never # finish with a timeout seems to be the only way with the rclpy.Executor API to # spin for a fixed time. self.executor.spin_until_future_complete(rclpy.Future(), sec) def _check_match_event_future( self, future: rclpy.Future[rmw_matched_status_t], total_count: int, current_count: int, ) -> None: # NOTE: fastdds appears to be buggy and reports a change in total_count with # total_count_change staying zero. cyclonedds works as expected. Rather than # have this test be sensitive to which RMW is selected, let's just avoid testing # the change fields altogether. self._expect_future_done(future) info: typing.Optional[rmw_matched_status_t] = future.result() assert info is not None self.assertEqual(info.total_count, total_count) self.assertEqual(info.current_count, current_count) def _check_message_future( self, future: rclpy.Future[test_msgs.msg.BasicTypes], value: float ) -> None: self._expect_future_done(future) msg: typing.Optional[test_msgs.msg.BasicTypes] = future.result() assert msg is not None self.assertAlmostEqual(msg.float32_value, value, places=5) def _check_service_request_future( self, future: rclpy.Future[test_msgs.srv.BasicTypes.Request], value: float ) -> None: self._expect_future_done(future) req: typing.Optional[test_msgs.srv.BasicTypes.Request] = future.result() assert req is not None self.assertAlmostEqual(req.float32_value, value, places=5) def _check_service_response_future( self, future: rclpy.Future[test_msgs.srv.BasicTypes.Response], success: bool, error_msg: str, ) -> None: self._expect_future_done(future) res: typing.Optional[test_msgs.srv.BasicTypes.Response] = future.result() assert res is not None self.assertEqual(res.bool_value, success) self.assertEqual(res.string_value, error_msg) def test_pub_sub(self) -> None: sub_node = SubTestNode() new_pub_future = sub_node.expect_pub_info() received_future = sub_node.expect_message() self.executor.add_node(sub_node) # With subscriber node alone, should be no publisher or messages self._expect_future_not_done(new_pub_future) self.assertFalse(received_future.done()) # Already waited a bit pub_node = PubTestNode() new_sub_future = pub_node.expect_sub_info() self.executor.add_node(pub_node) # Publisher and subscriber should find each other but no messages should be # exchanged yet self._check_match_event_future(new_pub_future, 1, 1) new_pub_future = sub_node.expect_pub_info() self._check_match_event_future(new_sub_future, 1, 1) new_sub_future = pub_node.expect_sub_info() self._expect_future_not_done(received_future) # Send messages and make sure they're received. for i in range(300): pub_node.publish(0.1 * i) self._check_message_future(received_future, 0.1 * i) received_future = sub_node.expect_message() # Destroy the subscription, make sure the publisher is notified sub_node.drop_subscription() self._check_match_event_future(new_sub_future, 1, 0) new_sub_future = pub_node.expect_sub_info() # Publish another message to ensure all subscriber callbacks got cleaned up pub_node.publish(4.7) self._expect_future_not_done(new_pub_future) self.assertFalse(received_future.done()) # Already waited a bit # Delete the subscribing node entirely. There should be no additional match activity and # still no subscriber callbacks. self.executor.remove_node(sub_node) sub_node.destroy_node() self._expect_future_not_done(new_sub_future) self.assertFalse(new_pub_future.done()) # Already waited a bit self.assertFalse(received_future.done()) # Already waited a bit def test_async_sub(self) -> None: sub_node = SubTestNode(use_async_handler=True) received_future = sub_node.expect_message() self.executor.add_node(sub_node) self._expect_future_not_done(received_future) pub_node = PubTestNode() self.executor.add_node(pub_node) pub_node.publish(0.0) self._check_message_future(received_future, 0.0) def test_pub_sub_multi_message(self) -> None: # Creates a transient local publisher and queues multiple messages on it. Then # creates a subscriber and makes sure all sent messages get delivered when it # comes up. pub_node = PubTestNode(transient_local=True) self.executor.add_node(pub_node) for i in range(5): pub_node.publish(0.1 * i) sub_node = SubTestNode(transient_local=True) received_future = sub_node.expect_message() received_messages: list[test_msgs.msg.BasicTypes] = [] def handle_message(future: rclpy.Future[test_msgs.msg.BasicTypes]) -> None: nonlocal received_future msg = future.result() assert msg is not None received_messages.append(msg) received_future = sub_node.expect_message() received_future.add_done_callback(handle_message) received_future.add_done_callback(handle_message) self._expect_future_not_done(received_future) self.executor.add_node(sub_node) while len(received_messages) < 5: self._expect_future_done(received_future) self.assertEqual(len(received_messages), 5) for i in range(5): self.assertAlmostEqual(received_messages[i].float32_value, 0.1 * i, places=5) self._expect_future_not_done(received_future) pub_node.publish(0.5) self._check_message_future(received_future, 0.5) def test_service(self) -> None: server_node = ServiceServerTestNode() got_request_future = server_node.expect_request(True, 'test response 0') self.executor.add_node(server_node) self._expect_future_not_done(got_request_future) client_node = ServiceClientTestNode() self.executor.add_node(client_node) self._expect_future_not_done(got_request_future) for i in range(300): got_response_future = client_node.issue_request(7.1) self._check_service_request_future(got_request_future, 7.1) got_request_future = server_node.expect_request(True, f'test response {i + 1}') self._check_service_response_future(got_response_future, True, f'test response {i}') # Destroy server node and retry issuing a request self.executor.remove_node(server_node) server_node.destroy_node() self._expect_future_not_done(got_request_future) got_response_future = client_node.issue_request(5.0) self._expect_future_not_done(got_request_future) self.assertFalse(got_response_future.done()) # Already waited a bit def test_async_service(self) -> None: server_node = ServiceServerTestNode( use_async_handler=True, parameter_overrides=[rclpy.parameter.Parameter('use_sim_time', value=True)], ) got_request_future = server_node.expect_request(True, 'test response') client_node = ServiceClientTestNode() clock_node = ClockPublisherNode() for node in [server_node, client_node, clock_node]: self.executor.add_node(node) self._expect_future_not_done(got_request_future) got_response_future = client_node.issue_request(7.1) self._check_service_request_future(got_request_future, 7.1) self._expect_future_not_done(got_response_future) clock_node.advance_time(1000) self._check_service_response_future(got_response_future, True, 'test response') def test_timers(self) -> None: realtime_node = TimerTestNode(index=0) rostime_node = TimerTestNode( index=1, parameter_overrides=[rclpy.parameter.Parameter('use_sim_time', value=True)] ) clock_node = ClockPublisherNode() for node in [realtime_node, rostime_node, clock_node]: self.executor.add_node(node) # Wait a bit, and make sure the realtime timer ticks, and the rostime one does # not. Since this is based on wall time, be very flexible on tolerances here. realtime_tick_future = realtime_node.expect_tick() self._spin_for(1.0) realtime_ticks = realtime_node.timer_events self.assertGreater(realtime_ticks, 1) self.assertLess(realtime_ticks, 50) self.assertEqual(rostime_node.timer_events, 0) info = realtime_tick_future.result() assert info is not None self.assertGreaterEqual(info.actual_call_time, info.expected_call_time) # Manually tick the rostime timer by less than a full interval. rostime_tick_future = rostime_node.expect_tick() for _ in range(99): clock_node.advance_time(1) self._expect_future_not_done(rostime_tick_future) clock_node.advance_time(1) self._expect_future_done(rostime_tick_future) info = rostime_tick_future.result() assert info is not None self.assertEqual(info.actual_call_time, info.expected_call_time) self.assertEqual(info.actual_call_time, clock_node.now) # Now tick by a bunch of full intervals. for _ in range(300): rostime_tick_future = rostime_node.expect_tick() clock_node.advance_time(100) self._expect_future_done(rostime_tick_future) # Ensure the realtime timer ticked much less than the rostime one. self.assertLess(realtime_node.timer_events, rostime_node.timer_events) # Create two timers with the same interval, both set to cancel the other from the callback. # Only one of the callbacks should be delivered, though we can't necessarily predict which # one. def handler() -> None: nonlocal count, timer1, timer2 # type: ignore[misc] count += 1 timer1.cancel() timer2.cancel() count = 0 timer1 = rostime_node.create_timer(0.01, handler) timer2 = rostime_node.create_timer(0.01, handler) self._spin_for(0.0) self.assertEqual(count, 0) clock_node.advance_time(10) self._spin_for(0.0) self.assertEqual(count, 1) clock_node.advance_time(10) self._spin_for(0.0) self.assertEqual(count, 1) def test_action(self) -> None: clock_node = ClockPublisherNode() self.executor.add_node(clock_node) server_node = ActionServerTestNode() got_goal_future = server_node.expect_goal() self.executor.add_node(server_node) clock_node.advance_time(0) self._expect_future_not_done(got_goal_future) client_node = ActionClientTestNode() self.executor.add_node(client_node) self._expect_future_not_done(got_goal_future) for i in range(300): order = (i % 40) + 1 # Don't want sequence to get too big goal_acknowledged_future = client_node.send_goal(order) self._expect_future_done(got_goal_future) self._expect_future_done(goal_acknowledged_future) req: typing.Optional[test_msgs.action.Fibonacci.Goal] = got_goal_future.result() assert req is not None self.assertEqual(req.order, order) result_future = client_node.expect_result() while True: got_feedback_future = client_node.expect_feedback() seq = server_node.advance_feedback() if seq is None: break self._expect_future_done(got_feedback_future) feedback = got_feedback_future.result() assert feedback is not None self.assertEqual(len(feedback.sequence), len(seq)) last_handle = server_node.execute() self._expect_future_done(result_future) self.assertFalse(got_feedback_future.done()) res: typing.Optional[test_msgs.action.Fibonacci.Result] = result_future.result() assert res is not None self.assertEqual(len(res.sequence), order + 1) got_goal_future = server_node.expect_goal() # Test completed goal expiration by time self.assertEqual(last_handle.status, action_msgs.msg.GoalStatus.STATUS_SUCCEEDED) clock_node.advance_time(9999) self._spin_for(0.2) self.assertEqual(last_handle.status, action_msgs.msg.GoalStatus.STATUS_SUCCEEDED) clock_node.advance_time(2) self._spin_for(0.2) self.assertEqual(last_handle.status, action_msgs.msg.GoalStatus.STATUS_UNKNOWN) # Destroy server node and retry issuing a goal self.executor.remove_node(server_node) server_node.destroy_node() self._expect_future_not_done(got_goal_future) goal_acknowledged_future = client_node.send_goal(5) self._expect_future_not_done(got_goal_future) self.assertFalse(goal_acknowledged_future.done()) # Already waited a bit if __name__ == '__main__': unittest.main()
rclpy
python
# Copyright 2016 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from enum import Enum import inspect from types import TracebackType from typing import Callable from typing import Generic from typing import Literal from typing import Optional from typing import overload from typing import Type from typing import TypedDict from typing import TypeVar from typing import Union from rclpy.callback_groups import CallbackGroup from rclpy.event_handler import SubscriptionEventCallbacks from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy from rclpy.qos import QoSProfile from rclpy.subscription_content_filter_options import ContentFilterOptions from rclpy.type_support import MsgT from typing_extensions import TypeAlias class PublisherGID(TypedDict): implementation_identifier: str data: bytes class MessageInfo(TypedDict): source_timestamp: int received_timestamp: int publication_sequence_number: Optional[int] reception_sequence_number: Optional[int] publisher_gid: Optional[PublisherGID] # Re-export exception defined in _rclpy C extension. RCLError = _rclpy.RCLError # Left to support Legacy TypeVars. MsgType = TypeVar('MsgType') # Can be redone with TypeVar(default=MsgT) when either typing-extensions4.11.0+ or python3.13+ T = TypeVar('T') GenericSubscriptionCallback: TypeAlias = Union[Callable[[T], None], Callable[[T, MessageInfo], None]] SubscriptionCallbackUnion: TypeAlias = Union[GenericSubscriptionCallback[MsgT], GenericSubscriptionCallback[bytes]] class Subscription(Generic[MsgT]): class CallbackType(Enum): MessageOnly = 0 WithMessageInfo = 1 @overload def __init__( self, subscription_impl: '_rclpy.Subscription[MsgT]', msg_type: Type[MsgT], topic: str, callback: GenericSubscriptionCallback[bytes], callback_group: CallbackGroup, qos_profile: QoSProfile, raw: Literal[True], event_callbacks: SubscriptionEventCallbacks, ) -> None: ... @overload def __init__( self, subscription_impl: '_rclpy.Subscription[MsgT]', msg_type: Type[MsgT], topic: str, callback: GenericSubscriptionCallback[MsgT], callback_group: CallbackGroup, qos_profile: QoSProfile, raw: Literal[False], event_callbacks: SubscriptionEventCallbacks, ) -> None: ... @overload def __init__( self, subscription_impl: '_rclpy.Subscription[MsgT]', msg_type: Type[MsgT], topic: str, callback: SubscriptionCallbackUnion[MsgT], callback_group: CallbackGroup, qos_profile: QoSProfile, raw: bool, event_callbacks: SubscriptionEventCallbacks, ) -> None: ... def __init__( self, subscription_impl: '_rclpy.Subscription[MsgT]', msg_type: Type[MsgT], topic: str, callback: SubscriptionCallbackUnion[MsgT], callback_group: CallbackGroup, qos_profile: QoSProfile, raw: bool, event_callbacks: SubscriptionEventCallbacks, ) -> None: """ Create a container for a ROS subscription. .. warning:: Users should not create a subscription with this constructor, instead they should call :meth:`.Node.create_subscription`. :param subscription_impl: :class:`Subscription` wrapping the underlying ``rcl_subscription_t`` object. :param msg_type: The type of ROS messages the subscription will subscribe to. :param topic: The name of the topic the subscription will subscribe to. :param callback: A user-defined callback function that is called when a message is received by the subscription. :param callback_group: The callback group for the subscription. If ``None``, then the nodes default callback group is used. :param qos_profile: The quality of service profile to apply to the subscription. :param raw: If ``True``, then received messages will be stored in raw binary representation. """ self.__subscription = subscription_impl self.msg_type = msg_type self.topic = topic self.callback = callback self.callback_group = callback_group # True when the callback is ready to fire but has not been "taken" by an executor self._executor_event = False self.qos_profile = qos_profile self.raw = raw self.event_handlers = event_callbacks.create_event_handlers( callback_group, subscription_impl, topic) def get_publisher_count(self) -> int: """Get the number of publishers that this subscription has.""" with self.handle: return self.__subscription.get_publisher_count() @property def handle(self) -> '_rclpy.Subscription[MsgT]': return self.__subscription def destroy(self) -> None: """ Destroy a container for a ROS subscription. .. warning:: Users should not destroy a subscription with this method, instead they should call :meth:`.Node.destroy_subscription`. """ for handler in self.event_handlers: handler.destroy() self.handle.destroy_when_not_in_use() @property def topic_name(self) -> str: with self.handle: return self.__subscription.get_topic_name() @property def callback(self) -> SubscriptionCallbackUnion[MsgT]: return self._callback @callback.setter def callback(self, value: SubscriptionCallbackUnion[MsgT]) -> None: self._callback = value self._callback_type = Subscription.CallbackType.MessageOnly try: inspect.signature(value).bind(object()) return except TypeError: pass try: inspect.signature(value).bind(object(), object()) self._callback_type = Subscription.CallbackType.WithMessageInfo return except TypeError: pass raise RuntimeError( 'Subscription.__init__(): callback should be either be callable with one argument' '(to get only the message) or two (to get message and message info)') @property def logger_name(self) -> str: """Get the name of the logger associated with the node of the subscription.""" with self.handle: return self.__subscription.get_logger_name() @property def is_cft_enabled(self) -> bool: """Check if content filtering is enabled for the subscription.""" with self.handle: return self.__subscription.is_cft_enabled() def set_content_filter(self, filter_expression: str, expression_parameters: list[str]) -> None: """ Set the filter expression and expression parameters for the subscription. :param filter_expression: The filter expression to set. :param expression_parameters: The expression parameters to set. :raises: RCLError if internal error occurred when calling the rcl function. """ with self.handle: self.__subscription.set_content_filter(filter_expression, expression_parameters) def get_content_filter(self) -> ContentFilterOptions: """ Get the filter expression and expression parameters for the subscription. :return: ContentFilterOptions object containing the filter expression and expression parameters. :raises: RCLError if internal error occurred when calling the rcl function. """ with self.handle: return self.__subscription.get_content_filter() def __enter__(self) -> 'Subscription[MsgT]': return self def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: self.destroy()
# Copyright 2020 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time from typing import List from typing import Optional from unittest.mock import Mock import pytest import rclpy from rclpy.node import Node from rclpy.subscription import Subscription from rclpy.subscription_content_filter_options import ContentFilterOptions from test_msgs.msg import BasicTypes from test_msgs.msg import Empty NODE_NAME = 'test_node' @pytest.fixture(scope='session', autouse=True) def setup_ros() -> None: rclpy.init() @pytest.fixture def test_node(): node = Node(NODE_NAME) yield node node.destroy_node() @pytest.mark.parametrize('topic_name, namespace, expected', [ # No namespaces ('topic', None, '/topic'), ('example/topic', None, '/example/topic'), # Using topics with namespaces ('topic', 'ns', '/ns/topic'), ('example/topic', 'ns', '/ns/example/topic'), ('example/topic', 'my/ns', '/my/ns/example/topic'), ('example/topic', '/my/ns', '/my/ns/example/topic'), # Global topics ('/topic', 'ns', '/topic'), ('/example/topic', 'ns', '/example/topic'), ]) def test_get_subscription_topic_name(topic_name: str, namespace: Optional[str], expected: str) -> None: node = Node('node_name', namespace=namespace, cli_args=None) sub = node.create_subscription( msg_type=Empty, topic=topic_name, callback=lambda _: None, qos_profile=10, ) assert sub.topic_name == expected sub.destroy() node.destroy_node() def test_logger_name_is_equal_to_node_name(test_node): sub = test_node.create_subscription( msg_type=Empty, topic='topic', callback=lambda _: None, qos_profile=10, ) assert sub.logger_name == NODE_NAME @pytest.mark.parametrize('topic_name, namespace, cli_args, expected', [ ('topic', None, ['--ros-args', '--remap', 'topic:=new_topic'], '/new_topic'), ('topic', 'ns', ['--ros-args', '--remap', 'topic:=new_topic'], '/ns/new_topic'), ('topic', 'ns', ['--ros-args', '--remap', 'topic:=example/new_topic'], '/ns/example/new_topic'), ('example/topic', 'ns', ['--ros-args', '--remap', 'example/topic:=new_topic'], '/ns/new_topic'), ]) def test_get_subscription_topic_name_after_remapping(topic_name: str, namespace: Optional[str], cli_args: List[str], expected: str) -> None: node = Node('node_name', namespace=namespace, cli_args=cli_args) sub = node.create_subscription( msg_type=Empty, topic=topic_name, callback=lambda _: None, qos_profile=10, ) assert sub.topic_name == expected sub.destroy() node.destroy_node() def test_subscription_callback_type() -> None: node = Node('test_node', namespace='test_subscription/test_subscription_callback_type') sub = node.create_subscription( msg_type=Empty, topic='test_subscription/test_subscription_callback_type/topic', qos_profile=10, callback=lambda _: None) assert sub._callback_type == Subscription.CallbackType.MessageOnly sub.destroy() sub = node.create_subscription( msg_type=Empty, topic='test_subscription/test_subscription_callback_type/topic', qos_profile=10, callback=lambda _, _2: None) assert sub._callback_type == Subscription.CallbackType.WithMessageInfo sub.destroy() with pytest.raises(RuntimeError): node.create_subscription( msg_type=Empty, topic='test_subscription/test_subscription_callback_type/topic', qos_profile=10, callback=lambda _, _2, _3: None) # type: ignore[arg-type] node.destroy_node() def test_subscription_context_manager() -> None: node = Node('test_node', namespace='test_subscription/test_subscription_callback_type') with node.create_subscription( msg_type=Empty, topic='test_subscription/test_subscription_callback_type/topic', qos_profile=10, callback=lambda _: None) as sub: assert sub._callback_type == Subscription.CallbackType.MessageOnly with node.create_subscription( msg_type=Empty, topic='test_subscription/test_subscription_callback_type/topic', qos_profile=10, callback=lambda _, _2: None) as sub: assert sub._callback_type == Subscription.CallbackType.WithMessageInfo node.destroy_node() def test_subscription_publisher_count() -> None: topic_name = 'test_subscription/test_subscription_publisher_count/topic' node = Node('test_node', namespace='test_subscription/test_subscription_publisher_count') sub = node.create_subscription( msg_type=Empty, topic=topic_name, qos_profile=10, callback=lambda _: None) assert sub.get_publisher_count() == 0 pub = node.create_publisher(Empty, topic_name, 10) max_seconds_to_wait = 5 end_time = time.time() + max_seconds_to_wait while sub.get_publisher_count() != 1: time.sleep(0.05) assert time.time() <= end_time # timeout waiting for pub/sub to discover each other assert sub.get_publisher_count() == 1 pub.destroy() sub.destroy() node.destroy_node() def test_on_new_message_callback(test_node) -> None: topic_name = '/topic' cb = Mock() sub = test_node.create_subscription( msg_type=Empty, topic=topic_name, qos_profile=10, callback=cb) pub = test_node.create_publisher(Empty, topic_name, 10) sub.handle.set_on_new_message_callback(cb) cb.assert_not_called() pub.publish(Empty()) cb.assert_called_once_with(1) sub.handle.clear_on_new_message_callback() pub.publish(Empty()) cb.assert_called_once() def test_subscription_set_content_filter(test_node) -> None: if rclpy.get_rmw_implementation_identifier() != 'rmw_fastrtps_cpp' and \ rclpy.get_rmw_implementation_identifier() != 'rmw_connextdds': pytest.skip('Content filter is now only supported in FastDDS and ConnextDDS.') topic_name = '/topic' sub = test_node.create_subscription( msg_type=BasicTypes, topic=topic_name, qos_profile=10, callback=lambda _: None) filter_expression = 'int32_value > %0' expression_parameters: List[str] = ['10'] # There should not be any exceptions. try: sub.set_content_filter( filter_expression, expression_parameters ) except Exception as e: pytest.fail(f'Unexpected exception raised: {e}') sub.destroy() def test_subscription_is_cft_enabled(test_node) -> None: if rclpy.get_rmw_implementation_identifier() != 'rmw_fastrtps_cpp' and \ rclpy.get_rmw_implementation_identifier() != 'rmw_connextdds': pytest.skip('Content filter is now only supported in FastDDS and Connext DDS.') topic_name = '/topic' sub = test_node.create_subscription( msg_type=BasicTypes, topic=topic_name, qos_profile=10, callback=lambda _: None) sub.set_content_filter( filter_expression='bool_value = %0', expression_parameters=['TRUE'] ) # There should not be any exceptions. try: _ = sub.is_cft_enabled except Exception as e: pytest.fail(f'Unexpected exception raised: {e}') sub.destroy() def test_subscription_get_content_filter(test_node) -> None: if rclpy.get_rmw_implementation_identifier() != 'rmw_fastrtps_cpp' and \ rclpy.get_rmw_implementation_identifier() != 'rmw_connextdds': pytest.skip('Content filter is now only supported in FastDDS and ConnextDDS.') topic_name = '/topic' sub = test_node.create_subscription( msg_type=BasicTypes, topic=topic_name, qos_profile=10, callback=lambda _: None) assert sub.is_cft_enabled is False filter_expression = 'int32_value > %0' expression_parameters: List[str] = ['60'] sub.set_content_filter( filter_expression, expression_parameters ) assert sub.is_cft_enabled is True cf_option = sub.get_content_filter() assert cf_option.filter_expression == filter_expression assert len(cf_option.expression_parameters) == len(expression_parameters) assert cf_option.expression_parameters[0] == expression_parameters[0] sub.destroy() def test_subscription_content_filter_effect(test_node) -> None: if rclpy.get_rmw_implementation_identifier() != 'rmw_fastrtps_cpp' and \ rclpy.get_rmw_implementation_identifier() != 'rmw_connextdds': pytest.skip('Content filter is now only supported in FastDDS and ConnextDDS.') topic_name = '/topic' pub = test_node.create_publisher(BasicTypes, topic_name, 10) received_msgs = [] def sub_callback(msg): received_msgs.append(msg.int32_value) sub = test_node.create_subscription( msg_type=BasicTypes, topic=topic_name, qos_profile=10, callback=sub_callback) assert sub.is_cft_enabled is False def wait_msgs(timeout, expected_msg_count): end_time = time.time() + timeout while rclpy.ok() and time.time() < end_time and len(received_msgs) < expected_msg_count: rclpy.spin_once(test_node, timeout_sec=0.2) # Publish 3 messages def publish_messages(pub): msg = BasicTypes() msg.int32_value = 10 pub.publish(msg) msg.int32_value = 20 pub.publish(msg) msg.int32_value = 30 pub.publish(msg) # Publish messages and them should be all received. publish_messages(pub) # Check within 2 seconds whether the desired number of messages has been received. expected_msg_count = 3 wait_msgs(timeout=2.0, expected_msg_count=expected_msg_count) assert len(received_msgs) == expected_msg_count # Set content filter to filter out messages with int32_value <= 15 sub.set_content_filter( filter_expression='int32_value > %0', expression_parameters=['15'] ) assert sub.is_cft_enabled is True received_msgs = [] # Publish messages again and part of messages should be received. publish_messages(pub) # Check within 2 seconds whether the desired number of messages has been received. expected_msg_count = 2 wait_msgs(timeout=2.0, expected_msg_count=expected_msg_count) assert len(received_msgs) == expected_msg_count assert received_msgs[0] == 20 assert received_msgs[1] == 30 pub.destroy() sub.destroy() def test_subscription_content_filter_reset(test_node) -> None: if rclpy.get_rmw_implementation_identifier() != 'rmw_fastrtps_cpp' and \ rclpy.get_rmw_implementation_identifier() != 'rmw_connextdds': pytest.skip('Content filter is now only supported in FastDDS and ConnextDDS.') topic_name = '/topic' pub = test_node.create_publisher(BasicTypes, topic_name, 10) received_msgs = [] def sub_callback(msg): received_msgs.append(msg.int32_value) sub = test_node.create_subscription( msg_type=BasicTypes, topic=topic_name, qos_profile=10, callback=sub_callback) # Set content filter to filter out messages with int32_value <= 15 sub.set_content_filter( filter_expression='int32_value > %0', expression_parameters=['15'] ) assert sub.is_cft_enabled is True def wait_msgs(timeout, expected_msg_count): end_time = time.time() + timeout while rclpy.ok() and time.time() < end_time and len(received_msgs) < expected_msg_count: rclpy.spin_once(test_node, timeout_sec=0.2) # Publish 3 messages def publish_messages(pub): msg = BasicTypes() msg.int32_value = 10 pub.publish(msg) msg.int32_value = 20 pub.publish(msg) msg.int32_value = 30 pub.publish(msg) publish_messages(pub) expected_msg_count = 2 wait_msgs(timeout=2.0, expected_msg_count=expected_msg_count) assert len(received_msgs) == expected_msg_count received_msgs = [] # Reset content filter sub.set_content_filter( filter_expression='', expression_parameters=[] ) assert sub.is_cft_enabled is False publish_messages(pub) expected_msg_count = 3 wait_msgs(timeout=2.0, expected_msg_count=expected_msg_count) assert len(received_msgs) == expected_msg_count def test_subscription_content_filter_at_create_subscription(test_node) -> None: if rclpy.get_rmw_implementation_identifier() != 'rmw_fastrtps_cpp' and \ rclpy.get_rmw_implementation_identifier() != 'rmw_connextdds': pytest.skip('Content filter is now only supported in FastDDS and ConnextDDS.') topic_name = '/topic' pub = test_node.create_publisher(BasicTypes, topic_name, 10) received_msgs = [] content_filter_options = ContentFilterOptions( filter_expression='int32_value > %0', expression_parameters=['15']) def sub_callback(msg): received_msgs.append(msg.int32_value) sub = test_node.create_subscription( msg_type=BasicTypes, topic=topic_name, qos_profile=10, callback=sub_callback, content_filter_options=content_filter_options) assert sub.is_cft_enabled is True def wait_msgs(timeout, expected_msg_count): end_time = time.time() + timeout while rclpy.ok() and time.time() < end_time and len(received_msgs) < expected_msg_count: rclpy.spin_once(test_node, timeout_sec=0.2) # Publish 3 messages def publish_messages(pub): msg = BasicTypes() msg.int32_value = 10 pub.publish(msg) msg.int32_value = 20 pub.publish(msg) msg.int32_value = 30 pub.publish(msg) # Publish messages and part of messages should be received. publish_messages(pub) # Check within 2 seconds whether the desired number of messages has been received. expected_msg_count = 2 wait_msgs(timeout=2.0, expected_msg_count=expected_msg_count) assert len(received_msgs) == expected_msg_count assert received_msgs[0] == 20 assert received_msgs[1] == 30 pub.destroy() sub.destroy()
rclpy
python
# Copyright 2023 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional, TYPE_CHECKING import weakref from rcl_interfaces.msg import ParameterDescriptor from rcl_interfaces.msg import ParameterType from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy from rclpy.parameter import Parameter from rclpy.qos import qos_profile_services_default from rclpy.service import Service from rclpy.type_support import check_is_valid_srv_type from rclpy.validate_topic_name import TOPIC_SEPARATOR_STRING from type_description_interfaces.srv import GetTypeDescription START_TYPE_DESCRIPTION_SERVICE_PARAM = 'start_type_description_service' if TYPE_CHECKING: from rclpy.node import Node class TypeDescriptionService: """ Optionally initializes and contains the ~/get_type_description service. The service is implemented in rcl, but should be enabled via parameter and have its callbacks handled via end-client execution framework, such as callback groups and waitsets. This is not intended for use by end users, rather it is a component to be used by Node. """ def __init__(self, node: 'Node'): """Initialize the service, if the parameter is set to true.""" self._node_weak_ref = weakref.ref(node) node_name = node.get_name() self.service_name = TOPIC_SEPARATOR_STRING.join((node_name, 'get_type_description')) self._type_description_srv: Optional[_rclpy.TypeDescriptionService] = None self.enabled = False if not node.has_parameter(START_TYPE_DESCRIPTION_SERVICE_PARAM): descriptor = ParameterDescriptor( name=START_TYPE_DESCRIPTION_SERVICE_PARAM, type=ParameterType.PARAMETER_BOOL, description='If enabled, start the ~/get_type_description service.', read_only=True) node.declare_parameter( START_TYPE_DESCRIPTION_SERVICE_PARAM, True, descriptor) param = node.get_parameter(START_TYPE_DESCRIPTION_SERVICE_PARAM) if param.type_ != Parameter.Type.NOT_SET: if param.type_ == Parameter.Type.BOOL: self.enabled = param.value else: node.get_logger().error( "Invalid type for parameter '{}' {!r} should be bool" .format(START_TYPE_DESCRIPTION_SERVICE_PARAM, param.type_)) else: node.get_logger().debug( 'Parameter {} not set, defaulting to true.' .format(START_TYPE_DESCRIPTION_SERVICE_PARAM)) if self.enabled: self._start_service() def destroy(self) -> None: # Required manual destruction because this is not managed by rclpy.Service if self._type_description_srv is not None: self._type_description_srv.destroy_when_not_in_use() self._type_description_srv = None def _start_service(self) -> None: node = self._get_node() self._type_description_srv = _rclpy.TypeDescriptionService(node.handle) # Because we are creating our own service wrapper, must manually add the service # to the appropriate parts of Node because we cannot call create_service. check_is_valid_srv_type(GetTypeDescription) service = Service( service_impl=self._type_description_srv.impl, srv_type=GetTypeDescription, srv_name=self.service_name, callback=self._service_callback, callback_group=node.default_callback_group, qos_profile=qos_profile_services_default) node.default_callback_group.add_entity(service) node._services.append(service) node._wake_executor() def _service_callback( self, request: GetTypeDescription.Request, response: GetTypeDescription.Response ) -> GetTypeDescription.Response: if self._type_description_srv is None: raise RuntimeError('Cannot handle request if TypeDescriptionService is None.') return self._type_description_srv.handle_request( request, GetTypeDescription.Response, self._get_node().handle) def _get_node(self) -> 'Node': node = self._node_weak_ref() if node is None: raise ReferenceError('Expected valid node weak reference') return node
# Copyright 2023 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import rclpy from rclpy.client import Client import rclpy.context from rclpy.executors import SingleThreadedExecutor from rclpy.qos import qos_profile_services_default from test_msgs.msg import BasicTypes from type_description_interfaces.srv import GetTypeDescription class TestTypeDescriptionService(unittest.TestCase): def setUp(self) -> None: self.context = rclpy.context.Context() rclpy.init(context=self.context) self.test_node = rclpy.create_node( 'test_type_description_service', namespace='/rclpy', context=self.context) self.test_topic = '/rclpy/basic_types' self.test_pub = self.test_node.create_publisher( BasicTypes, self.test_topic, 10) self.get_type_description_client: Client[GetTypeDescription.Request, GetTypeDescription.Response] = \ self.test_node.create_client( GetTypeDescription, '/rclpy/test_parameter_service/get_type_description', qos_profile=qos_profile_services_default) self.executor = SingleThreadedExecutor(context=self.context) self.executor.add_node(self.test_node) def tearDown(self) -> None: self.executor.shutdown() self.test_node.destroy_node() rclpy.shutdown(context=self.context) def test_get_type_description(self) -> None: pub_infos = self.test_node.get_publishers_info_by_topic(self.test_topic) assert len(pub_infos) type_hash = pub_infos[0].topic_type_hash request = GetTypeDescription.Request( type_name='test_msgs/msg/BasicTypes', type_hash=type_hash, include_type_sources=True) future = self.get_type_description_client.call_async(request) self.executor.spin_until_future_complete(future) response = future.result() assert response is not None assert response.successful assert response.type_description.type_description.type_name == 'test_msgs/msg/BasicTypes' assert len(response.type_sources)
rclpy
python
# Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING import weakref from rcl_interfaces.msg import ListParametersResult from rcl_interfaces.msg import SetParametersResult from rcl_interfaces.srv import DescribeParameters, GetParameters, GetParameterTypes from rcl_interfaces.srv import ListParameters, SetParameters, SetParametersAtomically from rclpy.exceptions import ParameterNotDeclaredException, ParameterUninitializedException from rclpy.parameter import Parameter from rclpy.qos import qos_profile_parameters from rclpy.validate_topic_name import TOPIC_SEPARATOR_STRING if TYPE_CHECKING: from rclpy.node import Node class ParameterService: def __init__(self, node: 'Node'): self._node_weak_ref = weakref.ref(node) nodename = node.get_name() describe_parameters_service_name = \ TOPIC_SEPARATOR_STRING.join((nodename, 'describe_parameters')) node.create_service( DescribeParameters, describe_parameters_service_name, self._describe_parameters_callback, qos_profile=qos_profile_parameters ) get_parameters_service_name = TOPIC_SEPARATOR_STRING.join((nodename, 'get_parameters')) node.create_service( GetParameters, get_parameters_service_name, self._get_parameters_callback, qos_profile=qos_profile_parameters ) get_parameter_types_service_name = \ TOPIC_SEPARATOR_STRING.join((nodename, 'get_parameter_types')) node.create_service( GetParameterTypes, get_parameter_types_service_name, self._get_parameter_types_callback, qos_profile=qos_profile_parameters ) list_parameters_service_name = TOPIC_SEPARATOR_STRING.join((nodename, 'list_parameters')) node.create_service( ListParameters, list_parameters_service_name, self._list_parameters_callback, qos_profile=qos_profile_parameters ) set_parameters_service_name = TOPIC_SEPARATOR_STRING.join((nodename, 'set_parameters')) node.create_service( SetParameters, set_parameters_service_name, self._set_parameters_callback, qos_profile=qos_profile_parameters ) set_parameters_atomically_service_name = \ TOPIC_SEPARATOR_STRING.join((nodename, 'set_parameters_atomically')) node.create_service( SetParametersAtomically, set_parameters_atomically_service_name, self._set_parameters_atomically_callback, qos_profile=qos_profile_parameters ) def _describe_parameters_callback( self, request: DescribeParameters.Request, response: DescribeParameters.Response ) -> DescribeParameters.Response: node = self._get_node() for name in request.names: try: descriptor = node.describe_parameter(name) except ParameterNotDeclaredException: response.descriptors = node.describe_parameters([]) return response response.descriptors.append(descriptor) return response def _get_parameters_callback( self, request: GetParameters.Request, response: GetParameters.Response ) -> GetParameters.Response: node = self._get_node() for name in request.names: try: param = node.get_parameter(name) except (ParameterNotDeclaredException, ParameterUninitializedException): response.values = node.get_parameters([]) return response response.values.append(param.get_parameter_value()) return response def _get_parameter_types_callback( self, request: GetParameterTypes.Request, response: GetParameterTypes.Response ) -> GetParameterTypes.Response: node = self._get_node() for name in request.names: try: value = node.get_parameter_type(name) except ParameterNotDeclaredException: response.types = node.get_parameter_types([]) return response response.types.append(value) return response def _list_parameters_callback( self, request: ListParameters.Request, response: ListParameters.Response ) -> ListParameters.Response: node = self._get_node() try: response.result = node.list_parameters(request.prefixes, request.depth) except (TypeError, ValueError): response.result = ListParametersResult() return response def _set_parameters_callback( self, request: SetParameters.Request, response: SetParameters.Response ) -> SetParameters.Response: node = self._get_node() for p in request.parameters: param = Parameter.from_parameter_msg(p) try: result = node.set_parameters_atomically([param]) except ParameterNotDeclaredException as e: result = SetParametersResult( successful=False, reason=str(e) ) response.results.append(result) return response def _set_parameters_atomically_callback( self, request: SetParametersAtomically.Request, response: SetParametersAtomically.Response ) -> SetParametersAtomically.Response: node = self._get_node() try: response.result = node.set_parameters_atomically([ Parameter.from_parameter_msg(p) for p in request.parameters]) except ParameterNotDeclaredException as e: response.result = SetParametersResult( successful=False, reason=str(e) ) return response def _get_node(self) -> 'Node': node = self._node_weak_ref() if node is None: raise ReferenceError('Expected valid node weak reference') return node
# Copyright 2022 Sony Group Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from rcl_interfaces.msg import ParameterType from rcl_interfaces.srv import DescribeParameters from rcl_interfaces.srv import GetParameters import rclpy from rclpy.client import Client import rclpy.context from rclpy.executors import SingleThreadedExecutor from rclpy.parameter import Parameter from rclpy.qos import qos_profile_services_default class TestParameterService(unittest.TestCase): def setUp(self) -> None: self.context = rclpy.context.Context() rclpy.init(context=self.context) self.test_node = rclpy.create_node( 'test_parameter_service', namespace='/rclpy', context=self.context) self.get_parameter_client: Client[GetParameters.Request, GetParameters.Response] = self.test_node.create_client( GetParameters, '/rclpy/test_parameter_service/get_parameters', qos_profile=qos_profile_services_default ) self.describe_parameters_client: Client[DescribeParameters.Response, DescribeParameters.Response] = \ self.test_node.create_client( DescribeParameters, '/rclpy/test_parameter_service/describe_parameters', qos_profile=qos_profile_services_default) self.executor = SingleThreadedExecutor(context=self.context) self.executor.add_node(self.test_node) def tearDown(self) -> None: self.executor.shutdown() self.test_node.destroy_node() rclpy.shutdown(context=self.context) def test_get_uninitialized_parameter(self) -> None: self.test_node.declare_parameter('uninitialized_parameter', Parameter.Type.STRING) # The type in description should be STRING request = DescribeParameters.Request() request.names = ['uninitialized_parameter'] future = self.describe_parameters_client.call_async(request) self.executor.spin_until_future_complete(future) results = future.result() assert results is not None assert len(results.descriptors) == 1 assert results.descriptors[0].type == ParameterType.PARAMETER_STRING assert results.descriptors[0].name == 'uninitialized_parameter' # The value should be empty request = GetParameters.Request() request.names = ['uninitialized_parameter'] future = self.get_parameter_client.call_async(request) self.executor.spin_until_future_complete(future) results = future.result() assert results is not None assert results.values == [] if __name__ == '__main__': unittest.main()
rclpy
python
# Copyright 2020 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Any from typing import Callable from typing import Iterable from typing import List from typing import Optional from typing import Text from typing import Type from typing import TYPE_CHECKING from typing import Union from rcl_interfaces.msg import ParameterDescriptor from rcl_interfaces.msg import SetParametersResult import rclpy from rclpy.duration import Duration from rclpy.exceptions import ParameterAlreadyDeclaredException from rclpy.parameter import Parameter from rclpy.publisher import Publisher from rclpy.qos import QoSDurabilityPolicy from rclpy.qos import QoSHistoryPolicy from rclpy.qos import QoSLivelinessPolicy from rclpy.qos import QoSPolicyKind from rclpy.qos import QoSProfile from rclpy.qos import QoSReliabilityPolicy from rclpy.subscription import Subscription from typing_extensions import TypeAlias if TYPE_CHECKING: from rclpy.node import Node class InvalidQosOverridesError(Exception): pass # Return type of qos validation callbacks QosCallbackResult: TypeAlias = SetParametersResult # Qos callback type annotation QosCallbackType = Callable[[QoSProfile], QosCallbackResult] class QoSOverridingOptions: """Options to customize QoS parameter overrides.""" def __init__( self, policy_kinds: Iterable[QoSPolicyKind], *, callback: Optional[QosCallbackType] = None, entity_id: Optional[Text] = None ): """ Construct a QoSOverridingOptions object. :param policy_kinds: QoS kinds that will have a declared parameter. :param callback: Callback that will be used to validate the QoS profile after the paramter overrides get applied. :param entity_id: Optional identifier, to disambiguate in the case that different QoS policies for the same topic are desired. """ self._policy_kinds = policy_kinds self._callback = callback self._entity_id = entity_id @property def policy_kinds(self) -> Iterable[QoSPolicyKind]: """Get QoS policy kinds that will have a parameter override.""" return self._policy_kinds @property def callback(self) -> Optional[QosCallbackType]: """Get the validation callback.""" return self._callback @property def entity_id(self) -> Optional[Text]: """Get the optional entity ID.""" return self._entity_id @classmethod def with_default_policies( cls, *, callback: Optional[QosCallbackType] = None, entity_id: Optional[Text] = None ) -> 'QoSOverridingOptions': return cls( policy_kinds=(QoSPolicyKind.HISTORY, QoSPolicyKind.DEPTH, QoSPolicyKind.RELIABILITY), callback=callback, entity_id=entity_id, ) def _declare_qos_parameters( entity_type: Union[Type[Publisher[Any]], Type[Subscription[Any]]], node: 'Node', topic_name: Text, qos: QoSProfile, options: QoSOverridingOptions ) -> None: """ Declare QoS parameters for a Publisher or a Subscription. :param entity_type: Either `rclpy.node.Publisher` or `rclpy.node.Subscription`. :param node: Node used to declare the parameters. :param topic_name: Topic name of the entity being created. :param qos: Default QoS settings of the entity being created, that will be overridden with the user provided QoS parameter overrides. :param options: Options that indicates which parameters are going to be declared. """ if not issubclass(entity_type, (Publisher, Subscription)): raise TypeError('Argument `entity_type` should be a subclass of Publisher or Subscription') entity_type_str = 'publisher' if issubclass(entity_type, Publisher) else 'subscription' id_suffix = '' if options.entity_id is None else f'_{options.entity_id}' name = f'qos_overrides.{topic_name}.{entity_type_str}{id_suffix}.' '{}' description = '{}' f' for {entity_type_str} `{topic_name}` with id `{options.entity_id}`' allowed_policies = _get_allowed_policies(entity_type) for policy in options.policy_kinds: if policy not in allowed_policies: continue policy_name = policy.name.lower() descriptor = ParameterDescriptor() descriptor.description = description.format(policy_name) descriptor.read_only = True try: param: Parameter[Any] = node.declare_parameter( name.format(policy_name), _get_qos_policy_parameter(qos, policy), descriptor) except ParameterAlreadyDeclaredException: param = node.get_parameter(name.format(policy_name)) _override_qos_policy_with_param(qos, policy, param) if options.callback is not None: result = options.callback(qos) if not result.successful: raise InvalidQosOverridesError( f"{description.format('Provided QoS overrides')}, are not valid: {result.reason}") def _get_allowed_policies(entity_type: Union[Type[Publisher[Any]], Type[Subscription[Any]]]) -> List[QoSPolicyKind]: allowed_policies = list(QoSPolicyKind.__members__.values()) if issubclass(entity_type, Subscription): allowed_policies.remove(QoSPolicyKind.LIFESPAN) return allowed_policies QoSProfileAttributes = Union[QoSHistoryPolicy, int, QoSReliabilityPolicy, QoSDurabilityPolicy, Duration, QoSLivelinessPolicy, bool] def _get_qos_policy_parameter(qos: QoSProfile, policy: QoSPolicyKind) -> Union[str, int, bool]: value: QoSProfileAttributes = getattr(qos, policy.name.lower()) if isinstance(value, (QoSHistoryPolicy, QoSReliabilityPolicy, QoSDurabilityPolicy, QoSLivelinessPolicy)): return_value: Union[str, int, bool] = value.name.lower() if return_value == 'unknown': raise ValueError('User provided QoS profile is invalid') elif isinstance(value, Duration): return_value = value.nanoseconds else: return_value = value return return_value def _override_qos_policy_with_param(qos: QoSProfile, policy: QoSPolicyKind, param: Parameter[Any]) -> None: value = param.value policy_name = policy.name.lower() if policy in ( QoSPolicyKind.LIVELINESS, QoSPolicyKind.RELIABILITY, QoSPolicyKind.HISTORY, QoSPolicyKind.DURABILITY ): def capitalize_first_letter(x: str) -> str: return x[0].upper() + x[1:] # e.g. `policy=QosPolicyKind.LIVELINESS` -> `policy_enum_class=rclpy.qos.LivelinessPolicy` policy_enum_class = getattr( rclpy.qos, f'{capitalize_first_letter(policy_name)}Policy') try: value = policy_enum_class[value.upper()] except KeyError: raise RuntimeError( f'Unexpected QoS override for policy `{policy.name.lower()}`: `{value}`') if policy in ( QoSPolicyKind.LIFESPAN, QoSPolicyKind.DEADLINE, QoSPolicyKind.LIVELINESS_LEASE_DURATION ): value = Duration(nanoseconds=value) setattr(qos, policy.name.lower(), value)
# Copyright 2020 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Generator import pytest import rclpy from rclpy.duration import Duration from rclpy.node import Node from rclpy.parameter import Parameter from rclpy.publisher import Publisher from rclpy.qos import QoSDurabilityPolicy from rclpy.qos import QoSHistoryPolicy from rclpy.qos import QoSLivelinessPolicy from rclpy.qos import QoSPolicyKind from rclpy.qos import QoSProfile from rclpy.qos import QoSReliabilityPolicy from rclpy.qos_overriding_options import _declare_qos_parameters from rclpy.qos_overriding_options import _get_qos_policy_parameter from rclpy.qos_overriding_options import InvalidQosOverridesError from rclpy.qos_overriding_options import QosCallbackResult from rclpy.qos_overriding_options import QoSOverridingOptions @pytest.fixture(autouse=True) def init_shutdown() -> Generator[None, None, None]: rclpy.init() yield rclpy.shutdown() def test_get_qos_policy_parameter() -> None: qos = QoSProfile( history=QoSHistoryPolicy.KEEP_LAST, depth=10, reliability=QoSReliabilityPolicy.RELIABLE, durability=QoSDurabilityPolicy.VOLATILE, lifespan=Duration(nanoseconds=1e3), deadline=Duration(nanoseconds=1e6), liveliness=QoSLivelinessPolicy.SYSTEM_DEFAULT, liveliness_lease_duration=Duration(nanoseconds=1e9) ) value = _get_qos_policy_parameter(qos, QoSPolicyKind.HISTORY) assert value == 'keep_last' value = _get_qos_policy_parameter(qos, QoSPolicyKind.DEPTH) assert value == qos.depth value = _get_qos_policy_parameter(qos, QoSPolicyKind.RELIABILITY) assert value == 'reliable' value = _get_qos_policy_parameter(qos, QoSPolicyKind.DURABILITY) assert value == 'volatile' value = _get_qos_policy_parameter(qos, QoSPolicyKind.LIFESPAN) assert value == qos.lifespan.nanoseconds value = _get_qos_policy_parameter(qos, QoSPolicyKind.DEADLINE) assert value == qos.deadline.nanoseconds value = _get_qos_policy_parameter(qos, QoSPolicyKind.LIVELINESS) assert value == 'system_default' value = _get_qos_policy_parameter(qos, QoSPolicyKind.LIVELINESS_LEASE_DURATION) assert value == qos.liveliness_lease_duration.nanoseconds def test_declare_qos_parameters() -> None: node = Node('my_node') _declare_qos_parameters( Publisher, node, '/my_topic', QoSProfile(depth=10), QoSOverridingOptions.with_default_policies() ) qos_overrides = node.get_parameters_by_prefix('qos_overrides') assert len(qos_overrides) == 3 expected_params = ( ('/my_topic.publisher.depth', 10), ('/my_topic.publisher.history', 'keep_last'), ('/my_topic.publisher.reliability', 'reliable'), ) for actual, expected in zip( sorted(qos_overrides.items(), key=lambda x: x[0]), expected_params ): assert actual[0] == expected[0] # same param name assert actual[1].value == expected[1] # same param value def test_declare_qos_parameters_with_overrides() -> None: node = Node('my_node', parameter_overrides=[ Parameter('qos_overrides./my_topic.publisher.depth', value=100), Parameter('qos_overrides./my_topic.publisher.reliability', value='best_effort'), ]) for i in range(2): # try twice, the second time the parameters will be get and not declared _declare_qos_parameters( Publisher, node, '/my_topic', QoSProfile(depth=10), QoSOverridingOptions.with_default_policies() ) qos_overrides = node.get_parameters_by_prefix('qos_overrides') assert len(qos_overrides) == 3 expected_params = ( ('/my_topic.publisher.depth', 100), ('/my_topic.publisher.history', 'keep_last'), ('/my_topic.publisher.reliability', 'best_effort'), ) for actual, expected in zip( sorted(qos_overrides.items(), key=lambda x: x[0]), expected_params ): assert actual[0] == expected[0] # same param name assert actual[1].value == expected[1] # same param value def test_declare_qos_parameters_with_happy_callback() -> None: def qos_validation_callback(qos: QoSProfile) -> QosCallbackResult: result = QosCallbackResult() result.successful = True return result node = Node('my_node') _declare_qos_parameters( Publisher, node, '/my_topic', QoSProfile(depth=10), QoSOverridingOptions.with_default_policies(callback=qos_validation_callback) ) qos_overrides = node.get_parameters_by_prefix('qos_overrides') assert len(qos_overrides) == 3 expected_params = ( ('/my_topic.publisher.depth', 10), ('/my_topic.publisher.history', 'keep_last'), ('/my_topic.publisher.reliability', 'reliable'), ) for actual, expected in zip( sorted(qos_overrides.items(), key=lambda x: x[0]), expected_params ): assert actual[0] == expected[0] # same param name assert actual[1].value == expected[1] # same param value def test_declare_qos_parameters_with_unhappy_callback() -> None: def qos_validation_callback(qos: QoSProfile) -> QosCallbackResult: result = QosCallbackResult() result.successful = False result.reason = 'my_custom_error_message' return result node = Node('my_node') with pytest.raises(InvalidQosOverridesError) as err: _declare_qos_parameters( Publisher, node, '/my_topic', QoSProfile(depth=10), QoSOverridingOptions.with_default_policies(callback=qos_validation_callback) ) assert 'my_custom_error_message' in str(err.value) def test_declare_qos_parameters_with_id() -> None: node = Node('my_node') _declare_qos_parameters( Publisher, node, '/my_topic', QoSProfile(depth=10), QoSOverridingOptions.with_default_policies(entity_id='i_have_an_id') ) qos_overrides = node.get_parameters_by_prefix('qos_overrides') assert len(qos_overrides) == 3 expected_params = ( ('/my_topic.publisher_i_have_an_id.depth', 10), ('/my_topic.publisher_i_have_an_id.history', 'keep_last'), ('/my_topic.publisher_i_have_an_id.reliability', 'reliable'), ) for actual, expected in zip( sorted(qos_overrides.items(), key=lambda x: x[0]), expected_params ): assert actual[0] == expected[0] # same param name assert actual[1].value == expected[1] # same param value
rclpy
python
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy def expand_topic_name(topic_name: str, node_name: str, node_namespace: str) -> str: """ Expand a given topic name using given node name and namespace as well. Note that this function can succeed but the expanded topic name may still be invalid. The :py:func:validate_full_topic_name(): should be used on the expanded topic name to ensure it is valid after expansion. :param topic_name: topic name to be expanded :param node_name: name of the node that this topic is associated with :param namespace: namespace that the topic is within :returns: expanded topic name which is fully qualified :raises: ValueError if the topic name, node name or namespace are invalid """ return _rclpy.rclpy_expand_topic_name(topic_name, node_name, node_namespace)
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from rclpy.expand_topic_name import expand_topic_name class TestExpandTopicName(unittest.TestCase): def test_expand_topic_name(self) -> None: tests = { # 'expected output': ['input topic', 'node', '/ns'] '/ns/chatter': ['chatter', 'node_name', '/ns'], '/chatter': ['chatter', 'node_name', '/'], '/ns/node_name/chatter': ['~/chatter', 'node_name', '/ns'], '/node_name/chatter': ['~/chatter', 'node_name', '/'], } for expected_topic, input_tuple in tests.items(): topic, node, namespace = input_tuple expanded_topic = expand_topic_name(topic, node, namespace) self.assertEqual(expanded_topic, expected_topic) def test_expand_topic_name_invalid_node_name(self) -> None: # node name may not contain '?' with self.assertRaisesRegex(ValueError, 'node name'): expand_topic_name('topic', 'invalid_node_name?', '/ns') def test_expand_topic_name_invalid_namespace_empty(self) -> None: # namespace may not be empty with self.assertRaisesRegex(ValueError, 'namespace'): expand_topic_name('topic', 'node_name', '') def test_expand_topic_name_invalid_namespace_relative(self) -> None: # namespace may not be relative with self.assertRaisesRegex(ValueError, 'namespace'): expand_topic_name('topic', 'node_name', 'ns') def test_expand_topic_name_invalid_topic(self) -> None: # topic may not contain '?' with self.assertRaisesRegex(ValueError, 'topic name'): expand_topic_name('invalid/topic?', 'node_name', '/ns') if __name__ == '__main__': unittest.main()
rclpy
python
# Copyright 2020 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Type from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy from rclpy.type_support import check_for_type_support, Msg, MsgT def serialize_message(message: Msg) -> bytes: """ Serialize a ROS message. :param message: The ROS message to serialize. :return: The serialized bytes. """ message_type = type(message) # this line imports the typesupport for the message module if not already done check_for_type_support(message_type) return _rclpy.rclpy_serialize(message, message_type) def deserialize_message(serialized_message: bytes, message_type: Type[MsgT]) -> MsgT: """ Deserialize a ROS message. :param serialized_message: The ROS message to deserialize. :param message_type: The type of the serialized ROS message. :return: The deserialized ROS message. """ # this line imports the typesupport for the message module if not already done check_for_type_support(message_type) return _rclpy.rclpy_deserialize(serialized_message, message_type)
# Copyright 2020 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import List from typing import Type import pytest from rclpy.serialization import deserialize_message from rclpy.serialization import serialize_message from rclpy.type_support import Msg from test_msgs.message_fixtures import get_test_msg from test_msgs.msg import Arrays from test_msgs.msg import BasicTypes from test_msgs.msg import BoundedSequences from test_msgs.msg import Builtins from test_msgs.msg import Constants from test_msgs.msg import Defaults from test_msgs.msg import Empty from test_msgs.msg import MultiNested from test_msgs.msg import Nested from test_msgs.msg import Strings from test_msgs.msg import UnboundedSequences from test_msgs.msg import WStrings test_msgs = [ (get_test_msg('Arrays'), Arrays), (get_test_msg('BasicTypes'), BasicTypes), (get_test_msg('BoundedSequences'), BoundedSequences), (get_test_msg('Builtins'), Builtins), (get_test_msg('Constants'), Constants), (get_test_msg('Defaults'), Defaults), (get_test_msg('Empty'), Empty), (get_test_msg('MultiNested'), MultiNested), (get_test_msg('Nested'), Nested), (get_test_msg('Strings'), Strings), (get_test_msg('UnboundedSequences'), UnboundedSequences), (get_test_msg('WStrings'), WStrings), ] @pytest.mark.parametrize('msgs,msg_type', test_msgs) def test_serialize_deserialize(msgs: List[Msg], msg_type: Type[Msg]) -> None: """Test message serialization/deserialization.""" for msg in msgs: msg_serialized = serialize_message(msg) msg_deserialized = deserialize_message(msg_serialized, msg_type) assert msg == msg_deserialized def test_set_float32() -> None: """Test message serialization/deserialization of float32 type.""" # During (de)serialization we convert to a C float before converting to a PyObject. # This can result in a loss of precision msg = BasicTypes() msg.float32_value = 1.125 # can be represented without rounding msg_serialized = serialize_message(msg) msg_deserialized = deserialize_message(msg_serialized, BasicTypes) assert msg.float32_value == msg_deserialized.float32_value msg = BasicTypes() msg.float32_value = 3.14 # can NOT be represented without rounding msg_serialized = serialize_message(msg) msg_deserialized = deserialize_message(msg_serialized, BasicTypes) assert msg.float32_value == round(msg_deserialized.float32_value, 2)
rclpy
python
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from collections import deque from concurrent.futures import ThreadPoolExecutor from contextlib import ExitStack from dataclasses import dataclass from functools import partial import inspect import os from threading import Condition from threading import Lock from threading import RLock import time from types import TracebackType from typing import Any from typing import Callable from typing import ContextManager from typing import Coroutine from typing import Deque from typing import Dict from typing import Generator from typing import List from typing import Optional from typing import overload from typing import Set from typing import Tuple from typing import Type from typing import TYPE_CHECKING from typing import TypeVar from typing import Union import warnings from rclpy.client import Client from rclpy.clock import Clock from rclpy.clock_type import ClockType from rclpy.context import Context from rclpy.exceptions import InvalidHandle, TimerCancelledError from rclpy.guard_condition import GuardCondition from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy from rclpy.service import Service from rclpy.signals import SignalHandlerGuardCondition from rclpy.subscription import MessageInfo from rclpy.subscription import Subscription from rclpy.task import Future from rclpy.task import Task from rclpy.timer import Timer from rclpy.timer import TimerCallbackType from rclpy.timer import TimerInfo from rclpy.type_support import Msg from rclpy.utilities import get_default_context from rclpy.utilities import timeout_sec_to_nsec from rclpy.waitable import NumberOfEntities from rclpy.waitable import Waitable # For documentation purposes # TODO(jacobperron): Make all entities implement the 'Waitable' interface for better type checking T = TypeVar('T') # Avoid import cycle if TYPE_CHECKING: from typing import TypeAlias from rclpy.node import Node # noqa: F401 from .callback_groups import Entity EntityT = TypeVar('EntityT', bound=Entity) YieldedCallback: 'TypeAlias' = Generator[Tuple[Task[None], 'Optional[Entity]', 'Optional[Node]'], None, None] class _WorkTracker: """Track the amount of work that is in progress.""" def __init__(self) -> None: # Number of tasks that are being executed self._num_work_executing = 0 self._work_condition = Condition() def __enter__(self) -> None: """Increment the amount of executing work by 1.""" with self._work_condition: self._num_work_executing += 1 def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exctb: Optional[TracebackType]) -> None: """Decrement the amount of work executing by 1.""" with self._work_condition: self._num_work_executing -= 1 self._work_condition.notify_all() def wait(self, timeout_sec: Optional[float] = None) -> bool: """ Wait until all work completes. :param timeout_sec: Seconds to wait. Block forever if None or negative. Don't wait if 0 :type timeout_sec: float or None :rtype: bool True if all work completed """ if timeout_sec is not None and timeout_sec < 0.0: timeout_sec = None # Wait for all work to complete with self._work_condition: if not self._work_condition.wait_for( lambda: self._num_work_executing == 0, timeout_sec): return False return True @overload async def await_or_execute(callback: Callable[..., Coroutine[Any, Any, T]], *args: Any) -> T: ... @overload async def await_or_execute(callback: Callable[..., T], *args: Any) -> T: ... async def await_or_execute(callback: Callable[..., Any], *args: Any) -> Any: """Await a callback if it is a coroutine, else execute it.""" if inspect.iscoroutinefunction(callback): # Await a coroutine return await callback(*args) else: # Call a normal function return callback(*args) class TimeoutException(Exception): """Signal that a timeout occurred.""" pass class ShutdownException(Exception): """Signal that executor was shut down.""" pass class ExternalShutdownException(Exception): """Context has been shutdown.""" pass class ConditionReachedException(Exception): """Future has been completed.""" pass class TimeoutObject: """Use timeout object to save timeout.""" def __init__(self, timeout: float) -> None: self._timeout = timeout @property def timeout(self) -> float: return self._timeout @timeout.setter def timeout(self, timeout: float) -> None: self._timeout = timeout @dataclass class TaskData: source_node: 'Optional[Node]' = None source_entity: 'Optional[Entity]' = None class Executor(ContextManager['Executor']): """ The base class for an executor. An executor controls the threading model used to process callbacks. Callbacks are units of work like subscription callbacks, timer callbacks, service calls, and received client responses. An executor controls which threads callbacks get executed in. A custom executor must define :meth:`spin_once`. If the executor has any cleanup then it should also define :meth:`shutdown`. :param context: The context to be associated with, or ``None`` for the default global context. :Example: >>> from rclpy.executor import Executor >>> from rclpy.node import Node >>> >>> with Executor() as executor: >>> executor.add_node(Node('example_node')) >>> executor.spin_once() >>> len(executor.get_nodes()) 1 """ def __init__(self, *, context: Optional[Context] = None) -> None: super().__init__() self._context = get_default_context() if context is None else context self._nodes: Set[Node] = set() self._nodes_lock = RLock() # all tasks that are not complete or canceled self._pending_tasks: Dict[Task, TaskData] = {} # tasks that are ready to execute self._ready_tasks: Deque[Task[Any]] = deque() self._tasks_lock = Lock() # This is triggered when wait_for_ready_callbacks should rebuild the wait list self._guard: Optional[GuardCondition] = GuardCondition( callback=None, callback_group=None, context=self._context) # True if shutdown has been called self._is_shutdown = False self._work_tracker = _WorkTracker() # Protect against shutdown() being called in parallel in two threads self._shutdown_lock = Lock() # State for wait_for_ready_callbacks to reuse generator self._cb_iter: Optional[YieldedCallback] = None self._last_args: Optional[tuple[object, ...]] = None self._last_kwargs: Optional[Dict[str, object]] = None # Executor cannot use ROS clock because that requires a node self._clock = Clock(clock_type=ClockType.STEADY_TIME) self._sigint_gc: Optional[SignalHandlerGuardCondition] = \ SignalHandlerGuardCondition(context) self._context.on_shutdown(self.wake) # True when the executor is spinning self._is_spinning = False # Protects access to _is_spinning self._is_spinning_lock = Lock() def _enter_spin(self) -> None: """Mark the executor as spinning and prevent concurrent spins.""" with self._is_spinning_lock: if self._is_spinning: raise RuntimeError('Executor is already spinning') self._is_spinning = True def _exit_spin(self) -> None: """Clear the spinning flag.""" with self._is_spinning_lock: self._is_spinning = False @property def is_spinning(self) -> bool: """Return whether the executor is currently spinning.""" with self._is_spinning_lock: return self._is_spinning @property def context(self) -> Context: """Get the context associated with the executor.""" return self._context @overload def create_task(self, callback: Callable[..., Coroutine[Any, Any, T]], *args: Any, **kwargs: Any ) -> Task[T]: ... @overload def create_task(self, callback: Callable[..., T], *args: Any, **kwargs: Any ) -> Task[T]: ... def create_task(self, callback: Callable[..., Any], *args: Any, **kwargs: Any ) -> Task[Any]: """ Add a callback or coroutine to be executed during :meth:`spin` and return a Future. Arguments to this function are passed to the callback. .. warning:: Created task is queued in the executor in FIFO order, but users should not rely on the task execution order. :param callback: A callback to be run in the executor. """ task = Task(callback, args, kwargs, executor=self) with self._tasks_lock: self._pending_tasks[task] = TaskData() self._call_task_in_next_spin(task) return task def _call_task_in_next_spin(self, task: Task) -> None: """ Add a task to the executor to be executed in the next spin. :param task: A task to be run in the executor. """ with self._tasks_lock: self._ready_tasks.append(task) if self._guard: self._guard.trigger() def create_future(self) -> Future: """Create a Future object attached to the Executor.""" return Future(executor=self) def shutdown(self, timeout_sec: Optional[float] = None) -> bool: """ Stop executing callbacks and wait for their completion. :param timeout_sec: Seconds to wait. Block forever if ``None`` or negative. Don't wait if 0. :return: ``True`` if all outstanding callbacks finished executing, or ``False`` if the timeout expires before all outstanding work is done. """ with self._shutdown_lock: if not self._is_shutdown: self._is_shutdown = True # Tell executor it's been shut down if self._guard: self._guard.trigger() if not self._is_shutdown: if not self._work_tracker.wait(timeout_sec): return False # Clean up stuff that won't be used anymore with self._nodes_lock: self._nodes = set() with self._shutdown_lock: if self._guard: self._guard.destroy() self._guard = None if self._sigint_gc: self._sigint_gc.destroy() self._sigint_gc = None self._cb_iter = None self._last_args = None self._last_kwargs = None return True def __del__(self) -> None: if self._sigint_gc is not None: self._sigint_gc.destroy() def add_node(self, node: 'Node') -> bool: """ Add a node whose callbacks should be managed by this executor. :param node: The node to add to the executor. :return: ``True`` if the node was added, ``False`` otherwise. """ with self._nodes_lock: if node not in self._nodes: self._nodes.add(node) node.executor = self # Rebuild the wait set so it includes this new node if self._guard: self._guard.trigger() return True return False def remove_node(self, node: 'Node') -> None: """ Stop managing this node's callbacks. :param node: The node to remove from the executor. """ with self._nodes_lock: try: self._nodes.remove(node) except KeyError: pass else: # Rebuild the wait set so it doesn't include this node if self._guard: self._guard.trigger() def wake(self) -> None: """ Wake the executor because something changed. This is used to tell the executor when entities are created or destroyed. """ if self._guard: self._guard.trigger() def get_nodes(self) -> List['Node']: """Return nodes that have been added to this executor.""" with self._nodes_lock: return list(self._nodes) def spin(self) -> None: """Execute callbacks until shutdown.""" # Mark executor as spinning to prevent concurrent spins self._enter_spin() try: while self._context.ok() and not self._is_shutdown: self._spin_once_impl() finally: self._exit_spin() def spin_until_future_complete( self, future: Future[Any], timeout_sec: Optional[float] = None ) -> None: """Execute callbacks until a given future is done or a timeout occurs.""" # Mark executor as spinning to prevent concurrent spins self._enter_spin() # Make sure the future wakes this executor when it is done future.add_done_callback(lambda x: self.wake()) try: if timeout_sec is None or timeout_sec < 0: while ( self._context.ok() and not future.done() and not future.cancelled() and not self._is_shutdown ): self._spin_once_until_future_complete(future, timeout_sec) else: start = time.monotonic() end = start + timeout_sec timeout_left = TimeoutObject(timeout_sec) while ( self._context.ok() and not future.done() and not future.cancelled() and not self._is_shutdown ): self._spin_once_until_future_complete(future, timeout_left) now = time.monotonic() if now >= end: self._exit_spin() return timeout_left.timeout = end - now finally: self._exit_spin() def spin_once(self, timeout_sec: Optional[float] = None) -> None: """ Wait for and execute a single callback. A custom executor should use :meth:`wait_for_ready_callbacks` to get work. This method should not be called from multiple threads. :param timeout_sec: Seconds to wait. Block forever if ``None`` or negative. Don't wait if 0. """ raise NotImplementedError() def _spin_once_impl( self, timeout_sec: Optional[Union[float, TimeoutObject]] = None, wait_condition: Callable[[], bool] = lambda: False ) -> None: raise NotImplementedError() def spin_once_until_future_complete( self, future: Future[Any], timeout_sec: Optional[Union[float, TimeoutObject]] = None ) -> None: """ Wait for and execute a single callback. This should behave in the same way as :meth:`spin_once`. If needed by the implementation, it should awake other threads waiting. :param future: The executor will wait until this future is done. :param timeout_sec: Maximum seconds to wait. Block forever if ``None`` or negative. Don't wait if 0. """ raise NotImplementedError() def _spin_once_until_future_complete( self, future: Future[Any], timeout_sec: Optional[Union[float, TimeoutObject]] = None ) -> None: raise NotImplementedError() def _take_timer(self, tmr: Timer) -> Optional[Callable[[], Coroutine[None, None, None]]]: try: with tmr.handle: info = tmr.handle.call_timer_with_info() timer_info = TimerInfo( expected_call_time=info['expected_call_time'], actual_call_time=info['actual_call_time'], clock_type=tmr.clock.clock_type) def check_argument_type(callback_func: TimerCallbackType, target_type: Type[TimerInfo]) -> Optional[str]: sig = inspect.signature(callback_func) for param in sig.parameters.values(): if param.annotation == target_type: # return 1st one immediately return param.name # We could not find the target type in the signature return None # User might change the Timer.callback function signature at runtime, # so it needs to check the signature every time. if tmr.callback: arg_name = check_argument_type(tmr.callback, target_type=TimerInfo) if arg_name is not None: prefilled_arg = {arg_name: timer_info} async def _execute() -> None: if tmr.callback: await await_or_execute(partial(tmr.callback, **prefilled_arg)) return _execute else: async def _execute() -> None: if tmr.callback: await await_or_execute(tmr.callback) return _execute except InvalidHandle: # Timer is a Destroyable, which means that on __enter__ it can throw an # InvalidHandle exception if the entity has already been destroyed. Handle that here # by just returning an empty argument, which means we will skip doing any real work. pass except TimerCancelledError: # If TimerCancelledError exception occurs when calling call_timer_with_info(), we will # skip doing any real work. pass return None def _take_subscription(self, sub: Subscription[Any] ) -> Optional[Callable[[], Coroutine[None, None, None]]]: try: with sub.handle: msg_info = sub.handle.take_message(sub.msg_type, sub.raw) if msg_info is None: return None if sub._callback_type is Subscription.CallbackType.MessageOnly: msg_tuple: Union[Tuple[Msg], Tuple[Msg, MessageInfo]] = (msg_info[0], ) else: msg_tuple = msg_info async def _execute() -> None: await await_or_execute(sub.callback, *msg_tuple) return _execute except InvalidHandle: # Subscription is a Destroyable, which means that on __enter__ it can throw an # InvalidHandle exception if the entity has already been destroyed. Handle that here # by just returning an empty argument, which means we will skip doing any real work # in _execute_subscription below pass return None def _take_client(self, client: Client[Any, Any] ) -> Optional[Callable[[], Coroutine[None, None, None]]]: try: with client.handle: header_and_response = client.handle.take_response(client.srv_type.Response) async def _execute() -> None: header, response = header_and_response if header is None: return try: sequence = header.request_id.sequence_number future = client.get_pending_request(sequence) except KeyError: # The request was cancelled pass else: future._set_executor(self) future.set_result(response) return _execute except InvalidHandle: # Client is a Destroyable, which means that on __enter__ it can throw an # InvalidHandle exception if the entity has already been destroyed. Handle that here # by just returning an empty argument, which means we will skip doing any real work # in _execute_client below pass return None def _take_service(self, srv: Service[Any, Any] ) -> Optional[Callable[[], Coroutine[None, None, None]]]: try: with srv.handle: request_and_header = srv.handle.service_take_request(srv.srv_type.Request) async def _execute() -> None: (request, header) = request_and_header if header is None: return response = await await_or_execute(srv.callback, request, srv.srv_type.Response()) srv.send_response(response, header) return _execute except InvalidHandle: # Service is a Destroyable, which means that on __enter__ it can throw an # InvalidHandle exception if the entity has already been destroyed. Handle that here # by just returning an empty argument, which means we will skip doing any real work # in _execute_service below pass return None def _take_guard_condition(self, gc: GuardCondition ) -> Callable[[], Coroutine[None, None, None]]: gc._executor_triggered = False async def _execute() -> None: if gc.callback: await await_or_execute(gc.callback) return _execute def _take_waitable(self, waitable: Waitable[Any]) -> Callable[[], Coroutine[None, None, None]]: data = waitable.take_data() async def _execute() -> None: for future in waitable._futures: future._set_executor(self) await waitable.execute(data) return _execute def _make_handler( self, entity: 'EntityT', node: 'Node', take_from_wait_list: Callable[['EntityT'], Optional[Callable[[], Coroutine[None, None, None]]]], ) -> Task[None]: """ Make a handler that performs work on an entity. :param entity: An entity to wait on. :param node: The node associated with the entity. :param take_from_wait_list: Makes the entity to stop appearing in the wait list. """ # Mark this so it doesn't get added back to the wait list entity._executor_event = True async def handler(entity: 'EntityT', gc: GuardCondition, is_shutdown: bool, work_tracker: _WorkTracker) -> None: if is_shutdown or entity.callback_group is not None and \ not entity.callback_group.beginning_execution(entity): # Didn't get the callback, or the executor has been ordered to stop entity._executor_event = False gc.trigger() return with work_tracker: # The take_from_wait_list method here is expected to return either an async def # method or None if there is no work to do. call_coroutine = take_from_wait_list(entity) # Signal that this has been 'taken' and can be added back to the wait list entity._executor_event = False gc.trigger() try: if call_coroutine is not None: await call_coroutine() finally: if entity.callback_group: entity.callback_group.ending_execution(entity) # Signal that work has been done so the next callback in a mutually exclusive # callback group can get executed # Catch expected error where calling executor.shutdown() # from callback causes the GuardCondition to be destroyed try: gc.trigger() except InvalidHandle: pass task: Task[None] = Task( handler, (entity, self._guard, self._is_shutdown, self._work_tracker), executor=self) with self._tasks_lock: self._pending_tasks[task] = TaskData( source_entity=entity, source_node=node ) return task def can_execute(self, entity: 'Entity') -> bool: """ Determine if a callback for an entity can be executed. :param entity: Subscription, Timer, Guard condition, etc :returns: ``True`` if the entity callback can be executed, ``False`` otherwise. """ return not entity._executor_event and entity.callback_group is not None \ and entity.callback_group.can_execute(entity) def _wait_for_ready_callbacks( self, timeout_sec: Optional[Union[float, TimeoutObject]] = None, nodes: Optional[List['Node']] = None, condition: Callable[[], bool] = lambda: False, ) -> YieldedCallback: """ Yield callbacks that are ready to be executed. :raise TimeoutException: on timeout. :raise ShutdownException: on if executor was shut down. :param timeout_sec: Seconds to wait. Block forever if ``None`` or negative. Don't wait if 0. :param nodes: A list of nodes to wait on. Wait on all nodes if ``None``. :param condition: A callable that makes the function return immediately when it evaluates to True. """ timeout_timer = None timeout_nsec = timeout_sec_to_nsec( timeout_sec.timeout if isinstance(timeout_sec, TimeoutObject) else timeout_sec) if timeout_nsec > 0: timeout_timer = Timer(None, None, timeout_nsec, self._clock, context=self._context) yielded_work = False while not yielded_work and not self._is_shutdown and not condition(): # Refresh "all" nodes in case executor was woken by a node being added or removed nodes_to_use = nodes if nodes_to_use is None: nodes_to_use = self.get_nodes() # Yield tasks in-progress before waiting for new work with self._tasks_lock: # Get rid of any tasks that are done or cancelled for task in list(self._pending_tasks.keys()): if task.done() or task.cancelled(): del self._pending_tasks[task] ready_tasks_count = len(self._ready_tasks) for _ in range(ready_tasks_count): task = self._ready_tasks.popleft() task_data = self._pending_tasks[task] node = task_data.source_node if node is None or node in nodes_to_use: entity = task_data.source_entity yielded_work = True yield task, entity, node else: # Asked not to execute these tasks, so don't do them yet with self._tasks_lock: self._ready_tasks.append(task) # Gather entities that can be waited on subscriptions: List[Subscription[Any, ]] = [] guards: List[GuardCondition] = [] timers: List[Timer] = [] clients: List[Client[Any, Any]] = [] services: List[Service[Any, Any]] = [] waitables: List[Waitable[Any]] = [] for node in nodes_to_use: subscriptions.extend(filter(self.can_execute, node.subscriptions)) timers.extend(filter(self.can_execute, node.timers)) clients.extend(filter(self.can_execute, node.clients)) services.extend(filter(self.can_execute, node.services)) node_guards = filter(self.can_execute, node.guards) waitables.extend(filter(self.can_execute, node.waitables)) # retrigger a guard condition that was triggered but not handled for gc in node_guards: if gc._executor_triggered: gc.trigger() guards.append(gc) if timeout_timer is not None: timers.append(timeout_timer) if self._guard: guards.append(self._guard) if self._sigint_gc: guards.append(self._sigint_gc) entity_count = NumberOfEntities( len(subscriptions), len(guards), len(timers), len(clients), len(services)) # Construct a wait set wait_set = None with ExitStack() as context_stack: sub_handles = [] for sub in subscriptions: try: context_stack.enter_context(sub.handle) sub_handles.append(sub.handle) except InvalidHandle: entity_count.num_subscriptions -= 1 client_handles = [] for cli in clients: try: context_stack.enter_context(cli.handle) client_handles.append(cli.handle) except InvalidHandle: entity_count.num_clients -= 1 service_handles = [] for srv in services: try: context_stack.enter_context(srv.handle) service_handles.append(srv.handle) except InvalidHandle: entity_count.num_services -= 1 timer_handles = [] for tmr in timers: try: context_stack.enter_context(tmr.handle) timer_handles.append(tmr.handle) except InvalidHandle: entity_count.num_timers -= 1 guard_handles = [] for gc in guards: try: context_stack.enter_context(gc.handle) guard_handles.append(gc.handle) except InvalidHandle: entity_count.num_guard_conditions -= 1 for waitable in waitables: try: context_stack.enter_context(waitable) entity_count += waitable.get_num_entities() except InvalidHandle: pass if self._context.handle is None: raise RuntimeError('Cannot enter context if context is None') context_stack.enter_context(self._context.handle) wait_set = _rclpy.WaitSet( entity_count.num_subscriptions, entity_count.num_guard_conditions, entity_count.num_timers, entity_count.num_clients, entity_count.num_services, entity_count.num_events, self._context.handle) wait_set.clear_entities() for sub_handle in sub_handles: wait_set.add_subscription(sub_handle) for cli_handle in client_handles: wait_set.add_client(cli_handle) for srv_capsule in service_handles: wait_set.add_service(srv_capsule) for tmr_handle in timer_handles: wait_set.add_timer(tmr_handle) for gc_handle in guard_handles: wait_set.add_guard_condition(gc_handle) for waitable in waitables: waitable.add_to_wait_set(wait_set) # Wait for something to become ready wait_set.wait(timeout_nsec) if self._is_shutdown: raise ShutdownException() if not self._context.ok(): raise ExternalShutdownException() # get ready entities subs_ready = wait_set.get_ready_entities('subscription') guards_ready = wait_set.get_ready_entities('guard_condition') timers_ready = wait_set.get_ready_entities('timer') clients_ready = wait_set.get_ready_entities('client') services_ready = wait_set.get_ready_entities('service') # Mark all guards as triggered before yielding since they're auto-taken for gc in guards: if gc.handle.pointer in guards_ready: gc._executor_triggered = True # Check waitables before wait set is destroyed for node in nodes_to_use: for wt in node.waitables: # Only check waitables that were added to the wait set if wt in waitables and wt.is_ready(wait_set): if wt.callback_group.can_execute(wt): handler = self._make_handler(wt, node, self._take_waitable) yielded_work = True yield handler, wt, node # Process ready entities one node at a time for node in nodes_to_use: for tmr in node.timers: if tmr.handle.pointer in timers_ready: # Check timer is ready to workaround rcl issue with cancelled timers if tmr.handle.is_timer_ready(): if tmr.callback_group and tmr.callback_group.can_execute(tmr): handler = self._make_handler(tmr, node, self._take_timer) yielded_work = True yield handler, tmr, node for sub in node.subscriptions: if sub.handle.pointer in subs_ready: if sub.callback_group.can_execute(sub): handler = self._make_handler(sub, node, self._take_subscription) yielded_work = True yield handler, sub, node for gc in node.guards: if gc._executor_triggered: if gc.callback_group and gc.callback_group.can_execute(gc): handler = self._make_handler(gc, node, self._take_guard_condition) yielded_work = True yield handler, gc, node for client in node.clients: if client.handle.pointer in clients_ready: if client.callback_group.can_execute(client): handler = self._make_handler(client, node, self._take_client) yielded_work = True yield handler, client, node for srv in node.services: if srv.handle.pointer in services_ready: if srv.callback_group.can_execute(srv): handler = self._make_handler(srv, node, self._take_service) yielded_work = True yield handler, srv, node # Check timeout timer if ( timeout_nsec == 0 or (timeout_timer is not None and timeout_timer.handle.pointer in timers_ready) ): raise TimeoutException() if self._is_shutdown: raise ShutdownException() if condition(): raise ConditionReachedException() def wait_for_ready_callbacks(self, *args: Any, **kwargs: Any) -> Tuple[Task[None], 'Optional[Entity]', 'Optional[Node]']: """ Return callbacks that are ready to be executed. The arguments to this function are passed to the internal method :meth:`_wait_for_ready_callbacks` to get a generator for ready callbacks: .. Including the docstring for the hidden function for reference .. automethod:: _wait_for_ready_callbacks """ while True: if self._cb_iter is None or self._last_args != args or self._last_kwargs != kwargs: # Create a new generator self._last_args = args self._last_kwargs = kwargs self._cb_iter = self._wait_for_ready_callbacks(*args, **kwargs) try: return next(self._cb_iter) except StopIteration: # Generator ran out of work self._cb_iter = None def __enter__(self) -> 'Executor': # Nothing to do here return self def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: self.shutdown() class SingleThreadedExecutor(Executor): """Runs callbacks in the thread that calls :meth:`Executor.spin`.""" def __init__(self, *, context: Optional[Context] = None) -> None: super().__init__(context=context) def _spin_once_impl( self, timeout_sec: Optional[Union[float, TimeoutObject]] = None, wait_condition: Callable[[], bool] = lambda: False ) -> None: try: handler, entity, node = self.wait_for_ready_callbacks( timeout_sec, None, wait_condition) except ShutdownException: pass except TimeoutException: pass except ConditionReachedException: pass else: handler() exception = handler.exception() if exception is not None: raise exception handler.result() # raise any exceptions def spin_once(self, timeout_sec: Optional[float] = None) -> None: # Mark executor as spinning to prevent concurrent spins self._enter_spin() try: self._spin_once_impl(timeout_sec) finally: self._exit_spin() def _spin_once_until_future_complete( self, future: Future[Any], timeout_sec: Optional[Union[float, TimeoutObject]] = None ) -> None: self._spin_once_impl(timeout_sec, future.done) def spin_once_until_future_complete( self, future: Future[Any], timeout_sec: Optional[Union[float, TimeoutObject]] = None ) -> None: # Mark executor as spinning to prevent concurrent spins self._enter_spin() future.add_done_callback(lambda x: self.wake()) try: self._spin_once_until_future_complete(future, timeout_sec) finally: self._exit_spin() class MultiThreadedExecutor(Executor): """ Runs callbacks in a pool of threads. :param num_threads: number of worker threads in the pool. If ``None``, the number of threads will be automatically set by querying the underlying OS for the CPU affinity of the process space. If the OS doesn't provide this information, defaults to 2. :param context: The context associated with the executor. """ def __init__( self, num_threads: Optional[int] = None, *, context: Optional[Context] = None ) -> None: super().__init__(context=context) if num_threads is None: # On Linux, it will try to use the number of CPU this process has access to. # Other platforms, os.sched_getaffinity() doesn't exist so we use the number of CPUs. if hasattr(os, 'sched_getaffinity'): num_threads = len(os.sched_getaffinity(0)) else: num_threads = os.cpu_count() # The calls above may still return None if they aren't supported if num_threads is None: num_threads = 2 if num_threads == 1: warnings.warn( 'MultiThreadedExecutor is used with a single thread.\n' 'Use the SingleThreadedExecutor instead.') self._futures: List[Future[Any]] = [] self._executor = ThreadPoolExecutor(num_threads) self._futures_lock = Lock() def _spin_once_impl( self, timeout_sec: Optional[Union[float, TimeoutObject]] = None, wait_condition: Callable[[], bool] = lambda: False ) -> None: try: handler, entity, node = self.wait_for_ready_callbacks( timeout_sec, None, wait_condition) except ExternalShutdownException: pass except ShutdownException: pass except TimeoutException: pass except ConditionReachedException: pass else: self._executor.submit(handler) self._futures.append(handler) with self._futures_lock: for future in self._futures: if future.done(): self._futures.remove(future) future.result() # raise any exceptions def spin_once(self, timeout_sec: Optional[float] = None) -> None: # Mark executor as spinning to prevent concurrent spins self._enter_spin() try: self._spin_once_impl(timeout_sec) finally: self._exit_spin() def _spin_once_until_future_complete( self, future: Future[Any], timeout_sec: Optional[Union[float, TimeoutObject]] = None ) -> None: self._spin_once_impl(timeout_sec, future.done) def spin_once_until_future_complete( self, future: Future[Any], timeout_sec: Optional[Union[float, TimeoutObject]] = None ) -> None: # Mark executor as spinning to prevent concurrent spins self._enter_spin() future.add_done_callback(lambda x: self.wake()) try: self._spin_once_until_future_complete(future, timeout_sec) finally: self._exit_spin() def shutdown( self, timeout_sec: Optional[float] = None, *, wait_for_threads: bool = True ) -> bool: """ Stop executing callbacks and wait for their completion. :param timeout_sec: Seconds to wait. Block forever if ``None`` or negative. Don't wait if 0. :param wait_for_threads: If true, this function will block until all executor threads have joined. :return: ``True`` if all outstanding callbacks finished executing, or ``False`` if the timeout expires before all outstanding work is done. """ success: bool = super().shutdown(timeout_sec) self._executor.shutdown(wait=wait_for_threads) return success
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import asyncio import os import threading import time from typing import Generator from typing import Optional from typing import Set import unittest import warnings import rclpy from rclpy.callback_groups import ReentrantCallbackGroup from rclpy.client import Client from rclpy.executors import Executor from rclpy.executors import MultiThreadedExecutor from rclpy.executors import ShutdownException from rclpy.executors import SingleThreadedExecutor from rclpy.experimental import EventsExecutor from rclpy.task import Future from test_msgs.srv import Empty class TestExecutor(unittest.TestCase): def setUp(self) -> None: self.context = rclpy.context.Context() rclpy.init(context=self.context) self.node = rclpy.create_node('TestExecutor', namespace='/rclpy', context=self.context) def tearDown(self) -> None: self.node.destroy_node() rclpy.shutdown(context=self.context) self.context.destroy() def func_execution(self, executor: Executor) -> bool: got_callback = False def timer_callback() -> None: nonlocal got_callback got_callback = True tmr = self.node.create_timer(0.1, timer_callback) assert executor.add_node(self.node) executor.spin_once(timeout_sec=1.23) # TODO(sloretz) redesign test, sleeping to workaround race condition between test cleanup # and MultiThreadedExecutor thread pool time.sleep(0.1) self.node.destroy_timer(tmr) return got_callback def test_single_threaded_executor_executes(self) -> None: self.assertIsNotNone(self.node.handle) for cls in [SingleThreadedExecutor, EventsExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) try: self.assertTrue(self.func_execution(executor)) finally: executor.shutdown() def test_executor_immediate_shutdown(self) -> None: self.assertIsNotNone(self.node.handle) for cls in [SingleThreadedExecutor, EventsExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) try: got_callback = False def timer_callback() -> None: nonlocal got_callback got_callback = True timer_period = 1 tmr = self.node.create_timer(timer_period, timer_callback) self.assertTrue(executor.add_node(self.node)) t = threading.Thread(target=executor.spin, daemon=True) start_time = time.perf_counter() t.start() executor.shutdown() t.join() end_time = time.perf_counter() self.node.destroy_timer(tmr) self.assertLess(end_time - start_time, timer_period / 2) self.assertFalse(got_callback) finally: executor.shutdown() def test_shutdown_executor_before_waiting_for_callbacks(self) -> None: self.assertIsNotNone(self.node.handle) # EventsExecutor does not support the wait_for_ready_callbacks() API for cls in [SingleThreadedExecutor, MultiThreadedExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) executor.shutdown() with self.assertRaises(ShutdownException): executor.wait_for_ready_callbacks() def test_shutdown_exception_from_callback_generator(self) -> None: self.assertIsNotNone(self.node.handle) # This test touches the Executor private API and is not compatible with EventsExecutor for cls in [SingleThreadedExecutor, MultiThreadedExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) cb_generator = executor._wait_for_ready_callbacks() executor.shutdown() with self.assertRaises(ShutdownException): next(cb_generator) def test_remove_node(self) -> None: self.assertIsNotNone(self.node.handle) for cls in [SingleThreadedExecutor, EventsExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) got_callback = False def timer_callback() -> None: nonlocal got_callback got_callback = True try: tmr = self.node.create_timer(0.1, timer_callback) try: executor.add_node(self.node) executor.remove_node(self.node) executor.spin_once(timeout_sec=0.2) finally: self.node.destroy_timer(tmr) finally: executor.shutdown() assert not got_callback def test_multi_threaded_executor_num_threads(self) -> None: self.assertIsNotNone(self.node.handle) # check default behavior, either platform configuration or defaults to 2 executor = MultiThreadedExecutor(context=self.context) if hasattr(os, 'sched_getaffinity'): platform_threads: Optional[int] = len(os.sched_getaffinity(0)) else: platform_threads = os.cpu_count() self.assertEqual(platform_threads, executor._executor._max_workers) executor.shutdown() # check specified thread number w/o warning executor = MultiThreadedExecutor(num_threads=3, context=self.context) self.assertEqual(3, executor._executor._max_workers) executor.shutdown() # check specified thread number = 1, expecting UserWarning with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always', category=UserWarning) executor = MultiThreadedExecutor(num_threads=1, context=self.context) self.assertEqual(1, executor._executor._max_workers) executor.shutdown() assert len(w) == 1 assert issubclass(w[0].category, UserWarning) def test_multi_threaded_executor_executes(self) -> None: self.assertIsNotNone(self.node.handle) executor = MultiThreadedExecutor(context=self.context) try: self.assertTrue(self.func_execution(executor)) finally: executor.shutdown() def test_multi_threaded_executor_closes_threads(self) -> None: self.assertIsNotNone(self.node.handle) def get_threads() -> Set[str]: return {t.name for t in threading.enumerate()} main_thread_name = get_threads() # Explicitly specify 2_threads for single thread system failure executor = MultiThreadedExecutor(context=self.context, num_threads=2) try: # Give the executor a callback so at least one thread gets spun up self.assertTrue(self.func_execution(executor)) finally: self.assertTrue(main_thread_name != get_threads()) executor.shutdown(wait_for_threads=True) self.assertTrue(main_thread_name == get_threads()) def test_add_node_to_executor(self) -> None: self.assertIsNotNone(self.node.handle) for cls in [SingleThreadedExecutor, EventsExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) executor.add_node(self.node) self.assertIn(self.node, executor.get_nodes()) def test_executor_spin_non_blocking(self) -> None: self.assertIsNotNone(self.node.handle) for cls in [SingleThreadedExecutor, EventsExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) executor.add_node(self.node) start = time.perf_counter() executor.spin_once(timeout_sec=0) end = time.perf_counter() self.assertLess(start - end, 0.001) def test_execute_coroutine_timer(self) -> None: self.assertIsNotNone(self.node.handle) for cls in [SingleThreadedExecutor, EventsExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) executor.add_node(self.node) called1 = False called2 = False async def coroutine() -> None: nonlocal called1 nonlocal called2 called1 = True await asyncio.sleep(0) called2 = True tmr = self.node.create_timer(0.1, coroutine) try: executor.spin_once(timeout_sec=1.23) self.assertTrue(called1) self.assertFalse(called2) called1 = False executor.spin_once(timeout_sec=0) self.assertFalse(called1) self.assertTrue(called2) finally: self.node.destroy_timer(tmr) def test_execute_coroutine_guard_condition(self) -> None: self.assertIsNotNone(self.node.handle) # TODO(bmartin427) Does EventsExecutor need to support guard conditions? executor = SingleThreadedExecutor(context=self.context) executor.add_node(self.node) called1 = False called2 = False async def coroutine() -> None: nonlocal called1 nonlocal called2 called1 = True await asyncio.sleep(0) called2 = True gc = self.node.create_guard_condition(coroutine) try: gc.trigger() executor.spin_once(timeout_sec=0) self.assertTrue(called1) self.assertFalse(called2) called1 = False executor.spin_once(timeout_sec=1) self.assertFalse(called1) self.assertTrue(called2) finally: self.node.destroy_guard_condition(gc) def test_create_task_coroutine(self) -> None: self.assertIsNotNone(self.node.handle) for cls in [SingleThreadedExecutor, EventsExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) executor.add_node(self.node) async def coroutine() -> str: return 'Sentinel Result' future = executor.create_task(coroutine) self.assertFalse(future.done()) executor.spin_once(timeout_sec=0) self.assertTrue(future.done()) self.assertEqual('Sentinel Result', future.result()) def test_create_task_coroutine_yield(self) -> None: self.assertIsNotNone(self.node.handle) for cls in [SingleThreadedExecutor, EventsExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) executor.add_node(self.node) called1 = False called2 = False async def coroutine() -> str: nonlocal called1 nonlocal called2 called1 = True await asyncio.sleep(0) called2 = True return 'Sentinel Result' future = executor.create_task(coroutine) self.assertFalse(future.done()) self.assertFalse(called1) self.assertFalse(called2) executor.spin_once(timeout_sec=0) self.assertFalse(future.done()) self.assertTrue(called1) self.assertFalse(called2) executor.spin_once(timeout_sec=1) self.assertTrue(future.done()) self.assertTrue(called1) self.assertTrue(called2) self.assertEqual('Sentinel Result', future.result()) def test_create_task_coroutine_cancel(self) -> None: self.assertIsNotNone(self.node.handle) for cls in [SingleThreadedExecutor, EventsExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) executor.add_node(self.node) async def coroutine() -> str: return 'Sentinel Result' future = executor.create_task(coroutine) self.assertFalse(future.done()) self.assertFalse(future.cancelled()) future.cancel() self.assertTrue(future.cancelled()) executor.spin_until_future_complete(future) self.assertFalse(future.done()) self.assertTrue(future.cancelled()) self.assertEqual(None, future.result()) def test_create_task_coroutine_wake_from_another_thread(self) -> None: self.assertIsNotNone(self.node.handle) for cls in [SingleThreadedExecutor, MultiThreadedExecutor, EventsExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) thread_future = executor.create_future() async def coroutine(): await thread_future def future_thread(): threading.Event().wait(0.1) # Simulate some work thread_future.set_result(None) t = threading.Thread(target=future_thread) coroutine_future = executor.create_task(coroutine) start_time = time.monotonic() t.start() executor.spin_until_future_complete(coroutine_future, timeout_sec=1.0) end_time = time.monotonic() self.assertTrue(coroutine_future.done()) # The coroutine should take at least 0.1 seconds to complete because it waits for # the thread to set the future but nowhere near the 1 second timeout assert 0.1 <= end_time - start_time < 0.2 def test_create_task_normal_function(self) -> None: self.assertIsNotNone(self.node.handle) for cls in [SingleThreadedExecutor, EventsExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) executor.add_node(self.node) def func() -> str: return 'Sentinel Result' future = executor.create_task(func) self.assertFalse(future.done()) executor.spin_once(timeout_sec=0) self.assertTrue(future.done()) self.assertEqual('Sentinel Result', future.result()) def test_create_task_fifo_order(self) -> None: self.assertIsNotNone(self.node.handle) for cls in [SingleThreadedExecutor, EventsExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) executor.add_node(self.node) async def coro1() -> str: return 'Sentinel Result 1' future1 = executor.create_task(coro1) async def coro2() -> str: return 'Sentinel Result 2' future2 = executor.create_task(coro2) # Coro1 is the 1st task, so it gets executed in this spin executor.spin_once(timeout_sec=0) self.assertTrue(future1.done()) self.assertEqual('Sentinel Result 1', future1.result()) self.assertFalse(future2.done()) # Coro2 is the next in the queue, so it gets executed in this spin executor.spin_once(timeout_sec=0) self.assertTrue(future2.done()) self.assertEqual('Sentinel Result 2', future2.result()) def test_create_task_dependent_coroutines(self) -> None: self.assertIsNotNone(self.node.handle) for cls in [SingleThreadedExecutor, EventsExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) executor.add_node(self.node) async def coro1() -> str: nonlocal future2 # type: ignore[misc] await future2 return 'Sentinel Result 1' future1 = executor.create_task(coro1) async def coro2() -> str: return 'Sentinel Result 2' future2 = executor.create_task(coro2) # Coro1 is the 1st task, so it gets to await future2 in this spin executor.spin_once(timeout_sec=0) # Coro2 execs in this spin executor.spin_once(timeout_sec=0) self.assertFalse(future1.done()) self.assertTrue(future2.done()) self.assertEqual('Sentinel Result 2', future2.result()) # Coro1 passes the await step here (timeout change forces new generator) executor.spin_once(timeout_sec=1) self.assertTrue(future1.done()) self.assertEqual('Sentinel Result 1', future1.result()) def test_create_task_during_spin(self) -> None: self.assertIsNotNone(self.node.handle) for cls in [SingleThreadedExecutor, EventsExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) executor.add_node(self.node) future = None def spin_until_task_done(executor: Executor) -> None: nonlocal future while future is None or not future.done(): try: executor.spin_once() finally: executor.shutdown() break # Start spinning in a separate thread thr = threading.Thread(target=spin_until_task_done, args=(executor, ), daemon=True) thr.start() # Sleep in this thread to give the executor a chance to reach the loop in # '_wait_for_ready_callbacks()' time.sleep(1) def func() -> str: return 'Sentinel Result' # Create a task future = executor.create_task(func) thr.join(timeout=0.5) # If the join timed out, remove the node to cause the spin thread to stop if thr.is_alive(): executor.remove_node(self.node) self.assertTrue(future.done()) self.assertEqual('Sentinel Result', future.result()) def test_global_executor_completes_async_task(self) -> None: self.assertIsNotNone(self.node.handle) class TriggerAwait: def __init__(self) -> None: self.do_yield = True def __await__(self) -> Generator[None, None, None]: while self.do_yield: yield return for cls in [SingleThreadedExecutor, EventsExecutor]: with self.subTest(cls=cls): trigger = TriggerAwait() did_callback = False did_return = False async def timer_callback() -> None: nonlocal trigger, did_callback, did_return did_callback = True await trigger did_return = True timer = self.node.create_timer(0.1, timer_callback) executor = cls(context=self.context) rclpy.spin_once(self.node, timeout_sec=0.5, executor=executor) self.assertTrue(did_callback) timer.cancel() trigger.do_yield = False rclpy.spin_once(self.node, timeout_sec=0, executor=executor) self.assertTrue(did_return) def test_executor_add_node(self) -> None: self.assertIsNotNone(self.node.handle) for cls in [SingleThreadedExecutor, EventsExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) assert executor.add_node(self.node) assert id(executor) == id(self.node.executor) assert not executor.add_node(self.node) assert id(executor) == id(self.node.executor) def test_executor_spin_until_future_complete_timeout(self) -> None: self.assertIsNotNone(self.node.handle) for cls in [SingleThreadedExecutor, EventsExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) executor.add_node(self.node) def timer_callback() -> None: pass timer = self.node.create_timer(0.003, timer_callback) # Timeout future = executor.create_future() self.assertFalse(future.done()) start = time.perf_counter() executor.spin_until_future_complete(future=future, timeout_sec=0.1) end = time.perf_counter() # Nothing is ever setting the future, so this should have waited # at least 0.1 seconds. self.assertGreaterEqual(end - start, 0.1) self.assertFalse(future.done()) timer.cancel() def test_executor_spin_until_future_complete_future_done(self) -> None: self.assertIsNotNone(self.node.handle) for cls in [SingleThreadedExecutor, EventsExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) executor.add_node(self.node) def timer_callback() -> None: pass timer = self.node.create_timer(0.003, timer_callback) def set_future_result(future: Future[str]) -> None: future.set_result('finished') # Future complete timeout_sec > 0 future = executor.create_future() self.assertFalse(future.done()) t = threading.Thread(target=lambda: set_future_result(future)) t.start() executor.spin_until_future_complete(future=future, timeout_sec=0.2) self.assertTrue(future.done()) self.assertEqual(future.result(), 'finished') # Future complete timeout_sec = None future = executor.create_future() self.assertFalse(future.done()) t = threading.Thread(target=lambda: set_future_result(future)) t.start() executor.spin_until_future_complete(future=future, timeout_sec=None) self.assertTrue(future.done()) self.assertEqual(future.result(), 'finished') # Future complete timeout < 0 future = executor.create_future() self.assertFalse(future.done()) t = threading.Thread(target=lambda: set_future_result(future)) t.start() executor.spin_until_future_complete(future=future, timeout_sec=-1) self.assertTrue(future.done()) self.assertEqual(future.result(), 'finished') timer.cancel() def test_executor_spin_until_future_complete_do_not_wait(self) -> None: self.assertIsNotNone(self.node.handle) for cls in [SingleThreadedExecutor, EventsExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) executor.add_node(self.node) def timer_callback() -> None: pass timer = self.node.create_timer(0.003, timer_callback) # Do not wait timeout_sec = 0 future = executor.create_future() self.assertFalse(future.done()) executor.spin_until_future_complete(future=future, timeout_sec=0) self.assertFalse(future.done()) timer.cancel() def test_executor_add_node_wakes_executor(self) -> None: self.assertIsNotNone(self.node.handle) for cls in [SingleThreadedExecutor, EventsExecutor]: with self.subTest(cls=cls): got_callback = False def timer_callback() -> None: nonlocal got_callback got_callback = True timer_period = 0.1 tmr = self.node.create_timer(timer_period, timer_callback) executor = cls(context=self.context) try: # spin in background t = threading.Thread(target=executor.spin_once, daemon=True) t.start() # sleep to make sure executor is blocked in rcl_wait time.sleep(0.5) self.assertTrue(executor.add_node(self.node)) # Make sure timer has time to trigger time.sleep(timer_period) self.assertTrue(got_callback) finally: executor.shutdown() self.node.destroy_timer(tmr) def test_shutdown_executor_from_callback(self) -> None: """https://github.com/ros2/rclpy/issues/944: allow for executor shutdown from callback.""" self.assertIsNotNone(self.node.handle) timer_period = 0.1 # TODO(bmartin427) This seems like an invalid test to me? executor.shutdown() is # documented as blocking until all callbacks are complete, unless you pass a non-negative # timeout value which this doesn't. I'm not sure how that's supposed to *not* deadlock if # you block on all callbacks from within a callback. executor = SingleThreadedExecutor(context=self.context) shutdown_event = threading.Event() def timer_callback() -> None: nonlocal shutdown_event, executor executor.shutdown() shutdown_event.set() tmr = self.node.create_timer(timer_period, timer_callback) executor.add_node(self.node) t = threading.Thread(target=executor.spin, daemon=True) t.start() self.assertTrue(shutdown_event.wait(120)) self.node.destroy_timer(tmr) def test_context_manager(self) -> None: self.assertIsNotNone(self.node.handle) # This test touches the Executor private API and is not compatible with EventsExecutor executor: Executor = SingleThreadedExecutor(context=self.context) with executor as the_executor: # Make sure the correct instance is returned assert the_executor is executor assert not executor._is_shutdown, 'the executor should not be shut down' assert executor._is_shutdown, 'the executor should now be shut down' # Make sure it does not raise (smoke test) executor.shutdown() def test_single_threaded_spin_once_until_future(self) -> None: self.assertIsNotNone(self.node.handle) for cls in [SingleThreadedExecutor, EventsExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) future = executor.create_future() # Setup a thread to spin_once_until_future_complete, which will spin # for a maximum of 10 seconds. start = time.time() thread = threading.Thread(target=executor.spin_once_until_future_complete, args=(future, 10)) thread.start() # Mark the future as complete immediately future.set_result(True) thread.join() end = time.time() time_spent = end - start # Since we marked the future as complete immediately, the amount of # time we spent should be *substantially* less than the 10 second # timeout we set on the spin. assert time_spent < 10 executor.shutdown() def test_multi_threaded_spin_once_until_future(self) -> None: self.assertIsNotNone(self.node.handle) executor = MultiThreadedExecutor(context=self.context) future: Future[bool] = executor.create_future() # Setup a thread to spin_once_until_future_complete, which will spin # for a maximum of 10 seconds. start = time.time() thread = threading.Thread(target=executor.spin_once_until_future_complete, args=(future, 10)) thread.start() # Mark the future as complete immediately future.set_result(True) thread.join() end = time.time() time_spent = end - start # Since we marked the future as complete immediately, the amount of # time we spent should be *substantially* less than the 10 second # timeout we set on the spin. assert time_spent < 10 executor.shutdown() def test_not_lose_callback(self) -> None: self.assertIsNotNone(self.node.handle) for cls in [SingleThreadedExecutor, EventsExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) callback_group = ReentrantCallbackGroup() cli: Client[Empty.Request, Empty.Response] = self.node.create_client( srv_type=Empty, srv_name='test_service', callback_group=callback_group) async def timer1_callback() -> None: timer1.cancel() await cli.call_async(Empty.Request()) timer1 = self.node.create_timer(0.5, timer1_callback, callback_group) count = 0 def timer2_callback() -> None: nonlocal count count += 1 timer2 = self.node.create_timer(1.5, timer2_callback, callback_group) executor.add_node(self.node) future = executor.create_future() executor.spin_until_future_complete(future, 4) assert count == 2 executor.shutdown() self.node.destroy_timer(timer2) self.node.destroy_timer(timer1) self.node.destroy_client(cli) def test_create_future_returns_future_with_executor_attached(self) -> None: self.assertIsNotNone(self.node.handle) for cls in [SingleThreadedExecutor, MultiThreadedExecutor, EventsExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) try: fut = executor.create_future() self.assertEqual(executor, fut._executor()) finally: executor.shutdown() def test_spinning_multiple_times_spin(self) -> None: self.assertIsNotNone(self.node.handle) # Test all executor types including base Executor class for cls in [SingleThreadedExecutor, MultiThreadedExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) try: executor.add_node(self.node) # Start spinning in a background thread def spin_thread(): executor.spin() t = threading.Thread(target=spin_thread, daemon=True) t.start() # Give the executor time to start spinning time.sleep(1.0) # Check that executor is spinning self.assertTrue(executor.is_spinning) # Try to spin again, should raise an exception with self.assertRaises(RuntimeError): executor.spin() # Shutdown the executor to stop the background thread executor.shutdown() t.join(timeout=1.0) finally: executor.shutdown() def test_spinning_multiple_times_spin_once(self) -> None: self.assertIsNotNone(self.node.handle) # Test all executor types including base Executor class for cls in [SingleThreadedExecutor, MultiThreadedExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) try: executor.add_node(self.node) # Start spinning in a background thread def spin_thread(): executor.spin_once(timeout_sec=10.0) t = threading.Thread(target=spin_thread, daemon=True) t.start() # Give the executor time to start spinning time.sleep(1.0) # Check that executor is spinning self.assertTrue(executor.is_spinning) # Try to spin again, should raise an exception with self.assertRaises(RuntimeError): executor.spin_once(timeout_sec=1.0) # Wait for the background thread to complete t.join(timeout=1.0) executor.shutdown() finally: executor.shutdown() def test_spinning_multiple_times_spin_until_future_complete(self) -> None: self.assertIsNotNone(self.node.handle) # Test all executor types including base Executor class for cls in [SingleThreadedExecutor, MultiThreadedExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) try: executor.add_node(self.node) future = executor.create_future() # Start spinning in a background thread def spin_thread(): executor.spin_until_future_complete(future, timeout_sec=10.0) t = threading.Thread(target=spin_thread, daemon=True) t.start() # Give the executor time to start spinning time.sleep(1.0) # Check that executor is spinning self.assertTrue(executor.is_spinning) # Try to spin again, should raise an exception with self.assertRaises(RuntimeError): executor.spin_until_future_complete(future, timeout_sec=1.0) # Complete the future and shutdown future.set_result(True) t.join(timeout=1.0) executor.shutdown() finally: executor.shutdown() def test_spinning_multiple_times_spin_once_until_future_complete(self) -> None: self.assertIsNotNone(self.node.handle) # Test all executor types including base Executor class for cls in [SingleThreadedExecutor, MultiThreadedExecutor]: with self.subTest(cls=cls): executor = cls(context=self.context) try: executor.add_node(self.node) future = executor.create_future() # Start spinning in a background thread def spin_thread(): executor.spin_once_until_future_complete(future, timeout_sec=10.0) t = threading.Thread(target=spin_thread, daemon=True) t.start() # Give the executor time to start spinning time.sleep(1.0) # Check that executor is spinning self.assertTrue(executor.is_spinning) # Try to spin again, should raise an exception with self.assertRaises(RuntimeError): executor.spin_once_until_future_complete(future, timeout_sec=1.0) # Complete the future and shutdown future.set_result(True) t.join(timeout=1.0) executor.shutdown() finally: executor.shutdown() if __name__ == '__main__': unittest.main()
rclpy
python
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Literal from rclpy.exceptions import InvalidNamespaceException from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy def validate_namespace(namespace: str) -> Literal[True]: """ Validate a given namespace, and raise an exception if it is invalid. Unlike the node constructor, which allows namespaces without a leading '/' and empty namespaces "", this function requires that the namespace be absolute and non-empty. If the namespace is invalid then rclpy.exceptions.InvalidNamespaceException will be raised. :param namespace: namespace to be validated :returns: True when it is valid :raises: InvalidNamespaceException: when the namespace is invalid """ result = _rclpy.rclpy_get_validation_error_for_namespace(namespace) if result is None: return True error_msg, invalid_index = result raise InvalidNamespaceException(namespace, error_msg, invalid_index)
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from rclpy.exceptions import InvalidNamespaceException from rclpy.validate_namespace import validate_namespace class TestValidateNamespace(unittest.TestCase): def test_validate_namespace(self) -> None: tests = [ '/my_ns', '/', ] for topic in tests: # Will raise if invalid validate_namespace(topic) def test_validate_namespace_failures(self) -> None: # namespace must not be empty with self.assertRaisesRegex(InvalidNamespaceException, 'empty'): validate_namespace('') # namespace must start with / with self.assertRaisesRegex(InvalidNamespaceException, 'must be absolute'): validate_namespace('invalid_namespace') if __name__ == '__main__': unittest.main()
rclpy
python
# Copyright 2023 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from collections import defaultdict from itertools import chain from multiprocessing import Lock from typing import Callable, Dict, Iterable, List, Optional, Tuple from rcl_interfaces.msg import Parameter as ParameterMsg from rcl_interfaces.msg import ParameterEvent from rclpy.callback_groups import CallbackGroup from rclpy.event_handler import SubscriptionEventCallbacks from rclpy.node import Node from rclpy.qos import qos_profile_parameter_events from rclpy.qos import QoSProfile from rclpy.qos_overriding_options import QoSOverridingOptions class ParameterCallbackHandle: def __init__( self, parameter_name: str, node_name: str, callback: Callable[[ParameterMsg], None], ) -> None: self.parameter_name = parameter_name self.node_name = node_name self.callback = callback self.mutex = Lock() class ParameterEventCallbackHandle: def __init__( self, callback: Callable[[ParameterEvent], None] ) -> None: self.callback = callback self.mutex = Lock() class ParameterEventHandler: class Callbacks: def __init__( self ) -> None: """ Create a Callbacks container for ParameterEventHandler. Callbacks container is used to store and manage parameter and parameter-event callbacks """ self.parameter_callbacks: Dict[ Tuple[str, str], List[ParameterCallbackHandle] ] = defaultdict(list) self.event_callbacks: List[ParameterEventCallbackHandle] = [] self.mutex = Lock() def event_callback(self, event: ParameterEvent) -> None: """ Search for callback and execute it. Method to be utilized by ParameterEventHandler object as a callback for subscription to a /parameter_events topic. Used to traverse parameter_callbacks dict and perform callbacks, related to Parameter, specified in event. :param event: ParameterEvent message. By design, originates from /parameter_events topic """ with self.mutex: for (param_name, node_name), callbacks_list in self.parameter_callbacks.items(): if parameter := ParameterEventHandler.get_parameter_from_event( event, parameter_name=param_name, node_name=node_name ): for callback_handle in callbacks_list: with callback_handle.mutex: callback_handle.callback(parameter) for event_callback in self.event_callbacks: with event_callback.mutex: event_callback.callback(event) def add_parameter_callback( self, parameter_name: str, node_name: str, callback: Callable[[ParameterMsg], None], ) -> ParameterCallbackHandle: """ Add new parameter callback. Callbacks are called in FILO manner. :param parameter_name: Name of a parameter to bind the callback to :param node_name: Name of a node, that the parameter should be related to :param callback: A callable to be called when a parameter event occurs :return ParameterCallbackHandle: A handle that should be saved by the user so that the callback can be later removed. """ handle = ParameterCallbackHandle( parameter_name=parameter_name, node_name=node_name, callback=callback, ) with self.mutex: self.parameter_callbacks[(parameter_name, node_name)].insert(0, handle) return handle def remove_parameter_callback( self, handle: ParameterCallbackHandle, ) -> None: """ Remove the parameter callback related to provided handle. :param handle: The handle of the callback that is to be removed """ with self.mutex: handle_key = (handle.parameter_name, handle.node_name) if handle_key in self.parameter_callbacks: if handle in self.parameter_callbacks[handle_key]: self.parameter_callbacks[handle_key].remove(handle) else: raise RuntimeError("Callback doesn't exist") if len(self.parameter_callbacks[handle_key]) == 0: self.parameter_callbacks.pop(handle_key) else: raise RuntimeError("Callback doesn't exist") def add_parameter_event_callback( self, callback: Callable[[ParameterEvent], None], ) -> ParameterEventCallbackHandle: """ Add new parameter event callback. Callbacks are called in FILO manner. :param callback: A callable to be referenced on a ParameterEvent :return ParameterEventCallbackHandle: A handle that should be saved by the user so that the event_callback can be later removed. """ handle = ParameterEventCallbackHandle(callback=callback) with self.mutex: self.event_callbacks.insert(0, handle) return handle def remove_parameter_event_callback( self, handle: ParameterEventCallbackHandle, ) -> None: """ Remove the parameter event callback related to provided handle. :param handle: A handle of the callback that is to be removed """ with self.mutex: if handle in self.event_callbacks: self.event_callbacks.remove(handle) else: raise RuntimeError("Callback doesn't exist") def __init__( self, node: Node, qos_profile: QoSProfile = qos_profile_parameter_events, callback_group: Optional[CallbackGroup] = None, event_callbacks: Optional[SubscriptionEventCallbacks] = None, qos_overriding_options: Optional[QoSOverridingOptions] = None, raw: bool = False, ) -> None: """ Create ParameterEventHandler. Usage example: .. code-block:: python import rclpy from rclpy.parameter_event_handler import ParameterEventHandler handler = ParameterEventHandler(node) # Add parameter callback handle = handler.add_parameter_callback( parameter_name="example_parameter", node_name="example", callback=example_callable, ) # Remove parameter callback handler.remove_parameter_callback(handle) # Add parameter event callback handle = handler.add_parameter_event_callback( callback=example_callable, ) # Remove parameter event callback handler.remove_parameter_event_callback(handle) .. A class used to "handle" (monitor and respond to) changes to parameters. :param node: Used to subscribe to parameter_events topic :param qos_profile: A QoSProfile or a history depth to apply to the subscription. In the case that a history depth is provided, the QoS history is set to KEEP_LAST, the QoS history depth is set to the value of the parameter, and all other QoS settings are set to their default values. :param callback_group: The callback group for the subscription. If ``None``, then the default callback group for the node is used. :param event_callbacks: User-defined callbacks for middleware events. :param qos_overriding_options: Options to customize QoS parameter overrides. :param raw: If ``True``, then received messages will be stored in raw binary representation. """ self.node = node self.qos_profile = qos_profile self._callbacks = ParameterEventHandler.Callbacks() self.parameter_event_subscription = node.create_subscription( ParameterEvent, '/parameter_events', self._callbacks.event_callback, self.qos_profile, callback_group=callback_group, event_callbacks=event_callbacks, qos_overriding_options=qos_overriding_options, raw=raw, ) def destroy(self) -> None: self.node.destroy_subscription( self.parameter_event_subscription ) @staticmethod def get_parameter_from_event( event: ParameterEvent, parameter_name: str, node_name: str, ) -> Optional[ParameterMsg]: """ Get specified parameter value from ParameterEvent message. :param event: ParameterEvent message to be read :param parameter_name: Name of a parameter to get from ParameterEvent message :param node_name: Name of a node, that the parameter should be related to :return Optional[Parameter]: If specified parameter is found, returns Parameter object. Otherwise, returns None """ if event.node == node_name: for parameter in chain(event.new_parameters, event.changed_parameters): if parameter.name == parameter_name: return parameter return None @staticmethod def get_parameters_from_event(event: ParameterEvent) -> Iterable[ParameterMsg]: """ Get all parameters from a ParameterEvent message. :param event: ParameterEvent message to read """ for parameter in chain(event.new_parameters, event.changed_parameters): yield parameter def add_parameter_callback( self, parameter_name: str, node_name: str, callback: Callable[[ParameterMsg], None], ) -> ParameterCallbackHandle: """ Add new parameter callback. Callbacks are called in FILO manner. The configure_nodes_filter() function will affect the behavior of this function. If the node specified in this function isn't included in the nodes specified in configure_nodes_filter(), the callback will never be called. :param parameter_name: Name of a parameter to tie callback to :param node_name: Name of a node, that the parameter should be related to :param callback: A callable to be called when the parameter is modified :return ParameterCallbackHandle: A handle that should be saved by the user so that the event_callback can be later removed. """ return self._callbacks.add_parameter_callback( parameter_name=parameter_name, node_name=self._resolve_path(node_name), callback=callback, ) def remove_parameter_callback( self, handle: ParameterCallbackHandle, ) -> None: """ Remove a ParameterCallbackHandle. Perform no callbacks on this parameter events in the future. :param handle: ParameterCallbackHandle of a callback to be removed """ self._callbacks.remove_parameter_callback(handle) def add_parameter_event_callback( self, callback: Callable[[ParameterEvent], None], ) -> ParameterEventCallbackHandle: """ Add new parameter callback. Callbacks are called in FILO manner. :param callback: A callable to be referenced on a ParameterEvent :return ParameterEventCallbackHandle: A handle that should be saved by the user so that the event_callback can be later removed. """ return self._callbacks.add_parameter_event_callback(callback) def remove_parameter_event_callback( self, handle: ParameterEventCallbackHandle, ) -> None: """ Remove a ParameterEventCallbackHandle. Perform no callbacks on parameter events in the future. :param handle: ParameterEventCallbackHandle of a callback to be removed """ self._callbacks.remove_parameter_event_callback(handle) def configure_nodes_filter( self, node_names: Optional[List[str]] = None, ) -> bool: """ Configure which node parameter events will be received. This function depends on rmw implementation support for content filtering. If middleware doesn't support contentfilter, return false. If node_names is empty, the configured node filter will be cleared. If this function return true, only parameter events from the specified node will be received. It affects the behavior of the following two functions. - add_parameter_event_callback() The callback will only be called for parameter events from the specified nodes which are configured in this function. - add_parameter_callback() The callback will only be called for parameter events from the specified nodes which are configured in this function and add_parameter_callback(). If the nodes specified in this function is different from the nodes specified in add_parameter_callback(), the callback will never be called. :param node_names: Node names to filter parameter events from :return: True if the filter was successfully applied, False otherwise. :raises: RCLError if internal error occurred when calling the rcl function. """ if node_names is None or len(node_names) == 0: # Clear content filter self.parameter_event_subscription.set_content_filter('', []) if (self.parameter_event_subscription.is_cft_enabled is True): return False return True filter_expression = ' OR '.join([f'node = %{i}' for i in range(len(node_names))]) # Enclose each node name in "'" quoted_node_names = [f"'{node_name}'" for node_name in node_names] self.parameter_event_subscription.set_content_filter(filter_expression, quoted_node_names) return self.parameter_event_subscription.is_cft_enabled def _resolve_path( self, node_path: Optional[str] = None, ) -> str: """ Get full name of a node. :param node_path: Name of a node with namespaces. """ if not node_path: return self.node.get_fully_qualified_name() if node_path.startswith('/'): return node_path node_namespace = self.node.get_namespace().lstrip('/') resolved_path = '/'.join([node_namespace, node_path]) return resolved_path if resolved_path.startswith('/') else f'/{resolved_path}'
# Copyright 2023 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import threading import time from typing import Any from typing import Callable, Optional from typing import Union import unittest import pytest from rcl_interfaces.msg import Parameter as ParameterMsg from rcl_interfaces.msg import ParameterEvent import rclpy.context from rclpy.executors import SingleThreadedExecutor from rclpy.parameter import Parameter from rclpy.parameter_event_handler import ParameterCallbackHandle from rclpy.parameter_event_handler import ParameterEventCallbackHandle from rclpy.parameter_event_handler import ParameterEventHandler from rclpy.qos import qos_profile_parameter_events class ParameterEventHandlerTester(ParameterEventHandler): def test_event(self, parameter_event: ParameterEvent) -> None: self._callbacks.event_callback(parameter_event) class CallbackChecker: def __init__(self) -> None: self.received = False def callback(self, _: Union[Parameter[Any], ParameterEvent]) -> None: self.received = True class CallCounter: def __init__(self) -> None: self.counter = 0 self.first_callback_call_order = 0 self.second_callback_call_order = 0 def first_callback(self, _: Union[Parameter[Any], ParameterEvent]) -> None: self.counter += 1 self.first_callback_call_order = self.counter def second_callback(self, _: Union[Parameter[Any], ParameterEvent]) -> None: self.counter += 1 self.second_callback_call_order = self.counter class TestParameterEventHandler(unittest.TestCase): def setUp(self) -> None: self.context = rclpy.context.Context() rclpy.init(context=self.context) self.handler_node = rclpy.create_node( 'test_parameter_event_handler', namespace='/rclpy', context=self.context ) self.target_node = rclpy.create_node( 'test_parameter_event_handler_target', namespace='/rclpy', allow_undeclared_parameters=True, context=self.context ) self.target_node.declare_parameter('int_arr_param', [1, 2, 3]) self.target_node.declare_parameter('float.param..', 3.14) self.parameter_event_handler = ParameterEventHandlerTester( self.handler_node, qos_profile_parameter_events, ) self.executor = SingleThreadedExecutor(context=self.context) self.executor.add_node(self.handler_node) self.executor.add_node(self.target_node) def tearDown(self) -> None: self.executor.shutdown() self.handler_node.destroy_node() self.target_node.destroy_node() rclpy.shutdown(context=self.context) def test_register_parameter_callback(self) -> None: self.parameter_event_handler._callbacks.parameter_callbacks.clear() parameter_name = 'double_param' node_name = self.target_node.get_fully_qualified_name() # Callback is not called in this test anyway handle = self.parameter_event_handler.add_parameter_callback( parameter_name, node_name, lambda _: None ) assert isinstance(handle, ParameterCallbackHandle) assert {(parameter_name, node_name): [handle]} ==\ self.parameter_event_handler._callbacks.parameter_callbacks def test_get_parameter_from_event(self) -> None: int_param = Parameter('int_param', Parameter.Type.INTEGER, 1) str_param = Parameter('str_param', Parameter.Type.STRING, 'hello world') new_params_event = ParameterEvent( node=self.target_node.get_fully_qualified_name(), new_parameters=[int_param, str_param] ) # Correct parameter name, corrent node name assert int_param == ParameterEventHandler.get_parameter_from_event( new_params_event, 'int_param', self.target_node.get_fully_qualified_name() ) assert str_param == ParameterEventHandler.get_parameter_from_event( new_params_event, 'str_param', self.target_node.get_fully_qualified_name() ) # Correct parameter name, incorrect node name assert None is ParameterEventHandler.get_parameter_from_event( new_params_event, 'int_param', '/wrong_node_name' ) assert None is ParameterEventHandler.get_parameter_from_event( new_params_event, 'str_param', '/wrong_node_name' ) # Incorrect parameter name, correct node name assert None is ParameterEventHandler.get_parameter_from_event( new_params_event, 'wrong_int_param', self.target_node.get_fully_qualified_name() ) assert None is ParameterEventHandler.get_parameter_from_event( new_params_event, 'wrong_str_param', self.target_node.get_fully_qualified_name() ) # Incorrect parameter name, incorrect node name assert None is ParameterEventHandler.get_parameter_from_event( new_params_event, 'wrong_int_param', '/wrong_node_name' ) assert None is ParameterEventHandler.get_parameter_from_event( new_params_event, 'wrong_str_param', '/wrong_node_name' ) def test_get_parameters_from_event(self) -> None: int_param = Parameter('int_param', Parameter.Type.INTEGER, 1) str_param = Parameter('str_param', Parameter.Type.STRING, 'hello world') event = ParameterEvent( node=self.target_node.get_fully_qualified_name(), changed_parameters=[int_param, str_param] ) res = ParameterEventHandler.get_parameters_from_event(event) assert {int_param, str_param} == set(res) def test_register_parameter_event_callback(self) -> None: self.parameter_event_handler._callbacks.event_callbacks.clear() handle = self.parameter_event_handler.add_parameter_event_callback( lambda x: None ) assert isinstance(handle, ParameterEventCallbackHandle) assert [handle] == self.parameter_event_handler._callbacks.event_callbacks def test_parameter_callback(self) -> None: callback_checker = CallbackChecker() parameter_name = 'int_param' node_name = self.target_node.get_fully_qualified_name() parameter = Parameter(parameter_name, Parameter.Type.INTEGER, 1) parameter_event = ParameterEvent( node=node_name, changed_parameters=[parameter] ) callback_handle = self.parameter_event_handler.add_parameter_callback( parameter_name, node_name, callback_checker.callback ) assert not callback_checker.received self.parameter_event_handler.test_event(parameter_event) assert callback_checker.received self.parameter_event_handler.remove_parameter_callback(callback_handle) callback_checker.received = False self.parameter_event_handler.test_event(parameter_event) assert not callback_checker.received with pytest.raises(RuntimeError): self.parameter_event_handler.remove_parameter_callback(callback_handle) def test_parameter_event_callback(self) -> None: callback_checker = CallbackChecker() parameter_name = 'int_param' node_name = self.target_node.get_fully_qualified_name() parameter = Parameter(parameter_name, Parameter.Type.INTEGER, 1) parameter_event = ParameterEvent( node=node_name, changed_parameters=[parameter] ) callback_handle = self.parameter_event_handler.add_parameter_event_callback( callback_checker.callback ) assert not callback_checker.received self.parameter_event_handler.test_event(parameter_event) assert callback_checker.received self.parameter_event_handler.remove_parameter_event_callback(callback_handle) callback_checker.received = False self.parameter_event_handler.test_event(parameter_event) assert not callback_checker.received with pytest.raises(RuntimeError): self.parameter_event_handler.remove_parameter_event_callback(callback_handle) def test_last_in_first_call_for_parameter_callbacks(self) -> None: call_counter = CallCounter() parameter_name = 'int_param' parameter = Parameter(parameter_name, Parameter.Type.INTEGER, 1) node_name = self.target_node.get_fully_qualified_name() parameter_event = ParameterEvent( node=node_name, changed_parameters=[parameter] ) self.parameter_event_handler.add_parameter_callback( parameter_name, node_name, call_counter.first_callback ) self.parameter_event_handler.add_parameter_callback( parameter_name, node_name, call_counter.second_callback ) assert call_counter.first_callback_call_order == 0 assert call_counter.second_callback_call_order == 0 self.parameter_event_handler.test_event(parameter_event) # Last in first called assert call_counter.first_callback_call_order == 2 assert call_counter.second_callback_call_order == 1 def test_last_in_first_call_for_parameter_event_callbacks(self) -> None: call_counter = CallCounter() parameter_name = 'int_param' parameter = Parameter(parameter_name, Parameter.Type.INTEGER, 1) node_name = self.target_node.get_fully_qualified_name() parameter_event = ParameterEvent( node=node_name, changed_parameters=[parameter] ) self.parameter_event_handler.add_parameter_event_callback( call_counter.first_callback ) self.parameter_event_handler.add_parameter_event_callback( call_counter.second_callback ) assert call_counter.first_callback_call_order == 0 assert call_counter.second_callback_call_order == 0 self.parameter_event_handler.test_event(parameter_event) # Last in first called assert call_counter.first_callback_call_order == 2 assert call_counter.second_callback_call_order == 1 def test_resolve_path_empty_path(self) -> None: assert '/rclpy/test_parameter_event_handler' ==\ self.parameter_event_handler._resolve_path() def test_resolve_path_same_namespace(self) -> None: assert '/rclpy/test_node' == self.parameter_event_handler._resolve_path('test_node') def test_resolve_path_other_namespace(self) -> None: assert '/test_node' == self.parameter_event_handler._resolve_path('/test_node') def test_configure_nodes_filter_with_check_add_parameter_event_callback(self) -> None: remote_node_name1 = 'remote_node_1' remote_node1 = rclpy.create_node( remote_node_name1, namespace='/rclpy', context=self.context) remote_node_name2 = 'remote_node_2' remote_node2 = rclpy.create_node( remote_node_name2, namespace='/rclpy', context=self.context) remote_node1_param_name = 'param_node1' remote_node2_param_name = 'param_node2' remote_node1.declare_parameter(remote_node1_param_name, 10) remote_node2.declare_parameter(remote_node2_param_name, 'Default') received_event_from_remote_node1 = False received_event_from_remote_node2 = False def callback(param: ParameterEvent) -> None: nonlocal received_event_from_remote_node1, received_event_from_remote_node2 if param.node == f'/rclpy/{remote_node_name1}': received_event_from_remote_node1 = True elif param.node == f'/rclpy/{remote_node_name2}': received_event_from_remote_node2 = True # Configure to only receive parameter events from remote_node_name2 assert self.parameter_event_handler.configure_nodes_filter( [f'/rclpy/{remote_node_name2}']) self.parameter_event_handler.add_parameter_event_callback(callback) def wait_param_event(executor: SingleThreadedExecutor, timeout: int, condition: Optional[Callable[[], bool]] = None): start = time.monotonic() while time.monotonic() - start < timeout: executor.spin_once(0.2) if condition is not None and condition(): break thread = threading.Thread(target=wait_param_event, args=(self.executor, 2)) thread.start() time.sleep(0.1) # 100ms remote_node1.set_parameters( [Parameter(remote_node1_param_name, Parameter.Type.INTEGER, 20)]) remote_node2.set_parameters( [Parameter(remote_node2_param_name, Parameter.Type.STRING, 'abc')]) thread.join() assert not received_event_from_remote_node1 assert received_event_from_remote_node2 # Clear node filter and all parameter events from remote nodes should be received assert self.parameter_event_handler.configure_nodes_filter() received_event_from_remote_node1 = False received_event_from_remote_node2 = False def check_both_received(): return received_event_from_remote_node1 and received_event_from_remote_node2 thread = threading.Thread( target=wait_param_event, args=(self.executor, 2, check_both_received)) thread.start() time.sleep(0.1) # 100ms remote_node1.set_parameters( [Parameter(remote_node1_param_name, Parameter.Type.INTEGER, 30)]) remote_node2.set_parameters( [Parameter(remote_node2_param_name, Parameter.Type.STRING, 'def')]) thread.join() assert received_event_from_remote_node1 assert received_event_from_remote_node2 remote_node1.destroy_node() remote_node2.destroy_node() def test_configure_nodes_filter_with_check_add_parameter_callback(self) -> None: remote_node_name1 = 'remote_node_1' remote_node1 = rclpy.create_node( remote_node_name1, namespace='/rclpy', context=self.context) remote_node_name2 = 'remote_node_2' remote_node2 = rclpy.create_node( remote_node_name2, namespace='/rclpy', context=self.context) remote_node1_param_name = 'param_node1' remote_node2_param_name = 'param_node2' remote_node1.declare_parameter(remote_node1_param_name, 10) remote_node2.declare_parameter(remote_node2_param_name, 'Default') received_event_from_remote_node1 = False received_event_from_remote_node2 = False def callback_remote_node1(param: ParameterMsg) -> None: nonlocal received_event_from_remote_node1 if param.name == remote_node1_param_name: received_event_from_remote_node1 = True def callback_remote_node2(param: ParameterMsg) -> None: nonlocal received_event_from_remote_node2 if param.name == remote_node2_param_name: received_event_from_remote_node2 = True # Configure to only receive parameter events from remote_node_name2 assert self.parameter_event_handler.configure_nodes_filter( [f'/rclpy/{remote_node_name2}']) self.parameter_event_handler.add_parameter_callback( remote_node1_param_name, remote_node_name1, callback_remote_node1) self.parameter_event_handler.add_parameter_callback( remote_node2_param_name, remote_node_name2, callback_remote_node2) def wait_param_event(executor: SingleThreadedExecutor, timeout: int, condition: Optional[Callable[[], bool]] = None): start = time.monotonic() while time.monotonic() - start < timeout: executor.spin_once(0.2) if condition is not None and condition(): break thread = threading.Thread(target=wait_param_event, args=(self.executor, 2)) thread.start() time.sleep(0.1) # 100ms remote_node1.set_parameters( [Parameter(remote_node1_param_name, Parameter.Type.INTEGER, 20)]) remote_node2.set_parameters( [Parameter(remote_node2_param_name, Parameter.Type.STRING, 'abc')]) thread.join() assert not received_event_from_remote_node1 assert received_event_from_remote_node2 # Clear node filter and all parameter events from remote nodes should be received assert self.parameter_event_handler.configure_nodes_filter() received_event_from_remote_node1 = False received_event_from_remote_node2 = False def check_both_received(): return received_event_from_remote_node1 and received_event_from_remote_node2 thread = threading.Thread( target=wait_param_event, args=(self.executor, 2, check_both_received)) thread.start() time.sleep(0.1) # 100ms remote_node1.set_parameters( [Parameter(remote_node1_param_name, Parameter.Type.INTEGER, 30)]) remote_node2.set_parameters( [Parameter(remote_node2_param_name, Parameter.Type.STRING, 'def')]) thread.join() assert received_event_from_remote_node1 assert received_event_from_remote_node2 remote_node1.destroy_node() remote_node2.destroy_node() if __name__ == '__main__': unittest.main()
rclpy
python
# Copyright 2019 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Literal from rclpy.exceptions import InvalidParameterException def validate_parameter_name(name: str) -> Literal[True]: """ Validate a given parameter name, and raise an exception if invalid. The name does not have to be fully-qualified and is not expanded. If the name is invalid then rclpy.exceptions.InvalidParameterException will be raised. :param name: parameter name to be validated. :raises: InvalidParameterException: when the name is invalid. """ # TODO(jubeira): add parameter name check to be implemented at RCL level. if not name: raise InvalidParameterException(name) return True
# Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from array import array import os from tempfile import NamedTemporaryFile import unittest import pytest from rcl_interfaces.msg import Parameter as ParameterMsg from rcl_interfaces.msg import ParameterType from rcl_interfaces.msg import ParameterValue from rclpy.parameter import get_parameter_value from rclpy.parameter import Parameter from rclpy.parameter import parameter_dict_from_yaml_file from rclpy.parameter import parameter_value_to_python class TestParameter(unittest.TestCase): def test_create_boolean_parameter(self) -> None: p = Parameter('myparam', Parameter.Type.BOOL, True) self.assertEqual(p.name, 'myparam') self.assertEqual(p.value, True) p = Parameter('myparam', value=True) self.assertEqual(p.name, 'myparam') self.assertEqual(p.value, True) def test_create_bytes_parameter(self) -> None: p = Parameter('myparam', Parameter.Type.BYTE_ARRAY, [b'p', b'v', b'a', b'l', b'u', b'e']) self.assertEqual(p.name, 'myparam') self.assertEqual(p.value, [b'p', b'v', b'a', b'l', b'u', b'e']) p = Parameter('myparam', value=[b'p', b'v', b'a', b'l', b'u', b'e']) self.assertEqual(p.name, 'myparam') self.assertEqual(p.type_, Parameter.Type.BYTE_ARRAY) self.assertEqual(p.value, [b'p', b'v', b'a', b'l', b'u', b'e']) def test_create_float_parameter(self) -> None: p = Parameter('myparam', Parameter.Type.DOUBLE, 2.41) self.assertEqual(p.name, 'myparam') self.assertEqual(p.value, 2.41) p = Parameter('myparam', value=2.41) self.assertEqual(p.name, 'myparam') self.assertEqual(p.type_, Parameter.Type.DOUBLE) self.assertEqual(p.value, 2.41) def test_create_integer_parameter(self) -> None: p = Parameter('myparam', Parameter.Type.INTEGER, 42) self.assertEqual(p.name, 'myparam') self.assertEqual(p.value, 42) p = Parameter('myparam', value=42) self.assertEqual(p.name, 'myparam') self.assertEqual(p.type_, Parameter.Type.INTEGER) self.assertEqual(p.value, 42) def test_create_string_parameter(self) -> None: p = Parameter('myparam', Parameter.Type.STRING, 'pvalue') self.assertEqual(p.name, 'myparam') self.assertEqual(p.value, 'pvalue') p = Parameter('myparam', value='pvalue') self.assertEqual(p.name, 'myparam') self.assertEqual(p.type_, Parameter.Type.STRING) self.assertEqual(p.value, 'pvalue') def test_create_boolean_array_parameter(self) -> None: p = Parameter('myparam', Parameter.Type.BOOL_ARRAY, [True, False, True]) self.assertEqual(p.value, [True, False, True]) p = Parameter('myparam', value=[True, False, True]) self.assertEqual(p.type_, Parameter.Type.BOOL_ARRAY) self.assertEqual(p.value, [True, False, True]) def test_create_float_array_parameter(self) -> None: p = Parameter('myparam', Parameter.Type.DOUBLE_ARRAY, [2.41, 6.28]) self.assertEqual(p.value, [2.41, 6.28]) p = Parameter('myparam', value=[2.41, 6.28]) self.assertEqual(p.type_, Parameter.Type.DOUBLE_ARRAY) self.assertEqual(p.value, [2.41, 6.28]) def test_create_integer_array_parameter(self) -> None: p = Parameter('myparam', Parameter.Type.INTEGER_ARRAY, [1, 2, 3]) self.assertEqual(p.value, [1, 2, 3]) p = Parameter('myparam', value=[1, 2, 3]) self.assertEqual(p.type_, Parameter.Type.INTEGER_ARRAY) self.assertEqual(p.value, [1, 2, 3]) def test_create_string_array_parameter(self) -> None: p = Parameter('myparam', Parameter.Type.STRING_ARRAY, ['hello', 'world']) self.assertEqual(p.value, ['hello', 'world']) p = Parameter('myparam', value=['hello', 'world']) self.assertEqual(p.type_, Parameter.Type.STRING_ARRAY) self.assertEqual(p.value, ['hello', 'world']) def test_create_not_set_parameter(self) -> None: p = Parameter('myparam', Parameter.Type.NOT_SET) self.assertIsNone(p.value) p = Parameter('myparam') self.assertIsNone(p.value) self.assertEqual(p.type_, Parameter.Type.NOT_SET) p = Parameter('myparam', value=None) self.assertIsNone(p.value) self.assertEqual(p.type_, Parameter.Type.NOT_SET) def test_value_and_type_must_agree(self) -> None: with self.assertRaises(ValueError): Parameter('myparam', Parameter.Type.NOT_SET, 42) with self.assertRaises(ValueError): Parameter('myparam', Parameter.Type.BOOL_ARRAY, 42) def test_error_on_illegal_value_type(self) -> None: with self.assertRaises(TypeError): Parameter('illegaltype', 'mytype', 'myvalue') # type: ignore[call-overload] with self.assertRaises(TypeError): Parameter('illegaltype', value={'invalid': 'type'}) # type: ignore[call-overload] def test_integer_tuple_array(self) -> None: # list int_list = [1, 2, 3] self.assertEqual( Parameter.Type.INTEGER_ARRAY, Parameter.Type.from_parameter_value(int_list)) self.assertTrue(Parameter.Type.check(Parameter.Type.INTEGER_ARRAY, int_list)) # tuple int_tuple = (1, 2, 3) self.assertEqual( Parameter.Type.INTEGER_ARRAY, Parameter.Type.from_parameter_value(int_tuple)) self.assertTrue(Parameter.Type.check(Parameter.Type.INTEGER_ARRAY, int_tuple)) def test_integer_array(self) -> None: int_array = array('i', [1, 2, 3]) self.assertEqual( Parameter.Type.INTEGER_ARRAY, Parameter.Type.from_parameter_value(int_array)) # test that it doesn't raise Parameter.from_parameter_msg(ParameterMsg( name='int_array', value=ParameterValue(type=7, integer_array_value=[1, 2, 3]) )) def test_double_array(self) -> None: double_array = array('d', [1.0, 2.0, 3.0]) self.assertEqual( Parameter.Type.DOUBLE_ARRAY, Parameter.Type.from_parameter_value(double_array)) # test that it doesn't raise Parameter.from_parameter_msg(ParameterMsg( name='double_array', value=ParameterValue(type=8, double_array_value=[1.0, 2.0, 3.0]) )) def test_get_parameter_value(self) -> None: """Test the get_parameter_value function.""" test_cases = [ (True, ParameterValue(type=int(ParameterType.PARAMETER_BOOL), bool_value=True)), (42, ParameterValue(type=int(ParameterType.PARAMETER_INTEGER), integer_value=42)), (3.5, ParameterValue(type=int(ParameterType.PARAMETER_DOUBLE), double_value=3.5)), ('foo', ParameterValue(type=int(ParameterType.PARAMETER_STRING), string_value='foo')), (' ', ParameterValue(type=int(ParameterType.PARAMETER_STRING), string_value=' ')), ('', ParameterValue(type=int(ParameterType.PARAMETER_STRING), string_value='')), ( [True, False], ParameterValue( type=int(ParameterType.PARAMETER_BOOL_ARRAY), bool_array_value=[True, False]) ), ( [1, 2, 3], ParameterValue( type=int(ParameterType.PARAMETER_INTEGER_ARRAY), integer_array_value=[1, 2, 3]) ), ( [1.0, 2.0, 3.0], ParameterValue( type=int(ParameterType.PARAMETER_DOUBLE_ARRAY), double_array_value=[1.0, 2.0, 3.0]) ), ( ['foo', 'bar'], ParameterValue( type=int(ParameterType.PARAMETER_STRING_ARRAY), string_array_value=['foo', 'bar']) ), ] for input_value, expected_value in test_cases: try: p = get_parameter_value(str(input_value)) except Exception as e: assert False, f'failed to get param_value, reason: {e}' self.assertEqual(p, expected_value) def test_parameter_value_to_python(self) -> None: """Test the parameter_value_to_python conversion function.""" test_cases = [ (ParameterValue(type=int(ParameterType.PARAMETER_NOT_SET)), None), (ParameterValue(type=int(ParameterType.PARAMETER_INTEGER), integer_value=42), 42), (ParameterValue(type=int(ParameterType.PARAMETER_DOUBLE), double_value=3.5), 3.5), (ParameterValue(type=int(ParameterType.PARAMETER_STRING), string_value='foo'), 'foo'), ( ParameterValue( type=int(ParameterType.PARAMETER_BYTE_ARRAY), byte_array_value=[b'J', b'P'] ), [b'J', b'P'] ), ( ParameterValue( type=int(ParameterType.PARAMETER_INTEGER_ARRAY), integer_array_value=[1, 2, 3]), [1, 2, 3] ), ( ParameterValue( type=int(ParameterType.PARAMETER_DOUBLE_ARRAY), double_array_value=[1.0, 2.0, 3.0]), [1.0, 2.0, 3.0] ), ( ParameterValue( type=int(ParameterType.PARAMETER_STRING_ARRAY), string_array_value=['foo', 'bar']), ['foo', 'bar'] ), ] for input_value, expected_value in test_cases: result_value = parameter_value_to_python(input_value) if isinstance(result_value, list) and isinstance(expected_value, list): assert len(result_value) == len(expected_value) # element-wise comparison for lists assert all(x == y for x, y in zip(result_value, expected_value)) else: assert result_value == expected_value # Test invalid 'type' member parameter_value = ParameterValue(type=42) with pytest.raises(RuntimeError): parameter_value_to_python(parameter_value) def test_parameter_dict_from_yaml_file(self) -> None: yaml_string = """ /param_test_target: ros__parameters: abs-nodename: true param_test_target: ros__parameters: base-nodename: true /foo/param_test_target: ros__parameters: abs-ns-nodename: true /foo: param_test_target: ros__parameters: abs-ns-base-nodename: true /bar/param_test_target: ros__parameters: abs-ns-nodename: false /bar: param_test_target: ros__parameters: abs-ns-base-nodename: false /**: ros__parameters: wildcard: true """ # target nodes is specified, so it should only parse wildcard expected_no_target_node = { 'wildcard': Parameter('wildcard', Parameter.Type.BOOL, True).to_parameter_msg(), } # target nodes is specified with wildcard enabled expected_target_node_wildcard = { 'wildcard': Parameter( 'wildcard', Parameter.Type.BOOL, True).to_parameter_msg(), 'abs-nodename': Parameter( 'abs-nodename', Parameter.Type.BOOL, True).to_parameter_msg(), 'base-nodename': Parameter( 'base-nodename', Parameter.Type.BOOL, True).to_parameter_msg(), } # target nodes is specified with wildcard disabled expected_target_node = { 'abs-nodename': Parameter( 'abs-nodename', Parameter.Type.BOOL, True).to_parameter_msg(), 'base-nodename': Parameter( 'base-nodename', Parameter.Type.BOOL, True).to_parameter_msg(), } # target nodes is specified with wildcard and namespace expected_target_node_ns = { 'wildcard': Parameter('wildcard', Parameter.Type.BOOL, True).to_parameter_msg(), 'abs-ns-nodename': Parameter( 'abs-ns-nodename', Parameter.Type.BOOL, True).to_parameter_msg(), 'abs-ns-base-nodename': Parameter( 'abs-ns-base-nodename', Parameter.Type.BOOL, True).to_parameter_msg(), } try: with NamedTemporaryFile(mode='w', delete=False) as f: f.write(yaml_string) f.flush() f.close() parameter_dict = parameter_dict_from_yaml_file(f.name, True) assert parameter_dict == expected_no_target_node parameter_dict = parameter_dict_from_yaml_file( f.name, True, target_nodes=['']) assert parameter_dict == expected_no_target_node parameter_dict = parameter_dict_from_yaml_file( f.name, True, target_nodes=['param_test_target']) assert parameter_dict == expected_target_node_wildcard parameter_dict = parameter_dict_from_yaml_file( f.name, False, target_nodes=['/param_test_target']) assert parameter_dict == expected_target_node parameter_dict = parameter_dict_from_yaml_file( f.name, True, target_nodes=['/foo/param_test_target']) assert parameter_dict == expected_target_node_ns finally: if os.path.exists(f.name): os.unlink(f.name) self.assertRaises(FileNotFoundError, parameter_dict_from_yaml_file, 'unknown_file') if __name__ == '__main__': unittest.main()
rclpy
python
# Copyright 2016 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from types import TracebackType from typing import Generic, List, Optional, Type, TypeVar, Union from rclpy.callback_groups import CallbackGroup from rclpy.duration import Duration from rclpy.event_handler import EventHandler, PublisherEventCallbacks from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy from rclpy.qos import QoSProfile from rclpy.type_support import MsgT # Left to support Legacy TypeVars. MsgType = TypeVar('MsgType') class Publisher(Generic[MsgT]): def __init__( self, publisher_impl: '_rclpy.Publisher[MsgT]', msg_type: Type[MsgT], topic: str, qos_profile: QoSProfile, event_callbacks: PublisherEventCallbacks, callback_group: CallbackGroup, ) -> None: """ Create a container for a ROS publisher. .. warning:: Users should not create a publisher with this constructor, instead they should call :meth:`.Node.create_publisher`. A publisher is used as a primary means of communication in a ROS system by publishing messages on a ROS topic. :param publisher_impl: Publisher wrapping the underlying ``rcl_publisher_t`` object. :param msg_type: The type of ROS messages the publisher will publish. :param topic: The name of the topic the publisher will publish to. :param qos_profile: The quality of service profile to apply to the publisher. """ self.__publisher = publisher_impl self.msg_type = msg_type self.topic = topic self.qos_profile = qos_profile self.event_handlers: List[EventHandler] = event_callbacks.create_event_handlers( callback_group, publisher_impl, topic) def publish(self, msg: Union[MsgT, bytes]) -> None: """ Send a message to the topic for the publisher. :param msg: The ROS message to publish. :raises: TypeError if the type of the passed message isn't an instance of the provided type when the publisher was constructed. """ with self.handle: if isinstance(msg, self.msg_type): self.__publisher.publish(msg) elif isinstance(msg, bytes): self.__publisher.publish_raw(msg) else: raise TypeError('Expected {}, got {}'.format(self.msg_type, type(msg))) def get_subscription_count(self) -> int: """Get the amount of subscribers that this publisher has.""" with self.handle: return self.__publisher.get_subscription_count() @property def topic_name(self) -> str: with self.handle: return self.__publisher.get_topic_name() @property def handle(self) -> '_rclpy.Publisher[MsgT]': return self.__publisher @property def logger_name(self) -> str: """Get the name of the logger associated with the node of the publisher.""" with self.handle: return self.__publisher.get_logger_name() def destroy(self) -> None: """ Destroy a container for a ROS publisher. .. warning:: Users should not destroy a publisher with this method, instead they should call :meth:`.Node.destroy_publisher`. """ for handler in self.event_handlers: handler.destroy() self.__publisher.destroy_when_not_in_use() def assert_liveliness(self) -> None: """ Manually assert that this Publisher is alive. If the QoS Liveliness policy is set to MANUAL_BY_TOPIC, the application must call this at least as often as ``QoSProfile.liveliness_lease_duration``. """ with self.handle: _rclpy.rclpy_assert_liveliness(self.handle) def wait_for_all_acked(self, timeout: Duration = Duration(seconds=-1)) -> bool: """ Wait until all published message data is acknowledged or until the timeout elapses. If the timeout is negative then this function will block indefinitely until all published message data is acknowledged. If the timeout is 0 then it will check if all published message has been acknowledged without waiting. If the timeout is greater than 0 then it will return after that period of time has elapsed or all published message data is acknowledged. This function only waits for acknowledgments if the publisher's QOS profile is RELIABLE. Otherwise this function will immediately return true. :param timeout: the duration to wait for all published message data to be acknowledged. :returns: true if all published message data is acknowledged before the timeout, otherwise false. """ with self.handle: return self.__publisher.wait_for_all_acked(timeout._duration_handle) def __enter__(self) -> 'Publisher[MsgT]': return self def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: self.destroy()
# Copyright 2020 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time from typing import List from typing import Tuple from typing import TYPE_CHECKING import unittest import rclpy from rclpy.duration import Duration import rclpy.node from test_msgs.msg import BasicTypes TEST_NODE_NAMESPACE = 'test_node_ns' TEST_TOPIC = 'my_topic' TEST_TOPIC_FROM = 'topic_from' TEST_TOPIC_TO = 'topic_to' TEST_FQN_TOPIC_FROM = '/original/my_ns/my_topic' TEST_FQN_TOPIC_TO = '/remapped/another_ns/new_topic' class TestPublisher(unittest.TestCase): if TYPE_CHECKING: context: rclpy.context.Context node: rclpy.node.Node node_with_ns: rclpy.node.Node @classmethod def setUp(cls) -> None: cls.context = rclpy.context.Context() rclpy.init(context=cls.context) cls.node = rclpy.create_node( 'node', context=cls.context, cli_args=[ '--ros-args', '-r', '{}:={}'.format(TEST_TOPIC_FROM, TEST_TOPIC_TO), '--ros-args', '-r', '{}:={}'.format(TEST_FQN_TOPIC_FROM, TEST_FQN_TOPIC_TO) ], ) cls.node_with_ns = rclpy.create_node( 'node_withns', context=cls.context, namespace=TEST_NODE_NAMESPACE, ) @classmethod def tearDown(cls) -> None: cls.node.destroy_node() cls.node_with_ns.destroy_node() rclpy.shutdown(context=cls.context) @classmethod def do_test_topic_name(cls, test_topics: List[Tuple[str, str]], node: rclpy.node.Node) -> None: """ Test the topic names of publishers created by the given node. The node will create publishers with topic in test_topics, and then test if the publisher's topic_name property is equal to the expected value. :param test_topics: A list of binary tuple in the form (topic, expected topic), the former will be passed to node.create_publisher and the latter will be compared with publisher.topic_name :param node: The node used to create the publisher. The node's namespace will have an effect on the publisher's topic_name. """ for topic, target_topic in test_topics: publisher = node.create_publisher(BasicTypes, topic, 1) assert publisher.topic_name == target_topic publisher.destroy() def test_topic_name(self) -> None: test_topics = [ (TEST_TOPIC, '/' + TEST_TOPIC), ('/' + TEST_TOPIC, '/' + TEST_TOPIC), ('/my_ns/' + TEST_TOPIC, '/my_ns/' + TEST_TOPIC), ('my_ns/' + TEST_TOPIC, '/my_ns/' + TEST_TOPIC), ] TestPublisher.do_test_topic_name(test_topics, self.node) # topics in a node which has a namespace test_topics = [ (TEST_TOPIC, '/' + TEST_NODE_NAMESPACE + '/' + TEST_TOPIC), ('/' + TEST_TOPIC, '/' + TEST_TOPIC), ('/my_ns/' + TEST_TOPIC, '/my_ns/' + TEST_TOPIC), ('my_ns/' + TEST_TOPIC, '/' + TEST_NODE_NAMESPACE + '/my_ns/' + TEST_TOPIC), ] TestPublisher.do_test_topic_name(test_topics, self.node_with_ns) def test_topic_name_remapping(self) -> None: test_topics = [ (TEST_TOPIC_FROM, '/' + TEST_TOPIC_TO), ('/' + TEST_TOPIC_FROM, '/' + TEST_TOPIC_TO), ('/my_ns/' + TEST_TOPIC_FROM, '/my_ns/' + TEST_TOPIC_FROM), ('my_ns/' + TEST_TOPIC_FROM, '/my_ns/' + TEST_TOPIC_FROM), (TEST_FQN_TOPIC_FROM, TEST_FQN_TOPIC_TO), ] TestPublisher.do_test_topic_name(test_topics, self.node) def test_wait_for_all_acked(self) -> None: qos = rclpy.qos.QoSProfile( depth=1, reliability=rclpy.qos.QoSReliabilityPolicy.RELIABLE) pub = self.node.create_publisher(BasicTypes, TEST_TOPIC, qos) sub = self.node.create_subscription(BasicTypes, TEST_TOPIC, lambda msg: print(msg), qos) max_seconds_to_wait = 5 end_time = time.time() + max_seconds_to_wait while pub.get_subscription_count() != 1: time.sleep(0.05) assert time.time() <= end_time # timeout waiting for pub/sub to discover each other assert pub.get_subscription_count() == 1 basic_types_msg = BasicTypes() pub.publish(basic_types_msg) assert pub.wait_for_all_acked(Duration(seconds=max_seconds_to_wait)) pub.destroy() sub.destroy() def test_logger_name_is_equal_to_node_name(self) -> None: with self.node.create_publisher(BasicTypes, TEST_TOPIC, 10) as pub: self.assertEqual(pub.logger_name, 'node') def test_publisher_context_manager() -> None: rclpy.init() try: with rclpy.create_node('pub_node', namespace='/pub_node_ns') as node: with node.create_publisher(BasicTypes, 'chatter', 1) as pub: assert pub.get_subscription_count() == 0 finally: rclpy.shutdown() if __name__ == '__main__': unittest.main()
rclpy
python
# Copyright 2016-2021 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Any, ClassVar, Optional, Protocol, Type, TypeVar, Union from builtin_interfaces.msg import Time from rclpy.exceptions import NoTypeSupportImportedException from service_msgs.msg import ServiceEventInfo from typing_extensions import TypeAlias from unique_identifier_msgs.msg import UUID class PyCapsule(Protocol): """Alias for PyCapsule Pybind object.""" pass # Done because metaclasses need to inherit from type ProtocolType: Any = type(Protocol) class CommonMsgSrvMetaClass(ProtocolType): """Shared attributes between messages and services.""" _TYPE_SUPPORT: ClassVar[Optional[PyCapsule]] @classmethod def __import_type_support__(cls) -> None: ... class MsgMetaClass(CommonMsgSrvMetaClass): """Generic Message Metaclass Alias.""" _CREATE_ROS_MESSAGE: ClassVar[Optional[PyCapsule]] _CONVERT_FROM_PY: ClassVar[Optional[PyCapsule]] _CONVERT_TO_PY: ClassVar[Optional[PyCapsule]] _DESTROY_ROS_MESSAGE: ClassVar[Optional[PyCapsule]] class Msg(Protocol, metaclass=MsgMetaClass): """Generic Message Alias.""" pass MsgT = TypeVar('MsgT', bound=Msg) SrvRequestT = TypeVar('SrvRequestT', bound=Msg) SrvResponseT = TypeVar('SrvResponseT', bound=Msg) class EventMessage(Msg, Protocol): info: ServiceEventInfo class Srv(Protocol, metaclass=CommonMsgSrvMetaClass): """Generic Service Type Alias.""" pass # Request: ClassVar[Type[Any]] # Response: ClassVar[Type[Any]] # Event: ClassVar[Type[Any]] GoalT = TypeVar('GoalT', bound=Msg) ResultT = TypeVar('ResultT', bound=Msg) FeedbackT = TypeVar('FeedbackT', bound=Msg) class SendGoalServiceRequest(Msg, Protocol[GoalT]): goal_id: UUID goal: GoalT class SendGoalServiceResponse(Msg, Protocol): accepted: bool stamp: Time SendGoalService: TypeAlias = Srv class GetResultServiceRequest(Msg, Protocol): goal_id: UUID class GetResultServiceResponse(Msg, Protocol[ResultT]): status: int result: ResultT GetResultService: TypeAlias = Srv class FeedbackMessage(Msg, Protocol[FeedbackT]): goal_id: UUID feedback: FeedbackT class Action(Protocol, metaclass=CommonMsgSrvMetaClass): pass # Goal: ClassVar[Type[Any]] # Result: ClassVar[Type[Any]] # Feedback: ClassVar[Type[Any]] # class Impl(Protocol): # SendGoalService: ClassVar[Type[Any]] # GetResultService: ClassVar[Type[Any]] # FeedbackMessage: ClassVar[Type[Any]] # CancelGoalService: ClassVar[Type[CancelGoal]] # GoalStatusMessage: ClassVar[Type[GoalStatusArray]] # Can be used if https://github.com/python/typing/issues/548 ever gets approved. SrvT = TypeVar('SrvT', bound=Srv) ActionT = TypeVar('ActionT', bound=Action) def check_for_type_support(msg_or_srv_type: Type[Union[Msg, Srv, Action]]) -> None: try: ts = msg_or_srv_type._TYPE_SUPPORT except AttributeError as e: e.args = ( e.args[0] + ' This might be a ROS 1 message type but it should be a ROS 2 message type.' ' Make sure to source your ROS 2 workspace after your ROS 1 workspace.', *e.args[1:]) raise if ts is None: msg_or_srv_type.__import_type_support__() if msg_or_srv_type._TYPE_SUPPORT is None: raise NoTypeSupportImportedException() def check_is_valid_msg_type(msg_type: Type[Msg]) -> None: check_for_type_support(msg_type) try: assert None not in ( msg_type._CREATE_ROS_MESSAGE, msg_type._CONVERT_FROM_PY, msg_type._CONVERT_TO_PY, msg_type._DESTROY_ROS_MESSAGE, ) except (AssertionError, AttributeError): raise RuntimeError( f'The message type provided is not valid ({msg_type}),' ' this might be a service or action' ) from None def check_is_valid_srv_type(srv_type: Type[Srv]) -> None: check_for_type_support(srv_type) try: assert None not in ( srv_type.Response, srv_type.Request, ) except (AssertionError, AttributeError): raise RuntimeError( f'The service type provided is not valid ({srv_type}),' ' this might be a message or action' ) from None
# Copyright 2021 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest from rclpy import type_support from rclpy.exceptions import NoTypeSupportImportedException from test_msgs.msg import Strings from test_msgs.srv import Empty class MockTypeMetaclass(type): _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls) -> None: pass class MockType(metaclass=MockTypeMetaclass): pass def test_check_for_type_support() -> None: type_support.check_for_type_support(Strings) type_support.check_for_type_support(Empty) with pytest.raises(AttributeError): type_support.check_for_type_support(object()) # type: ignore[arg-type] with pytest.raises(NoTypeSupportImportedException): type_support.check_for_type_support(MockType) def test_check_valid_msg_type() -> None: type_support.check_is_valid_msg_type(Strings) with pytest.raises(RuntimeError): type_support.check_is_valid_msg_type(Empty) def test_check_valid_srv_type() -> None: type_support.check_is_valid_srv_type(Empty) with pytest.raises(RuntimeError): type_support.check_is_valid_srv_type(Strings)
rclpy
python
# Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING import weakref from rcl_interfaces.msg import ListParametersResult from rcl_interfaces.msg import SetParametersResult from rcl_interfaces.srv import DescribeParameters, GetParameters, GetParameterTypes from rcl_interfaces.srv import ListParameters, SetParameters, SetParametersAtomically from rclpy.exceptions import ParameterNotDeclaredException, ParameterUninitializedException from rclpy.parameter import Parameter from rclpy.qos import qos_profile_parameters from rclpy.validate_topic_name import TOPIC_SEPARATOR_STRING if TYPE_CHECKING: from rclpy.node import Node class ParameterService: def __init__(self, node: 'Node'): self._node_weak_ref = weakref.ref(node) nodename = node.get_name() describe_parameters_service_name = \ TOPIC_SEPARATOR_STRING.join((nodename, 'describe_parameters')) node.create_service( DescribeParameters, describe_parameters_service_name, self._describe_parameters_callback, qos_profile=qos_profile_parameters ) get_parameters_service_name = TOPIC_SEPARATOR_STRING.join((nodename, 'get_parameters')) node.create_service( GetParameters, get_parameters_service_name, self._get_parameters_callback, qos_profile=qos_profile_parameters ) get_parameter_types_service_name = \ TOPIC_SEPARATOR_STRING.join((nodename, 'get_parameter_types')) node.create_service( GetParameterTypes, get_parameter_types_service_name, self._get_parameter_types_callback, qos_profile=qos_profile_parameters ) list_parameters_service_name = TOPIC_SEPARATOR_STRING.join((nodename, 'list_parameters')) node.create_service( ListParameters, list_parameters_service_name, self._list_parameters_callback, qos_profile=qos_profile_parameters ) set_parameters_service_name = TOPIC_SEPARATOR_STRING.join((nodename, 'set_parameters')) node.create_service( SetParameters, set_parameters_service_name, self._set_parameters_callback, qos_profile=qos_profile_parameters ) set_parameters_atomically_service_name = \ TOPIC_SEPARATOR_STRING.join((nodename, 'set_parameters_atomically')) node.create_service( SetParametersAtomically, set_parameters_atomically_service_name, self._set_parameters_atomically_callback, qos_profile=qos_profile_parameters ) def _describe_parameters_callback( self, request: DescribeParameters.Request, response: DescribeParameters.Response ) -> DescribeParameters.Response: node = self._get_node() for name in request.names: try: descriptor = node.describe_parameter(name) except ParameterNotDeclaredException: response.descriptors = node.describe_parameters([]) return response response.descriptors.append(descriptor) return response def _get_parameters_callback( self, request: GetParameters.Request, response: GetParameters.Response ) -> GetParameters.Response: node = self._get_node() for name in request.names: try: param = node.get_parameter(name) except (ParameterNotDeclaredException, ParameterUninitializedException): response.values = node.get_parameters([]) return response response.values.append(param.get_parameter_value()) return response def _get_parameter_types_callback( self, request: GetParameterTypes.Request, response: GetParameterTypes.Response ) -> GetParameterTypes.Response: node = self._get_node() for name in request.names: try: value = node.get_parameter_type(name) except ParameterNotDeclaredException: response.types = node.get_parameter_types([]) return response response.types.append(value) return response def _list_parameters_callback( self, request: ListParameters.Request, response: ListParameters.Response ) -> ListParameters.Response: node = self._get_node() try: response.result = node.list_parameters(request.prefixes, request.depth) except (TypeError, ValueError): response.result = ListParametersResult() return response def _set_parameters_callback( self, request: SetParameters.Request, response: SetParameters.Response ) -> SetParameters.Response: node = self._get_node() for p in request.parameters: param = Parameter.from_parameter_msg(p) try: result = node.set_parameters_atomically([param]) except ParameterNotDeclaredException as e: result = SetParametersResult( successful=False, reason=str(e) ) response.results.append(result) return response def _set_parameters_atomically_callback( self, request: SetParametersAtomically.Request, response: SetParametersAtomically.Response ) -> SetParametersAtomically.Response: node = self._get_node() try: response.result = node.set_parameters_atomically([ Parameter.from_parameter_msg(p) for p in request.parameters]) except ParameterNotDeclaredException as e: response.result = SetParametersResult( successful=False, reason=str(e) ) return response def _get_node(self) -> 'Node': node = self._node_weak_ref() if node is None: raise ReferenceError('Expected valid node weak reference') return node
# Copyright 2023 Sony Group Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Generator from typing import List from typing import Optional from unittest.mock import Mock import pytest import rclpy from rclpy.node import Node from rclpy.service import Service from test_msgs.srv import Empty from typing_extensions import TypeAlias EmptyService: TypeAlias = Service[Empty.Request, Empty.Response] NODE_NAME = 'test_node' @pytest.fixture(autouse=True) def default_context() -> Generator[None, None, None]: rclpy.init() yield rclpy.shutdown() @pytest.fixture def test_node(): node = Node(NODE_NAME) yield node node.destroy_node() def test_logger_name_is_equal_to_node_name(test_node): srv = test_node.create_service( srv_type=Empty, srv_name='test_srv', callback=lambda _: None ) assert srv.logger_name == NODE_NAME @pytest.mark.parametrize('service_name, namespace, expected', [ # No namespaces ('service', None, '/service'), ('example/service', None, '/example/service'), # Using service names with namespaces ('service', 'ns', '/ns/service'), ('example/service', 'ns', '/ns/example/service'), ('example/service', 'my/ns', '/my/ns/example/service'), ('example/service', '/my/ns', '/my/ns/example/service'), # Global service name ('/service', 'ns', '/service'), ('/example/service', 'ns', '/example/service'), ]) def test_get_service_name(service_name: str, namespace: Optional[str], expected: str) -> None: node = Node('node_name', namespace=namespace, cli_args=None, start_parameter_services=False) srv: EmptyService = node.create_service( srv_type=Empty, srv_name=service_name, callback=lambda _, _1: None ) assert srv.service_name == expected srv.destroy() node.destroy_node() @pytest.mark.parametrize('service_name, namespace, cli_args, expected', [ ('service', None, ['--ros-args', '--remap', 'service:=new_service'], '/new_service'), ('service', 'ns', ['--ros-args', '--remap', 'service:=new_service'], '/ns/new_service'), ('service', 'ns', ['--ros-args', '--remap', 'service:=example/new_service'], '/ns/example/new_service'), ('example/service', 'ns', ['--ros-args', '--remap', 'example/service:=new_service'], '/ns/new_service'), ]) def test_get_service_name_after_remapping(service_name: str, namespace: Optional[str], cli_args: List[str], expected: str) -> None: node = Node( 'node_name', namespace=namespace, cli_args=cli_args, start_parameter_services=False) srv: EmptyService = node.create_service( srv_type=Empty, srv_name=service_name, callback=lambda _, _1: None ) assert srv.service_name == expected srv.destroy() node.destroy_node() def test_service_context_manager() -> None: with rclpy.create_node('ctx_mgr_test') as node: srv: EmptyService with node.create_service( srv_type=Empty, srv_name='empty_service', callback=lambda _, _1: None) as srv: assert srv.service_name == '/empty_service' def test_set_on_new_request_callback(test_node) -> None: cli = test_node.create_client(Empty, '/service') srv = test_node.create_service(Empty, '/service', lambda req, res: res) cb = Mock() srv.handle.set_on_new_request_callback(cb) cb.assert_not_called() cli.call_async(Empty.Request()) cb.assert_called_once_with(1) srv.handle.clear_on_new_request_callback() cli.call_async(Empty.Request()) cb.assert_called_once()
rclpy
python
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Literal from rclpy.exceptions import InvalidServiceNameException from rclpy.exceptions import InvalidTopicNameException from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy TOPIC_SEPARATOR_STRING = '/' def validate_topic_name(name: str, *, is_service: bool = False) -> Literal[True]: """ Validate a given topic or service name, and raise an exception if invalid. The name does not have to be fully-qualified and is not expanded. If the name is invalid then rclpy.exceptions.InvalidTopicNameException will be raised. :param name: topic or service name to be validated :param is_service: if true, InvalidServiceNameException is raised :returns: True when it is valid :raises: InvalidTopicNameException: when the name is invalid """ result = _rclpy.rclpy_get_validation_error_for_topic_name(name) if result is None: return True error_msg, invalid_index = result if is_service: raise InvalidServiceNameException(name, error_msg, invalid_index) else: raise InvalidTopicNameException(name, error_msg, invalid_index)
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from rclpy.exceptions import InvalidServiceNameException from rclpy.exceptions import InvalidTopicNameException from rclpy.validate_topic_name import validate_topic_name class TestValidateTopicName(unittest.TestCase): def test_validate_topic_name(self) -> None: tests = [ 'chatter', '{node}/chatter', '~/chatter', ] for topic in tests: # Will raise if invalid validate_topic_name(topic) def test_validate_topic_name_failures(self) -> None: # topic name may not contain '?' with self.assertRaisesRegex(InvalidTopicNameException, 'must not contain characters'): validate_topic_name('/invalid_topic?') # topic name must start with number in any token with self.assertRaisesRegex(InvalidTopicNameException, 'must not start with a number'): validate_topic_name('invalid/42topic') def test_validate_topic_name_failures_service(self) -> None: # service name may not contain '?' with self.assertRaisesRegex(InvalidServiceNameException, 'must not contain characters'): validate_topic_name('/invalid_service?', is_service=True) # service name must start with number in any token with self.assertRaisesRegex(InvalidServiceNameException, 'must not start with a number'): validate_topic_name('invalid/42service', is_service=True) if __name__ == '__main__': unittest.main()
rclpy
python
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from threading import Lock from typing import Any, Literal, Optional, TYPE_CHECKING, Union import weakref if TYPE_CHECKING: from rclpy.subscription import Subscription from rclpy.timer import Timer from rclpy.client import Client from rclpy.service import Service from rclpy.waitable import Waitable from rclpy.guard_condition import GuardCondition Entity = Union[Subscription[Any], Timer, Client[Any, Any], Service[Any, Any], GuardCondition, Waitable[Any]] class CallbackGroup: """ The base class for a callback group. A callback group controls when callbacks are allowed to be executed. This class should not be instantiated. Instead, classes should extend it and implement :meth:`can_execute`, :meth:`beginning_execution`, and :meth:`ending_execution`. """ def __init__(self) -> None: super().__init__() self.entities: set[weakref.ReferenceType['Entity']] = set() def add_entity(self, entity: 'Entity') -> None: """ Add an entity to the callback group. :param entity: a subscription, timer, client, service, or waitable instance. """ self.entities.add(weakref.ref(entity)) def has_entity(self, entity: 'Entity') -> bool: """ Determine if an entity has been added to this group. :param entity: a subscription, timer, client, service, or waitable instance. """ return weakref.ref(entity) in self.entities def can_execute(self, entity: 'Entity') -> bool: """ Determine if an entity can be executed. :param entity: a subscription, timer, client, service, or waitable instance. :return: ``True`` if the entity can be executed, ``False`` otherwise. """ raise NotImplementedError() def beginning_execution(self, entity: 'Entity') -> bool: """ Get permission for the callback from the group to begin executing an entity. If this returns ``True`` then :meth:`CallbackGroup.ending_execution` must be called after the callback has been executed. :param entity: a subscription, timer, client, service, or waitable instance. :return: ``True`` if the callback can be executed, ``False`` otherwise. """ raise NotImplementedError() def ending_execution(self, entity: 'Entity') -> None: """ Notify group that a callback has finished executing. :param entity: a subscription, timer, client, service, or waitable instance. """ raise NotImplementedError() class ReentrantCallbackGroup(CallbackGroup): """Allow callbacks to be executed in parallel without restriction.""" def can_execute(self, entity: 'Entity') -> Literal[True]: return True def beginning_execution(self, entity: 'Entity') -> Literal[True]: return True def ending_execution(self, entity: 'Entity') -> None: pass class MutuallyExclusiveCallbackGroup(CallbackGroup): """Allow only one callback to be executing at a time.""" def __init__(self) -> None: super().__init__() self._active_entity: Optional['Entity'] = None self._lock = Lock() def can_execute(self, entity: 'Entity') -> bool: with self._lock: assert weakref.ref(entity) in self.entities return self._active_entity is None def beginning_execution(self, entity: 'Entity') -> bool: with self._lock: assert weakref.ref(entity) in self.entities if self._active_entity is None: self._active_entity = entity return True return False def ending_execution(self, entity: 'Entity') -> None: with self._lock: assert self._active_entity == entity self._active_entity = None
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time from typing import TYPE_CHECKING import unittest from rcl_interfaces.srv import GetParameters import rclpy from rclpy.callback_groups import MutuallyExclusiveCallbackGroup from rclpy.callback_groups import ReentrantCallbackGroup from rclpy.client import Client import rclpy.context from rclpy.executors import MultiThreadedExecutor from rclpy.service import Service from rclpy.task import Future from test_msgs.msg import BasicTypes, Empty from typing_extensions import TypeAlias GetParametersClient: TypeAlias = Client[GetParameters.Request, GetParameters.Response] GetParametersService: TypeAlias = Service[GetParameters.Request, GetParameters.Response] class TestCallbackGroup(unittest.TestCase): if TYPE_CHECKING: context: rclpy.context.Context node: rclpy.node.Node @classmethod def setUpClass(cls) -> None: cls.context = rclpy.context.Context() rclpy.init(context=cls.context) cls.node = rclpy.create_node('TestCallbackGroup', namespace='/rclpy', context=cls.context) @classmethod def tearDownClass(cls) -> None: cls.node.destroy_node() rclpy.shutdown(context=cls.context) def test_reentrant_group(self) -> None: self.assertIsNotNone(self.node.handle) group = ReentrantCallbackGroup() t1 = self.node.create_timer(1.0, lambda: None, callback_group=group) t2 = self.node.create_timer(1.0, lambda: None, callback_group=group) self.assertTrue(group.can_execute(t1)) self.assertTrue(group.can_execute(t2)) self.assertTrue(group.beginning_execution(t1)) self.assertTrue(group.beginning_execution(t2)) def test_reentrant_group_not_blocking(self) -> None: self.assertIsNotNone(self.node.handle) # Create multithreaded executor needed for parallel callback handling executor = MultiThreadedExecutor(num_threads=2, context=self.context) executor.add_node(self.node) try: # Setup flags for different scopes, # which indicate that the short callback has been called got_short_callback = False received_short_callback_in_long_callback = False # Setup two future objects that control the executor future_up: Future[None] = Future() future_down: Future[None] = Future() # This callback is used to check if a callback can be received while another # long running callback is being executed def short_callback(msg: Empty) -> None: nonlocal got_short_callback # Set flag so signal that the callback has been received got_short_callback = True # This callback is as a long running callback # It will be checking that the short callback can # run in parallel to this long running one def long_callback(msg: Empty) -> None: nonlocal received_short_callback_in_long_callback nonlocal future_up nonlocal future_down # The following future is used to delay the publishing of # the message that triggers the short callback. # This is done to ensure the long running callback is being executed # while the short callback is called future_up.set_result(None) # Wait for a maximum of 5 seconds # The short callback needs to be called in this time window for i in range(50): time.sleep(0.1) # Check if the short callback was called if got_short_callback: # Set a flag to signal that the short callback # was executed during the long one received_short_callback_in_long_callback = True # Skip the rest of the waiting break # Stop the executor from running any longer as there is nothing left to do future_down.set_result(None) # Create ReentrantCallbackGroup which is needed in combination with the # MultiThreadedExecutor to run callbacks not mutually exclusive group = ReentrantCallbackGroup() # Create subscriptions to trigger the callbacks self.node.create_subscription( Empty, 'trigger_long', long_callback, 1, callback_group=group) self.node.create_subscription( Empty, 'trigger_short', short_callback, 1, callback_group=group) # Create publishers to trigger both callbacks pub_trigger_long = self.node.create_publisher(Empty, 'trigger_long', 1) pub_trigger_short = self.node.create_publisher(Empty, 'trigger_short', 1) # Start the long running callback pub_trigger_long.publish(Empty()) # Spin until we are sure that the long running callback is running executor.spin_until_future_complete(future_up) # Publish the short callback pub_trigger_short.publish(Empty()) # Wait until the long running callback ends # (due to the signal from the short one or a timeout) executor.spin_until_future_complete(future_down) # Check if we were able to receive the short callback during the long running one self.assertTrue(received_short_callback_in_long_callback) finally: executor.shutdown() def test_mutually_exclusive_group(self) -> None: self.assertIsNotNone(self.node.handle) group = MutuallyExclusiveCallbackGroup() t1 = self.node.create_timer(1.0, lambda: None, callback_group=group) t2 = self.node.create_timer(1.0, lambda: None, callback_group=group) self.assertTrue(group.can_execute(t1)) self.assertTrue(group.can_execute(t2)) self.assertTrue(group.beginning_execution(t1)) self.assertFalse(group.can_execute(t2)) self.assertFalse(group.beginning_execution(t2)) group.ending_execution(t1) self.assertTrue(group.can_execute(t2)) self.assertTrue(group.beginning_execution(t2)) def test_create_timer_with_group(self) -> None: tmr1 = self.node.create_timer(1.0, lambda: None) group = ReentrantCallbackGroup() tmr2 = self.node.create_timer(1.0, lambda: None, callback_group=group) self.assertFalse(group.has_entity(tmr1)) self.assertTrue(group.has_entity(tmr2)) def test_create_subscription_with_group(self) -> None: sub1 = self.node.create_subscription(BasicTypes, 'chatter', lambda msg: print(msg), 1) group = ReentrantCallbackGroup() sub2 = self.node.create_subscription( BasicTypes, 'chatter', lambda msg: print(msg), 1, callback_group=group) self.assertFalse(group.has_entity(sub1)) self.assertTrue(group.has_entity(sub2)) def test_create_client_with_group(self) -> None: cli1: GetParametersClient = self.node.create_client(GetParameters, 'get/parameters') group = ReentrantCallbackGroup() cli2: GetParametersClient = self.node.create_client(GetParameters, 'get/parameters', callback_group=group) self.assertFalse(group.has_entity(cli1)) self.assertTrue(group.has_entity(cli2)) def test_create_service_with_group(self) -> None: srv1: GetParametersService = self.node.create_service(GetParameters, 'get/parameters', lambda req, res: None) group = ReentrantCallbackGroup() srv2: GetParametersService = self.node.create_service( GetParameters, 'get/parameters', lambda req, res: None, callback_group=group) self.assertFalse(group.has_entity(srv1)) self.assertTrue(group.has_entity(srv2)) if __name__ == '__main__': unittest.main()
rclpy
python
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Callable from typing import Coroutine from typing import Optional from typing import Union from rclpy.callback_groups import CallbackGroup from rclpy.context import Context from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy from rclpy.utilities import get_default_context from typing_extensions import TypeAlias GuardConditionCallbackType: TypeAlias = Callable[[], Union[Coroutine[None, None, None], None]] class GuardCondition: def __init__(self, callback: Optional[GuardConditionCallbackType], callback_group: Optional[CallbackGroup], context: Optional[Context] = None) -> None: """ Create a GuardCondition. .. warning:: Users should not create a guard condition with this constructor, instead they should call :meth:`.Node.create_guard_condition`. """ self._context = get_default_context() if context is None else context if self._context.handle is None: raise RuntimeError('Context must be initialized a GuardCondition can be created') with self._context.handle: self.__gc = _rclpy.GuardCondition(self._context.handle) self.callback = callback self.callback_group = callback_group # True when the callback is ready to fire but has not been "taken" by an executor self._executor_event = False # True when the executor sees this has been triggered but has not yet been handled self._executor_triggered = False def trigger(self) -> None: with self.__gc: self.__gc.trigger_guard_condition() @property def handle(self) -> _rclpy.GuardCondition: return self.__gc def destroy(self) -> None: """ Destroy a container for a ROS guard condition. .. warning:: Users should not destroy a guard condition with this method, instead they should call :meth:`.Node.destroy_guard_condition`. """ self.handle.destroy_when_not_in_use()
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING import unittest import rclpy import rclpy.context from rclpy.executors import SingleThreadedExecutor class TestGuardCondition(unittest.TestCase): if TYPE_CHECKING: context: rclpy.context.Context node: rclpy.node.Node executor: SingleThreadedExecutor @classmethod def setUpClass(cls) -> None: cls.context = rclpy.context.Context() rclpy.init(context=cls.context) cls.node = rclpy.create_node( 'TestGuardCondition', namespace='/rclpy/test', context=cls.context) cls.executor = SingleThreadedExecutor(context=cls.context) cls.executor.add_node(cls.node) @classmethod def tearDownClass(cls) -> None: cls.executor.shutdown() cls.node.destroy_node() rclpy.shutdown(context=cls.context) def test_trigger(self) -> None: called = False def func() -> None: nonlocal called called = True gc = self.node.create_guard_condition(func) self.executor.spin_once(timeout_sec=0) self.assertFalse(called) gc.trigger() self.executor.spin_once(timeout_sec=0) self.assertTrue(called) self.node.destroy_guard_condition(gc) def test_double_trigger(self) -> None: called1 = False called2 = False def func1() -> None: nonlocal called1 called1 = True def func2() -> None: nonlocal called2 called2 = True gc1 = self.node.create_guard_condition(func1) gc2 = self.node.create_guard_condition(func2) self.executor.spin_once(timeout_sec=0) self.assertFalse(called1) self.assertFalse(called2) gc1.trigger() gc2.trigger() self.executor.spin_once(timeout_sec=0) self.executor.spin_once(timeout_sec=0) self.assertTrue(called1) self.assertTrue(called2) called1 = False called2 = False self.executor.spin_once(timeout_sec=0) self.assertFalse(called1) self.assertFalse(called2) self.node.destroy_guard_condition(gc1) self.node.destroy_guard_condition(gc2) if __name__ == '__main__': unittest.main()
rclpy
python
# Copyright 2023 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TypedDict class TypeHashDictionary(TypedDict): version: int value: bytes class TypeHash: """Type hash.""" _TYPE_HASH_SIZE = 32 # ros2cli needs __slots__ to avoid API break from https://github.com/ros2/rclpy/pull/1243. # __slots__ is also used improve performance of Python objects. __slots__ = [ '_version', '_value', ] def __init__(self, version: int = -1, value: bytes = bytes(_TYPE_HASH_SIZE)): self.version = version self.value = value @property def version(self) -> int: """ Get field 'version'. :returns: version attribute """ return self._version @version.setter def version(self, value: int) -> None: assert isinstance(value, int) self._version = value @property def value(self) -> bytes: """ Get field 'value'. :returns: value attribute """ return self._value @value.setter def value(self, value: bytes) -> None: assert isinstance(value, bytes) self._value = value def __eq__(self, other: object) -> bool: if not isinstance(other, TypeHash): return False return all( self.__getattribute__(slot) == other.__getattribute__(slot) for slot in self.__slots__) def __str__(self) -> str: if self._version <= 0 or len(self._value) != self._TYPE_HASH_SIZE: return 'INVALID' return f'RIHS{self._version:02}_{self._value.hex()}'
# Copyright 2023 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from rclpy.type_hash import TypeHash from rclpy.type_hash import TypeHashDictionary # From std_msgs/msg/String.json STD_MSGS_STRING_TYPE_HASH_DICT: TypeHashDictionary = { 'version': 1, 'value': b'\xdf\x66\x8c\x74\x04\x82\xbb\xd4\x8f\xb3\x9d\x76\xa7\x0d\xfd\x4b' b'\xd5\x9d\xb1\x28\x80\x21\x74\x35\x03\x25\x9e\x94\x8f\x6b\x1a\x18', } STD_MSGS_STRING_TYPE_HASH_STR = 'RIHS01_' \ 'df668c740482bbd48fb39d76a70dfd4bd59db1288021743503259e948f6b1a18' class TestTypeHash(unittest.TestCase): def test_dict_constructor(self) -> None: type_hash = TypeHash(**STD_MSGS_STRING_TYPE_HASH_DICT) self.assertTrue(hasattr(type_hash, '__slots__')) self.assertEqual(STD_MSGS_STRING_TYPE_HASH_DICT['version'], type_hash.version) self.assertEqual(STD_MSGS_STRING_TYPE_HASH_DICT['value'], type_hash.value) def test_print_valid(self) -> None: actual_str = str(TypeHash(**STD_MSGS_STRING_TYPE_HASH_DICT)) expected_str = STD_MSGS_STRING_TYPE_HASH_STR self.assertEqual(expected_str, actual_str) def test_print_invalid(self) -> None: actual_str = str(TypeHash()) expected_str = 'INVALID' self.assertEqual(expected_str, actual_str) def test_equals(self) -> None: self.assertEqual(TypeHash(), TypeHash()) self.assertNotEqual(TypeHash(version=5), TypeHash())
rclpy
python
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. HIDDEN_TOPIC_PREFIX = '_' def topic_or_service_is_hidden(name: str) -> bool: """ Return True if a given topic or service name is hidden, otherwise False. A topic or service name is considered hidden if any of the name tokens begins with an underscore (``_``). See: http://design.ros2.org/articles/topic_and_service_names.html#hidden-topic-or-service-names :param name: topic or service name to test :returns: True if name is hidden, otherwise False """ return any(token for token in name.split('/') if token.startswith(HIDDEN_TOPIC_PREFIX))
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from rclpy.topic_or_service_is_hidden import topic_or_service_is_hidden class TestTopicOrServiceIsHidden(unittest.TestCase): def test_topic_or_service_is_hidden(self) -> None: tests = [ ('/chatter', False), ('chatter', False), ('/_chatter', True), ('_chatter', True), ('/more/complex/chatter', False), ('/_more/complex/chatter', True), ('/more/_complex/chatter', True), ('/more/complex/_chatter', True), ('/more/complex_/chatter', False), ('/more/complex/_/chatter', True), ('_/chatter', True), ('/chatter_', False), ('/more_/complex/chatter', False), ('/more/complex_/chatter', False), ('/more/complex/chatter_', False), ('/_more/_complex/_chatter', True), ('', False), ('_', True), ] for topic, expected in tests: self.assertEqual(expected, topic_or_service_is_hidden(topic)) if __name__ == '__main__': unittest.main()
rclpy
python
# Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from datetime import datetime from typing import overload, Tuple, Union import builtin_interfaces.msg from rclpy.constants import S_TO_NS from rclpy.duration import Duration from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy from .clock_type import ClockType class Time: """ Represents a point in time. A ``Time`` object is the combination of a duration since an epoch, and a clock type. ``Time`` objects are only comparable with other time points from the same type of clock. """ def __init__( self, *, seconds: Union[int, float] = 0, nanoseconds: Union[int, float] = 0, clock_type: ClockType = ClockType.SYSTEM_TIME, ) -> None: if not isinstance(clock_type, ClockType): raise TypeError('Clock type must be a ClockType enum') if seconds < 0: raise ValueError('Seconds value must not be negative') if nanoseconds < 0: raise ValueError('Nanoseconds value must not be negative') total_nanoseconds = int(seconds * S_TO_NS) total_nanoseconds += int(nanoseconds) if total_nanoseconds >= 2**63: # pybind11 would raise TypeError, but we want OverflowError raise OverflowError( 'Total nanoseconds value is too large to store in C time point.') self._time_handle = _rclpy.rcl_time_point_t(total_nanoseconds, clock_type) @property def nanoseconds(self) -> int: """:return: the total number of nanoseconds since the clock's epoch.""" return self._time_handle.nanoseconds def seconds_nanoseconds(self) -> Tuple[int, int]: """ Get time separated into seconds and nanoseconds components. :return: 2-tuple seconds and nanoseconds """ nanoseconds = self.nanoseconds return (nanoseconds // S_TO_NS, nanoseconds % S_TO_NS) @property def clock_type(self) -> _rclpy.ClockType: """:return: the type of clock that produced this instance.""" return self._time_handle.clock_type def __repr__(self) -> str: return 'Time(nanoseconds={0}, clock_type={1})'.format( self.nanoseconds, self.clock_type.name) def __add__(self, other: Duration) -> 'Time': if isinstance(other, Duration): try: return Time( nanoseconds=(self.nanoseconds + other.nanoseconds), clock_type=self.clock_type) except OverflowError as e: raise OverflowError('Addition leads to overflow in C storage.') from e else: return NotImplemented def __radd__(self, other: Duration) -> 'Time': return self.__add__(other) @overload def __sub__(self, other: 'Time') -> Duration: ... @overload def __sub__(self, other: Duration) -> 'Time': ... def __sub__(self, other: Union['Time', Duration]) -> Union['Time', Duration]: if isinstance(other, Time): if self.clock_type != other.clock_type: raise TypeError("Can't subtract times with different clock types") try: return Duration(nanoseconds=(self.nanoseconds - other.nanoseconds)) except ValueError as e: raise ValueError('Subtraction leads to negative duration.') from e if isinstance(other, Duration): try: return Time( nanoseconds=(self.nanoseconds - other.nanoseconds), clock_type=self.clock_type) except ValueError as e: raise ValueError('Subtraction leads to negative time.') from e else: return NotImplemented def __eq__(self, other: object) -> bool: if isinstance(other, Time): if self.clock_type != other.clock_type: raise TypeError("Can't compare times with different clock types") return self.nanoseconds == other.nanoseconds return NotImplemented def __ne__(self, other: object) -> bool: if isinstance(other, Time): return not self.__eq__(other) return NotImplemented def __lt__(self, other: 'Time') -> bool: if isinstance(other, Time): if self.clock_type != other.clock_type: raise TypeError("Can't compare times with different clock types") return self.nanoseconds < other.nanoseconds return NotImplemented def __le__(self, other: 'Time') -> bool: if isinstance(other, Time): if self.clock_type != other.clock_type: raise TypeError("Can't compare times with different clock types") return self.nanoseconds <= other.nanoseconds return NotImplemented def __gt__(self, other: 'Time') -> bool: if isinstance(other, Time): if self.clock_type != other.clock_type: raise TypeError("Can't compare times with different clock types") return self.nanoseconds > other.nanoseconds return NotImplemented def __ge__(self, other: 'Time') -> bool: if isinstance(other, Time): if self.clock_type != other.clock_type: raise TypeError("Can't compare times with different clock types") return self.nanoseconds >= other.nanoseconds return NotImplemented def to_msg(self) -> builtin_interfaces.msg.Time: """ Create a ROS message instance from a ``Time`` object. :rtype: builtin_interfaces.msg.Time """ seconds, nanoseconds = self.seconds_nanoseconds() return builtin_interfaces.msg.Time(sec=seconds, nanosec=nanoseconds) def to_datetime(self) -> datetime: """ Create a datetime object from a ``Time`` object. :rtype: datetime """ if self.clock_type not in (ClockType.ROS_TIME, ClockType.SYSTEM_TIME): raise TypeError("Time object's clock type should be either ROS_TIME or SYSTEM_TIME") return datetime.fromtimestamp(self.nanoseconds / S_TO_NS) @classmethod def from_msg( cls, msg: builtin_interfaces.msg.Time, clock_type: ClockType = ClockType.ROS_TIME ) -> 'Time': """ Create a ``Time`` instance from a ROS message. :param msg: the message instance to convert. :type msg: builtin_interfaces.msg.Time :rtype: Time """ if not isinstance(msg, builtin_interfaces.msg.Time): raise TypeError('Must pass a builtin_interfaces.msg.Time object') return cls(seconds=msg.sec, nanoseconds=msg.nanosec, clock_type=clock_type)
# Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from datetime import datetime import unittest from rclpy.clock_type import ClockType from rclpy.constants import S_TO_NS from rclpy.duration import Duration from rclpy.duration import Infinite from rclpy.time import Time from test_msgs.msg import Builtins class TestTime(unittest.TestCase): def test_time_construction(self) -> None: time = Time() assert time.nanoseconds == 0 time = Time(seconds=1, nanoseconds=5e8, clock_type=ClockType.SYSTEM_TIME) assert time.nanoseconds == 1500000000 assert time.clock_type == ClockType.SYSTEM_TIME with self.assertRaises(OverflowError): time = Time(nanoseconds=2**63) time = Time(nanoseconds=2**63 - 1) assert time.nanoseconds == 2**63 - 1 with self.assertRaises(ValueError): time = Time(seconds=-1) with self.assertRaises(ValueError): time = Time(nanoseconds=-1) with self.assertRaises(TypeError): time = Time(clock_type='SYSTEM_TIME') # type: ignore[arg-type] def test_duration_construction(self) -> None: duration = Duration() assert duration.nanoseconds == 0 duration = Duration(seconds=1, nanoseconds=5e8) assert duration.nanoseconds == 1500000000 with self.assertRaises(OverflowError): duration = Duration(nanoseconds=2**63) duration = Duration(nanoseconds=2**63 - 1) assert duration.nanoseconds == 2**63 - 1 assert Duration(seconds=-1).nanoseconds == -1 * 1000 * 1000 * 1000 assert Duration(nanoseconds=-1).nanoseconds == -1 assert Duration(seconds=-2**63 / 1e9).nanoseconds == -2**63 with self.assertRaises(OverflowError): # Much smaller number because float to integer conversion of seconds is imprecise duration = Duration(seconds=-2**63 / 1e9 - 1) assert Duration(nanoseconds=-2**63).nanoseconds == -2**63 with self.assertRaises(OverflowError): Duration(nanoseconds=-2**63 - 1) def test_duration_operators(self) -> None: duration1 = Duration(seconds=1, nanoseconds=0) duration2 = Duration(seconds=2, nanoseconds=0) assert (duration1 + duration2).nanoseconds == 3 * S_TO_NS assert (duration2 - duration1).nanoseconds == 1 * S_TO_NS assert (duration1 * 2) == duration2 assert (duration2 * 0.5) == duration1 assert (duration2 * float('inf')) == Infinite with self.assertRaises(ValueError): duration2 * float('NaN') def test_time_operators(self) -> None: time1 = Time(nanoseconds=1, clock_type=ClockType.STEADY_TIME) # Addition/subtraction of time and duration duration = Duration(nanoseconds=1) time2 = time1 + duration assert isinstance(time2, Time) assert time2.nanoseconds == 2 assert time2.clock_type == ClockType.STEADY_TIME time2 = duration + time1 assert isinstance(time2, Time) assert time2.nanoseconds == 2 assert time2.clock_type == ClockType.STEADY_TIME time2 = time1 - duration assert isinstance(time2, Time) assert time2.nanoseconds == 0 assert time2.clock_type == ClockType.STEADY_TIME with self.assertRaises(OverflowError): Duration(nanoseconds=1) + Time(nanoseconds=2**63 - 1) with self.assertRaises(ValueError): Time(nanoseconds=1) - Duration(nanoseconds=2) # Subtraction of times with the same clock type diff = time1 - time2 assert isinstance(diff, Duration) assert diff.nanoseconds == 1 # Subtraction resulting in a negative duration assert (Time(nanoseconds=1) - Time(nanoseconds=2)).nanoseconds == -1 # Subtraction of times with different clock types with self.assertRaises(TypeError): Time(nanoseconds=2, clock_type=ClockType.SYSTEM_TIME) - \ Time(nanoseconds=1, clock_type=ClockType.STEADY_TIME) # Invalid arithmetic combinations with self.assertRaises(TypeError): time1 + time2 # type: ignore[operator] with self.assertRaises(TypeError): duration - time1 # type: ignore[operator] def test_time_comparators(self) -> None: # Times with the same clock type time1 = Time(nanoseconds=1) time2 = Time(nanoseconds=2) self.assertFalse(time1 == time2) self.assertTrue(time1 != time2) self.assertFalse(time1 > time2) self.assertFalse(time1 >= time2) self.assertTrue(time1 < time2) self.assertTrue(time1 <= time2) time1 = Time(nanoseconds=5e9) time2 = Time(seconds=5) self.assertTrue(time1 == time2) # Times with different clock types time1 = Time(nanoseconds=1, clock_type=ClockType.SYSTEM_TIME) time2 = Time(nanoseconds=2, clock_type=ClockType.STEADY_TIME) with self.assertRaises(TypeError): time1 == time2 with self.assertRaises(TypeError): time1 != time2 with self.assertRaises(TypeError): time1 > time2 with self.assertRaises(TypeError): time1 >= time2 with self.assertRaises(TypeError): time1 < time2 with self.assertRaises(TypeError): time1 <= time2 # Invalid combinations time1 = Time(nanoseconds=1) self.assertFalse(time1 == 1) duration = Duration(nanoseconds=1) self.assertFalse(time1 == duration) self.assertTrue(time1 != duration) with self.assertRaises(TypeError): time1 > duration with self.assertRaises(TypeError): time1 >= duration with self.assertRaises(TypeError): time1 < duration with self.assertRaises(TypeError): time1 <= duration def test_duration_comparators(self) -> None: duration1 = Duration(nanoseconds=1) duration2 = Duration(nanoseconds=2) self.assertFalse(duration1 == duration2) self.assertTrue(duration1 != duration2) self.assertFalse(duration1 > duration2) self.assertFalse(duration1 >= duration2) self.assertTrue(duration1 < duration2) self.assertTrue(duration1 <= duration2) duration1 = Duration(nanoseconds=5e9) duration2 = Duration(seconds=5) self.assertTrue(duration1 == duration2) # Invalid combinations duration1 = Duration(nanoseconds=1) self.assertFalse(duration1 == 1) time = Time(nanoseconds=1) self.assertFalse(duration1 == time) self.assertTrue(duration1 != time) with self.assertRaises(TypeError): duration1 > time with self.assertRaises(TypeError): duration1 >= time with self.assertRaises(TypeError): duration1 < time with self.assertRaises(TypeError): duration1 <= time def test_time_message_conversions(self) -> None: time1 = Time(nanoseconds=1, clock_type=ClockType.ROS_TIME) builtins_msg = Builtins() builtins_msg.time_value = time1.to_msg() # Default clock type resulting from from_msg will be ROS time time2 = Time.from_msg(builtins_msg.time_value) assert isinstance(time2, Time) assert time1 == time2 # Clock type can be specified if appropriate time3 = Time.from_msg(builtins_msg.time_value, clock_type=ClockType.SYSTEM_TIME) assert time3.clock_type == ClockType.SYSTEM_TIME def test_time_message_conversions_big_nanoseconds(self) -> None: time1 = Time(nanoseconds=1553575413247045598, clock_type=ClockType.ROS_TIME) builtins_msg = Builtins() builtins_msg.time_value = time1.to_msg() # Default clock type resulting from from_msg will be ROS time time2 = Time.from_msg(builtins_msg.time_value) assert isinstance(time2, Time) assert time1 == time2 def test_duration_message_conversions(self) -> None: duration = Duration(nanoseconds=1) builtins_msg = Builtins() builtins_msg.duration_value = duration.to_msg() duration2 = Duration.from_msg(builtins_msg.duration_value) assert isinstance(duration2, Duration) assert duration2.nanoseconds == 1 def test_seconds_nanoseconds(self) -> None: assert (1, int(5e8)) == Time(seconds=1, nanoseconds=5e8).seconds_nanoseconds() assert (1, int(5e8)) == Time(seconds=0, nanoseconds=15e8).seconds_nanoseconds() assert (0, 0) == Time().seconds_nanoseconds() def test_infinite_duration(self) -> None: duration = Infinite assert str(duration) == 'Infinite' def test_time_datetime_conversions(self) -> None: time1 = Time(seconds=1, nanoseconds=5e8, clock_type=ClockType.SYSTEM_TIME) assert time1.to_datetime() == datetime.fromtimestamp(time1.nanoseconds / 1e9) time2 = Time(nanoseconds=174893823272323, clock_type=ClockType.ROS_TIME) assert int(time2.to_datetime().timestamp()) == time2.seconds_nanoseconds()[0] assert time2.to_datetime() == datetime.fromtimestamp(time2.nanoseconds / 1e9) with self.assertRaises(TypeError): time3 = Time(nanoseconds=5e8, clock_type=ClockType.STEADY_TIME) time3.to_datetime() with self.assertRaises(TypeError): time4 = Time(nanoseconds=0, clock_type=ClockType.UNINITIALIZED) time4.to_datetime()
rclpy
python
# Copyright 2023 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy from typing_extensions import TypeAlias ServiceIntrospectionState: TypeAlias = _rclpy.service_introspection.ServiceIntrospectionState
# Copyright 2022 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time from typing import List from typing import TYPE_CHECKING import unittest import rclpy from rclpy.client import Client import rclpy.context import rclpy.executors from rclpy.qos import qos_profile_system_default from rclpy.service_introspection import ServiceIntrospectionState from service_msgs.msg import ServiceEventInfo from test_msgs.srv import BasicTypes class TestServiceEvents(unittest.TestCase): if TYPE_CHECKING: context: rclpy.context.Context node: rclpy.node.Node @classmethod def setUpClass(cls) -> None: cls.context = rclpy.context.Context() rclpy.init(context=cls.context) def setUp(self) -> None: self.node = rclpy.create_node( 'TestServiceIntrospection', context=self.context) self.executor = rclpy.executors.SingleThreadedExecutor(context=self.context) self.executor.add_node(self.node) self.srv = self.node.create_service(BasicTypes, 'test_service', self.srv_callback) self.cli: Client[BasicTypes.Request, BasicTypes.Response] = \ self.node.create_client(BasicTypes, 'test_service') self.sub = self.node.create_subscription(BasicTypes.Event, 'test_service/_service_event', self.sub_callback, 10) self.event_messages: List[BasicTypes.Event] = [] def tearDown(self) -> None: self.node.destroy_node() @classmethod def tearDownClass(cls) -> None: rclpy.shutdown(context=cls.context) def sub_callback(self, msg: BasicTypes.Event) -> None: self.event_messages.append(msg) def srv_callback(self, req: BasicTypes.Request, resp: BasicTypes.Response) -> BasicTypes.Response: resp.bool_value = not req.bool_value resp.int64_value = req.int64_value return resp def test_service_introspection_metadata(self) -> None: req = BasicTypes.Request() req.bool_value = False req.int64_value = 12345 self.cli.configure_introspection(self.node.get_clock(), qos_profile_system_default, ServiceIntrospectionState.METADATA) self.srv.configure_introspection(self.node.get_clock(), qos_profile_system_default, ServiceIntrospectionState.METADATA) future = self.cli.call_async(req) self.executor.spin_until_future_complete(future, timeout_sec=5.0) self.assertTrue(future.done()) start = time.monotonic() end = start + 5.0 while len(self.event_messages) < 4: self.executor.spin_once(timeout_sec=0.1) now = time.monotonic() self.assertTrue(now < end) self.assertEqual(len(self.event_messages), 4) result_dict = {} for msg in self.event_messages: result_dict[msg.info.event_type] = msg self.assertEqual( set(result_dict.keys()), {ServiceEventInfo.REQUEST_SENT, ServiceEventInfo.REQUEST_RECEIVED, ServiceEventInfo.RESPONSE_SENT, ServiceEventInfo.RESPONSE_RECEIVED}) self.assertEqual(len(result_dict[ServiceEventInfo.REQUEST_SENT].request), 0) self.assertEqual(len(result_dict[ServiceEventInfo.REQUEST_SENT].response), 0) self.assertEqual(len(result_dict[ServiceEventInfo.RESPONSE_SENT].request), 0) self.assertEqual(len(result_dict[ServiceEventInfo.RESPONSE_SENT].response), 0) self.assertEqual(len(result_dict[ServiceEventInfo.REQUEST_RECEIVED].request), 0) self.assertEqual(len(result_dict[ServiceEventInfo.REQUEST_RECEIVED].response), 0) self.assertEqual(len(result_dict[ServiceEventInfo.RESPONSE_RECEIVED].request), 0) self.assertEqual(len(result_dict[ServiceEventInfo.RESPONSE_RECEIVED].response), 0) def test_service_introspection_contents(self) -> None: req = BasicTypes.Request() req.bool_value = False req.int64_value = 12345 self.cli.configure_introspection(self.node.get_clock(), qos_profile_system_default, ServiceIntrospectionState.CONTENTS) self.srv.configure_introspection(self.node.get_clock(), qos_profile_system_default, ServiceIntrospectionState.CONTENTS) future = self.cli.call_async(req) self.executor.spin_until_future_complete(future, timeout_sec=5.0) self.assertTrue(future.done()) start = time.monotonic() end = start + 5.0 while len(self.event_messages) < 4: self.executor.spin_once(timeout_sec=0.1) now = time.monotonic() self.assertTrue(now < end) self.assertEqual(len(self.event_messages), 4) result_dict = {} for msg in self.event_messages: result_dict[msg.info.event_type] = msg self.assertEqual( set(result_dict.keys()), {ServiceEventInfo.REQUEST_SENT, ServiceEventInfo.REQUEST_RECEIVED, ServiceEventInfo.RESPONSE_SENT, ServiceEventInfo.RESPONSE_RECEIVED}) self.assertEqual(len(result_dict[ServiceEventInfo.REQUEST_SENT].request), 1) self.assertEqual(result_dict[ServiceEventInfo.REQUEST_SENT].request[0].bool_value, False) self.assertEqual(result_dict[ServiceEventInfo.REQUEST_SENT].request[0].int64_value, 12345) self.assertEqual(len(result_dict[ServiceEventInfo.REQUEST_SENT].response), 0) self.assertEqual(len(result_dict[ServiceEventInfo.RESPONSE_SENT].request), 0) self.assertEqual(len(result_dict[ServiceEventInfo.RESPONSE_SENT].response), 1) self.assertEqual(result_dict[ServiceEventInfo.RESPONSE_SENT].response[0].bool_value, True) self.assertEqual( result_dict[ServiceEventInfo.RESPONSE_SENT].response[0].int64_value, 12345) self.assertEqual(len(result_dict[ServiceEventInfo.REQUEST_RECEIVED].request), 1) self.assertEqual( result_dict[ServiceEventInfo.REQUEST_RECEIVED].request[0].bool_value, False) self.assertEqual( result_dict[ServiceEventInfo.REQUEST_RECEIVED].request[0].int64_value, 12345) self.assertEqual(len(result_dict[ServiceEventInfo.REQUEST_RECEIVED].response), 0) self.assertEqual(len(result_dict[ServiceEventInfo.RESPONSE_RECEIVED].request), 0) self.assertEqual(len(result_dict[ServiceEventInfo.RESPONSE_RECEIVED].response), 1) self.assertEqual( result_dict[ServiceEventInfo.RESPONSE_RECEIVED].response[0].bool_value, True) self.assertEqual( result_dict[ServiceEventInfo.RESPONSE_RECEIVED].response[0].int64_value, 12345) if __name__ == '__main__': unittest.main()
rclpy
python
# Copyright 2022 Sony Group Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Literal, Tuple, Type, Union from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy from rclpy.node import Node from rclpy.qos import QoSProfile from rclpy.signals import SignalHandlerGuardCondition from rclpy.type_support import MsgT from rclpy.utilities import timeout_sec_to_nsec def wait_for_message( msg_type: Type[MsgT], node: 'Node', topic: str, *, qos_profile: Union[QoSProfile, int] = 1, time_to_wait: Union[int, float] = -1 ) -> Union[Tuple[Literal[True], MsgT], Tuple[Literal[False], None]]: """ Wait for the next incoming message. :param msg_type: message type :param node: node to initialize the subscription on :param topic: topic name to wait for message :param qos_profile: QoS profile to use for the subscription :param time_to_wait: seconds to wait before returning :returns: (True, msg) if a message was successfully received, (False, None) if message could not be obtained or shutdown was triggered asynchronously on the context. """ context = node.context if context.handle is None: raise RuntimeError('Cannot create Waitset without a context.handle') wait_set = _rclpy.WaitSet(1, 1, 0, 0, 0, 0, context.handle) wait_set.clear_entities() sub = node.create_subscription(msg_type, topic, lambda _: None, qos_profile=qos_profile) try: wait_set.add_subscription(sub.handle) sigint_gc = SignalHandlerGuardCondition(context=context) wait_set.add_guard_condition(sigint_gc.handle) timeout_nsec = timeout_sec_to_nsec(time_to_wait) wait_set.wait(timeout_nsec) subs_ready = wait_set.get_ready_entities('subscription') guards_ready = wait_set.get_ready_entities('guard_condition') if guards_ready: if sigint_gc.handle.pointer in guards_ready: return False, None if subs_ready: if sub.handle.pointer in subs_ready: msg_info = sub.handle.take_message(sub.msg_type, sub.raw) if msg_info is not None: return True, msg_info[0] finally: node.destroy_subscription(sub) return False, None
# Copyright 2022 Sony Group Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import threading import time from typing import TYPE_CHECKING import unittest import rclpy import rclpy.context from rclpy.qos import QoSProfile from rclpy.wait_for_message import wait_for_message from test_msgs.msg import BasicTypes MSG_DATA = 100 TOPIC_NAME = 'wait_for_message_topic' class TestWaitForMessage(unittest.TestCase): if TYPE_CHECKING: context: rclpy.context.Context node: rclpy.node.Node @classmethod def setUpClass(cls) -> None: cls.context = rclpy.context.Context() rclpy.init(context=cls.context) cls.node = rclpy.create_node('publisher_node', context=cls.context) @classmethod def tearDownClass(cls) -> None: cls.node.destroy_node() rclpy.shutdown(context=cls.context) def _publish_message(self) -> None: pub = self.node.create_publisher(BasicTypes, TOPIC_NAME, 1) msg = BasicTypes() msg.int32_value = MSG_DATA while True: if self.node.count_subscribers(TOPIC_NAME) > 0: pub.publish(msg) break time.sleep(1) pub.destroy() def test_wait_for_message(self) -> None: t = threading.Thread(target=self._publish_message) t.start() ret, msg = wait_for_message(BasicTypes, self.node, TOPIC_NAME, qos_profile=1) self.assertTrue(ret) self.assertEqual(msg.int32_value, MSG_DATA) # type: ignore[union-attr] t.join() def test_wait_for_message_qos(self) -> None: t = threading.Thread(target=self._publish_message) t.start() ret, msg = wait_for_message( BasicTypes, self.node, TOPIC_NAME, qos_profile=QoSProfile(depth=1)) self.assertTrue(ret) self.assertEqual(msg.int32_value, MSG_DATA) # type: ignore[union-attr] t.join() def test_wait_for_message_timeout(self) -> None: ret, _ = wait_for_message(BasicTypes, self.node, TOPIC_NAME, time_to_wait=1) self.assertFalse(ret) if __name__ == '__main__': unittest.main()
rclpy
python
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys import threading from typing import List from typing import Optional from typing import Sequence from typing import Set import ament_index_python from rclpy.constants import S_TO_NS from rclpy.context import Context g_default_context = None g_context_lock = threading.Lock() def get_default_context(*, shutting_down: bool = False) -> Context: """Return the global default context singleton.""" global g_context_lock with g_context_lock: global g_default_context if g_default_context is None: g_default_context = Context() if shutting_down: old_context = g_default_context g_default_context = None return old_context return g_default_context def remove_ros_args(args: Optional[Sequence[str]] = None) -> List[str]: """ Return a list of only the non-ROS command line arguments. :param args: A list of command line arguments to filter from. If None then ``sys.argv`` is used instead. :returns: A list of all command line arguments that are not used by ROS. """ # imported locally to avoid loading extensions on module import from rclpy.impl.implementation_singleton import rclpy_implementation return rclpy_implementation.rclpy_remove_ros_args( args if args is not None else sys.argv) def ok(*, context: Optional[Context] = None) -> bool: """ Return ``True`` if the given ``Context`` is initialized and not shut down. :param context: a ``Context`` to check, else the global default context is used. :return: ``True`` if the context is valid. """ if context is None: context = get_default_context() return context.ok() def shutdown(*, context: Optional[Context] = None) -> None: """ Shutdown the given ``Context``. :param context: a ``Context`` to check, else the global default context is used. """ if context is None: context = get_default_context(shutting_down=True) context.shutdown() def try_shutdown(*, context: Optional[Context] = None) -> None: """ Shutdown the given ``Context`` if not already shutdown. :param context: a ``Context`` to check, else the global default context is used. """ global g_context_lock global g_default_context if context is None: # Replace the default context with a new one if shutdown was successful # or if the context was already shutdown. with g_context_lock: if g_default_context is None: g_default_context = Context() g_default_context.try_shutdown() if not g_default_context.ok(): g_default_context = None else: context.try_shutdown() def get_rmw_implementation_identifier() -> str: """Return the identifier of the current RMW implementation.""" # imported locally to avoid loading extensions on module import from rclpy.impl.implementation_singleton import rclpy_implementation return rclpy_implementation.rclpy_get_rmw_implementation_identifier() def get_available_rmw_implementations() -> Set[str]: """ Return the set of all available RMW implementations as registered in the ament index. The result can be overridden by setting an environment variable named ``RMW_IMPLEMENTATIONS``. The variable can contain RMW implementation names separated by the platform specific path separator. :raises RuntimeError: if the environment variable includes a missing RMW implementation. """ available_rmw_implementations_dictionary = ament_index_python.get_resources( 'rmw_typesupport') available_rmw_implementations = { name for name in available_rmw_implementations_dictionary if name != 'rmw_implementation'} # filter by implementations in environment variable if provided rmw_implementations = os.environ.get('RMW_IMPLEMENTATIONS') if rmw_implementations: rmw_implementations_array = rmw_implementations.split(os.pathsep) missing_rmw_implementations = set(rmw_implementations_array) - \ available_rmw_implementations if missing_rmw_implementations: # TODO(sloretz) function name suggets to me it would return available ones even # if some were missing. raise RuntimeError( f'The RMW implementations {missing_rmw_implementations} ' "specified in 'RMW_IMPLEMENTATIONS' are not available (" + ', '.join(sorted(available_rmw_implementations)) + ')') available_rmw_implementations = { name for name in available_rmw_implementations if name in rmw_implementations} return available_rmw_implementations def timeout_sec_to_nsec(timeout_sec: Optional[float]) -> int: """ Convert timeout in seconds to rcl compatible timeout in nanoseconds. Python tends to use floating point numbers in seconds for timeouts. This utility converts a python-style timeout to an integer in nanoseconds that can be used by ``rcl_wait``. :param timeout_sec: Seconds to wait. Block forever if None or negative. Don't wait if < 1ns :returns: rcl_wait compatible timeout in nanoseconds """ if timeout_sec is None or timeout_sec < 0: # Block forever return -1 else: # wait for given time return int(float(timeout_sec) * S_TO_NS)
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from rclpy.constants import S_TO_NS import rclpy.utilities class TestValidateRemoveRosArgs(unittest.TestCase): def test_remove_ros_args(self) -> None: args = [ 'process_name', '-d', '--ros-args', '-r', '__ns:=/foo/bar', '-r', '__ns:=/fiz/buz', '--', '--foo=bar', '--baz' ] stripped_args = rclpy.utilities.remove_ros_args(args=args) self.assertEqual(4, len(stripped_args)) self.assertEqual('process_name', stripped_args[0]) self.assertEqual('-d', stripped_args[1]) self.assertEqual('--foo=bar', stripped_args[2]) self.assertEqual('--baz', stripped_args[3]) class TestUtilities(unittest.TestCase): def test_timeout_sec_to_nsec(self) -> None: self.assertGreater(0, rclpy.utilities.timeout_sec_to_nsec(None)) self.assertGreater(0, rclpy.utilities.timeout_sec_to_nsec(-1)) self.assertEqual(0, rclpy.utilities.timeout_sec_to_nsec(0)) self.assertEqual(0, rclpy.utilities.timeout_sec_to_nsec(0.5 / S_TO_NS)) self.assertEqual(int(1.5 * S_TO_NS), rclpy.utilities.timeout_sec_to_nsec(1.5)) if __name__ == '__main__': unittest.main()
rclpy
python
# Copyright 2022 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time from typing import Any, Callable, List, Optional, Sequence, Union from rcl_interfaces.msg import Parameter as ParameterMsg from rcl_interfaces.msg import ParameterEvent from rcl_interfaces.srv import DescribeParameters from rcl_interfaces.srv import GetParameters from rcl_interfaces.srv import GetParameterTypes from rcl_interfaces.srv import ListParameters from rcl_interfaces.srv import SetParameters from rcl_interfaces.srv import SetParametersAtomically from rclpy.callback_groups import CallbackGroup from rclpy.client import Client from rclpy.event_handler import SubscriptionEventCallbacks from rclpy.node import Node from rclpy.parameter import Parameter as Parameter from rclpy.parameter import parameter_dict_from_yaml_file from rclpy.qos import qos_profile_parameter_events from rclpy.qos import qos_profile_services_default from rclpy.qos import QoSProfile from rclpy.qos_overriding_options import QoSOverridingOptions from rclpy.subscription import MessageInfo from rclpy.subscription import Subscription from rclpy.task import Future class AsyncParameterClient: def __init__( self, node: Node, remote_node_name: str, qos_profile: QoSProfile = qos_profile_services_default, callback_group: Optional[CallbackGroup] = None, ) -> None: """ Create an AsyncParameterClient. An AsyncParameterClient that uses services offered by a remote node to query and modify parameters in a streamlined way. Usage example: .. code-block:: python import rclpy from rclpy.parameter import Parameter node = rclpy.create_node('my_node') client = AsyncParameterClient(node, 'example_node') # set parameters on example node future = client.set_parameters([ Parameter('int_param', Parameter.Type.INTEGER, 88), Parameter('string/param', Parameter.Type.STRING, 'hello world').to_parameter_msg(), ]) self.executor.spin_until_future_complete(future) results = future.result() # rcl_interfaces.srv.SetParameters.Response For more on service names, see: `ROS 2 docs`_. .. _ROS 2 docs: https://docs.ros.org/en/rolling/Concepts/About-ROS-2-Parameters.html#interacting-with-parameters # noqa E501 :param node: Node used to create clients that will interact with the remote node :param remote_node_name: Name of remote node for which the parameters will be managed """ self.remote_node_name = remote_node_name self.node = node self._get_parameter_client: Client[GetParameters.Request, GetParameters.Response] = self.node.create_client( GetParameters, f'{remote_node_name}/get_parameters', qos_profile=qos_profile, callback_group=callback_group ) self._list_parameter_client: Client[ListParameters.Request, ListParameters.Response] = self.node.create_client( ListParameters, f'{remote_node_name}/list_parameters', qos_profile=qos_profile, callback_group=callback_group ) self._set_parameter_client: Client[SetParameters.Request, SetParameters.Response] = self.node.create_client( SetParameters, f'{remote_node_name}/set_parameters', qos_profile=qos_profile, callback_group=callback_group ) self._get_parameter_types_client: Client[GetParameterTypes.Request, GetParameterTypes.Response] = \ self.node.create_client( GetParameterTypes, f'{remote_node_name}/get_parameter_types', qos_profile=qos_profile, callback_group=callback_group ) self._describe_parameters_client: Client[DescribeParameters.Request, DescribeParameters.Response] = \ self.node.create_client( DescribeParameters, f'{remote_node_name}/describe_parameters', qos_profile=qos_profile, callback_group=callback_group ) self._set_parameters_atomically_client: Client[SetParametersAtomically.Request, SetParametersAtomically.Response] = \ self.node.create_client( SetParametersAtomically, f'{remote_node_name}/set_parameters_atomically', qos_profile=qos_profile, callback_group=callback_group ) def services_are_ready(self) -> bool: """ Check if all services are ready. :return: ``True`` if all services are available, False otherwise. """ return all([ self._list_parameter_client.service_is_ready(), self._set_parameter_client.service_is_ready(), self._get_parameter_client.service_is_ready(), self._get_parameter_types_client.service_is_ready(), self._describe_parameters_client.service_is_ready(), self._set_parameters_atomically_client.service_is_ready(), ]) def wait_for_services(self, timeout_sec: Optional[float] = None) -> bool: """ Wait for all parameter services to be available. :param timeout_sec: Seconds to wait. If ``None``, then wait forever. :return: ``True`` if all services becomes available, ``False`` otherwise. """ # TODO(ihasdapie) See: rclpy.Client.wait_for_service sleep_time = 0.25 if timeout_sec is None: timeout_sec = float('inf') while not self.services_are_ready() and timeout_sec > 0.0: time.sleep(sleep_time) timeout_sec -= sleep_time return self.services_are_ready() def list_parameters( self, prefixes: Optional[List[str]] = None, depth: Optional[int] = None, callback: Optional[Callable[[Future[ListParameters.Response]], None]] = None ) -> Future[ListParameters.Response]: """ List all parameters with given prefixes. :param prefixes: List of prefixes to filter by. :param depth: Depth of the parameter tree to list. ``None`` means unlimited. :param callback: Callback function to call when the request is complete. :return: ``Future`` with the result of the request. """ request = ListParameters.Request() if prefixes: request.prefixes = prefixes if depth: request.depth = depth future = self._list_parameter_client.call_async(request) if callback: future.add_done_callback(callback) return future def get_parameters(self, names: List[str], callback: Optional[Callable[[Future[GetParameters.Response]], None]] = None ) -> Future[GetParameters.Response]: """ Get parameters given names. :param names: List of parameter names to get. :param callback: Callback function to call when the request is complete. :return: ``Future`` with the result of the request. """ request = GetParameters.Request() request.names = names future = self._get_parameter_client.call_async(request) if callback: future.add_done_callback(callback) return future def set_parameters( self, parameters: Sequence[Union[Parameter[Any], ParameterMsg]], callback: Optional[Callable[[Future[SetParameters.Response]], None]] = None ) -> Future[SetParameters.Response]: """ Set parameters given a list of parameters. The result after the returned future is complete will be of type ``rcl_interfaces.srv.SetParameters.Response``. :param parameters: Sequence of parameters to set. :param callback: Callback function to call when the request is complete. :return: ``Future`` with the result of the request. """ request = SetParameters.Request() request.parameters = [ param.to_parameter_msg() if isinstance(param, Parameter) else param for param in parameters ] future = self._set_parameter_client.call_async(request) if callback: future.add_done_callback(callback) return future def describe_parameters( self, names: List[str], callback: Optional[Callable[[Future[DescribeParameters.Response]], None]] = None ) -> Future[DescribeParameters.Response]: """ Describe parameters given names. The result after the returned future is complete will be of type ``rcl_interfaces.srv.DescribeParameters.Response``. :param names: List of parameter names to describe :param callback: Callback function to call when the request is complete. :return: ``Future`` with the result of the request. """ request = DescribeParameters.Request() request.names = names future = self._describe_parameters_client.call_async(request) if callback: future.add_done_callback(callback) return future def get_parameter_types( self, names: List[str], callback: Optional[Callable[[Future[GetParameterTypes.Response]], None]] = None ) -> Future[GetParameterTypes.Response]: """ Get parameter types given names. The result after the returned future is complete will be of type ``rcl_interfaces.srv.GetParameterTypes.Response``. Parameter type definitions are given in Parameter.Type :param names: List of parameter names to get types for. :param callback: Callback function to call when the request is complete. :return: ``Future`` with the result of the request. """ request = GetParameterTypes.Request() request.names = names future = self._get_parameter_types_client.call_async(request) if callback: future.add_done_callback(callback) return future def set_parameters_atomically( self, parameters: Sequence[Union[Parameter[Any], ParameterMsg]], callback: Optional[Callable[[Future[SetParametersAtomically.Response]], None]] = None ) -> Future[SetParametersAtomically.Response]: """ Set parameters atomically. The result after the returned future is complete will be of type ``rcl_interfaces.srv.SetParametersAtomically.Response``. :param parameters: Sequence of parameters to set. :param callback: Callback function to call when the request is complete. :return: ``Future`` with the result of the request. """ request = SetParametersAtomically.Request() request.parameters = [ param.to_parameter_msg() if isinstance(param, Parameter) else param for param in parameters ] future = self._set_parameters_atomically_client.call_async(request) if callback: future.add_done_callback(callback) return future def delete_parameters( self, names: List[str], callback: Optional[Callable[[Future[SetParameters.Response]], None]] = None ) -> Future[SetParameters.Response]: """ Unset parameters with given names. The result after the returned future is complete will be of type ``rcl_interfaces.srv.SetParameters.Response``. Note: Only parameters that have been declared as dynamically typed can be unset. :param names: List of parameter names to unset. :param callback: Callback function to call when the request is complete. :return: ``Future`` with the result of the request. """ request = SetParameters.Request() request.parameters = [Parameter(name=i).to_parameter_msg() for i in names] future = self._set_parameter_client.call_async(request) if callback: future.add_done_callback(callback) return future def load_parameter_file( self, parameter_file: str, use_wildcard: bool = False, callback: Optional[Callable[[Future[SetParameters.Response]], None]] = None ) -> Future[SetParameters.Response]: """ Load parameters from a yaml file. Wrapper around `rclpy.parameter.parameter_dict_from_yaml_file`. The result after the returned future is complete will be of type ``rcl_interfaces.srv.SetParameters.Response``. :param parameter_file: Path to the parameter file. :param use_wildcard: Whether to use wildcard expansion. :return: Future with the result from the set_parameters call. """ param_dict = parameter_dict_from_yaml_file( parameter_file, use_wildcard, target_nodes=[self.remote_node_name]) future = self.set_parameters(list(param_dict.values()), callback=callback) return future def load_parameter_file_atomically( self, parameter_file: str, use_wildcard: bool = False, callback: Optional[Callable[[Future[SetParametersAtomically.Response]], None]] = None ) -> Future[SetParametersAtomically.Response]: """ Load parameters from a yaml file atomically. Wrapper around `rclpy.parameter.parameter_dict_from_yaml_file`. The result after the returned future is complete will be of type ``rcl_interfaces.srv.SetParametersAtomically.Response``. :param parameter_file: Path to the parameter file. :param use_wildcard: Whether to use wildcard expansion. :return: Future with the result from the set_parameters_atomically call. """ param_dict = parameter_dict_from_yaml_file( parameter_file, use_wildcard, target_nodes=[self.remote_node_name]) future = self.set_parameters_atomically(list(param_dict.values()), callback=callback) return future def on_parameter_event( self, callback: Union[Callable[[ParameterEvent], None], Callable[[ParameterEvent, MessageInfo], None]], qos_profile: QoSProfile = qos_profile_parameter_events, *, callback_group: Optional[CallbackGroup] = None, event_callbacks: Optional[SubscriptionEventCallbacks] = None, qos_overriding_options: Optional[QoSOverridingOptions] = None, raw: bool = False ) -> Subscription[ParameterEvent]: return self.node.create_subscription( ParameterEvent, '/parameter_events', callback, qos_profile, callback_group=callback_group, event_callbacks=event_callbacks, qos_overriding_options=qos_overriding_options, raw=raw)
# Copyright 2022 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from tempfile import NamedTemporaryFile import unittest import rcl_interfaces.msg from rcl_interfaces.msg import ParameterEvent from rcl_interfaces.msg import ParameterType import rcl_interfaces.srv import rclpy import rclpy.context from rclpy.executors import SingleThreadedExecutor from rclpy.parameter import Parameter from rclpy.parameter_client import AsyncParameterClient class TestParameterClient(unittest.TestCase): def setUp(self) -> None: self.context = rclpy.context.Context() rclpy.init(context=self.context) self.client_node = rclpy.create_node( 'test_parameter_client', namespace='/rclpy', context=self.context) self.target_node = rclpy.create_node( 'test_parameter_client_target', namespace='/rclpy', allow_undeclared_parameters=True, context=self.context) self.target_node.declare_parameter('int_arr_param', [1, 2, 3]) self.target_node.declare_parameter('float.param..', 3.14) self.client = AsyncParameterClient(self.client_node, 'test_parameter_client_target') self.executor = SingleThreadedExecutor(context=self.context) self.executor.add_node(self.client_node) self.executor.add_node(self.target_node) def tearDown(self) -> None: self.executor.shutdown() self.client_node.destroy_node() self.target_node.destroy_node() rclpy.shutdown(context=self.context) def test_set_parameter(self) -> None: future = self.client.set_parameters([ Parameter('int_param', Parameter.Type.INTEGER, 88).to_parameter_msg(), Parameter('string.param', Parameter.Type.STRING, 'hello world'), ]) self.executor.spin_until_future_complete(future) results = future.result() assert results is not None assert len(results.results) == 2 res = [i.successful for i in results.results] assert all(res) def test_get_parameter(self) -> None: future = self.client.get_parameters(['int_arr_param', 'float.param..']) self.executor.spin_until_future_complete(future) results = future.result() assert results is not None assert len(results.values) == 2 assert list(results.values[0].integer_array_value) == [1, 2, 3] assert results.values[1].double_value == 3.14 def test_list_parameters(self) -> None: future = self.client.list_parameters() self.executor.spin_until_future_complete(future) results = future.result() assert results is not None assert 'int_arr_param' in results.result.names assert 'float.param..' in results.result.names future = self.client.list_parameters(['float.param.'], 1) self.executor.spin_until_future_complete(future) results = future.result() assert results is not None assert 'int_arr_param' not in results.result.names assert 'float.param..' in results.result.names assert 'float.param.' in results.result.prefixes def test_describe_parameters(self) -> None: future = self.client.describe_parameters(['int_arr_param']) self.executor.spin_until_future_complete(future) results = future.result() assert results is not None assert len(results.descriptors) == 1 assert results.descriptors[0].type == ParameterType.PARAMETER_INTEGER_ARRAY assert results.descriptors[0].name == 'int_arr_param' def test_get_paramter_types(self) -> None: future = self.client.get_parameter_types(['int_arr_param']) self.executor.spin_until_future_complete(future) results = future.result() assert results is not None assert len(results.types) == 1 assert results.types[0] == ParameterType.PARAMETER_INTEGER_ARRAY def test_set_parameters_atomically(self) -> None: future = self.client.set_parameters_atomically([ Parameter('int_param', Parameter.Type.INTEGER, 888), Parameter('string.param', Parameter.Type.STRING, 'Hello World').to_parameter_msg(), ]) self.executor.spin_until_future_complete(future) results = future.result() assert results is not None assert results.result.successful def test_delete_parameters(self) -> None: self.target_node.declare_parameter('delete_param', 10) descriptor = rcl_interfaces.msg.ParameterDescriptor(dynamic_typing=True) self.target_node.declare_parameter('delete_param_dynamic', 10, descriptor=descriptor) future = self.client.delete_parameters(['delete_param']) self.executor.spin_until_future_complete(future) result = future.result() assert result is not None assert len(result.results) == 1 assert not result.results[0].successful assert result.results[0].reason == 'Static parameter cannot be undeclared' future = self.client.delete_parameters(['delete_param_dynamic']) self.executor.spin_until_future_complete(future) result = future.result() assert result is not None assert len(result.results) == 1 assert result.results[0].successful def test_load_parameter_file(self) -> None: yaml_string = """/test_parameter_client_target: ros__parameters: param_1: 1 param_str: "string" """ try: with NamedTemporaryFile(mode='w', delete=False) as f: f.write(yaml_string) f.flush() f.close() future = self.client.load_parameter_file(f.name) self.executor.spin_until_future_complete(future) result = future.result() assert result is not None assert len(result.results) == 2 assert all(i.successful for i in result.results) finally: if os.path.exists(f.name): os.unlink(f.name) def test_load_parameter_file_atomically(self) -> None: yaml_string = """/test_parameter_client_target: ros__parameters: param_1: 1 param_str: "string" """ try: with NamedTemporaryFile(mode='w', delete=False) as f: f.write(yaml_string) f.flush() f.close() future = self.client.load_parameter_file_atomically(f.name) self.executor.spin_until_future_complete(future) result = future.result() assert result is not None assert result.result.successful finally: if os.path.exists(f.name): os.unlink(f.name) def test_get_uninitialized_parameter(self) -> None: self.target_node.declare_parameter('uninitialized_parameter', Parameter.Type.STRING) # The type in description should be STRING future = self.client.describe_parameters(['uninitialized_parameter']) self.executor.spin_until_future_complete(future) results = future.result() assert results is not None assert len(results.descriptors) == 1 assert results.descriptors[0].type == ParameterType.PARAMETER_STRING assert results.descriptors[0].name == 'uninitialized_parameter' # The value should be empty future = self.client.get_parameters(['uninitialized_parameter']) self.executor.spin_until_future_complete(future) results = future.result() assert results is not None assert results.values == [] self.target_node.undeclare_parameter('uninitialized_parameter') def test_on_parameter_event_new(self) -> None: def on_new_parameter_event(msg: ParameterEvent) -> None: assert msg.node == '/rclpy/test_parameter_client_target' assert len(msg.new_parameters) == 1 assert msg.new_parameters[0].name == 'int_param' assert msg.new_parameters[0].value.integer_value == 88 assert len(msg.changed_parameters) == 0 assert len(msg.deleted_parameters) == 0 param_event_sub = self.client.on_parameter_event(on_new_parameter_event) future = self.client.set_parameters([ Parameter('int_param', Parameter.Type.INTEGER, 88).to_parameter_msg(), ]) self.executor.spin_until_future_complete(future) results = future.result() assert results is not None assert len(results.results) == 1 res = [i.successful for i in results.results] assert all(res) param_event_sub.destroy() def test_on_parameter_event_changed(self) -> None: future = self.client.set_parameters([ Parameter('int_param', Parameter.Type.INTEGER, 88).to_parameter_msg(), ]) self.executor.spin_until_future_complete(future) results = future.result() assert results is not None assert len(results.results) == 1 res = [i.successful for i in results.results] assert all(res) def on_changed_parameter_event(msg: ParameterEvent) -> None: assert msg.node == '/rclpy/test_parameter_client_target' assert len(msg.new_parameters) == 0 assert len(msg.changed_parameters) == 1 assert msg.changed_parameters[0].name == 'int_param' assert msg.changed_parameters[0].value.integer_value == 99 assert len(msg.deleted_parameters) == 0 param_event_sub = self.client.on_parameter_event(on_changed_parameter_event) future = self.client.set_parameters([ Parameter('int_param', Parameter.Type.INTEGER, 99).to_parameter_msg(), ]) self.executor.spin_until_future_complete(future) results = future.result() assert results is not None assert len(results.results) == 1 res = [i.successful for i in results.results] assert all(res) param_event_sub.destroy() def test_on_parameter_event_deleted(self) -> None: future = self.client.set_parameters([ Parameter('int_param', Parameter.Type.INTEGER, 88).to_parameter_msg(), ]) self.executor.spin_until_future_complete(future) results = future.result() assert results is not None assert len(results.results) == 1 res = [i.successful for i in results.results] assert all(res) def on_deleted_parameter_event(msg: ParameterEvent) -> None: assert msg.node == '/rclpy/test_parameter_client_target' assert len(msg.new_parameters) == 0 assert len(msg.changed_parameters) == 0 assert len(msg.deleted_parameters) == 1 assert msg.deleted_parameters[0].name == 'int_param' param_event_sub = self.client.on_parameter_event(on_deleted_parameter_event) future = self.client.delete_parameters(['int_param']) self.executor.spin_until_future_complete(future) results = future.result() assert results is not None assert len(results.results) == 1 res = [i.successful for i in results.results] assert all(res) param_event_sub.destroy()
rclpy
python
# Copyright 2016 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import math import time from types import TracebackType from typing import Any from typing import Callable from typing import Dict from typing import Final from typing import Iterator from typing import List from typing import Literal from typing import Optional from typing import overload from typing import Sequence from typing import Tuple from typing import Type from typing import TypeVar from typing import Union import warnings import weakref from rcl_interfaces.msg import FloatingPointRange from rcl_interfaces.msg import IntegerRange from rcl_interfaces.msg import ListParametersResult from rcl_interfaces.msg import Parameter as ParameterMsg from rcl_interfaces.msg import ParameterDescriptor from rcl_interfaces.msg import ParameterEvent from rcl_interfaces.msg import ParameterType from rcl_interfaces.msg import ParameterValue from rcl_interfaces.msg import SetParametersResult from rcl_interfaces.srv import ListParameters from rclpy.callback_groups import CallbackGroup from rclpy.callback_groups import MutuallyExclusiveCallbackGroup from rclpy.callback_groups import ReentrantCallbackGroup from rclpy.client import Client from rclpy.clock import Clock from rclpy.clock import ROSClock from rclpy.constants import S_TO_NS from rclpy.context import Context from rclpy.endpoint_info import ServiceEndpointInfo, TopicEndpointInfo from rclpy.event_handler import PublisherEventCallbacks from rclpy.event_handler import SubscriptionEventCallbacks from rclpy.exceptions import InvalidHandle from rclpy.exceptions import InvalidParameterTypeException from rclpy.exceptions import InvalidParameterValueException from rclpy.exceptions import InvalidTopicNameException from rclpy.exceptions import NotInitializedException from rclpy.exceptions import ParameterAlreadyDeclaredException from rclpy.exceptions import ParameterImmutableException from rclpy.exceptions import ParameterNotDeclaredException from rclpy.exceptions import ParameterUninitializedException from rclpy.executors import Executor from rclpy.expand_topic_name import expand_topic_name from rclpy.guard_condition import GuardCondition from rclpy.guard_condition import GuardConditionCallbackType from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy from rclpy.impl.rcutils_logger import RcutilsLogger from rclpy.logging import get_logger from rclpy.logging_service import LoggingService from rclpy.parameter import (AllowableParameterValue, AllowableParameterValueT, Parameter, PARAMETER_SEPARATOR_STRING) from rclpy.parameter_service import ParameterService from rclpy.publisher import Publisher from rclpy.qos import qos_profile_parameter_events from rclpy.qos import qos_profile_rosout_default from rclpy.qos import qos_profile_services_default from rclpy.qos import QoSProfile from rclpy.qos_overriding_options import _declare_qos_parameters from rclpy.qos_overriding_options import QoSOverridingOptions from rclpy.service import Service from rclpy.subscription import GenericSubscriptionCallback from rclpy.subscription import Subscription from rclpy.subscription import SubscriptionCallbackUnion from rclpy.subscription_content_filter_options import ContentFilterOptions from rclpy.time_source import TimeSource from rclpy.timer import Rate from rclpy.timer import Timer from rclpy.timer import TimerCallbackType from rclpy.type_description_service import TypeDescriptionService from rclpy.type_support import check_is_valid_msg_type from rclpy.type_support import check_is_valid_srv_type from rclpy.type_support import MsgT from rclpy.type_support import Srv from rclpy.type_support import SrvRequestT from rclpy.type_support import SrvResponseT from rclpy.utilities import get_default_context from rclpy.validate_full_topic_name import validate_full_topic_name from rclpy.validate_namespace import validate_namespace from rclpy.validate_node_name import validate_node_name from rclpy.validate_parameter_name import validate_parameter_name from rclpy.validate_topic_name import validate_topic_name from rclpy.waitable import Waitable from typing_extensions import TypeAlias HIDDEN_NODE_PREFIX: Final = '_' # Left to support Legacy TypeVar. MsgType = TypeVar('MsgType') SrvType = TypeVar('SrvType') SrvTypeRequest = TypeVar('SrvTypeRequest') SrvTypeResponse = TypeVar('SrvTypeResponse') # Re-export exception defined in _rclpy C extension. # `Node.get_*_names_and_types_by_node` methods may raise this error. NodeNameNonExistentError: TypeAlias = _rclpy.NodeNameNonExistentError ParameterInput: TypeAlias = Union[AllowableParameterValue, Parameter.Type, ParameterValue] class Node: """ A Node in the ROS graph. A Node is the primary entrypoint in a ROS system for communication. It can be used to create ROS entities such as publishers, subscribers, services, etc. """ PARAM_REL_TOL = 1e-6 """ Relative tolerance for floating point parameter values' comparison. See `math.isclose` documentation. """ def __init__( self, node_name: str, *, context: Optional[Context] = None, cli_args: Optional[List[str]] = None, namespace: Optional[str] = None, use_global_arguments: bool = True, enable_rosout: bool = True, rosout_qos_profile: Union[QoSProfile, int] = qos_profile_rosout_default, start_parameter_services: bool = True, parameter_overrides: Optional[List[Parameter[Any]]] = None, allow_undeclared_parameters: bool = False, automatically_declare_parameters_from_overrides: bool = False, enable_logger_service: bool = False ) -> None: """ Create a Node. :param node_name: A name to give to this node. Validated by :func:`validate_node_name`. :param context: The context to be associated with, or ``None`` for the default global context. :param cli_args: A list of strings of command line args to be used only by this node. These arguments are used to extract remappings used by the node and other ROS specific settings, as well as user defined non-ROS arguments. :param namespace: The namespace to which relative topic and service names will be prefixed. Validated by :func:`validate_namespace`. :param use_global_arguments: ``False`` if the node should ignore process-wide command line args. :param enable_rosout: ``False`` if the node should ignore rosout logging. :param rosout_qos_profile: A QoSProfile or a history depth to apply to rosout publisher. In the case that a history depth is provided, the QoS history is set to KEEP_LAST the QoS history depth is set to the value of the parameter, and all other QoS settings are set to their default value. :param start_parameter_services: ``False`` if the node should not create parameter services. :param parameter_overrides: A list of overrides for initial values for parameters declared on the node. :param allow_undeclared_parameters: True if undeclared parameters are allowed. This flag affects the behavior of parameter-related operations. :param automatically_declare_parameters_from_overrides: If True, the "parameter overrides" will be used to implicitly declare parameters on the node during creation. :param enable_logger_service: ``True`` if ROS2 services are created to allow external nodes to get and set logger levels of this node. Otherwise, logger levels are only managed locally. That is, logger levels cannot be changed remotely. """ self._context = get_default_context() if context is None else context self._parameters: Dict[str, Parameter[Any]] = {} self._publishers: List[Publisher[Any]] = [] self._subscriptions: List[Subscription[Any]] = [] self._clients: List[Client[Any, Any]] = [] self._services: List[Service[Any, Any]] = [] self._timers: List[Timer] = [] self._guards: List[GuardCondition] = [] self.__waitables: List[Waitable[Any]] = [] self._default_callback_group = MutuallyExclusiveCallbackGroup() self._pre_set_parameters_callbacks: List[Callable[[List[Parameter[Any]]], List[Parameter[Any]]]] = [] self._on_set_parameters_callbacks: \ List[Callable[[List[Parameter[Any]]], SetParametersResult]] = [] self._post_set_parameters_callbacks: List[Callable[[List[Parameter[Any]]], None]] = [] self._rate_group = ReentrantCallbackGroup() self._allow_undeclared_parameters = allow_undeclared_parameters self._parameter_overrides: Dict[str, Parameter[Any]] = {} self._descriptors: Dict[str, ParameterDescriptor] = {} namespace = namespace or '' if self._context.handle is None or not self._context.ok(): raise NotInitializedException('cannot create node') rosout_qos_profile = self._validate_qos_or_depth_parameter(rosout_qos_profile) with self._context.handle: try: self.__node = _rclpy.Node( node_name, namespace, self._context.handle, cli_args, use_global_arguments, enable_rosout, rosout_qos_profile.get_c_qos_profile() ) except ValueError: # these will raise more specific errors if the name or namespace is bad validate_node_name(node_name) # emulate what rcl_node_init() does to accept '' and relative namespaces if not namespace: namespace = '/' if not namespace.startswith('/'): namespace = '/' + namespace validate_namespace(namespace) # Should not get to this point raise RuntimeError('rclpy_create_node failed for unknown reason') with self.handle: self._logger = get_logger(self.__node.logger_name()) self.__executor_weakref: Optional[weakref.ReferenceType[Executor]] = None self._parameter_event_publisher: Optional[Publisher[ParameterEvent]] = \ self.create_publisher(ParameterEvent, '/parameter_events', qos_profile_parameter_events) with self.handle: self._parameter_overrides = self.__node.get_parameters(Parameter) # Combine parameters from params files with those from the node constructor and # use the set_parameters_atomically API so a parameter event is published. if parameter_overrides is not None: self._parameter_overrides.update({p.name: p for p in parameter_overrides}) # Clock that has support for ROS time. self._clock = ROSClock() if automatically_declare_parameters_from_overrides: self.declare_parameters( '', [ (name, param.value, ParameterDescriptor()) for name, param in self._parameter_overrides.items()], ignore_override=True, ) # Init a time source. # Note: parameter overrides and parameter event publisher need to be ready at this point # to be able to declare 'use_sim_time' if it was not declared yet. self._time_source = TimeSource(node=self) self._time_source.attach_clock(self._clock) if start_parameter_services: self._parameter_service = ParameterService(self) if enable_logger_service: self._logger_service = LoggingService(self) self._type_description_service = TypeDescriptionService(self) self._context.track_node(self) @property def publishers(self) -> Iterator[Publisher[Any]]: """Get publishers that have been created on this node.""" yield from self._publishers @property def subscriptions(self) -> Iterator[Subscription[Any]]: """Get subscriptions that have been created on this node.""" yield from self._subscriptions @property def clients(self) -> Iterator[Client[Any, Any]]: """Get clients that have been created on this node.""" yield from self._clients @property def services(self) -> Iterator[Service[Any, Any]]: """Get services that have been created on this node.""" yield from self._services @property def timers(self) -> Iterator[Timer]: """Get timers that have been created on this node.""" yield from self._timers @property def guards(self) -> Iterator[GuardCondition]: """Get guards that have been created on this node.""" yield from self._guards @property def waitables(self) -> Iterator[Waitable[Any]]: """Get waitables that have been created on this node.""" yield from self.__waitables @property def executor(self) -> Optional[Executor]: """Get the executor if the node has been added to one, else return ``None``.""" if self.__executor_weakref: return self.__executor_weakref() return None @executor.setter def executor(self, new_executor: Optional[Executor]) -> None: """Set or change the executor the node belongs to.""" current_executor = self.executor if current_executor == new_executor: return if current_executor is not None: current_executor.remove_node(self) if new_executor is None: self.__executor_weakref = None else: new_executor.add_node(self) self.__executor_weakref = weakref.ref(new_executor) def _wake_executor(self) -> None: executor = self.executor if executor: executor.wake() @property def context(self) -> Context: """Get the context associated with the node.""" return self._context @property def default_callback_group(self) -> CallbackGroup: """ Get the default callback group. If no other callback group is provided when the a ROS entity is created with the node, then it is added to the default callback group. """ return self._default_callback_group @property def handle(self) -> _rclpy.Node: """ Get the handle to the underlying `rcl_node_t`. Cannot be modified after node creation. :raises: AttributeError if modified after creation. """ return self.__node @handle.setter def handle(self, value: None) -> None: raise AttributeError('handle cannot be modified after node creation') def get_name(self) -> str: """Get the name of the node.""" with self.handle: return self.handle.get_node_name() def get_namespace(self) -> str: """Get the namespace of the node.""" with self.handle: return self.handle.get_namespace() def get_clock(self) -> Clock: """Get the clock used by the node.""" return self._clock def get_logger(self) -> RcutilsLogger: """Get the nodes logger.""" return self._logger @overload def declare_parameter(self, name: str, value: AllowableParameterValueT, descriptor: Optional[ParameterDescriptor] = None, ignore_override: bool = False ) -> Parameter[AllowableParameterValueT]: ... @overload def declare_parameter(self, name: str, value: Union[None, Parameter.Type, ParameterValue] = None, descriptor: Optional[ParameterDescriptor] = None, ignore_override: bool = False) -> Parameter[Any]: ... def declare_parameter( self, name: str, value: Union[AllowableParameterValue, Parameter.Type, ParameterValue] = None, descriptor: Optional[ParameterDescriptor] = None, ignore_override: bool = False ) -> Parameter[Any]: """ Declare and initialize a parameter. This method, if successful, will result in any callback registered with :func:`add_on_set_parameters_callback` and :func:`add_post_set_parameters_callback` to be called. The name and type in the given descriptor is ignored, and should be specified using the name argument to this function and the default value's type instead. :param name: Fully-qualified name of the parameter, including its namespace. :param value: Value of the parameter to declare. :param descriptor: Descriptor for the parameter to declare. :param ignore_override: True if overrides shall not be taken into account; False otherwise. :return: Parameter with the effectively assigned value. :raises: ParameterAlreadyDeclaredException if the parameter had already been declared. :raises: InvalidParameterException if the parameter name is invalid. :raises: InvalidParameterValueException if the registered callback rejects the parameter. """ if value is None and descriptor is None: # Temporal patch so we get deprecation warning if only a name is provided. args: Union[Tuple[str], Tuple[str, ParameterInput, ParameterDescriptor]] = (name, ) else: descriptor = ParameterDescriptor() if descriptor is None else descriptor args = (name, value, descriptor) return self.declare_parameters('', [args], ignore_override)[0] def declare_parameters( self, namespace: str, parameters: Sequence[Union[ Tuple[str], Tuple[str, ParameterInput], Tuple[str, ParameterInput, ParameterDescriptor]]], ignore_override: bool = False ) -> List[Parameter[Any]]: """ Declare a list of parameters. The tuples in the given parameter list shall contain the name for each parameter, optionally providing a value and a descriptor. The name and type in the given descriptors are ignored, and should be specified using the name argument to this function and the default value's type instead. For each entry in the list, a parameter with a name of "namespace.name" will be declared. The resulting value for each declared parameter will be returned, considering parameter overrides set upon node creation as the first choice, or provided parameter values as the second one. The name expansion is naive, so if you set the namespace to be "foo.", then the resulting parameter names will be like "foo..name". However, if the namespace is an empty string, then no leading '.' will be placed before each name, which would have been the case when naively expanding "namespace.name". This allows you to declare several parameters at once without a namespace. This method will result in any callback registered with :func:`add_on_set_parameters_callback` and :func:`add_post_set_parameters_callback` to be called once for each parameter. If a callback was registered previously with :func:`add_on_set_parameters_callback`, it will be called prior to setting the parameters for the node, once for each parameter. If one of the calls due to :func:`add_on_set_parameters_callback` fail, an exception will be raised and the remaining parameters will not be declared. Parameters declared up to that point will not be undeclared. If a callback was registered previously with :func:`add_post_set_parameters_callback`, it will be called after setting the parameters successfully for the node, once for each parameter. This method will `not` result in any callbacks registered with :func:`add_pre_set_parameters_callback` to be called. :param namespace: Namespace for parameters. :param parameters: List of tuples with parameters to declare. :param ignore_override: True if overrides shall not be taken into account; False otherwise. :return: Parameter list with the effectively assigned values for each of them. :raises: ParameterAlreadyDeclaredException if the parameter had already been declared. :raises: InvalidParameterException if the parameter name is invalid. :raises: InvalidParameterValueException if the registered callback rejects any parameter. :raises: TypeError if any tuple in **parameters** does not match the annotated type. """ parameter_list: List[Parameter[Any]] = [] descriptors: Dict[str, ParameterDescriptor] = {} for index, parameter_tuple in enumerate(parameters): if len(parameter_tuple) < 1 or len(parameter_tuple) > 3: raise TypeError( 'Invalid parameter tuple length at index {index} in parameters list: ' '{parameter_tuple}; expecting length between 1 and 3'.format_map(locals()) ) value = None # Get the values from the tuple, checking its types. # Use defaults if the tuple doesn't contain value and / or descriptor. name = parameter_tuple[0] if not isinstance(name, str): raise TypeError( f'First element {name} at index {index} in parameters list ' 'is not a str.') if namespace: name = f'{namespace}.{name}' # Note(jubeira): declare_parameters verifies the name, but set_parameters doesn't. validate_parameter_name(name) second_arg = parameter_tuple[1] if len(parameter_tuple) > 1 else None descriptor = parameter_tuple[2] if len(parameter_tuple) > 2 else ParameterDescriptor() if not isinstance(descriptor, ParameterDescriptor): raise TypeError( f'Third element {descriptor} at index {index} in parameters list ' 'is not a ParameterDescriptor.' ) if len(parameter_tuple) == 1: raise TypeError( f"when declaring parameter named '{name}', " 'declaring a parameter only providing its name is not allowed. ' 'You have to either:\n' '\t- Pass a name and a default value different to "PARAMETER NOT SET"' ' (and optionally a descriptor).\n' '\t- Pass a name and a parameter type.\n' '\t- Pass a name and a descriptor with `dynamic_typing=True') if isinstance(second_arg, Parameter.Type): if second_arg == Parameter.Type.NOT_SET: raise ValueError( f'Cannot declare parameter {{{name}}} as statically typed of type NOT_SET') if descriptor.dynamic_typing is True: raise ValueError( f'When declaring parameter {{{name}}} passing a descriptor with' '`dynamic_typing=True` is not allowed when the parameter type is provided') descriptor.type = second_arg.value else: value = second_arg if not descriptor.dynamic_typing: # infer type from default value if isinstance(value, ParameterValue): descriptor.type = value.type else: descriptor.type = Parameter.Type.from_parameter_value(value).value if descriptor.type == ParameterType.PARAMETER_NOT_SET: raise ValueError( 'Cannot declare a statically typed parameter with default value ' 'of type PARAMETER_NOT_SET') # Get value from parameter overrides, of from tuple if it doesn't exist. if not ignore_override and name in self._parameter_overrides: value = self._parameter_overrides[name].value if isinstance(value, ParameterValue): raise ValueError('Cannot declare a Parameter from a ParameterValue without it ' 'being included in self._parameter_overrides, and ', 'ignore_override=False') from typing import cast value = cast(AllowableParameterValue, value) parameter_list.append(Parameter(name, value=value)) descriptors.update({name: descriptor}) parameters_already_declared = [ parameter.name for parameter in parameter_list if parameter.name in self._parameters ] if any(parameters_already_declared): raise ParameterAlreadyDeclaredException(parameters_already_declared) # Call the callback once for each of the parameters, using method that doesn't # check whether the parameter was declared beforehand or not. self._declare_parameter_common( parameter_list, descriptors ) # Don't call get_parameters() to bypass check for NOT_SET parameters return [self._parameters[parameter.name] for parameter in parameter_list] def _declare_parameter_common( self, parameter_list: List[Parameter[Any]], descriptors: Optional[Dict[str, ParameterDescriptor]] = None ) -> List[SetParametersResult]: """ Declare parameters for the node, and return the result for the declare action. Method for internal usage; applies a setter method for each parameters in the list. By default, it checks if the parameters were declared, raising an exception if at least one of them was not. This method will result in any callback registered with :func:`add_on_set_parameters_callback` and :func:`add_post_set_parameters_callback` to be called once for each parameter. If a callback was registered previously with :func:`add_on_set_parameters_callback`, it will be called prior to setting the parameters for the node, once for each parameter. If the callback doesn't succeed for a given parameter an exception will be raised. If a callback was registered previously with :func:`add_post_set_parameters_callback`, it will be called after setting the parameters successfully for the node, once for each parameter. This method will `not` result in any callbacks registered with :func:`add_pre_set_parameters_callback` to be called. :param parameter_list: List of parameters to set. :param descriptors: Descriptors to set to the given parameters. If descriptors are given, each parameter in the list must have a corresponding one. :return: The result for each set action as a list. :raises: InvalidParameterValueException if the user-defined callback rejects the parameter value. :raises: ParameterNotDeclaredException if undeclared parameters are not allowed in this method and at least one parameter in the list hadn't been declared beforehand.` """ if descriptors is not None: assert all(parameter.name in descriptors for parameter in parameter_list) results = [] for param in parameter_list: # If undeclared parameters are allowed, parameters with type NOT_SET shall be stored. result = self._set_parameters_atomically_common( [param], descriptors, allow_not_set_type=True ) if not result.successful: if result.reason.startswith('Wrong parameter type'): if descriptors: raise InvalidParameterTypeException( param, Parameter.Type(descriptors[param._name].type).name) raise InvalidParameterValueException(param.name, param.value, result.reason) results.append(result) return results def undeclare_parameter(self, name: str) -> None: """ Undeclare a previously declared parameter. This method will not cause a callback registered with any of the :func:`add_pre_set_parameters_callback`, and :func:`add_post_set_parameters_callback` to be called. :param name: Fully-qualified name of the parameter, including its namespace. :raises: ParameterNotDeclaredException if parameter had not been declared before. :raises: ParameterImmutableException if the parameter was created as read-only. """ if self.has_parameter(name): if self._descriptors[name].read_only: raise ParameterImmutableException(name) else: del self._parameters[name] del self._descriptors[name] else: raise ParameterNotDeclaredException(name) def has_parameter(self, name: str) -> bool: """Return True if parameter is declared; False otherwise.""" return name in self._parameters def get_parameter_types(self, names: List[str]) -> List[Parameter.Type]: """ Get a list of parameter types. :param names: Fully-qualified names of the parameters to get, including their namespaces. :return: The values for the given parameter types. A default Parameter.Type.NOT_SET will be returned for undeclared parameters if undeclared parameters are allowed. :raises: ParameterNotDeclaredException if undeclared parameters are not allowed, and at least one parameter hadn't been declared beforehand. """ if not all(isinstance(name, str) for name in names): raise TypeError('All names must be instances of type str') return [self.get_parameter_type(name) for name in names] def get_parameter_type(self, name: str) -> Parameter.Type: """ Get a parameter type by name. :param name: Fully-qualified name of the parameter, including its namespace. :return: The type for the given parameter name. A default Parameter.Type.NOT_SET will be returned for an undeclared parameter if undeclared parameters are allowed. :raises: ParameterNotDeclaredException if undeclared parameters are not allowed, and the parameter hadn't been declared beforehand. """ if self.has_parameter(name): return self._parameters[name].type_ elif self._allow_undeclared_parameters: return Parameter.Type.NOT_SET else: raise ParameterNotDeclaredException(name) def get_parameters(self, names: List[str]) -> List[Parameter[Any]]: """ Get a list of parameters. :param names: Fully-qualified names of the parameters to get, including their namespaces. :return: The values for the given parameter names. A default Parameter will be returned for undeclared parameters if undeclared parameters are allowed. :raises: ParameterNotDeclaredException if undeclared parameters are not allowed, and at least one parameter hadn't been declared beforehand. :raises: ParameterUninitializedException if at least one parameter is statically typed and uninitialized. """ if not all(isinstance(name, str) for name in names): raise TypeError('All names must be instances of type str') return [self.get_parameter(name) for name in names] def get_parameter(self, name: str) -> Parameter[Any]: """ Get a parameter by name. :param name: Fully-qualified name of the parameter, including its namespace. :return: The value for the given parameter name. A default Parameter will be returned for an undeclared parameter if undeclared parameters are allowed. :raises: ParameterNotDeclaredException if undeclared parameters are not allowed, and the parameter hadn't been declared beforehand. :raises: ParameterUninitializedException if the parameter is statically typed and uninitialized. """ if self.has_parameter(name): parameter = self._parameters[name] if ( parameter.type_ != Parameter.Type.NOT_SET or self._descriptors[name].dynamic_typing ): return self._parameters[name] # Statically typed, uninitialized parameter raise ParameterUninitializedException(name) elif self._allow_undeclared_parameters: return Parameter(name, Parameter.Type.NOT_SET, None) else: raise ParameterNotDeclaredException(name) def get_parameter_or( self, name: str, alternative_value: Optional[Parameter[Any]] = None) -> Parameter[Any]: """ Get a parameter or the alternative value. If the alternative value is None, a default Parameter with the given name and NOT_SET type will be returned if the parameter was not declared. :param name: Fully-qualified name of the parameter, including its namespace. :param alternative_value: Alternative parameter to get if it had not been declared before. :return: Requested parameter, or alternative value if it hadn't been declared before or is an uninitialized statically typed parameter. """ if alternative_value is None: alternative_value = Parameter(name, Parameter.Type.NOT_SET) if not self.has_parameter(name): return alternative_value # Return alternative for uninitialized parameters if (self._parameters[name].type_ == Parameter.Type.NOT_SET): return alternative_value return self._parameters[name] def get_parameters_by_prefix(self, prefix: str) -> Dict[str, Parameter[Any]]: """ Get parameters that have a given prefix in their names as a dictionary. The names which are used as keys in the returned dictionary have the prefix removed. For example, if you use the prefix "foo" and the parameters "foo.ping", "foo.pong" and "bar.baz" exist, then the returned dictionary will have the keys "ping" and "pong". Note that the parameter separator is also removed from the parameter name to create the keys. An empty string for the prefix will match all parameters. If no parameters with the prefix are found, an empty dictionary will be returned. :param prefix: The prefix of the parameters to get. :return: Dict of parameters with the given prefix. """ if prefix: prefix = prefix + PARAMETER_SEPARATOR_STRING prefix_len = len(prefix) return { param_name[prefix_len:]: param_value for param_name, param_value in self._parameters.items() if param_name.startswith(prefix) } def set_parameters(self, parameter_list: List[Parameter[Any]]) -> List[SetParametersResult]: """ Set parameters for the node, and return the result for the set action. If any parameter in the list was not declared beforehand and undeclared parameters are not allowed for the node, this method will raise a ParameterNotDeclaredException exception. Parameters are set in the order they are declared in the list. If setting a parameter fails due to not being declared, then the parameters which have already been set will stay set, and no attempt will be made to set the parameters which come after. If undeclared parameters are allowed, then all the parameters will be implicitly declared before being set even if they were not declared beforehand. Parameter overrides are ignored by this method. This method will result in any callback registered with :func:`add_pre_set_parameters_callback`, :func:`add_on_set_parameters_callback` and :func:`add_post_set_parameters_callback` to be called once for each parameter. If a callback was registered previously with :func:`add_pre_set_parameters_callback`, it will be called prior to the validation of parameters for the node, once for each parameter. If this callback makes modified parameter list empty, then it will be reflected in the returned result; no exceptions will be raised in this case. If a callback was registered previously with :func:`add_on_set_parameters_callback`, it will be called prior to setting the parameters for the node, once for each parameter. If this callback prevents a parameter from being set, then it will be reflected in the returned result; no exceptions will be raised in this case. If a callback was registered previously with :func:`add_post_set_parameters_callback`, it will be called after setting the parameters successfully for the node, once for each parameter. For each successfully set parameter, a :class:`ParameterEvent` message is published. If the value type of the parameter is NOT_SET, and the existing parameter type is something else, then the parameter will be implicitly undeclared. :param parameter_list: The list of parameters to set. :return: The result for each set action as a list. :raises: ParameterNotDeclaredException if undeclared parameters are not allowed, and at least one parameter in the list hadn't been declared beforehand. """ results = [] for param in parameter_list: result = self._set_parameters_atomically([param]) results.append(result) return results def set_parameters_atomically(self, parameter_list: List[Parameter[Any]] ) -> SetParametersResult: """ Set the given parameters, all at one time, and then aggregate result. If any parameter in the list was not declared beforehand and undeclared parameters are not allowed for the node, this method will raise a ParameterNotDeclaredException exception. Parameters are set all at once. If setting a parameter fails due to not being declared, then no parameter will be set. Either all of the parameters are set or none of them are set. If undeclared parameters are allowed for the node, then all the parameters will be implicitly declared before being set even if they were not declared beforehand. This method will result in any callback registered with :func:`add_pre_set_parameters_callback` :func:`add_on_set_parameters_callback` and :func:`add_post_set_parameters_callback` to be called only once for all parameters. If a callback was registered previously with :func:`add_pre_set_parameters_callback`, it will be called prior to the validation of node parameters only once for all parameters. If this callback makes modified parameter list empty, then it will be reflected in the returned result; no exceptions will be raised in this case. If a callback was registered previously with :func:`add_on_set_parameters_callback`, it will be called prior to setting the parameters for the node only once for all parameters. If the callback prevents the parameters from being set, then it will be reflected in the returned result; no exceptions will be raised in this case. If a callback was registered previously with :func:`add_post_set_parameters_callback`, it will be called after setting the node parameters successfully only once for all parameters. For each successfully set parameter, a :class:`ParameterEvent` message is published. If the value type of the parameter is NOT_SET, and the existing parameter type is something else, then the parameter will be implicitly undeclared. :param parameter_list: The list of parameters to set. :return: Aggregate result of setting all the parameters atomically. :raises: ParameterNotDeclaredException if undeclared parameters are not allowed, and at least one parameter in the list hadn't been declared beforehand. """ return self._set_parameters_atomically(parameter_list) def _set_parameters_atomically( self, parameter_list: List[Parameter[Any]], ) -> SetParametersResult: modified_parameter_list = self._call_pre_set_parameters_callback(parameter_list) if modified_parameter_list is not None: parameter_list = modified_parameter_list if len(parameter_list) == 0: result = SetParametersResult() result.successful = False result.reason = 'parameter list cannot be empty, this might be due to ' \ 'pre_set_parameters_callback modifying the original parameters ' \ 'list.' return result self._check_undeclared_parameters(parameter_list) return self._set_parameters_atomically_common(parameter_list) def _set_parameters_atomically_common( self, parameter_list: List[Parameter[Any]], descriptors: Optional[Dict[str, ParameterDescriptor]] = None, allow_not_set_type: bool = False ) -> SetParametersResult: """ Set the given parameters, all at one time, and then aggregate result. This internal method does not reject undeclared parameters. If :param:`allow_not_set_type` is False, a parameter with type NOT_SET will be undeclared. This method will result in any callback registered with :func:`add_on_set_parameters_callback` and :func:`add_post_set_parameters_callback` to be called only once for all parameters. If a callback was registered previously with :func:`add_on_set_parameters_callback`, it will be called prior to setting the parameters for the node only once for all parameters. If the callback prevents the parameters from being set, then it will be reflected in the returned result; no exceptions will be raised in this case. If a callback was registered previously with :func:`add_post_set_parameters_callback`, it will be called after setting the node parameters successfully only once for all parameters. For each successfully set parameter, a :class:`ParameterEvent` message is published. :param parameter_list: The list of parameters to set. :param descriptors: New descriptors to apply to the parameters before setting them. If descriptors are given, each parameter in the list must have a corresponding one. :param allow_not_set_type: False if parameters with NOT_SET type shall be undeclared, True if they should be stored despite not having an actual value. :return: Aggregate result of setting all the parameters atomically. """ if descriptors is not None: # If new descriptors are provided, ensure every parameter has an assigned descriptor # and do not check for read-only. assert all(parameter.name in descriptors for parameter in parameter_list) result = self._apply_descriptors(parameter_list, descriptors, False) else: # If new descriptors are not provided, use existing ones and check for read-only. result = self._apply_descriptors(parameter_list, self._descriptors, True) if not result.successful: return result elif self._on_set_parameters_callbacks: for callback in self._on_set_parameters_callbacks: result = callback(parameter_list) if not isinstance(result, SetParametersResult): warnings.warn( 'Callback returned an invalid type, it should return SetParameterResult.') result = SetParametersResult( successful=False, reason='Callback returned an invalid type') if not result.successful: return result result = SetParametersResult(successful=True) if result.successful: parameter_event = ParameterEvent() # Add fully qualified path of node to parameter event if self.get_namespace() == '/': parameter_event.node = self.get_namespace() + self.get_name() else: parameter_event.node = self.get_namespace() + '/' + self.get_name() for param in parameter_list: # If parameters without type and value are not allowed, they shall be undeclared. if not allow_not_set_type and Parameter.Type.NOT_SET == param.type_: # Parameter deleted. (Parameter had value and new value is not set). parameter_event.deleted_parameters.append(param.to_parameter_msg()) # Delete any unset parameters regardless of their previous value. if param.name in self._parameters: del self._parameters[param.name] if param.name in self._descriptors: del self._descriptors[param.name] else: # Update descriptors; set a default if it doesn't exist. # Don't update if it already exists for the current parameter and a new one # was not specified in this method call. if descriptors is not None: self._descriptors[param.name] = descriptors[param.name] elif param.name not in self._descriptors: descriptor = ParameterDescriptor() descriptor.dynamic_typing = True self._descriptors[param.name] = descriptor if Parameter.Type.NOT_SET == self.get_parameter_or(param.name).type_: # Parameter is new. (Parameter had no value and new value is set) parameter_event.new_parameters.append(param.to_parameter_msg()) else: parameter_event.changed_parameters.append( param.to_parameter_msg()) # Descriptors have already been applied by this point. self._parameters[param.name] = param parameter_event.stamp = self._clock.now().to_msg() if self._parameter_event_publisher: self._parameter_event_publisher.publish(parameter_event) # call post set parameter registered callbacks self._call_post_set_parameters_callback(parameter_list) return result def list_parameters( self, prefixes: List[str], depth: int ) -> ListParametersResult: """ Get a list of parameter names and their prefixes. :param prefixes: A list of prefixes to filter the parameter names. Only the parameter names that start with any of the prefixes are returned. If empty, all parameter names are returned. :param depth: The depth of nested parameter names to include. :return: The list of parameter names and their prefixes. :raises: TypeError if the type of any of the passed arguments is not an expected type. :raises: ValueError if depth is a negative integer. """ if not isinstance(prefixes, list): raise TypeError('The prefixes argument must be a list') if not all(isinstance(prefix, str) for prefix in prefixes): raise TypeError('All prefixes must be instances of type str') if not isinstance(depth, int): raise TypeError('The depth must be instance of type int') if depth < 0: raise ValueError('The depth must be greater than or equal to zero') result = ListParametersResult() separator_less_than_depth: Callable[[str], bool] = \ lambda s: s.count(PARAMETER_SEPARATOR_STRING) < depth recursive: bool = \ (len(prefixes) == 0) and (depth == ListParameters.Request.DEPTH_RECURSIVE) for param_name in self._parameters.keys(): if not recursive: get_all: bool = (len(prefixes) == 0) and (separator_less_than_depth(param_name)) if not get_all: prefix_matches = any( param_name == prefix or ( param_name.startswith(prefix+PARAMETER_SEPARATOR_STRING) and ( depth == ListParameters.Request.DEPTH_RECURSIVE or separator_less_than_depth(param_name[len(prefix)+1:]) ) ) for prefix in prefixes ) if not prefix_matches: continue result.names.append(param_name) last_separator = param_name.rfind(PARAMETER_SEPARATOR_STRING) if last_separator != -1: prefix = param_name[:last_separator] if prefix not in result.prefixes: result.prefixes.append(prefix) return result def _check_undeclared_parameters(self, parameter_list: List[Parameter[Any]]) -> None: """ Check if parameter list has correct types and was declared beforehand. :raises: ParameterNotDeclaredException if at least one parameter in the list was not declared beforehand. """ if not all(isinstance(parameter, Parameter) for parameter in parameter_list): raise TypeError("parameter must be instance of type '{}'".format(repr(Parameter))) undeclared_parameters = ( param.name for param in parameter_list if param.name not in self._parameters ) if not self._allow_undeclared_parameters and any(undeclared_parameters): raise ParameterNotDeclaredException(list(undeclared_parameters)) def _call_pre_set_parameters_callback(self, parameter_list: List[Parameter[Any]] ) -> Optional[List[Parameter[Any]]]: if self._pre_set_parameters_callbacks: modified_parameter_list: List[Parameter[Any]] = [] for callback in self._pre_set_parameters_callbacks: modified_parameter_list.extend(callback(parameter_list)) return modified_parameter_list else: return None def _call_post_set_parameters_callback(self, parameter_list: List[Parameter[Any]]) -> None: if self._post_set_parameters_callbacks: for callback in self._post_set_parameters_callbacks: callback(parameter_list) def add_pre_set_parameters_callback( self, callback: Callable[[List[Parameter[Any]]], List[Parameter[Any]]] ) -> None: """ Add a callback gets triggered before parameters are validated. Calling this function will add a callback in self._pre_set_parameter_callbacks list. This callback can be used to modify the original list of parameters being set by the user. The modified list of parameters is then forwarded to the "on set parameter" callback for validation. The callback takes a list of parameters to be set and returns a list of modified parameters. One of the use case of "pre set callback" can be updating additional parameters conditioned on changes to a parameter. All parameters in the modified list will be set atomically. Note that the callback is only called while setting parameters with ``set_parameters``, ``set_parameters_atomically``, or externally with a parameters service. The callback is not called when parameters are declared with ``declare_parameter`` or ``declare_parameters``. The callback is not called when parameters are undeclared with ``undeclare_parameter``. An empty modified parameter list from the callback will result in ``set_parameter*`` returning an unsuccessful result. :param callback: The function that is called before parameters are validated. """ self._pre_set_parameters_callbacks.insert(0, callback) def add_on_set_parameters_callback( self, callback: Callable[[List[Parameter[Any]]], SetParametersResult] ) -> None: """ Add a callback in front to the list of callbacks. Calling this function will add a callback in self._on_set_parameter_callbacks list. It is considered bad practice to reject changes for "unknown" parameters as this prevents other parts of the node (that may be aware of these parameters) from handling them. :param callback: The function that is called whenever parameters are being validated for the node. """ if not callable(callback): raise TypeError('Callback must be callable, got {}', type(callback)) self._on_set_parameters_callbacks.insert(0, callback) def add_post_set_parameters_callback( self, callback: Callable[[List[Parameter[Any]]], None] ) -> None: """ Add a callback gets triggered after parameters are set successfully. Calling this function will add a callback in self._post_set_parameter_callbacks list. The callback signature is designed to allow handling of the ``set_parameter*`` or ``declare_parameter*`` methods. The callback takes a list of parameters that have been set successfully. The callback can be valuable as a place to cause side effects based on parameter changes. For instance updating the internally tracked class attributes once the params have been changed successfully. :param callback: The function that is called after parameters are set for the node. """ if not callable(callback): raise TypeError('Callback must be callable, got {}', type(callback)) self._post_set_parameters_callbacks.insert(0, callback) def remove_pre_set_parameters_callback( self, callback: Callable[[List[Parameter[Any]]], List[Parameter[Any]]] ) -> None: """ Remove a callback from list of callbacks. Calling this function will remove the callback from self._pre_set_parameter_callbacks list. :param callback: The function that is called whenever parameters are set for the node. :raises: ValueError if a callback is not present in the list of callbacks. """ self._pre_set_parameters_callbacks.remove(callback) def remove_on_set_parameters_callback( self, callback: Callable[[List[Parameter[Any]]], SetParametersResult] ) -> None: """ Remove a callback from list of callbacks. Calling this function will remove the callback from self._parameter_callbacks list. :param callback: The function that is called whenever parameters are set for the node. :raises: ValueError if a callback is not present in the list of callbacks. """ self._on_set_parameters_callbacks.remove(callback) def remove_post_set_parameters_callback( self, callback: Callable[[List[Parameter[Any]]], None] ) -> None: """ Remove a callback from list of callbacks. Calling this function will remove the callback from self._parameter_callbacks list. :param callback: The function that is called whenever parameters are set for the node. :raises: ValueError if a callback is not present in the list of callbacks. """ self._post_set_parameters_callbacks.remove(callback) def _apply_descriptors( self, parameter_list: List[Parameter[Any]], descriptors: Dict[str, ParameterDescriptor], check_read_only: bool = True ) -> SetParametersResult: """ Apply descriptors to parameters and return an aggregated result without saving parameters. In case no descriptors are provided to the method, existing descriptors shall be used. In any case, if a given parameter doesn't have a descriptor it shall be skipped. :param parameter_list: Parameters to be checked. :param descriptors: Descriptors to apply. :param check_read_only: ``True`` if read-only check has to be applied. :return: SetParametersResult; successful if checks passed, unsuccessful otherwise. :raises: ParameterNotDeclaredException if a descriptor is not provided, the given parameter name had not been declared and undeclared parameters are not allowed. """ for param in parameter_list: if param.name in descriptors: result = self._apply_descriptor(param, descriptors[param.name], check_read_only) if not result.successful: return result return SetParametersResult(successful=True) def _apply_descriptor( self, parameter: Parameter[Any], descriptor: Optional[ParameterDescriptor] = None, check_read_only: bool = True ) -> SetParametersResult: """ Apply a descriptor to a parameter and return a result without saving the parameter. This method sets the type in the descriptor to match the parameter type. If a descriptor is provided, its name will be set to the name of the parameter. :param parameter: Parameter to be checked. :param descriptor: Descriptor to apply. If ``None``, the stored descriptor for the given parameter's name is used instead. :param check_read_only: ``True`` if read-only check has to be applied. :return: SetParametersResult; successful if checks passed, unsuccessful otherwise. :raises: ParameterNotDeclaredException if a descriptor is not provided, the given parameter name had not been declared and undeclared parameters are not allowed. """ if descriptor is None: descriptor = self.describe_parameter(parameter.name) else: descriptor.name = parameter.name if check_read_only and descriptor.read_only: return SetParametersResult( successful=False, reason='Trying to set a read-only parameter: {}.'.format(parameter.name)) if descriptor.dynamic_typing: descriptor.type = parameter.type_.value # If this parameter has already been declared, do not allow undeclaring it elif self.has_parameter(parameter.name) and parameter.type_ == Parameter.Type.NOT_SET: return SetParametersResult( successful=False, reason='Static parameter cannot be undeclared' ) elif ( parameter.type_ != Parameter.Type.NOT_SET and parameter.type_.value != descriptor.type ): return SetParametersResult( successful=False, reason=( 'Wrong parameter type, expected ' f"'{Parameter.Type(descriptor.type)}'" f" got '{parameter.type_}'") ) if parameter.type_ == Parameter.Type.INTEGER and descriptor.integer_range: return self._apply_integer_range(parameter, descriptor.integer_range[0]) if parameter.type_ == Parameter.Type.DOUBLE and descriptor.floating_point_range: return self._apply_floating_point_range(parameter, descriptor.floating_point_range[0]) return SetParametersResult(successful=True) def _apply_integer_range( self, parameter: Parameter[int], integer_range: IntegerRange ) -> SetParametersResult: min_value = min(integer_range.from_value, integer_range.to_value) max_value = max(integer_range.from_value, integer_range.to_value) # Values in the edge are always OK. if parameter.value == min_value or parameter.value == max_value: return SetParametersResult(successful=True) if not min_value < parameter.value < max_value: return SetParametersResult( successful=False, reason='Parameter {} out of range. ' 'Min: {}, Max: {}, value: {}'.format( parameter.name, min_value, max_value, parameter.value ) ) if integer_range.step != 0 and (parameter.value - min_value) % integer_range.step != 0: return SetParametersResult( successful=False, reason='The parameter value for {} is not a valid step. ' 'Min: {}, max: {}, value: {}, step: {}'.format( parameter.name, min_value, max_value, parameter.value, integer_range.step ) ) return SetParametersResult(successful=True) def _apply_floating_point_range( self, parameter: Parameter[float], floating_point_range: FloatingPointRange ) -> SetParametersResult: min_value = min(floating_point_range.from_value, floating_point_range.to_value) max_value = max(floating_point_range.from_value, floating_point_range.to_value) # Values in the edge are always OK. if ( math.isclose(parameter.value, min_value, rel_tol=self.PARAM_REL_TOL) or math.isclose(parameter.value, max_value, rel_tol=self.PARAM_REL_TOL) ): return SetParametersResult(successful=True) if not min_value < parameter.value < max_value: return SetParametersResult( successful=False, reason='Parameter {} out of range ' 'Min: {}, Max: {}, value: {}'.format( parameter.name, min_value, max_value, parameter.value ) ) if floating_point_range.step != 0.0: distance_int_steps = round((parameter.value - min_value) / floating_point_range.step) if not math.isclose( min_value + distance_int_steps * floating_point_range.step, parameter.value, rel_tol=self.PARAM_REL_TOL ): return SetParametersResult( successful=False, reason='The parameter value for {} is not close enough to a valid step. ' 'Min: {}, max: {}, value: {}, step: {}'.format( parameter.name, min_value, max_value, parameter.value, floating_point_range.step ) ) return SetParametersResult(successful=True) def _apply_descriptor_and_set( self, parameter: Parameter[Any], descriptor: Optional[ParameterDescriptor] = None, check_read_only: bool = True ) -> SetParametersResult: """Apply parameter descriptor and set parameter if successful.""" result = self._apply_descriptor(parameter, descriptor, check_read_only) if result.successful: self._parameters[parameter.name] = parameter return result def describe_parameter(self, name: str) -> ParameterDescriptor: """ Get the parameter descriptor of a given parameter. :param name: Fully-qualified name of the parameter, including its namespace. :return: ParameterDescriptor corresponding to the parameter, or default ParameterDescriptor if parameter had not been declared before and undeclared parameters are allowed. :raises: ParameterNotDeclaredException if parameter had not been declared before and undeclared parameters are not allowed. """ try: return self._descriptors[name] except KeyError: if self._allow_undeclared_parameters: return ParameterDescriptor() else: raise ParameterNotDeclaredException(name) def describe_parameters(self, names: List[str]) -> List[ParameterDescriptor]: """ Get the parameter descriptors of a given list of parameters. :param name: List of fully-qualified names of the parameters to describe. :return: List of ParameterDescriptors corresponding to the given parameters. Default ParameterDescriptors shall be returned for parameters that had not been declared before if undeclared parameters are allowed. :raises: ParameterNotDeclaredException if at least one parameter had not been declared before and undeclared parameters are not allowed. """ parameter_descriptors = [] for name in names: parameter_descriptors.append(self.describe_parameter(name)) return parameter_descriptors def set_descriptor( self, name: str, descriptor: ParameterDescriptor, alternative_value: Optional[ParameterValue] = None ) -> ParameterValue: """ Set a new descriptor for a given parameter. The name in the descriptor is ignored and set to ``name``. :param name: Fully-qualified name of the parameter to set the descriptor to. :param descriptor: New descriptor to apply to the parameter. :param alternative_value: Value to set to the parameter if the existing value does not comply with the new descriptor. :return: ParameterValue for the given parameter name after applying the new descriptor. :raises: ParameterNotDeclaredException if parameter had not been declared before and undeclared parameters are not allowed. :raises: ParameterImmutableException if the parameter exists and is read-only. :raises: ParameterValueException if neither the existing value nor the alternative value complies with the provided descriptor. """ if not self.has_parameter(name): if not self._allow_undeclared_parameters: raise ParameterNotDeclaredException(name) else: return self.get_parameter(name).get_parameter_value() if self.describe_parameter(name).read_only: raise ParameterImmutableException(name) current_parameter = self.get_parameter(name) if alternative_value is None: alternative_parameter = current_parameter else: alternative_parameter = Parameter.from_parameter_msg( ParameterMsg(name=name, value=alternative_value)) # First try keeping the parameter, then try the alternative one. # Don't check for read-only since we are applying a new descriptor now. if not self._apply_descriptor_and_set(current_parameter, descriptor, False).successful: alternative_set_result = ( self._apply_descriptor_and_set(alternative_parameter, descriptor, False) ) if not alternative_set_result.successful: raise InvalidParameterValueException( name, alternative_parameter.value, alternative_set_result.reason ) self._descriptors[name] = descriptor return self.get_parameter(name).get_parameter_value() def _validate_topic_or_service_name(self, topic_or_service_name: str, *, is_service: bool = False) -> None: name = self.get_name() namespace = self.get_namespace() validate_node_name(name) validate_namespace(namespace) validate_topic_name(topic_or_service_name, is_service=is_service) expanded_topic_or_service_name = expand_topic_name(topic_or_service_name, name, namespace) validate_full_topic_name(expanded_topic_or_service_name, is_service=is_service) def _validate_qos_or_depth_parameter(self, qos_or_depth: Union[QoSProfile, int]) -> QoSProfile: if isinstance(qos_or_depth, QoSProfile): return qos_or_depth elif isinstance(qos_or_depth, int): if qos_or_depth < 0: raise ValueError('history depth must be greater than or equal to zero') return QoSProfile(depth=qos_or_depth) else: raise TypeError( 'Expected QoSProfile or int, but received {!r}'.format(type(qos_or_depth))) def add_waitable(self, waitable: Waitable[Any]) -> None: """ Add a class that is capable of adding things to the wait set. :param waitable: An instance of a waitable that the node will add to the waitset. """ self.__waitables.append(waitable) self._wake_executor() def remove_waitable(self, waitable: Waitable[Any]) -> None: """ Remove a Waitable that was previously added to the node. :param waitable: The Waitable to remove. """ self.__waitables.remove(waitable) self._wake_executor() def resolve_topic_name(self, topic: str, *, only_expand: bool = False) -> str: """ Return a topic name expanded and remapped. :param topic: Topic name to be expanded and remapped. :param only_expand: If ``True``, remapping rules won't be applied. :return: A fully qualified topic name, the result of applying expansion and remapping to the given ``topic``. """ with self.handle: return _rclpy.rclpy_resolve_name(self.handle, topic, only_expand, False) def resolve_service_name( self, service: str, *, only_expand: bool = False ) -> str: """ Return a service name expanded and remapped. :param service: Service name to be expanded and remapped. :param only_expand: If ``True``, remapping rules won't be applied. :return: A fully qualified service name, the result of applying expansion and remapping to the given ``service``. """ with self.handle: return _rclpy.rclpy_resolve_name(self.handle, service, only_expand, True) def create_publisher( self, msg_type: Type[MsgT], topic: str, qos_profile: Union[QoSProfile, int], *, callback_group: Optional[CallbackGroup] = None, event_callbacks: Optional[PublisherEventCallbacks] = None, qos_overriding_options: Optional[QoSOverridingOptions] = None, publisher_class: Type[Publisher[MsgT]] = Publisher, ) -> Publisher[MsgT]: """ Create a new publisher. :param msg_type: The type of ROS messages the publisher will publish. :param topic: The name of the topic the publisher will publish to. :param qos_profile: A QoSProfile or a history depth to apply to the publisher. In the case that a history depth is provided, the QoS history is set to KEEP_LAST, the QoS history depth is set to the value of the parameter, and all other QoS settings are set to their default values. :param callback_group: The callback group for the publisher's event handlers. If ``None``, then the default callback group for the node is used. :param event_callbacks: User-defined callbacks for middleware events. :return: The new publisher. """ qos_profile = self._validate_qos_or_depth_parameter(qos_profile) callback_group = callback_group or self.default_callback_group failed = False try: final_topic = self.resolve_topic_name(topic) except RuntimeError: # if it's name validation error, raise a more appropriate exception. try: self._validate_topic_or_service_name(topic) except InvalidTopicNameException as ex: raise ex from None # else reraise the previous exception raise if qos_overriding_options is None: qos_overriding_options = QoSOverridingOptions([]) _declare_qos_parameters( Publisher, self, final_topic, qos_profile, qos_overriding_options) # this line imports the typesupport for the message module if not already done failed = False check_is_valid_msg_type(msg_type) try: with self.handle: publisher_object = _rclpy.Publisher( self.handle, msg_type, topic, qos_profile.get_c_qos_profile()) except ValueError: failed = True if failed: self._validate_topic_or_service_name(topic) try: publisher = publisher_class( publisher_object, msg_type, topic, qos_profile, event_callbacks=event_callbacks or PublisherEventCallbacks(), callback_group=callback_group) except Exception: publisher_object.destroy_when_not_in_use() raise self._publishers.append(publisher) self._wake_executor() for event_callback in publisher.event_handlers: self.add_waitable(event_callback) return publisher @overload def create_subscription( self, msg_type: Type[MsgT], topic: str, callback: GenericSubscriptionCallback[bytes], qos_profile: Union[QoSProfile, int], *, callback_group: Optional[CallbackGroup] = None, event_callbacks: Optional[SubscriptionEventCallbacks] = None, qos_overriding_options: Optional[QoSOverridingOptions] = None, raw: Literal[True], content_filter_options: Optional[ContentFilterOptions] = None ) -> Subscription[MsgT]: ... @overload def create_subscription( self, msg_type: Type[MsgT], topic: str, callback: GenericSubscriptionCallback[MsgT], qos_profile: Union[QoSProfile, int], *, callback_group: Optional[CallbackGroup] = None, event_callbacks: Optional[SubscriptionEventCallbacks] = None, qos_overriding_options: Optional[QoSOverridingOptions] = None, raw: bool = False, content_filter_options: Optional[ContentFilterOptions] = None ) -> Subscription[MsgT]: ... def create_subscription( self, msg_type: Type[MsgT], topic: str, callback: SubscriptionCallbackUnion[MsgT], qos_profile: Union[QoSProfile, int], *, callback_group: Optional[CallbackGroup] = None, event_callbacks: Optional[SubscriptionEventCallbacks] = None, qos_overriding_options: Optional[QoSOverridingOptions] = None, raw: bool = False, content_filter_options: Optional[ContentFilterOptions] = None ) -> Subscription[MsgT]: """ Create a new subscription. :param msg_type: The type of ROS messages the subscription will subscribe to. :param topic: The name of the topic the subscription will subscribe to. :param callback: A user-defined callback function that is called when a message is received by the subscription. :param qos_profile: A QoSProfile or a history depth to apply to the subscription. In the case that a history depth is provided, the QoS history is set to KEEP_LAST, the QoS history depth is set to the value of the parameter, and all other QoS settings are set to their default values. :param callback_group: The callback group for the subscription. If ``None``, then the default callback group for the node is used. :param event_callbacks: User-defined callbacks for middleware events. :param raw: If ``True``, then received messages will be stored in raw binary representation. :param content_filter_options: The filter expression and parameters for content filtering. """ qos_profile = self._validate_qos_or_depth_parameter(qos_profile) callback_group = callback_group or self.default_callback_group try: final_topic = self.resolve_topic_name(topic) except RuntimeError: # if it's name validation error, raise a more appropriate exception. try: self._validate_topic_or_service_name(topic) except InvalidTopicNameException as ex: raise ex from None # else reraise the previous exception raise if qos_overriding_options is None: qos_overriding_options = QoSOverridingOptions([]) _declare_qos_parameters( Subscription, self, final_topic, qos_profile, qos_overriding_options) # this line imports the typesupport for the message module if not already done failed = False check_is_valid_msg_type(msg_type) try: with self.handle: subscription_object = _rclpy.Subscription( self.handle, msg_type, topic, qos_profile.get_c_qos_profile(), content_filter_options) except ValueError: failed = True if failed: self._validate_topic_or_service_name(topic) try: subscription = Subscription( subscription_object, msg_type, topic, callback, callback_group, qos_profile, raw, event_callbacks=event_callbacks or SubscriptionEventCallbacks()) except Exception: subscription_object.destroy_when_not_in_use() raise callback_group.add_entity(subscription) self._subscriptions.append(subscription) self._wake_executor() for event_handler in subscription.event_handlers: self.add_waitable(event_handler) return subscription def create_client( self, srv_type: Type[Srv], srv_name: str, *, qos_profile: QoSProfile = qos_profile_services_default, callback_group: Optional[CallbackGroup] = None ) -> Client[SrvRequestT, SrvResponseT]: """ Create a new service client. :param srv_type: The service type. :param srv_name: The name of the service. :param qos_profile: The quality of service profile to apply the service client. :param callback_group: The callback group for the service client. If ``None``, then the default callback group for the node is used. """ if callback_group is None: callback_group = self.default_callback_group check_is_valid_srv_type(srv_type) failed = False try: with self.handle: client_impl: '_rclpy.Client[SrvRequestT, SrvResponseT]' = _rclpy.Client( self.handle, srv_type, srv_name, qos_profile.get_c_qos_profile()) except ValueError: failed = True if failed: self._validate_topic_or_service_name(srv_name, is_service=True) client: Client[SrvRequestT, SrvResponseT] = Client( self.context, client_impl, srv_type, srv_name, qos_profile, callback_group) callback_group.add_entity(client) self._clients.append(client) self._wake_executor() return client def create_service( self, srv_type: Type[Srv], srv_name: str, callback: Callable[[SrvRequestT, SrvResponseT], SrvResponseT], *, qos_profile: QoSProfile = qos_profile_services_default, callback_group: Optional[CallbackGroup] = None ) -> Service[SrvRequestT, SrvResponseT]: """ Create a new service server. :param srv_type: The service type. :param srv_name: The name of the service. :param callback: A user-defined callback function that is called when a service request received by the server. :param qos_profile: The quality of service profile to apply the service server. :param callback_group: The callback group for the service server. If ``None``, then the default callback group for the node is used. """ if callback_group is None: callback_group = self.default_callback_group check_is_valid_srv_type(srv_type) failed = False try: with self.handle: service_impl: '_rclpy.Service[SrvRequestT, SrvResponseT]' = _rclpy.Service( self.handle, srv_type, srv_name, qos_profile.get_c_qos_profile()) except ValueError: failed = True if failed: self._validate_topic_or_service_name(srv_name, is_service=True) service = Service( service_impl, srv_type, srv_name, callback, callback_group, qos_profile) callback_group.add_entity(service) self._services.append(service) self._wake_executor() return service def create_timer( self, timer_period_sec: float, callback: Optional[TimerCallbackType], callback_group: Optional[CallbackGroup] = None, clock: Optional[Clock] = None, autostart: bool = True, ) -> Timer: """ Create a new timer. If autostart is ``True`` (the default), the timer will be started and every ``timer_period_sec`` number of seconds the provided callback function will be called. If autostart is ``False``, the timer will be created but not started; it can then be started by calling ``reset()`` on the timer object. :param timer_period_sec: The period (in seconds) of the timer. :param callback: A user-defined callback function that is called when the timer expires. :param callback_group: The callback group for the timer. If ``None``, then the default callback group for the node is used. :param clock: The clock which the timer gets time from. :param autostart: Whether to automatically start the timer after creation; defaults to ``True``. """ timer_period_nsec = int(float(timer_period_sec) * S_TO_NS) if callback_group is None: callback_group = self.default_callback_group if clock is None: clock = self._clock timer = Timer( callback, callback_group, timer_period_nsec, clock, context=self.context, autostart=autostart) callback_group.add_entity(timer) self._timers.append(timer) self._wake_executor() return timer def create_guard_condition( self, callback: GuardConditionCallbackType, callback_group: Optional[CallbackGroup] = None ) -> GuardCondition: """ Create a new guard condition. .. warning:: Users should call :meth:`.Node.destroy_guard_condition` to destroy the GuardCondition object. """ if callback_group is None: callback_group = self.default_callback_group guard = GuardCondition(callback, callback_group, context=self.context) callback_group.add_entity(guard) self._guards.append(guard) self._wake_executor() return guard def create_rate( self, frequency: float, clock: Optional[Clock] = None, ) -> Rate: """ Create a Rate object. .. warning:: Users should call :meth:`.Node.destroy_rate` to destroy the Rate object. :param frequency: The frequency the Rate runs at (Hz). :param clock: The clock the Rate gets time from. """ if frequency <= 0: raise ValueError('frequency must be > 0') # Create a timer and give it to the rate object period = 1.0 / frequency # Rate will set its own callback callback = None # Rates get their own group so timing is not messed up by other callbacks group = self._rate_group timer = self.create_timer(period, callback, group, clock) return Rate(timer, context=self.context) def destroy_publisher(self, publisher: Publisher[Any]) -> bool: """ Destroy a publisher created by the node. :return: ``True`` if successful, ``False`` otherwise. """ if publisher in self._publishers: self._publishers.remove(publisher) for event_handler in publisher.event_handlers: self.__waitables.remove(event_handler) try: publisher.destroy() except InvalidHandle: return False self._wake_executor() return True return False def destroy_subscription(self, subscription: Subscription[Any]) -> bool: """ Destroy a subscription created by the node. :return: ``True`` if successful, ``False`` otherwise. """ if subscription in self._subscriptions: self._subscriptions.remove(subscription) for event_handler in subscription.event_handlers: self.__waitables.remove(event_handler) try: subscription.destroy() except InvalidHandle: return False self._wake_executor() return True return False def destroy_client(self, client: Client[Any, Any]) -> bool: """ Destroy a service client created by the node. :return: ``True`` if successful, ``False`` otherwise. """ if client in self._clients: self._clients.remove(client) try: client.destroy() except InvalidHandle: return False self._wake_executor() return True return False def destroy_service(self, service: Service[Any, Any]) -> bool: """ Destroy a service server created by the node. :return: ``True`` if successful, ``False`` otherwise. """ if service in self._services: self._services.remove(service) try: service.destroy() except InvalidHandle: return False self._wake_executor() return True return False def destroy_timer(self, timer: Timer) -> bool: """ Destroy a timer created by the node. :return: ``True`` if successful, ``False`` otherwise. """ if timer in self._timers: self._timers.remove(timer) try: timer.destroy() except InvalidHandle: return False self._wake_executor() return True return False def destroy_guard_condition(self, guard: GuardCondition) -> bool: """ Destroy a guard condition created by the node. :return: ``True`` if successful, ``False`` otherwise. """ if guard in self._guards: self._guards.remove(guard) try: guard.destroy() except InvalidHandle: return False self._wake_executor() return True return False def destroy_rate(self, rate: Rate) -> bool: """ Destroy a Rate object created by the node. :return: ``True`` if successful, ``False`` otherwise. """ success = self.destroy_timer(rate._timer) rate.destroy() return success def destroy_node(self) -> None: """ Destroy the node. Frees resources used by the node, including any entities created by the following methods: * :func:`create_publisher` * :func:`create_subscription` * :func:`create_client` * :func:`create_service` * :func:`create_timer` * :func:`create_guard_condition` """ self._context.untrack_node(self) # Drop extra reference to parameter event publisher. # It will be destroyed with other publishers below. self._parameter_event_publisher = None # Destroy dependent items eagerly to work around a possible hang # https://github.com/ros2/build_cop/issues/248 while self._publishers: self.destroy_publisher(self._publishers[0]) while self._subscriptions: self.destroy_subscription(self._subscriptions[0]) while self._clients: self.destroy_client(self._clients[0]) while self._services: self.destroy_service(self._services[0]) while self._timers: self.destroy_timer(self._timers[0]) while self._guards: self.destroy_guard_condition(self._guards[0]) self._type_description_service.destroy() self.__node.destroy_when_not_in_use() self._wake_executor() def get_publisher_names_and_types_by_node( self, node_name: str, node_namespace: str, no_demangle: bool = False ) -> List[Tuple[str, List[str]]]: """ Get a list of discovered topics for publishers of a remote node. :param node_name: Name of a remote node to get publishers for. :param node_namespace: Namespace of the remote node. :param no_demangle: If ``True``, then topic names and types returned will not be demangled. :return: List of tuples. The first element of each tuple is the topic name and the second element is a list of topic types. :raise NodeNameNonExistentError: If the node wasn't found. :raise RuntimeError: Unexpected failure. """ with self.handle: return _rclpy.rclpy_get_publisher_names_and_types_by_node( self.handle, no_demangle, node_name, node_namespace) def get_subscriber_names_and_types_by_node( self, node_name: str, node_namespace: str, no_demangle: bool = False ) -> List[Tuple[str, List[str]]]: """ Get a list of discovered topics for subscriptions of a remote node. :param node_name: Name of a remote node to get subscriptions for. :param node_namespace: Namespace of the remote node. :param no_demangle: If ``True``, then topic names and types returned will not be demangled. :return: List of tuples. The first element of each tuple is the topic name and the second element is a list of topic types. :raise NodeNameNonExistentError: If the node wasn't found. :raise RuntimeError: Unexpected failure. """ with self.handle: return _rclpy.rclpy_get_subscriber_names_and_types_by_node( self.handle, no_demangle, node_name, node_namespace) def get_service_names_and_types_by_node( self, node_name: str, node_namespace: str ) -> List[Tuple[str, List[str]]]: """ Get a list of discovered service servers for a remote node. :param node_name: Name of a remote node to get services for. :param node_namespace: Namespace of the remote node. :return: List of tuples. The first element of each tuple is the service server name and the second element is a list of service types. :raise NodeNameNonExistentError: If the node wasn't found. :raise RuntimeError: Unexpected failure. """ with self.handle: return _rclpy.rclpy_get_service_names_and_types_by_node( self.handle, node_name, node_namespace) def get_client_names_and_types_by_node( self, node_name: str, node_namespace: str ) -> List[Tuple[str, List[str]]]: """ Get a list of discovered service clients for a remote node. :param node_name: Name of a remote node to get service clients for. :param node_namespace: Namespace of the remote node. :return: List of tuples. The first element of each tuple is the service client name and the second element is a list of service client types. :raise NodeNameNonExistentError: If the node wasn't found. :raise RuntimeError: Unexpected failure. """ with self.handle: return _rclpy.rclpy_get_client_names_and_types_by_node( self.handle, node_name, node_namespace) def get_topic_names_and_types(self, no_demangle: bool = False) -> List[Tuple[str, List[str]]]: """ Get a list of discovered topic names and types. :param no_demangle: If ``True``, then topic names and types returned will not be demangled. :return: List of tuples. The first element of each tuple is the topic name and the second element is a list of topic types. """ with self.handle: return _rclpy.rclpy_get_topic_names_and_types(self.handle, no_demangle) def get_service_names_and_types(self) -> List[Tuple[str, List[str]]]: """ Get a list of discovered service names and types. :return: List of tuples. The first element of each tuple is the service name and the second element is a list of service types. """ with self.handle: return _rclpy.rclpy_get_service_names_and_types(self.handle) def get_node_names(self) -> List[str]: """ Get a list of names for discovered nodes. :return: List of node names. """ with self.handle: names_ns = self.handle.get_node_names_and_namespaces() return [n[0] for n in names_ns] def get_fully_qualified_node_names(self) -> List[str]: """ Get a list of fully qualified names for discovered nodes. Similar to ``get_node_names_namespaces()``, but concatenates the names and namespaces. :return: List of fully qualified node names. """ names_and_namespaces = self.get_node_names_and_namespaces() return [ ns + ('' if ns.endswith('/') else '/') + name for name, ns in names_and_namespaces ] def get_node_names_and_namespaces(self) -> List[Tuple[str, str]]: """ Get a list of names and namespaces for discovered nodes. :return: List of tuples containing two strings: the node name and node namespace. """ with self.handle: return self.handle.get_node_names_and_namespaces() def get_node_names_and_namespaces_with_enclaves(self) -> List[Tuple[str, str, str]]: """ Get a list of names, namespaces and enclaves for discovered nodes. :return: List of tuples containing three strings: the node name, node namespace and enclave. """ with self.handle: return self.handle.get_node_names_and_namespaces_with_enclaves() def get_fully_qualified_name(self) -> str: """ Get the node's fully qualified name. :return: Fully qualified node name. """ with self.handle: return self.handle.get_fully_qualified_name() def _count_publishers_or_subscribers(self, topic_name: str, func: Callable[[str], int]) -> int: fq_topic_name = expand_topic_name(topic_name, self.get_name(), self.get_namespace()) validate_full_topic_name(fq_topic_name) with self.handle: return func(fq_topic_name) def count_publishers(self, topic_name: str) -> int: """ Return the number of publishers on a given topic. ``topic_name`` may be a relative, private, or fully qualified topic name. A relative or private topic is expanded using this node's namespace and name. The queried topic name is not remapped. :param topic_name: The topic name on which to count the number of publishers. :return: The number of publishers on the topic. """ with self.handle: return self._count_publishers_or_subscribers( topic_name, self.handle.get_count_publishers) def count_subscribers(self, topic_name: str) -> int: """ Return the number of subscribers on a given topic. ``topic_name`` may be a relative, private, or fully qualified topic name. A relative or private topic is expanded using this node's namespace and name. The queried topic name is not remapped. :param topic_name: The topic name on which to count the number of subscribers. :return: The number of subscribers on the topic. """ with self.handle: return self._count_publishers_or_subscribers( topic_name, self.handle.get_count_subscribers) def _count_clients_or_servers(self, service_name: str, func: Callable[[str], int]) -> int: fq_service_name = expand_topic_name(service_name, self.get_name(), self.get_namespace()) validate_full_topic_name(fq_service_name, is_service=True) with self.handle: return func(fq_service_name) def count_clients(self, service_name: str) -> int: """ Return the number of clients on a given service. `service_name` may be a relative, private, or fully qualified service name. A relative or private service is expanded using this node's namespace and name. The queried service name is not remapped. :param service_name: the service_name on which to count the number of clients. :return: the number of clients on the service. """ with self.handle: return self._count_clients_or_servers( service_name, self.handle.get_count_clients) def count_services(self, service_name: str) -> int: """ Return the number of servers on a given service. `service_name` may be a relative, private, or fully qualified service name. A relative or private service is expanded using this node's namespace and name. The queried service name is not remapped. :param service_name: the service_name on which to count the number of clients. :return: the number of servers on the service. """ with self.handle: return self._count_clients_or_servers( service_name, self.handle.get_count_services) def _get_info_by_topic( self, topic_name: str, no_mangle: bool, func: Callable[[_rclpy.Node, str, bool], List['_rclpy._TopicEndpointInfoDict']] ) -> List[TopicEndpointInfo]: with self.handle: if no_mangle: fq_topic_name = topic_name else: fq_topic_name = expand_topic_name( topic_name, self.get_name(), self.get_namespace()) validate_full_topic_name(fq_topic_name) fq_topic_name = _rclpy.rclpy_remap_topic_name(self.handle, fq_topic_name) info_dicts = func(self.handle, fq_topic_name, no_mangle) infos = [TopicEndpointInfo(**x) for x in info_dicts] return infos def get_publishers_info_by_topic( self, topic_name: str, no_mangle: bool = False ) -> List[TopicEndpointInfo]: """ Return a list of publishers on a given topic. The returned parameter is a list of TopicEndpointInfo objects, where each will contain the node name, node namespace, topic type, topic endpoint's GID, and its QoS profile. When the ``no_mangle`` parameter is ``True``, the provided ``topic_name`` should be a valid topic name for the middleware (useful when combining ROS with native middleware (e.g. DDS) apps). When the ``no_mangle`` parameter is ``False``, the provided ``topic_name`` should follow ROS topic name conventions. ``topic_name`` may be a relative, private, or fully qualified topic name. A relative or private topic will be expanded using this node's namespace and name. The queried ``topic_name`` is not remapped. :param topic_name: The topic_name on which to find the publishers. :param no_mangle: If ``True``, ``topic_name`` needs to be a valid middleware topic name, otherwise it should be a valid ROS topic name. Defaults to ``False``. :return: a list of TopicEndpointInfo for all the publishers on this topic. """ return self._get_info_by_topic( topic_name, no_mangle, _rclpy.rclpy_get_publishers_info_by_topic) def get_subscriptions_info_by_topic( self, topic_name: str, no_mangle: bool = False ) -> List[TopicEndpointInfo]: """ Return a list of subscriptions on a given topic. The returned parameter is a list of TopicEndpointInfo objects, where each will contain the node name, node namespace, topic type, topic endpoint's GID, and its QoS profile. When the ``no_mangle`` parameter is ``True``, the provided ``topic_name`` should be a valid topic name for the middleware (useful when combining ROS with native middleware (e.g. DDS) apps). When the ``no_mangle`` parameter is ``False``, the provided ``topic_name`` should follow ROS topic name conventions. ``topic_name`` may be a relative, private, or fully qualified topic name. A relative or private topic will be expanded using this node's namespace and name. The queried ``topic_name`` is not remapped. :param topic_name: The topic_name on which to find the subscriptions. :param no_mangle: If ``True``, `topic_name` needs to be a valid middleware topic name, otherwise it should be a valid ROS topic name. Defaults to ``False``. :return: A list of TopicEndpointInfo for all the subscriptions on this topic. """ return self._get_info_by_topic( topic_name, no_mangle, _rclpy.rclpy_get_subscriptions_info_by_topic) def _get_info_by_service( self, service_name: str, no_mangle: bool, func: Callable[[_rclpy.Node, str, bool], List['_rclpy.ServiceEndpointInfoDict']] ) -> List[ServiceEndpointInfo]: with self.handle: if no_mangle: fq_topic_name = service_name else: fq_topic_name = expand_topic_name( service_name, self.get_name(), self.get_namespace()) validate_full_topic_name(fq_topic_name) fq_topic_name = _rclpy.rclpy_remap_topic_name(self.handle, fq_topic_name) info_dicts = func(self.handle, fq_topic_name, no_mangle) infos = [ServiceEndpointInfo(**x) for x in info_dicts] return infos def get_clients_info_by_service( self, service_name: str, no_mangle: bool = False ) -> List[ServiceEndpointInfo]: """ Return a list of clients on a given service. The returned parameter is a list of ServiceEndpointInfo objects, where each will contain the node name, node namespace, service type, service endpoint's GIDs, and its QoS profiles. When the ``no_mangle`` parameter is ``True``, the provided ``service_name`` should be a valid service name for the middleware (useful when combining ROS with native middleware apps). When the ``no_mangle`` parameter is ``False``,the provided ``service_name`` should follow ROS service name conventions. In DDS-based RMWs, services are implemented as topics with mangled names (e.g., `rq/my_serviceRequest` and `rp/my_serviceReply`), so `no_mangle = true` is not supported and will result in an error. Use `get_subscriptions_info_by_topic` or get_publishers_info_by_topic` for unmangled topic queries in such cases. Other RMWs (e.g., Zenoh) may support `no_mangle = true` if they natively handle services without topic-based ``service_name`` may be a relative, private, or fully qualified service name. A relative or private service will be expanded using this node's namespace and name. The queried ``service_name`` is not remapped. :param service_name: The service_name on which to find the clients. :param no_mangle: If ``True``, `service_name` needs to be a valid middleware service name, otherwise it should be a valid ROS service name. Defaults to ``False``. :return: A list of ServiceEndpointInfo for all the clients on this service. """ return self._get_info_by_service( service_name, no_mangle, _rclpy.rclpy_get_clients_info_by_service) def get_servers_info_by_service( self, service_name: str, no_mangle: bool = False ) -> List[ServiceEndpointInfo]: """ Return a list of servers on a given service. The returned parameter is a list of ServiceEndpointInfo objects, where each will contain the node name, node namespace, service type, service endpoint's GIDs, and its QoS profiles. When the ``no_mangle`` parameter is ``True``, the provided ``service_name`` should be a valid service name for the middleware (useful when combining ROS with native middleware apps). When the ``no_mangle`` parameter is ``False``,the provided ``service_name`` should follow ROS service name conventions. In DDS-based RMWs, services are implemented as topics with mangled names (e.g., `rq/my_serviceRequest` and `rp/my_serviceReply`), so `no_mangle = true` is not supported and will result in an error. Use `get_subscriptions_info_by_topic` or get_publishers_info_by_topic` for unmangled topic queries in such cases. Other RMWs (e.g., Zenoh) may support `no_mangle = true` if they natively handle services without topic-based ``service_name`` may be a relative, private, or fully qualified service name. A relative or private service will be expanded using this node's namespace and name. The queried ``service_name`` is not remapped. :param service_name: The service_name on which to find the servers. :param no_mangle: If ``True``, `service_name` needs to be a valid middleware service name, otherwise it should be a valid ROS service name. Defaults to ``False``. :return: A list of ServiceEndpointInfo for all the servers on this service. """ return self._get_info_by_service( service_name, no_mangle, _rclpy.rclpy_get_servers_info_by_service) def wait_for_node( self, fully_qualified_node_name: str, timeout: float ) -> bool: """ Wait until node name is present in the system or timeout. The node name should be the full name with namespace. :param node_name: Fully qualified name of the node to wait for. :param timeout: Seconds to wait for the node to be present. If negative, the function won't timeout. :return: ``True`` if the node was found, ``False`` if timeout. """ if not fully_qualified_node_name.startswith('/'): fully_qualified_node_name = f'/{fully_qualified_node_name}' start = time.time() flag = False # TODO refactor this implementation when we can react to guard condition events, or replace # it entirely with an implementation in rcl. see https://github.com/ros2/rclpy/issues/929 while time.time() - start < timeout and not flag: fully_qualified_node_names = self.get_fully_qualified_node_names() flag = fully_qualified_node_name in fully_qualified_node_names time.sleep(0.1) return flag def __enter__(self) -> 'Node': return self def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: self.destroy_node()
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pathlib import platform import time from typing import Any from typing import cast from typing import List from typing import Optional from typing import Tuple from typing import TYPE_CHECKING from typing import Union import unittest from unittest.mock import Mock import warnings import pytest from rcl_interfaces.msg import FloatingPointRange from rcl_interfaces.msg import IntegerRange from rcl_interfaces.msg import ListParametersResult from rcl_interfaces.msg import ParameterDescriptor from rcl_interfaces.msg import ParameterType from rcl_interfaces.msg import ParameterValue from rcl_interfaces.msg import SetParametersResult from rcl_interfaces.srv import GetParameters import rclpy from rclpy.clock_type import ClockType import rclpy.context from rclpy.duration import Duration from rclpy.endpoint_info import EndpointTypeEnum from rclpy.exceptions import InvalidParameterException from rclpy.exceptions import InvalidParameterTypeException from rclpy.exceptions import InvalidParameterValueException from rclpy.exceptions import InvalidServiceNameException from rclpy.exceptions import InvalidTopicNameException from rclpy.exceptions import ParameterAlreadyDeclaredException from rclpy.exceptions import ParameterImmutableException from rclpy.exceptions import ParameterNotDeclaredException from rclpy.exceptions import ParameterUninitializedException from rclpy.executors import SingleThreadedExecutor from rclpy.impl.logging_severity import LoggingSeverity from rclpy.parameter import Parameter from rclpy.qos import qos_profile_sensor_data from rclpy.qos import QoSDurabilityPolicy from rclpy.qos import QoSHistoryPolicy from rclpy.qos import QoSLivelinessPolicy from rclpy.qos import QoSProfile from rclpy.qos import QoSReliabilityPolicy from rclpy.time_source import USE_SIM_TIME_NAME from rclpy.type_description_service import START_TYPE_DESCRIPTION_SERVICE_PARAM from rclpy.utilities import get_rmw_implementation_identifier from test_msgs.msg import BasicTypes from test_msgs.srv import Empty TEST_NODE = 'my_node' TEST_NAMESPACE = '/my_ns' TEST_RESOURCES_DIR = pathlib.Path(__file__).resolve().parent / 'resources' / 'test_node' class TestNodeAllowUndeclaredParameters(unittest.TestCase): if TYPE_CHECKING: context: rclpy.context.Context @classmethod def setUpClass(cls) -> None: cls.context = rclpy.context.Context() rclpy.init(context=cls.context) @classmethod def tearDownClass(cls) -> None: rclpy.shutdown(context=cls.context) def setUp(self) -> None: self.node = rclpy.create_node( TEST_NODE, namespace=TEST_NAMESPACE, context=self.context, allow_undeclared_parameters=True) def tearDown(self) -> None: self.node.destroy_node() def test_accessors(self) -> None: self.assertIsNotNone(self.node.handle) with self.assertRaises(AttributeError): self.node.handle = 'garbage' # type: ignore[assignment] self.assertEqual(self.node.get_name(), TEST_NODE) self.assertEqual(self.node.get_namespace(), TEST_NAMESPACE) self.assertEqual(self.node.get_clock().clock_type, ClockType.ROS_TIME) def test_create_publisher(self) -> None: self.node.create_publisher(BasicTypes, 'chatter', 1) self.node.create_publisher(BasicTypes, 'chatter', qos_profile_sensor_data) with self.assertRaisesRegex(InvalidTopicNameException, 'must not contain characters'): self.node.create_publisher(BasicTypes, 'chatter?', 1) with self.assertRaisesRegex(InvalidTopicNameException, 'must not start with a number'): self.node.create_publisher(BasicTypes, '/chatter/42_is_the_answer', 1) with self.assertRaisesRegex(ValueError, 'unknown substitution'): self.node.create_publisher(BasicTypes, 'chatter/{bad_sub}', 1) with self.assertRaisesRegex(ValueError, 'must be greater than or equal to zero'): self.node.create_publisher(BasicTypes, 'chatter', -1) with self.assertRaisesRegex(TypeError, 'Expected QoSProfile or int'): self.node.create_publisher(BasicTypes, 'chatter', 'foo') # type: ignore[arg-type] def test_create_subscription(self) -> None: self.node.create_subscription(BasicTypes, 'chatter', lambda msg: print(msg), 1) self.node.create_subscription( BasicTypes, 'chatter', lambda msg: print(msg), qos_profile_sensor_data) with self.assertRaisesRegex(InvalidTopicNameException, 'must not contain characters'): self.node.create_subscription(BasicTypes, 'chatter?', lambda msg: print(msg), 1) with self.assertRaisesRegex(InvalidTopicNameException, 'must not start with a number'): self.node.create_subscription(BasicTypes, '/chatter/42ish', lambda msg: print(msg), 1) with self.assertRaisesRegex(ValueError, 'unknown substitution'): self.node.create_subscription(BasicTypes, 'foo/{bad_sub}', lambda msg: print(msg), 1) with self.assertRaisesRegex(ValueError, 'must be greater than or equal to zero'): self.node.create_subscription(BasicTypes, 'chatter', lambda msg: print(msg), -1) with self.assertRaisesRegex(TypeError, 'Expected QoSProfile or int'): self.node.create_subscription(BasicTypes, 'chatter', lambda msg: print(msg), 'foo') # type: ignore[call-overload] def raw_subscription_callback(self, msg: bytes) -> None: print('Raw subscription callback: %s length %d' % (msg.decode(), len(msg))) self.raw_subscription_msg: Optional[bytes] = msg def test_create_raw_subscription(self) -> None: executor = SingleThreadedExecutor(context=self.context) executor.add_node(self.node) basic_types_pub = self.node.create_publisher(BasicTypes, 'raw_subscription_test', 1) self.raw_subscription_msg = None # None=No result yet self.node.create_subscription( BasicTypes, 'raw_subscription_test', self.raw_subscription_callback, 1, raw=True ) basic_types_msg = BasicTypes() cycle_count = 0 while cycle_count < 5 and self.raw_subscription_msg is None: basic_types_pub.publish(basic_types_msg) cycle_count += 1 executor.spin_once(timeout_sec=1) self.assertIsNotNone(self.raw_subscription_msg, 'raw subscribe timed out') self.assertIs(type(self.raw_subscription_msg), bytes, 'raw subscribe did not return bytes') # The length might be implementation dependant, but shouldn't be zero # There may be a canonical serialization in the future at which point this can be updated self.assertNotEqual(len(cast(bytes, self.raw_subscription_msg)), 0, 'raw subscribe invalid length') executor.shutdown() def dummy_cb(self, msg: BasicTypes) -> None: pass @unittest.skipIf( get_rmw_implementation_identifier() == 'rmw_connextdds' and platform.system() == 'Windows', reason='Source timestamp not implemented for Connext on Windows') def test_take(self) -> None: basic_types_pub = self.node.create_publisher(BasicTypes, 'take_test', 1) sub = self.node.create_subscription( BasicTypes, 'take_test', self.dummy_cb, 1) basic_types_msg = BasicTypes() basic_types_pub.publish(basic_types_msg) for i in range(5): with sub.handle: result = sub.handle.take_message(sub.msg_type, False) if result is not None: msg, info = result self.assertNotEqual(0, info['source_timestamp']) assert info['publisher_gid'] is not None self.assertIn('data', info['publisher_gid']) self.assertIsInstance(info['publisher_gid']['data'], (bytes, bytearray)) self.assertGreater(len(info['publisher_gid']['data']), 0) self.assertEqual( get_rmw_implementation_identifier(), info['publisher_gid']['implementation_identifier']) return else: time.sleep(0.2) def test_create_client(self) -> None: self.node.create_client(GetParameters, 'get/parameters') with self.assertRaisesRegex(InvalidServiceNameException, 'must not contain characters'): self.node.create_client(GetParameters, 'get/parameters?') with self.assertRaisesRegex(InvalidServiceNameException, 'must not start with a number'): self.node.create_client(GetParameters, '/get/42parameters') with self.assertRaisesRegex(ValueError, 'unknown substitution'): self.node.create_client(GetParameters, 'foo/{bad_sub}') def test_create_service(self) -> None: self.node.create_service(GetParameters, 'get/parameters', lambda req, res: None) with self.assertRaisesRegex(InvalidServiceNameException, 'must not contain characters'): self.node.create_service(GetParameters, 'get/parameters?', lambda req, res: None) with self.assertRaisesRegex(InvalidServiceNameException, 'must not start with a number'): self.node.create_service(GetParameters, '/get/42parameters', lambda req, res: None) with self.assertRaisesRegex(ValueError, 'unknown substitution'): self.node.create_service(GetParameters, 'foo/{bad_sub}', lambda req, res: None) def test_service_names_and_types(self) -> None: # test that it doesn't raise self.node.get_service_names_and_types() def test_service_names_and_types_by_node(self) -> None: # test that it doesn't raise self.node.get_service_names_and_types_by_node(TEST_NODE, TEST_NAMESPACE) def test_client_names_and_types_by_node(self) -> None: # test that it doesn't raise self.node.get_client_names_and_types_by_node(TEST_NODE, TEST_NAMESPACE) def test_topic_names_and_types(self) -> None: # test that it doesn't raise self.node.get_topic_names_and_types(no_demangle=True) self.node.get_topic_names_and_types(no_demangle=False) def test_node_names(self) -> None: # test that it doesn't raise self.node.get_node_names() def test_node_names_and_namespaces(self) -> None: # test that it doesn't raise self.node.get_node_names_and_namespaces() def test_node_names_and_namespaces_with_enclaves(self) -> None: # test that it doesn't raise self.node.get_node_names_and_namespaces_with_enclaves() def assert_qos_equal(self, expected_qos_profile: QoSProfile, actual_qos_profile: QoSProfile, *, is_publisher: bool) -> None: # Depth and history are skipped because they are not retrieved. self.assertEqual( expected_qos_profile.durability, actual_qos_profile.durability, 'Durability is unequal') self.assertEqual( expected_qos_profile.reliability, actual_qos_profile.reliability, 'Reliability is unequal') if is_publisher: self.assertEqual( expected_qos_profile.lifespan, actual_qos_profile.lifespan, 'lifespan is unequal') self.assertEqual( expected_qos_profile.deadline, actual_qos_profile.deadline, 'Deadline is unequal') self.assertEqual( expected_qos_profile.liveliness, actual_qos_profile.liveliness, 'liveliness is unequal') self.assertEqual( expected_qos_profile.liveliness_lease_duration, actual_qos_profile.liveliness_lease_duration, 'liveliness_lease_duration is unequal') def test_get_publishers_subscriptions_info_by_topic(self) -> None: topic_name = 'test_topic_endpoint_info' fq_topic_name = '{namespace}/{name}'.format(namespace=TEST_NAMESPACE, name=topic_name) # Lists should be empty self.assertFalse(self.node.get_publishers_info_by_topic(fq_topic_name)) self.assertFalse(self.node.get_subscriptions_info_by_topic(fq_topic_name)) # Add a publisher qos_profile = QoSProfile( depth=10, history=QoSHistoryPolicy.KEEP_ALL, deadline=Duration(seconds=1, nanoseconds=12345), lifespan=Duration(seconds=20, nanoseconds=9887665), reliability=QoSReliabilityPolicy.BEST_EFFORT, durability=QoSDurabilityPolicy.TRANSIENT_LOCAL, liveliness_lease_duration=Duration(seconds=5, nanoseconds=23456), liveliness=QoSLivelinessPolicy.MANUAL_BY_TOPIC) self.node.create_publisher(BasicTypes, topic_name, qos_profile) # List should have one item publisher_list = self.node.get_publishers_info_by_topic(fq_topic_name) self.assertEqual(1, len(publisher_list)) # Subscription list should be empty self.assertFalse(self.node.get_subscriptions_info_by_topic(fq_topic_name)) # Verify publisher list has the right data self.assertEqual(self.node.get_name(), publisher_list[0].node_name) self.assertEqual(self.node.get_namespace(), publisher_list[0].node_namespace) self.assertEqual('test_msgs/msg/BasicTypes', publisher_list[0].topic_type) actual_qos_profile = publisher_list[0].qos_profile self.assert_qos_equal(qos_profile, actual_qos_profile, is_publisher=True) # Add a subscription qos_profile2 = QoSProfile( depth=1, history=QoSHistoryPolicy.KEEP_LAST, deadline=Duration(seconds=15, nanoseconds=1678), lifespan=Duration(seconds=29, nanoseconds=2345), reliability=QoSReliabilityPolicy.RELIABLE, durability=QoSDurabilityPolicy.VOLATILE, liveliness_lease_duration=Duration(seconds=5, nanoseconds=23456), liveliness=QoSLivelinessPolicy.AUTOMATIC) self.node.create_subscription(BasicTypes, topic_name, lambda msg: print(msg), qos_profile2) # Both lists should have one item publisher_list = self.node.get_publishers_info_by_topic(fq_topic_name) subscription_list = self.node.get_subscriptions_info_by_topic(fq_topic_name) self.assertEqual(1, len(publisher_list)) self.assertEqual(1, len(subscription_list)) # Verify subscription list has the right data self.assertEqual(self.node.get_name(), publisher_list[0].node_name) self.assertEqual(self.node.get_namespace(), publisher_list[0].node_namespace) self.assertEqual('test_msgs/msg/BasicTypes', publisher_list[0].topic_type) self.assertEqual('test_msgs/msg/BasicTypes', subscription_list[0].topic_type) publisher_qos_profile = publisher_list[0].qos_profile subscription_qos_profile = subscription_list[0].qos_profile self.assert_qos_equal(qos_profile, publisher_qos_profile, is_publisher=True) self.assert_qos_equal(qos_profile2, subscription_qos_profile, is_publisher=False) # Error cases with self.assertRaises(TypeError): self.node.get_subscriptions_info_by_topic(1) # type: ignore[arg-type] self.node.get_publishers_info_by_topic(1) # type: ignore[arg-type] with self.assertRaisesRegex(ValueError, 'is invalid'): self.node.get_subscriptions_info_by_topic('13') self.node.get_publishers_info_by_topic('13') def test_get_clients_servers_info_by_service(self): service_name = 'test_service_endpoint_info' fq_service_name = '{namespace}/{name}'.format(namespace=TEST_NAMESPACE, name=service_name) # Lists should be empty self.assertFalse(self.node.get_clients_info_by_service(fq_service_name)) self.assertFalse(self.node.get_servers_info_by_service(fq_service_name)) # Add a client qos_profile = QoSProfile( depth=10, history=QoSHistoryPolicy.KEEP_ALL, deadline=Duration(seconds=1, nanoseconds=12345), lifespan=Duration(seconds=20, nanoseconds=9887665), reliability=QoSReliabilityPolicy.BEST_EFFORT, durability=QoSDurabilityPolicy.TRANSIENT_LOCAL, liveliness_lease_duration=Duration(seconds=5, nanoseconds=23456), liveliness=QoSLivelinessPolicy.MANUAL_BY_TOPIC) self.node.create_client(Empty, service_name, qos_profile=qos_profile) # List should have at least one item client_list = self.node.get_clients_info_by_service(fq_service_name) self.assertGreaterEqual(len(client_list), 1) # Server list should be empty self.assertFalse(self.node.get_servers_info_by_service(fq_service_name)) # Verify client list has the right data self.assertEqual(self.node.get_name(), client_list[0].node_name) self.assertEqual(self.node.get_namespace(), client_list[0].node_namespace) self.assertEqual('test_msgs/srv/Empty', client_list[0].service_type) self.assertTrue(client_list[0].endpoint_count == 1 or client_list[0].endpoint_count == 2) self.assertEqual(client_list[0].endpoint_type, EndpointTypeEnum.CLIENT) for i in range(client_list[0].endpoint_count): actual_qos_profile = client_list[0].qos_profiles[i] self.assert_qos_equal(qos_profile, actual_qos_profile, is_publisher=False) # Add a server qos_profile2 = QoSProfile( depth=1, history=QoSHistoryPolicy.KEEP_LAST, deadline=Duration(seconds=15, nanoseconds=1678), lifespan=Duration(seconds=29, nanoseconds=2345), reliability=QoSReliabilityPolicy.RELIABLE, durability=QoSDurabilityPolicy.VOLATILE, liveliness_lease_duration=Duration(seconds=5, nanoseconds=23456), liveliness=QoSLivelinessPolicy.AUTOMATIC) self.node.create_service( Empty, service_name, lambda msg: print(msg), qos_profile=qos_profile2 ) # Both lists should have at least one item client_list = self.node.get_clients_info_by_service(fq_service_name) server_list = self.node.get_servers_info_by_service(fq_service_name) self.assertGreaterEqual(len(client_list), 1) self.assertGreaterEqual(len(server_list), 1) # Verify server list has the right data self.assertEqual(self.node.get_name(), server_list[0].node_name) self.assertEqual(self.node.get_namespace(), server_list[0].node_namespace) self.assertEqual('test_msgs/srv/Empty', server_list[0].service_type) self.assertTrue(server_list[0].endpoint_count == 1 or server_list[0].endpoint_count == 2) self.assertEqual(server_list[0].endpoint_type, EndpointTypeEnum.SERVER) for i in range(server_list[0].endpoint_count): actual_qos_profile = server_list[0].qos_profiles[i] self.assert_qos_equal(qos_profile2, actual_qos_profile, is_publisher=False) # Error cases with self.assertRaises(TypeError): self.node.get_clients_info_by_service(1) self.node.get_servers_info_by_service(1) with self.assertRaisesRegex(ValueError, 'is invalid'): self.node.get_clients_info_by_service('13') self.node.get_servers_info_by_service('13') def test_count_publishers_subscribers(self) -> None: short_topic_name = 'chatter' fq_topic_name = '%s/%s' % (TEST_NAMESPACE, short_topic_name) self.assertEqual(0, self.node.count_publishers(fq_topic_name)) self.assertEqual(0, self.node.count_subscribers(fq_topic_name)) short_topic_publisher = self.node.create_publisher(BasicTypes, short_topic_name, 1) self.assertEqual(1, self.node.count_publishers(short_topic_name)) self.assertEqual(1, self.node.count_publishers(fq_topic_name)) self.assertEqual(0, short_topic_publisher.get_subscription_count()) self.node.create_subscription(BasicTypes, short_topic_name, lambda msg: print(msg), 1) self.assertEqual(1, self.node.count_subscribers(short_topic_name)) self.assertEqual(1, self.node.count_subscribers(fq_topic_name)) self.assertEqual(1, short_topic_publisher.get_subscription_count()) self.node.create_subscription(BasicTypes, short_topic_name, lambda msg: print(msg), 1) self.assertEqual(2, self.node.count_subscribers(short_topic_name)) self.assertEqual(2, self.node.count_subscribers(fq_topic_name)) self.assertEqual(2, short_topic_publisher.get_subscription_count()) # error cases with self.assertRaises(TypeError): self.node.count_subscribers(1) # type: ignore[arg-type] with self.assertRaisesRegex(ValueError, 'is invalid'): self.node.count_subscribers('42') with self.assertRaisesRegex(ValueError, 'is invalid'): self.node.count_publishers('42') def test_count_clients_services(self) -> None: short_service_name = 'add_two_ints' fq_service_name = '%s/%s' % (TEST_NAMESPACE, short_service_name) self.assertEqual(0, self.node.count_clients(fq_service_name)) self.assertEqual(0, self.node.count_services(fq_service_name)) self.node.create_client(GetParameters, short_service_name) self.assertEqual(1, self.node.count_clients(short_service_name)) self.assertEqual(1, self.node.count_clients(fq_service_name)) self.assertEqual(0, self.node.count_services(short_service_name)) self.assertEqual(0, self.node.count_services(fq_service_name)) self.node.create_service(GetParameters, short_service_name, lambda req, res: None) self.assertEqual(1, self.node.count_clients(short_service_name)) self.assertEqual(1, self.node.count_clients(fq_service_name)) self.assertEqual(1, self.node.count_services(short_service_name)) self.assertEqual(1, self.node.count_services(fq_service_name)) self.node.create_client(GetParameters, short_service_name) self.assertEqual(2, self.node.count_clients(short_service_name)) self.assertEqual(2, self.node.count_clients(fq_service_name)) self.assertEqual(1, self.node.count_services(short_service_name)) self.assertEqual(1, self.node.count_services(fq_service_name)) self.node.create_service(GetParameters, short_service_name, lambda req, res: None) self.assertEqual(2, self.node.count_clients(short_service_name)) self.assertEqual(2, self.node.count_clients(fq_service_name)) self.assertEqual(2, self.node.count_services(short_service_name)) self.assertEqual(2, self.node.count_services(fq_service_name)) # error cases with self.assertRaises(TypeError): self.node.count_clients(1) # type: ignore[arg-type] with self.assertRaises(TypeError): self.node.count_services(1) # type: ignore[arg-type] with self.assertRaisesRegex(ValueError, 'is invalid'): self.node.count_clients('42') with self.assertRaisesRegex(ValueError, 'is invalid'): self.node.count_services('42') def test_node_logger(self) -> None: node_logger = self.node.get_logger() expected_name = '%s.%s' % (TEST_NAMESPACE.replace('/', '.')[1:], TEST_NODE) self.assertEqual(node_logger.name, expected_name) node_logger.set_level(LoggingSeverity.INFO) node_logger.debug('test') def modify_parameter_callback(self, parameters_list: List[Parameter[Any]] ) -> List[Parameter[Any]]: modified_list = parameters_list.copy() for param in parameters_list: if param.name == 'foo': modified_list.append(Parameter('bar', Parameter.Type.STRING, 'hello')) return modified_list def test_node_set_parameters(self) -> None: results = self.node.set_parameters([ Parameter('foo', Parameter.Type.INTEGER, 42), Parameter('bar', Parameter.Type.STRING, 'hello'), Parameter('baz', Parameter.Type.DOUBLE, 2.41) ]) self.assertTrue(all(isinstance(result, SetParametersResult) for result in results)) self.assertTrue(all(result.successful for result in results)) self.assertEqual(self.node.get_parameter('foo').value, 42) self.assertEqual(self.node.get_parameter('bar').value, 'hello') self.assertEqual(self.node.get_parameter('baz').value, 2.41) self.node.undeclare_parameter('foo') self.node.undeclare_parameter('bar') self.node.undeclare_parameter('baz') # adding a parameter using func: "add_pre_set parameter" callback when # that parameter has not been declared will not throw if undeclared # parameters are allowed self.node.add_pre_set_parameters_callback(self.modify_parameter_callback) results = self.node.set_parameters([ Parameter('foo', Parameter.Type.INTEGER, 42), Parameter('baz', Parameter.Type.DOUBLE, 2.41) ]) self.node.remove_pre_set_parameters_callback(self.modify_parameter_callback) self.assertEqual(2, len(results)) self.assertTrue(all(isinstance(result, SetParametersResult) for result in results)) self.assertTrue(all(result.successful for result in results)) self.assertTrue(self.node.has_parameter('foo')) self.assertTrue(self.node.has_parameter('bar')) self.assertTrue(self.node.has_parameter('baz')) self.assertEqual(self.node.get_parameter('foo').value, 42) self.assertEqual(self.node.get_parameter('bar').value, 'hello') self.assertEqual(self.node.get_parameter('baz').value, 2.41) def test_node_cannot_set_invalid_parameters(self) -> None: with self.assertRaises(TypeError): self.node.set_parameters([42]) # type: ignore[list-item] def test_node_set_parameters_atomically(self) -> None: result = self.node.set_parameters_atomically([ Parameter('foo', Parameter.Type.INTEGER, 42), Parameter('bar', Parameter.Type.STRING, 'hello'), Parameter('baz', Parameter.Type.DOUBLE, 2.41) ]) self.assertEqual(self.node.get_parameter('foo').value, 42) self.assertIsInstance(result, SetParametersResult) self.assertTrue(result.successful) self.node.undeclare_parameter('foo') self.node.undeclare_parameter('bar') self.node.undeclare_parameter('baz') # adding a parameter using func: "add_pre_set parameter" callback, # when that parameter has not been declared will not throw if undeclared # parameters are allowed self.node.add_pre_set_parameters_callback(self.modify_parameter_callback) result = self.node.set_parameters_atomically([ Parameter('foo', Parameter.Type.INTEGER, 42), Parameter('baz', Parameter.Type.DOUBLE, 2.41) ]) self.node.remove_pre_set_parameters_callback(self.modify_parameter_callback) self.assertEqual(True, result.successful) self.assertTrue(self.node.has_parameter('foo')) self.assertTrue(self.node.has_parameter('bar')) self.assertTrue(self.node.has_parameter('baz')) self.assertEqual(self.node.get_parameter('foo').value, 42) self.assertEqual(self.node.get_parameter('bar').value, 'hello') self.assertEqual(self.node.get_parameter('baz').value, 2.41) def test_describe_undeclared_parameter(self) -> None: self.assertFalse(self.node.has_parameter('foo')) descriptor = self.node.describe_parameter('foo') self.assertEqual(descriptor, ParameterDescriptor()) def test_describe_undeclared_parameters(self) -> None: self.assertFalse(self.node.has_parameter('foo')) self.assertFalse(self.node.has_parameter('bar')) # Check list. descriptor_list = self.node.describe_parameters(['foo', 'bar']) self.assertIsInstance(descriptor_list, list) self.assertEqual(len(descriptor_list), 2) self.assertEqual(descriptor_list[0], ParameterDescriptor()) self.assertEqual(descriptor_list[1], ParameterDescriptor()) def test_node_get_parameter(self) -> None: self.node.set_parameters([Parameter('foo', Parameter.Type.INTEGER, 42)]) self.assertIsInstance(self.node.get_parameter('foo'), Parameter) self.assertEqual(self.node.get_parameter('foo').value, 42) def test_node_get_parameter_returns_parameter_not_set(self) -> None: self.assertIsInstance(self.node.get_parameter('unset'), Parameter) self.assertEqual(self.node.get_parameter('unset').type_, Parameter.Type.NOT_SET) def test_node_declare_static_parameter(self) -> None: value = self.node.declare_parameter('an_integer', 5) self.assertEqual(value.value, 5) self.assertFalse( self.node.set_parameters([Parameter('an_integer', value='asd')])[0].successful) self.assertEqual(self.node.get_parameter('an_integer').value, 5) def test_node_undeclared_parameters_are_dynamically_typed(self) -> None: self.assertTrue(self.node.set_parameters([Parameter('my_param', value=5)])[0].successful) self.assertEqual(self.node.get_parameter('my_param').value, 5) self.assertTrue( self.node.set_parameters([Parameter('my_param', value='asd')])[0].successful) self.assertEqual(self.node.get_parameter('my_param').value, 'asd') def test_node_cannot_declare_after_set(self) -> None: self.assertTrue(self.node.set_parameters([Parameter('my_param', value=5)])[0].successful) self.assertEqual(self.node.get_parameter('my_param').value, 5) with pytest.raises(rclpy.exceptions.ParameterAlreadyDeclaredException): self.node.declare_parameter('my_param', 5) def test_node_has_parameter_services(self) -> None: service_names_and_types = self.node.get_service_names_and_types() self.assertIn( ('/my_ns/my_node/describe_parameters', ['rcl_interfaces/srv/DescribeParameters']), service_names_and_types ) self.assertIn( ('/my_ns/my_node/get_parameter_types', ['rcl_interfaces/srv/GetParameterTypes']), service_names_and_types ) self.assertIn( ('/my_ns/my_node/get_parameters', ['rcl_interfaces/srv/GetParameters']), service_names_and_types ) self.assertIn( ('/my_ns/my_node/list_parameters', ['rcl_interfaces/srv/ListParameters']), service_names_and_types ) self.assertIn( ('/my_ns/my_node/set_parameters', ['rcl_interfaces/srv/SetParameters']), service_names_and_types ) self.assertIn( ( '/my_ns/my_node/set_parameters_atomically', ['rcl_interfaces/srv/SetParametersAtomically'] ), service_names_and_types ) class TestExecutor(unittest.TestCase): if TYPE_CHECKING: context: rclpy.context.Context @classmethod def setUpClass(cls) -> None: cls.context = rclpy.context.Context() rclpy.init(context=cls.context) @classmethod def tearDownClass(cls) -> None: rclpy.shutdown(context=cls.context) def setUp(self) -> None: self.node = rclpy.create_node(TEST_NODE, context=self.context) def tearDown(self) -> None: self.node.destroy_node() def test_initially_no_executor(self) -> None: assert self.node.executor is None def test_set_executor_adds_node_to_it(self) -> None: executor = Mock() executor.add_node.return_value = True self.node.executor = executor assert id(executor) == id(self.node.executor) executor.add_node.assert_called_once_with(self.node) def test_set_executor_removes_node_from_old_executor(self) -> None: old_executor = Mock() old_executor.add_node.return_value = True new_executor = Mock() new_executor.add_node.return_value = True self.node.executor = old_executor assert id(old_executor) == id(self.node.executor) self.node.executor = new_executor assert id(new_executor) == id(self.node.executor) old_executor.remove_node.assert_called_once_with(self.node) new_executor.remove_node.assert_not_called() def test_set_executor_clear_executor(self) -> None: executor = Mock() executor.add_node.return_value = True self.node.executor = executor assert id(executor) == id(self.node.executor) self.node.executor = None assert self.node.executor is None class TestNode(unittest.TestCase): if TYPE_CHECKING: context: rclpy.context.Context @classmethod def setUpClass(cls) -> None: cls.context = rclpy.context.Context() rclpy.init(context=cls.context) @classmethod def tearDownClass(cls) -> None: rclpy.shutdown(context=cls.context) def setUp(self) -> None: self.node = rclpy.create_node( TEST_NODE, namespace=TEST_NAMESPACE, context=self.context, parameter_overrides=[ Parameter('initial_foo', Parameter.Type.INTEGER, 4321), Parameter('initial_bar', Parameter.Type.STRING, 'init_param'), Parameter('initial_baz', Parameter.Type.DOUBLE, 3.14), Parameter('initial_decl_with_type', Parameter.Type.DOUBLE, 3.14), Parameter('initial_decl_wrong_type', Parameter.Type.DOUBLE, 3.14), Parameter('namespace.k_initial_foo', Parameter.Type.INTEGER, 4321), Parameter('namespace.k_initial_bar', Parameter.Type.STRING, 'init_param'), Parameter('namespace.k_initial_baz', Parameter.Type.DOUBLE, 3.14), Parameter('namespace.k_initial_decl_with_type', Parameter.Type.DOUBLE, 3.14), Parameter('namespace.k_initial_decl_wrong_type', Parameter.Type.DOUBLE, 3.14), Parameter('namespace.k_initial_foo', Parameter.Type.INTEGER, 4321) ], cli_args=[ '--ros-args', '-p', 'initial_fizz:=buzz', '--params-file', str(TEST_RESOURCES_DIR / 'test_parameters.yaml'), '-p', 'initial_buzz:=1.' ], automatically_declare_parameters_from_overrides=False ) def tearDown(self) -> None: self.node.destroy_node() def test_declare_parameter(self) -> None: with pytest.raises(ValueError): result_initial_foo = self.node.declare_parameter( 'initial_foo', ParameterValue(), ParameterDescriptor()) result_initial_foo = self.node.declare_parameter( 'initial_foo', ParameterValue(), ParameterDescriptor(dynamic_typing=True)) result_initial_bar = self.node.declare_parameter( 'initial_bar', 'ignoring_override', ParameterDescriptor(), ignore_override=True) result_initial_fizz = self.node.declare_parameter( 'initial_fizz', 'default', ParameterDescriptor()) result_initial_baz = self.node.declare_parameter( 'initial_baz', 0., ParameterDescriptor()) result_initial_buzz = self.node.declare_parameter( 'initial_buzz', 0., ParameterDescriptor()) result_initial_foobar = self.node.declare_parameter( 'initial_foobar', True, ParameterDescriptor()) result_foo = self.node.declare_parameter( 'foo', 42, ParameterDescriptor()) result_bar = self.node.declare_parameter( 'bar', 'hello', ParameterDescriptor()) result_baz = self.node.declare_parameter( 'baz', 2.41, ParameterDescriptor()) with self.assertRaises(TypeError): self.node.declare_parameter('value_not_set') # OK cases. self.assertIsInstance(result_initial_foo, Parameter) self.assertIsInstance(result_initial_bar, Parameter) self.assertIsInstance(result_initial_fizz, Parameter) self.assertIsInstance(result_initial_baz, Parameter) self.assertIsInstance(result_foo, Parameter) self.assertIsInstance(result_bar, Parameter) self.assertIsInstance(result_baz, Parameter) # initial_foo and initial_fizz get override values; initial_bar does not. self.assertEqual(result_initial_foo.value, 4321) self.assertEqual(result_initial_bar.value, 'ignoring_override') # provided by CLI, overridden by file self.assertEqual(result_initial_fizz.value, 'param_file_override') self.assertEqual(result_initial_baz.value, 3.14) # provided by file, overridden manually self.assertEqual(result_initial_buzz.value, 1.) # provided by CLI self.assertEqual(result_initial_foobar.value, False) # provided by file self.assertEqual(result_foo.value, 42) self.assertEqual(result_bar.value, 'hello') self.assertEqual(result_baz.value, 2.41) self.assertEqual(self.node.get_parameter('initial_foo').value, 4321) self.assertEqual(self.node.get_parameter('initial_bar').value, 'ignoring_override') self.assertEqual(self.node.get_parameter('initial_fizz').value, 'param_file_override') self.assertEqual(self.node.get_parameter('initial_baz').value, 3.14) self.assertEqual(self.node.get_parameter('initial_buzz').value, 1) self.assertEqual(self.node.get_parameter('initial_foobar').value, False) self.assertEqual(self.node.get_parameter('foo').value, 42) self.assertEqual(self.node.get_parameter('bar').value, 'hello') self.assertEqual(self.node.get_parameter('baz').value, 2.41) # Error cases. # TODO(@jubeira): add failing test cases with invalid names once name # validation is implemented. with self.assertRaises(ParameterAlreadyDeclaredException): self.node.declare_parameter( 'foo', 'raise', ParameterDescriptor()) with self.assertRaises(InvalidParameterException): self.node.declare_parameter( '', 'raise', ParameterDescriptor()) with self.assertRaises(InvalidParameterException): self.node.declare_parameter( '', 'raise', ParameterDescriptor()) self.node.add_on_set_parameters_callback(self.reject_parameter_callback) with self.assertRaises(InvalidParameterValueException): self.node.declare_parameter( 'reject_me', 'raise', ParameterDescriptor()) with self.assertRaises(TypeError): self.node.declare_parameter( 1, 'wrong_name_type', ParameterDescriptor()) # type: ignore[call-overload] with self.assertRaises(ValueError): self.node.declare_parameter( 'wrong_parameter_value_type', ParameterValue(), ParameterDescriptor()) with self.assertRaises(TypeError): self.node.declare_parameter( 'wrong_parameter_descriptor_type', 1, ParameterValue()) with self.assertRaises(ValueError): self.node.declare_parameter( 'static_typing_wo_default_value', descriptor=ParameterDescriptor(type=ParameterType.PARAMETER_NOT_SET)) with self.assertRaises(ValueError): self.node.declare_parameter( 'static_typing_wo_default_value', descriptor=ParameterDescriptor(type=ParameterType.PARAMETER_STRING)) with self.assertRaises(ValueError): self.node.declare_parameter( 'dynamic_typing_and_static_type', Parameter.Type.DOUBLE, descriptor=ParameterDescriptor(dynamic_typing=True)) def test_declare_parameters(self) -> None: parameters: List[ Union[Tuple[str, Union[int, str, float], ParameterDescriptor], Tuple[str, float]]] = [ ('initial_foo', 0, ParameterDescriptor()), ('foo', 42, ParameterDescriptor()), ('bar', 'hello', ParameterDescriptor()), ('baz', 2.41) ] # Declare uninitialized parameter parameter_type = self.node.declare_parameter('no_override', Parameter.Type.INTEGER).type_ assert parameter_type == Parameter.Type.NOT_SET with pytest.raises(InvalidParameterTypeException): self.node.declare_parameter('initial_decl_wrong_type', Parameter.Type.INTEGER) self.assertAlmostEqual( self.node.declare_parameter('initial_decl_with_type', Parameter.Type.DOUBLE).value, 3.14) result = self.node.declare_parameters('', parameters) # OK cases - using overrides. self.assertIsInstance(result, list) self.assertEqual(len(result), len(parameters)) self.assertIsInstance(result[0], Parameter) self.assertIsInstance(result[1], Parameter) self.assertIsInstance(result[2], Parameter) self.assertIsInstance(result[3], Parameter) self.assertEqual(result[0].value, 4321) self.assertEqual(result[1].value, 42) self.assertEqual(result[2].value, 'hello') self.assertEqual(result[3].value, 2.41) self.assertEqual(self.node.get_parameter('initial_foo').value, 4321) self.assertEqual(self.node.get_parameter('foo').value, 42) self.assertEqual(self.node.get_parameter('bar').value, 'hello') self.assertEqual(self.node.get_parameter('baz').value, 2.41) parameters = [ ('k_initial_foo', 0, ParameterDescriptor()), ('k_foo', 42, ParameterDescriptor()), ('k_bar', 'hello', ParameterDescriptor()), ('k_baz', 2.41) ] result = self.node.declare_parameters('namespace', parameters) # OK cases. self.assertIsInstance(result, list) self.assertEqual(len(result), len(parameters)) self.assertIsInstance(result[0], Parameter) self.assertIsInstance(result[1], Parameter) self.assertIsInstance(result[2], Parameter) self.assertIsInstance(result[3], Parameter) self.assertEqual(result[0].value, 4321) self.assertEqual(result[1].value, 42) self.assertEqual(result[2].value, 'hello') self.assertEqual(result[3].value, 2.41) self.assertEqual(self.node.get_parameter('namespace.k_initial_foo').value, 4321) self.assertEqual(self.node.get_parameter('namespace.k_foo').value, 42) self.assertEqual(self.node.get_parameter('namespace.k_bar').value, 'hello') self.assertEqual(self.node.get_parameter('namespace.k_baz').value, 2.41) parameters = [ ('initial_bar', 'ignoring_override', ParameterDescriptor()), ('initial_baz', 'ignoring_override_again', ParameterDescriptor()), ] result = self.node.declare_parameters('', parameters, ignore_override=True) # OK cases - ignoring overrides. self.assertIsInstance(result, list) self.assertEqual(len(result), len(parameters)) self.assertIsInstance(result[0], Parameter) self.assertIsInstance(result[1], Parameter) self.assertEqual(result[0].value, 'ignoring_override') self.assertEqual(result[1].value, 'ignoring_override_again') self.assertEqual(self.node.get_parameter('initial_bar').value, 'ignoring_override') self.assertEqual(self.node.get_parameter('initial_baz').value, 'ignoring_override_again') # Error cases. with self.assertRaises(ParameterAlreadyDeclaredException): self.node.declare_parameters('', parameters) # Declare a new set of parameters; the first one is not already declared, # but 2nd and 3rd one are. parameters = [ ('foobar', 43, ParameterDescriptor()), ('bar', 'hello', ParameterDescriptor()), ('baz', 2.41, ParameterDescriptor()), ] with self.assertRaises(ParameterAlreadyDeclaredException): self.node.declare_parameters('', parameters) # Declare a new set; the third one shall fail because of its name. parameters = [ ('foobarbar', 44, ParameterDescriptor()), ('barbarbar', 'world', ParameterDescriptor()), ('', 2.41, ParameterDescriptor()), ] with self.assertRaises(InvalidParameterException): self.node.declare_parameters('', parameters) # Declare a new set; the third one shall be rejected by the callback. parameters = [ ('im_ok', 44, ParameterDescriptor()), ('im_also_ok', 'world', ParameterDescriptor()), ('reject_me', 2.41, ParameterDescriptor()), ] self.node.add_on_set_parameters_callback(self.reject_parameter_callback) with self.assertRaises(InvalidParameterValueException): self.node.declare_parameters('', parameters) with self.assertRaises(TypeError): self.node.declare_parameters( '', [( # type: ignore[list-item] 1, 'wrong_name_type', ParameterDescriptor() )] ) with self.assertRaises(ValueError): self.node.declare_parameters( '', [( 'wrong_parameter_value_type', ParameterValue(), ParameterDescriptor() )] ) with self.assertRaises(TypeError): self.node.declare_parameters( '', [( 'wrong_parameter_descriptor_type', ParameterValue(), ParameterValue() )] ) # Declare a parameter with parameter type 'Not Set' with self.assertRaises(ValueError): self.node.declare_parameter( 'wrong_parameter_value_type_not_set', Parameter.Type.NOT_SET) def return_none_parameter_callback(self, parameter_list: List[Parameter[Any]]) -> None: return None def reject_parameter_callback(self, parameter_list: List[Parameter[Any]] ) -> SetParametersResult: rejected_parameters = (param for param in parameter_list if 'reject' in param.name) return SetParametersResult(successful=(not any(rejected_parameters))) def reject_parameter_callback_1(self, parameter_list: List[Parameter[Any]] ) -> SetParametersResult: rejected_parameters = ( param for param in parameter_list if 'refuse' in param.name) return SetParametersResult(successful=(not any(rejected_parameters))) def test_node_undeclare_parameter_has_parameter(self) -> None: # Undeclare unexisting parameter. with self.assertRaises(ParameterNotDeclaredException): self.node.undeclare_parameter('foo') # Verify that it doesn't exist. self.assertFalse(self.node.has_parameter('foo')) # Declare parameter, verify existence, undeclare, and verify again. self.node.declare_parameter( 'foo', 'hello', ParameterDescriptor() ) self.assertTrue(self.node.has_parameter('foo')) self.node.undeclare_parameter('foo') self.assertFalse(self.node.has_parameter('foo')) # Try with a read only parameter. self.assertFalse(self.node.has_parameter('immutable_foo')) self.node.declare_parameter( 'immutable_foo', 'I am immutable', ParameterDescriptor(read_only=True) ) with self.assertRaises(ParameterImmutableException): self.node.undeclare_parameter('immutable_foo') # Verify that it still exists with the same value. self.assertTrue(self.node.has_parameter('immutable_foo')) self.assertEqual(self.node.get_parameter('immutable_foo').value, 'I am immutable') def test_node_set_undeclared_parameters(self) -> None: with self.assertRaises(ParameterNotDeclaredException): self.node.set_parameters([ Parameter('foo', Parameter.Type.INTEGER, 42), Parameter('bar', Parameter.Type.STRING, 'hello'), Parameter('baz', Parameter.Type.DOUBLE, 2.41) ]) def test_node_set_undeclared_parameters_atomically(self) -> None: with self.assertRaises(ParameterNotDeclaredException): self.node.set_parameters_atomically([ Parameter('foo', Parameter.Type.INTEGER, 42), Parameter('bar', Parameter.Type.STRING, 'hello'), Parameter('baz', Parameter.Type.DOUBLE, 2.41) ]) def test_node_get_undeclared_parameter(self) -> None: with self.assertRaises(ParameterNotDeclaredException): self.node.get_parameter('initial_foo') def test_node_get_undeclared_parameter_or(self) -> None: result = self.node.get_parameter_or( 'initial_foo', Parameter('foo', Parameter.Type.INTEGER, 152)) self.assertEqual(result.name, 'foo') self.assertEqual(result.value, 152) def test_node_get_uninitialized_parameter_or(self) -> None: # Statically typed parameter self.node.declare_parameter('uninitialized_foo', Parameter.Type.INTEGER) result = self.node.get_parameter_or( 'uninitialized_foo', Parameter('foo', Parameter.Type.INTEGER, 152)) self.assertEqual(result.name, 'foo') self.assertEqual(result.value, 152) # Dynamically typed parameter self.node.declare_parameter( 'uninitialized_bar', None, ParameterDescriptor(dynamic_typing=True)) result = self.node.get_parameter_or( 'uninitialized_bar', Parameter('foo', Parameter.Type.INTEGER, 153)) self.assertEqual(result.name, 'foo') self.assertEqual(result.value, 153) def test_node_get_parameters_by_prefix(self) -> None: parameter_tuples: List[Tuple[str, Union[int, str, float]]] = [ ('foo_prefix.foo', 43), ('foo_prefix.bar', 'hello'), ('foo_prefix.baz', 2.41), ('bar_prefix.foo', 1), ('bar_prefix.bar', 12.3), ('bar_prefix.baz', 'world'), ] self.node.declare_parameters('', parameter_tuples) parameters = self.node.get_parameters_by_prefix('foo_prefix') self.assertIsInstance(parameters, dict) self.assertEqual(len(parameters), 3) self.assertDictEqual( parameters, { 'foo': self.node.get_parameter('foo_prefix.foo'), 'bar': self.node.get_parameter('foo_prefix.bar'), 'baz': self.node.get_parameter('foo_prefix.baz') } ) parameters = self.node.get_parameters_by_prefix('bar_prefix') self.assertIsInstance(parameters, dict) self.assertEqual(len(parameters), 3) self.assertDictEqual( parameters, { 'foo': self.node.get_parameter('bar_prefix.foo'), 'bar': self.node.get_parameter('bar_prefix.bar'), 'baz': self.node.get_parameter('bar_prefix.baz') } ) parameters = self.node.get_parameters_by_prefix('') self.assertIsInstance(parameters, dict) # use_sim_time is automatically declared. self.assertDictEqual( parameters, { 'foo_prefix.foo': self.node.get_parameter('foo_prefix.foo'), 'foo_prefix.bar': self.node.get_parameter('foo_prefix.bar'), 'foo_prefix.baz': self.node.get_parameter('foo_prefix.baz'), 'bar_prefix.foo': self.node.get_parameter('bar_prefix.foo'), 'bar_prefix.bar': self.node.get_parameter('bar_prefix.bar'), 'bar_prefix.baz': self.node.get_parameter('bar_prefix.baz'), USE_SIM_TIME_NAME: self.node.get_parameter(USE_SIM_TIME_NAME), START_TYPE_DESCRIPTION_SERVICE_PARAM: self.node.get_parameter( START_TYPE_DESCRIPTION_SERVICE_PARAM), } ) parameters = self.node.get_parameters_by_prefix('baz') self.assertFalse(parameters) self.assertIsInstance(parameters, dict) def test_node_set_parameters(self) -> None: integer_value = 42 string_value = 'hello' float_value = 2.41 parameter_tuples = [ ( 'foo', integer_value, ParameterDescriptor() ), ( 'bar', string_value, ParameterDescriptor() ), ( 'baz', float_value, ParameterDescriptor() ) ] # Create rclpy.Parameter list from tuples. parameters: List[Parameter[Any]] = [ Parameter( name=parameter_tuples[0][0], value=integer_value ), Parameter( name=parameter_tuples[1][0], value=string_value ), Parameter( name=parameter_tuples[2][0], value=float_value ), ] with self.assertRaises(ParameterNotDeclaredException): self.node.set_parameters(parameters) self.node.declare_parameters('', parameter_tuples) result = self.node.set_parameters(parameters) # OK cases: check successful result and parameter value for each parameter set. self.assertIsInstance(result, list) self.assertIsInstance(result[0], SetParametersResult) self.assertIsInstance(result[1], SetParametersResult) self.assertIsInstance(result[2], SetParametersResult) self.assertTrue(result[0].successful) self.assertTrue(result[1].successful) self.assertTrue(result[2].successful) self.assertEqual(self.node.get_parameter('foo').value, 42) self.assertEqual(self.node.get_parameter('bar').value, 'hello') self.assertEqual(self.node.get_parameter('baz').value, 2.41) # Now we modify the declared parameters, add a new one and set them again. integer_value = 24 string_value = 'bye' float_value = 1.42 extra_value = 2.71 parameter_tuples.append( ( 'foobar', extra_value, ParameterDescriptor()) ) parameters = [ Parameter( name=parameter_tuples[0][0], value=integer_value ), Parameter( name=parameter_tuples[1][0], value=string_value ), Parameter( name=parameter_tuples[2][0], value=float_value ), Parameter( name=parameter_tuples[3][0], value=float_value ), ] # The first three parameters should have been set; the fourth one causes the exception. with self.assertRaises(ParameterNotDeclaredException): self.node.set_parameters(parameters) # Validate first three. self.assertEqual(self.node.get_parameter('foo').value, 24) self.assertEqual(self.node.get_parameter('bar').value, 'bye') self.assertEqual(self.node.get_parameter('baz').value, 1.42) # Confirm that the fourth one does not exist. with self.assertRaises(ParameterNotDeclaredException): self.node.get_parameter('foobar') def test_node_set_parameters_rejection(self) -> None: # Declare a new parameter and set a callback so that it's rejected when set. reject_parameter_tuple = ( 'reject_me', True, ParameterDescriptor() ) self.node.declare_parameter(*reject_parameter_tuple) self.node.add_on_set_parameters_callback(self.reject_parameter_callback) result = self.node.set_parameters( [ Parameter( name=reject_parameter_tuple[0], value=reject_parameter_tuple[1] ) ] ) self.assertIsInstance(result, list) self.assertIsInstance(result[0], SetParametersResult) self.assertFalse(result[0].successful) def test_node_set_parameters_return_none(self) -> None: # Declare a new parameter and set a callback that returns None. parameter_tuple = ( 'test_param', True, ParameterDescriptor() ) self.node.declare_parameter(*parameter_tuple) # Tries to set the parameter with a callback that returns None. self.node.add_on_set_parameters_callback(self.return_none_parameter_callback) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always', category=UserWarning) result = self.node.set_parameters( [ Parameter( name=parameter_tuple[0], value=parameter_tuple[1] ) ] ) assert len(w) == 1, f'Expected 1 warning, but got {len(w)}' assert issubclass(w[0].category, UserWarning) assert 'Callback returned an invalid type, it should return SetParameterResult.' \ in str(w[0].message) self.assertIsInstance(result, list) self.assertIsInstance(result[0], SetParametersResult) self.assertFalse(result[0].successful) self.assertEqual(result[0].reason, 'Callback returned an invalid type') def test_node_set_parameters_rejection_list(self) -> None: # Declare a new parameters and set a list of callbacks so that it's rejected when set. reject_list_parameter_tuple = [ ('reject', True, ParameterDescriptor()), ('accept', True, ParameterDescriptor()), ('accept', True, ParameterDescriptor()) ] self.node.declare_parameters('', reject_list_parameter_tuple) self.node.add_on_set_parameters_callback(self.reject_parameter_callback) self.node.add_on_set_parameters_callback(self.reject_parameter_callback_1) result = self.node.set_parameters( [ Parameter( name=reject_list_parameter_tuple[0][0], value=reject_list_parameter_tuple[0][1] ), Parameter( name=reject_list_parameter_tuple[1][0], value=reject_list_parameter_tuple[1][1] ), Parameter( name=reject_list_parameter_tuple[2][0], value=reject_list_parameter_tuple[2][1] ) ] ) self.assertEqual(3, len(result)) self.assertIsInstance(result, list) self.assertIsInstance(result[0], SetParametersResult) self.assertFalse(result[0].successful) self.assertIsInstance(result[1], SetParametersResult) self.assertTrue(result[1].successful) self.assertIsInstance(result[2], SetParametersResult) self.assertTrue(result[2].successful) def test_node_list_parameters(self) -> None: parameters: List[Tuple[str, Union[int, str, float]]] = [ ('foo_prefix.foo', 43), ('foo_prefix.bar', 'hello'), ('foo_prefix.baz', 2.41), ('bar_prefix.foo', 1), ('bar_prefix.bar', 12.3), ('bar_prefix.baz', 'world'), ] self.node.declare_parameters('', parameters) param_result = self.node.list_parameters([], 0) self.assertIsInstance(param_result, ListParametersResult) # Currently the default parameters are 'use_sim_time' and 'start_type_description_service'. # Those may change. e.g) QoS override parameters self.assertEqual(len(param_result.names), len(parameters)+2) self.assertCountEqual( param_result.names, [ 'foo_prefix.foo', 'foo_prefix.bar', 'foo_prefix.baz', 'bar_prefix.foo', 'bar_prefix.bar', 'bar_prefix.baz', USE_SIM_TIME_NAME, START_TYPE_DESCRIPTION_SERVICE_PARAM ] ) self.assertEqual(len(param_result.prefixes), 2) self.assertCountEqual( param_result.prefixes, [ 'foo_prefix', 'bar_prefix', ] ) param_result = self.node.list_parameters( prefixes=['foo_prefix', 'bar_prefix'], depth=0) self.assertIsInstance(param_result, ListParametersResult) self.assertEqual(len(param_result.names), len(parameters)) self.assertCountEqual( param_result.names, [ 'foo_prefix.foo', 'foo_prefix.bar', 'foo_prefix.baz', 'bar_prefix.foo', 'bar_prefix.bar', 'bar_prefix.baz' ] ) self.assertEqual(len(param_result.prefixes), 2) self.assertCountEqual( param_result.prefixes, [ 'foo_prefix', 'bar_prefix', ] ) param_result = self.node.list_parameters( prefixes=['foo_prefix'], depth=0) self.assertIsInstance(param_result, ListParametersResult) self.assertEqual(len(param_result.names), 3) self.assertCountEqual( param_result.names, [ 'foo_prefix.foo', 'foo_prefix.bar', 'foo_prefix.baz' ] ) self.assertEqual(len(param_result.prefixes), 1) self.assertCountEqual( param_result.prefixes, [ 'foo_prefix' ] ) param_result = self.node.list_parameters(prefixes=[], depth=1) self.assertIsInstance(param_result, ListParametersResult) self.assertEqual(len(param_result.names), 2) self.assertCountEqual( param_result.names, [USE_SIM_TIME_NAME, START_TYPE_DESCRIPTION_SERVICE_PARAM] ) self.assertEqual(len(param_result.prefixes), 0) self.assertCountEqual(param_result.prefixes, []) param_result = self.node.list_parameters(prefixes=[], depth=2) self.assertIsInstance(param_result, ListParametersResult) self.assertEqual(len(param_result.names), len(parameters)+2) self.assertCountEqual( param_result.names, [ 'foo_prefix.foo', 'foo_prefix.bar', 'foo_prefix.baz', 'bar_prefix.foo', 'bar_prefix.bar', 'bar_prefix.baz', USE_SIM_TIME_NAME, START_TYPE_DESCRIPTION_SERVICE_PARAM ] ) self.assertEqual(len(param_result.prefixes), 2) self.assertCountEqual( param_result.prefixes, [ 'foo_prefix', 'bar_prefix', ] ) param_result = self.node.list_parameters(prefixes=['foo_prefix', 'bar_prefix'], depth=1) self.assertIsInstance(param_result, ListParametersResult) self.assertEqual(len(param_result.names), len(parameters)) self.assertCountEqual( param_result.names, [ 'foo_prefix.foo', 'foo_prefix.bar', 'foo_prefix.baz', 'bar_prefix.foo', 'bar_prefix.bar', 'bar_prefix.baz', ] ) self.assertEqual(len(param_result.prefixes), 2) self.assertCountEqual( param_result.prefixes, [ 'foo_prefix', 'bar_prefix', ] ) with self.assertRaises(TypeError): self.node.list_parameters(prefixes='foo', depth=0) # type: ignore[arg-type] with self.assertRaises(ValueError): self.node.list_parameters(prefixes=[], depth=-1) with self.assertRaises(TypeError): self.node.list_parameters(prefixes=[], depth=1.5) # type: ignore[arg-type] def modify_parameter_callback(self, parameter_list: List[Parameter[Any]] ) -> List[Parameter[Any]]: modified_list = parameter_list.copy() for param in parameter_list: if param.name == 'foo': modified_list.append(Parameter('bar', Parameter.Type.STRING, 'hello')) return modified_list def empty_parameter_callback(self, parameter_list: List[Parameter[Any]] ) -> List[Parameter[Any]]: return [] def test_add_remove_pre_set_parameter_callback(self) -> None: callbacks = [self.modify_parameter_callback, self.empty_parameter_callback] for callback in callbacks: self.node.add_pre_set_parameters_callback(callback) self.assertTrue(callback in self.node._pre_set_parameters_callbacks) for callback in callbacks: self.node.remove_pre_set_parameters_callback(callback) self.assertFalse(callback in self.node._pre_set_parameters_callbacks) # register a callback self.node.add_pre_set_parameters_callback(self.modify_parameter_callback) self.node.declare_parameter('foo', 0) self.node.declare_parameter('bar', '') # check that declare_parameter will not result in a call to any of the # pre_set_parameter registered callbacks self.assertTrue(self.node.has_parameter('foo')) self.assertTrue(self.node.has_parameter('bar')) self.assertTrue(self.node.get_parameter('foo').value == 0) self.assertTrue(self.node.get_parameter('bar').value == '') # setting of parameter 'foo' will result in setting of parameter 'bar' results = self.node.set_parameters([Parameter('foo', Parameter.Type.INTEGER, 42)]) self.node.remove_pre_set_parameters_callback(self.modify_parameter_callback) # param 'bar' should be modified because of registered callback self.assertEqual(len(results), 1) self.assertTrue(results[0].successful) self.assertTrue(self.node.has_parameter('foo')) self.assertTrue(self.node.has_parameter('bar')) self.assertTrue(self.node.get_parameter('foo').value == 42) self.assertTrue(self.node.get_parameter('bar').value == 'hello') # result will be unsuccessful if the callback return an empty list self.node.add_pre_set_parameters_callback(self.empty_parameter_callback) results = self.node.set_parameters([Parameter('foo', Parameter.Type.INTEGER, 42)]) self.node.remove_pre_set_parameters_callback(self.empty_parameter_callback) self.assertFalse(results[0].successful) self.assertEqual(results[0].reason, 'parameter list cannot be empty, this might be due to ' 'pre_set_parameters_callback modifying the original parameters list.') def test_node_add_on_set_parameter_callback(self) -> None: # Add callbacks to the list of callbacks. callbacks = [ self.reject_parameter_callback, self.reject_parameter_callback_1 ] for callback in callbacks: self.node.add_on_set_parameters_callback(callback) for callback in callbacks: self.assertTrue(callback in self.node._on_set_parameters_callbacks) for callback in callbacks: self.node.remove_on_set_parameters_callback(callback) # Adding the parameters which will be accepted without any rejections. non_reject_parameter_tuple = [ ('accept_1', True, ParameterDescriptor()), ('accept_2', True, ParameterDescriptor()) ] self.node.declare_parameters('', non_reject_parameter_tuple) for callback in callbacks: self.node.add_on_set_parameters_callback(callback) result = self.node.set_parameters( [ Parameter( name=non_reject_parameter_tuple[0][0], value=non_reject_parameter_tuple[0][1] ), Parameter( name=non_reject_parameter_tuple[1][0], value=non_reject_parameter_tuple[1][1] ) ] ) self.assertEqual(2, len(result)) self.assertIsInstance(result, list) self.assertIsInstance(result[0], SetParametersResult) self.assertTrue(result[0].successful) self.assertIsInstance(result[1], SetParametersResult) self.assertTrue(result[1].successful) def test_node_remove_from_set_callback(self) -> None: # Remove callbacks from list of callbacks. parameter_tuple = ( 'refuse', True, ParameterDescriptor() ) self.node.declare_parameter(*parameter_tuple) callbacks = [ self.reject_parameter_callback_1, ] # Checking if the callbacks are not already present. for callback in callbacks: self.assertFalse(callback in self.node._on_set_parameters_callbacks) for callback in callbacks: self.node.add_on_set_parameters_callback(callback) result = self.node.set_parameters( [ Parameter( name=parameter_tuple[0], value=parameter_tuple[1] ) ] ) self.assertEqual(1, len(result)) self.assertIsInstance(result, list) self.assertIsInstance(result[0], SetParametersResult) self.assertFalse(result[0].successful) # Removing the callback which is causing the rejection. self.node.remove_on_set_parameters_callback(self.reject_parameter_callback_1) self.assertFalse(self.reject_parameter_callback_1 in self.node._on_set_parameters_callbacks) # Now the setting its value again. result = self.node.set_parameters( [ Parameter( name=parameter_tuple[0], value=parameter_tuple[1] ) ] ) self.assertEqual(1, len(result)) self.assertIsInstance(result, list) self.assertIsInstance(result[0], SetParametersResult) self.assertTrue(result[0].successful) def test_add_remove_post_set_parameter_callback(self) -> None: def successful_parameter_set_callback(parameter_list: List[Parameter[Any]]) -> None: for param in parameter_list: if param.name == 'param1': self.track_value1 = param.value elif param.name == 'param2': self.track_value2 = param.value callbacks = [successful_parameter_set_callback] for callback in callbacks: self.node.add_post_set_parameters_callback(callback) self.assertTrue(callback in self.node._post_set_parameters_callbacks) for callback in callbacks: self.node.remove_post_set_parameters_callback(callback) self.assertFalse(callback in self.node._post_set_parameters_callbacks) self.node.declare_parameter('param1', 0.0) self.node.declare_parameter('param2', 0.0) self.track_value1 = self.node.get_parameter('param1') self.track_value2 = self.node.get_parameter('param2') self.node.add_post_set_parameters_callback(successful_parameter_set_callback) results = self.node.set_parameters([Parameter('param1', Parameter.Type.DOUBLE, 1.0), Parameter('param2', Parameter.Type.DOUBLE, 2.0)]) # 'track_value1' and 'track_value2' should be updated to # 'param1' and 'param2' value respectively. self.assertEqual(len(results), 2) self.assertTrue(results[0].successful) self.assertTrue(results[1].successful) self.assertTrue(self.node.has_parameter('param1')) self.assertTrue(self.node.has_parameter('param2')) self.assertEqual(self.node.get_parameter('param1').value, 1.0) self.assertEqual(self.node.get_parameter('param2').value, 2.0) self.assertTrue(self.track_value1 == 1.0) # type: ignore[comparison-overlap] self.assertTrue(self.track_value2 == 2.0) # type: ignore[comparison-overlap] def test_node_set_parameters_read_only(self) -> None: integer_value = 42 string_value = 'hello' float_value = 2.41 parameter_tuples = [ ( 'immutable_foo', integer_value, ParameterDescriptor(read_only=True) ), ( 'bar', string_value, ParameterDescriptor() ), ( 'immutable_baz', float_value, ParameterDescriptor(read_only=True) ) ] # Create rclpy.Parameter list from tuples. parameters: List[Parameter[Any]] = [ Parameter( name=parameter_tuples[0][0], value=integer_value ), Parameter( name=parameter_tuples[1][0], value=string_value ), Parameter( name=parameter_tuples[2][0], value=float_value ), ] self.node.declare_parameters('', parameter_tuples) # Try setting a different value to the declared parameters. integer_value = 24 string_value = 'bye' float_value = 1.42 # Re-create parameters with modified values. parameters = [ Parameter( name=parameter_tuples[0][0], value=integer_value ), Parameter( name=parameter_tuples[1][0], value=string_value ), Parameter( name=parameter_tuples[2][0], value=float_value ), ] result = self.node.set_parameters(parameters) # Only the parameter that is not read_only should have succeeded. self.assertIsInstance(result, list) self.assertIsInstance(result[0], SetParametersResult) self.assertIsInstance(result[1], SetParametersResult) self.assertIsInstance(result[2], SetParametersResult) self.assertFalse(result[0].successful) self.assertTrue(result[1].successful) self.assertFalse(result[2].successful) self.assertEqual(self.node.get_parameter('immutable_foo').value, 42) self.assertEqual(self.node.get_parameter('bar').value, 'bye') self.assertEqual(self.node.get_parameter('immutable_baz').value, 2.41) def test_node_set_parameters_pre_set_parameter_callback(self) -> None: # parameter 'bar' not declared here, only declare 'foo' default_value = 0 self.node.declare_parameter('foo', default_value) self.node.add_pre_set_parameters_callback(self.modify_parameter_callback) # adding a parameter using "add_pre_set_parameter" callback, when that # parameter has not been declared before will throw. with self.assertRaises(ParameterNotDeclaredException): self.node.set_parameters([ Parameter('foo', Parameter.Type.INTEGER, 42)]) self.assertTrue(self.node.has_parameter('foo')) self.assertEqual(self.node.get_parameter('foo').value, default_value) self.assertFalse(self.node.has_parameter('bar')) self.node.remove_pre_set_parameters_callback(self.modify_parameter_callback) # An empty list from 'add_pre_set_parameter' callback will return # an unsuccessful result self.node.add_pre_set_parameters_callback(self.empty_parameter_callback) results = self.node.set_parameters([Parameter('foo', Parameter.Type.INTEGER, 42)]) self.assertFalse(results[0].successful) self.assertTrue(self.node.has_parameter('foo')) self.assertTrue(self.node.get_parameter('foo').value == default_value) self.assertFalse(self.node.has_parameter('bar')) def test_node_set_parameters_implicit_undeclare(self) -> None: parameter_tuples = [ ( 'foo', 42, ParameterDescriptor() ), ( 'bar', 'hello', ParameterDescriptor(dynamic_typing=True) ), ( 'baz', 2.41, ParameterDescriptor() ) ] self.node.declare_parameters('', parameter_tuples) # Verify that the parameters are set. self.assertEqual(self.node.get_parameter('foo').value, 42) self.assertEqual(self.node.get_parameter('bar').value, 'hello') self.assertEqual(self.node.get_parameter('baz').value, 2.41) # Now undeclare one of them implicitly. self.node.set_parameters([Parameter('bar', Parameter.Type.NOT_SET, None)]) self.assertEqual(self.node.get_parameter('foo').value, 42) self.assertFalse(self.node.has_parameter('bar')) self.assertEqual(self.node.get_parameter('baz').value, 2.41) def test_node_set_parameters_atomically(self) -> None: integer_value = 42 string_value = 'hello' float_value = 2.41 parameter_tuples = [ ( 'foo', integer_value, ParameterDescriptor() ), ( 'bar', string_value, ParameterDescriptor() ), ( 'baz', float_value, ParameterDescriptor() ) ] # Create rclpy.Parameter list from tuples. parameters: List[Parameter[Any]] = [ Parameter( name=parameter_tuples[0][0], value=integer_value ), Parameter( name=parameter_tuples[1][0], value=string_value ), Parameter( name=parameter_tuples[2][0], value=float_value ), ] with self.assertRaises(ParameterNotDeclaredException): self.node.set_parameters_atomically(parameters) self.node.declare_parameters('', parameter_tuples) result = self.node.set_parameters_atomically(parameters) # OK case: check successful aggregated result. self.assertIsInstance(result, SetParametersResult) self.assertTrue(result.successful) self.assertEqual(self.node.get_parameter('foo').value, 42) self.assertEqual(self.node.get_parameter('bar').value, 'hello') self.assertEqual(self.node.get_parameter('baz').value, 2.41) # Now we modify the declared parameters, add a new one and set them again. integer_value = 24 string_value = 'bye' float_value = 1.42 extra_value = 2.71 parameter_tuples.append( ( 'foobar', extra_value, ParameterDescriptor()) ) parameters = [ Parameter( name=parameter_tuples[0][0], value=integer_value ), Parameter( name=parameter_tuples[1][0], value=string_value ), Parameter( name=parameter_tuples[2][0], value=float_value ), Parameter( name=parameter_tuples[3][0], value=float_value ), ] # The fourth parameter causes the exception, hence none is set. with self.assertRaises(ParameterNotDeclaredException): self.node.set_parameters_atomically(parameters) # Confirm that the first three were not modified. self.assertEqual(self.node.get_parameter('foo').value, 42) self.assertEqual(self.node.get_parameter('bar').value, 'hello') self.assertEqual(self.node.get_parameter('baz').value, 2.41) # Confirm that the fourth one does not exist. with self.assertRaises(ParameterNotDeclaredException): self.node.get_parameter('foobar') def test_node_set_parameters_atomically_pre_set_parameter_callback(self) -> None: # parameter 'bar' not declared here, only declare 'foo' default_value = 0 self.node.declare_parameter('foo', default_value) self.node.add_pre_set_parameters_callback(self.modify_parameter_callback) # adding a parameter using "add_pre_set_parameter" callback, when that # parameter has not been declared before will throw. with self.assertRaises(ParameterNotDeclaredException): self.node.set_parameters_atomically([ Parameter('foo', Parameter.Type.INTEGER, 42)]) self.assertTrue(self.node.has_parameter('foo')) self.assertEqual(self.node.get_parameter('foo').value, default_value) self.assertFalse(self.node.has_parameter('bar')) self.node.remove_pre_set_parameters_callback(self.modify_parameter_callback) # An empty list from 'add_pre_set_parameter' callback will return # an unsuccessful result self.node.add_pre_set_parameters_callback(self.empty_parameter_callback) result = self.node.set_parameters_atomically( [Parameter('foo', Parameter.Type.INTEGER, 42)]) self.assertFalse(result.successful) self.assertTrue(self.node.has_parameter('foo')) self.assertTrue(self.node.get_parameter('foo').value == default_value) self.assertFalse(self.node.has_parameter('bar')) def test_node_set_parameters_atomically_rejection(self) -> None: # Declare a new parameter and set a callback so that it's rejected when set. reject_parameter_tuple = ( 'reject_me', True, ParameterDescriptor() ) self.node.declare_parameter(*reject_parameter_tuple) self.node.add_on_set_parameters_callback(self.reject_parameter_callback) result = self.node.set_parameters_atomically( [ Parameter( name=reject_parameter_tuple[0], value=reject_parameter_tuple[1] ) ] ) self.assertIsInstance(result, SetParametersResult) self.assertFalse(result.successful) def test_node_set_parameters_atomically_read_only(self) -> None: integer_value = 42 string_value = 'hello' float_value = 2.41 parameter_tuples = [ ( 'foo', integer_value, ParameterDescriptor() ), ( 'bar', string_value, ParameterDescriptor() ), ( 'immutable_baz', float_value, ParameterDescriptor(read_only=True) ) ] # Create rclpy.Parameter list from tuples. parameters: List[Parameter[Any]] = [ Parameter( name=parameter_tuples[0][0], value=integer_value ), Parameter( name=parameter_tuples[1][0], value=string_value ), Parameter( name=parameter_tuples[2][0], value=float_value ), ] self.node.declare_parameters('', parameter_tuples) # Try setting a different value to the declared parameters. integer_value = 24 string_value = 'bye' float_value = 1.42 parameters = [ Parameter( name=parameter_tuples[0][0], value=integer_value ), Parameter( name=parameter_tuples[1][0], value=string_value ), Parameter( name=parameter_tuples[2][0], value=float_value ), ] result = self.node.set_parameters_atomically(parameters) # At least one parameter is read-only, so the overall result should be a failure. # All the parameters should have their original value. self.assertIsInstance(result, SetParametersResult) self.assertFalse(result.successful) self.assertEqual(self.node.get_parameter('foo').value, 42) self.assertEqual(self.node.get_parameter('bar').value, 'hello') self.assertEqual(self.node.get_parameter('immutable_baz').value, 2.41) def test_node_set_parameters_atomically_implicit_undeclare(self) -> None: parameter_tuples = [ ( 'foo', 42, ParameterDescriptor() ), ( 'bar', 'hello', ParameterDescriptor(dynamic_typing=True) ), ( 'baz', 2.41, ParameterDescriptor() ) ] self.node.declare_parameters('', parameter_tuples) # Verify that the parameters are set. self.assertEqual(self.node.get_parameter('foo').value, 42) self.assertEqual(self.node.get_parameter('bar').value, 'hello') self.assertEqual(self.node.get_parameter('baz').value, 2.41) # Now undeclare one of them implicitly. result = self.node.set_parameters_atomically([ Parameter('bar', Parameter.Type.NOT_SET, None)]) self.assertEqual(result.successful, True) self.assertEqual(self.node.get_parameter('foo').value, 42) self.assertFalse(self.node.has_parameter('bar')) self.assertEqual(self.node.get_parameter('baz').value, 2.41) def test_describe_parameter(self) -> None: with self.assertRaises(ParameterNotDeclaredException): self.node.describe_parameter('foo') # Declare parameter with descriptor. self.node.declare_parameter( 'foo', 'hello', ParameterDescriptor( name='foo', type=ParameterType.PARAMETER_STRING, additional_constraints='some constraints', read_only=True, floating_point_range=[FloatingPointRange(from_value=-2.0, to_value=2.0, step=0.1)], integer_range=[IntegerRange(from_value=-10, to_value=10, step=2)] ) ) descriptor = self.node.describe_parameter('foo') self.assertEqual(descriptor.name, 'foo') self.assertEqual(descriptor.type, ParameterType.PARAMETER_STRING) self.assertEqual(descriptor.additional_constraints, 'some constraints') self.assertEqual(descriptor.read_only, True) self.assertEqual(descriptor.floating_point_range[0].from_value, -2.0) self.assertEqual(descriptor.floating_point_range[0].to_value, 2.0) self.assertEqual(descriptor.floating_point_range[0].step, 0.1) self.assertEqual(descriptor.integer_range[0].from_value, -10) self.assertEqual(descriptor.integer_range[0].to_value, 10) self.assertEqual(descriptor.integer_range[0].step, 2) def test_describe_parameters(self) -> None: with self.assertRaises(ParameterNotDeclaredException): self.node.describe_parameter('foo') with self.assertRaises(ParameterNotDeclaredException): self.node.describe_parameter('bar') # Declare parameters with descriptors. self.node.declare_parameter( 'foo', 'hello', ParameterDescriptor( name='foo', type=ParameterType.PARAMETER_STRING, additional_constraints='some constraints', read_only=True, floating_point_range=[FloatingPointRange(from_value=-2.0, to_value=2.0, step=0.1)], integer_range=[IntegerRange(from_value=-10, to_value=10, step=2)] ) ) self.node.declare_parameter( 'bar', 10, ParameterDescriptor( name='bar', type=ParameterType.PARAMETER_DOUBLE, additional_constraints='some more constraints', read_only=True, floating_point_range=[FloatingPointRange(from_value=-3.0, to_value=3.0, step=0.3)], integer_range=[IntegerRange(from_value=-20, to_value=20, step=3)] ) ) # Check list. descriptor_list = self.node.describe_parameters(['foo', 'bar']) self.assertIsInstance(descriptor_list, list) self.assertEqual(len(descriptor_list), 2) # Check individual descriptors. foo_descriptor = descriptor_list[0] self.assertEqual(foo_descriptor.name, 'foo') self.assertEqual(foo_descriptor.type, ParameterType.PARAMETER_STRING) self.assertEqual(foo_descriptor.additional_constraints, 'some constraints') self.assertEqual(foo_descriptor.read_only, True) self.assertEqual(foo_descriptor.floating_point_range[0].from_value, -2.0) self.assertEqual(foo_descriptor.floating_point_range[0].to_value, 2.0) self.assertEqual(foo_descriptor.floating_point_range[0].step, 0.1) self.assertEqual(foo_descriptor.integer_range[0].from_value, -10) self.assertEqual(foo_descriptor.integer_range[0].to_value, 10) self.assertEqual(foo_descriptor.integer_range[0].step, 2) # The descriptor gets the type of the parameter. bar_descriptor = descriptor_list[1] self.assertEqual(bar_descriptor.name, 'bar') self.assertEqual(bar_descriptor.type, ParameterType.PARAMETER_INTEGER) self.assertEqual(bar_descriptor.additional_constraints, 'some more constraints') self.assertEqual(bar_descriptor.read_only, True) self.assertEqual(bar_descriptor.floating_point_range[0].from_value, -3.0) self.assertEqual(bar_descriptor.floating_point_range[0].to_value, 3.0) self.assertEqual(bar_descriptor.floating_point_range[0].step, 0.3) self.assertEqual(bar_descriptor.integer_range[0].from_value, -20) self.assertEqual(bar_descriptor.integer_range[0].to_value, 20) self.assertEqual(bar_descriptor.integer_range[0].step, 3) def test_set_descriptor(self) -> None: with self.assertRaises(ParameterNotDeclaredException): self.node.set_descriptor('foo', ParameterDescriptor()) # Declare parameter with default descriptor. # The name and type of the stored descriptor shall match the parameter, self.node.declare_parameter( 'foo', 'hello', ParameterDescriptor() ) self.assertEqual( self.node.describe_parameter('foo'), ParameterDescriptor(name='foo', type=Parameter.Type.STRING.value) ) # Now modify the descriptor and check again. value = self.node.set_descriptor( 'foo', ParameterDescriptor( name='this will be ignored', type=ParameterType.PARAMETER_INTEGER, # Type will be ignored too. additional_constraints='some constraints', read_only=False, integer_range=[IntegerRange(from_value=-10, to_value=10, step=2)], dynamic_typing=True ) ) self.assertEqual(value.type, Parameter.Type.STRING.value) self.assertEqual(value.string_value, 'hello') # Name and type will match the parameter, not the given descriptor. descriptor = self.node.describe_parameter('foo') self.assertEqual(descriptor.name, 'foo') self.assertEqual(descriptor.type, ParameterType.PARAMETER_STRING) self.assertEqual(descriptor.additional_constraints, 'some constraints') self.assertEqual(descriptor.read_only, False) self.assertEqual(descriptor.integer_range[0].from_value, -10) self.assertEqual(descriptor.integer_range[0].to_value, 10) self.assertEqual(descriptor.integer_range[0].step, 2) # A descriptor that is not read-only can be replaced by a read-only one. value = self.node.set_descriptor( 'foo', ParameterDescriptor( name='bar', type=ParameterType.PARAMETER_STRING, additional_constraints='some more constraints', read_only=True, floating_point_range=[FloatingPointRange(from_value=-2.0, to_value=2.0, step=0.1)], ) ) self.assertEqual(value.type, Parameter.Type.STRING.value) self.assertEqual(value.string_value, 'hello') descriptor = self.node.describe_parameter('foo') self.assertEqual(descriptor.name, 'foo') self.assertEqual(descriptor.type, ParameterType.PARAMETER_STRING) self.assertEqual(descriptor.additional_constraints, 'some more constraints') self.assertEqual(descriptor.read_only, True) self.assertEqual(descriptor.floating_point_range[0].from_value, -2.0) self.assertEqual(descriptor.floating_point_range[0].to_value, 2.0) self.assertEqual(descriptor.floating_point_range[0].step, 0.1) def test_set_descriptor_read_only(self) -> None: with self.assertRaises(ParameterNotDeclaredException): self.node.set_descriptor('foo', ParameterDescriptor()) # Declare parameter with a read_only descriptor. self.node.declare_parameter( 'foo', 'hello', ParameterDescriptor(read_only=True) ) self.assertEqual( self.node.describe_parameter('foo'), ParameterDescriptor(name='foo', type=Parameter.Type.STRING.value, read_only=True) ) # Try modifying the descriptor. with self.assertRaises(ParameterImmutableException): self.node.set_descriptor( 'foo', ParameterDescriptor( name='foo', type=ParameterType.PARAMETER_STRING, additional_constraints='some constraints', read_only=False, ) ) def test_floating_point_range_descriptor(self) -> None: # OK cases; non-floats are not affected by the range. fp_range = FloatingPointRange(from_value=0.0, to_value=10.0, step=0.5) parameters = [ ('from_value', 0.0, ParameterDescriptor(floating_point_range=[fp_range])), ('to_value', 10.0, ParameterDescriptor(floating_point_range=[fp_range])), ('in_range', 4.5, ParameterDescriptor(floating_point_range=[fp_range])), ('str_value', 'I am no float', ParameterDescriptor(floating_point_range=[fp_range])), ('int_value', 123, ParameterDescriptor(floating_point_range=[fp_range])) ] declared_parameters_result = self.node.declare_parameters('', parameters) self.assertIsInstance(declared_parameters_result, list) self.assertIsInstance(declared_parameters_result[0], Parameter) self.assertIsInstance(declared_parameters_result[1], Parameter) self.assertIsInstance(declared_parameters_result[2], Parameter) self.assertIsInstance(declared_parameters_result[3], Parameter) self.assertIsInstance(declared_parameters_result[4], Parameter) self.assertAlmostEqual(declared_parameters_result[0].value, 0.0) self.assertAlmostEqual(declared_parameters_result[1].value, 10.0) self.assertAlmostEqual(declared_parameters_result[2].value, 4.5) self.assertEqual(declared_parameters_result[3].value, 'I am no float') self.assertEqual(declared_parameters_result[4].value, 123) self.assertEqual(self.node.get_parameter('from_value').value, 0.0) self.assertEqual(self.node.get_parameter('to_value').value, 10.0) self.assertEqual(self.node.get_parameter('in_range').value, 4.5) self.assertEqual(self.node.get_parameter('str_value').value, 'I am no float') self.assertAlmostEqual(self.node.get_parameter('int_value').value, 123) # Try to set a parameter out of range. result = self.node.set_parameters([Parameter('in_range', value=12.0)]) self.assertIsInstance(result, list) self.assertIsInstance(result[0], SetParametersResult) self.assertFalse(result[0].successful) self.assertEqual(self.node.get_parameter('in_range').value, 4.5) # Try to set a parameter out of range (bad step). result = self.node.set_parameters([Parameter('in_range', value=4.25)]) self.assertIsInstance(result, list) self.assertIsInstance(result[0], SetParametersResult) self.assertFalse(result[0].successful) self.assertEqual(self.node.get_parameter('in_range').value, 4.5) # From and to are always valid. # Parameters that don't comply with the description will raise an exception. fp_range = FloatingPointRange(from_value=-10.0, to_value=0.0, step=30.0) parameters = [ ('from_value_2', -10.0, ParameterDescriptor(floating_point_range=[fp_range])), ('to_value_2', 0.0, ParameterDescriptor(floating_point_range=[fp_range])), ('in_range_bad_step', -4.5, ParameterDescriptor(floating_point_range=[fp_range])), ('out_of_range', 30.0, ParameterDescriptor(floating_point_range=[fp_range])) ] with self.assertRaises(InvalidParameterValueException): self.node.declare_parameters('', parameters) self.assertAlmostEqual(self.node.get_parameter('from_value_2').value, -10.0) self.assertAlmostEqual(self.node.get_parameter('to_value_2').value, 0.0) self.assertFalse(self.node.has_parameter('in_range_bad_step')) self.assertFalse(self.node.has_parameter('out_of_range')) # Try some more parameters with no step. fp_range = FloatingPointRange(from_value=-10.0, to_value=10.0, step=0.0) parameters = [ ('from_value_no_step', -10.0, ParameterDescriptor(floating_point_range=[fp_range])), ('to_value_no_step', 10.0, ParameterDescriptor(floating_point_range=[fp_range])), ('in_range_no_step', 5.37, ParameterDescriptor(floating_point_range=[fp_range])), ] result = self.node.declare_parameters('', parameters) self.assertIsInstance(result, list) self.assertIsInstance(result[0], Parameter) self.assertIsInstance(result[1], Parameter) self.assertIsInstance(result[2], Parameter) self.assertAlmostEqual(result[0].value, -10.0) self.assertAlmostEqual(result[1].value, 10.0) self.assertAlmostEqual(result[2].value, 5.37) self.assertAlmostEqual(self.node.get_parameter('from_value_no_step').value, -10.0) self.assertAlmostEqual(self.node.get_parameter('to_value_no_step').value, 10.0) self.assertAlmostEqual(self.node.get_parameter('in_range_no_step').value, 5.37) def test_integer_range_descriptor(self) -> None: # OK cases; non-integers are not affected by the range. integer_range = IntegerRange(from_value=0, to_value=10, step=2) parameters = [ ('from_value', 0, ParameterDescriptor(integer_range=[integer_range])), ('to_value', 10, ParameterDescriptor(integer_range=[integer_range])), ('in_range', 4, ParameterDescriptor(integer_range=[integer_range])), ('str_value', 'I am no integer', ParameterDescriptor(integer_range=[integer_range])), ('float_value', 123.0, ParameterDescriptor(integer_range=[integer_range])) ] declared_parameters = self.node.declare_parameters('', parameters) self.assertIsInstance(declared_parameters, list) self.assertIsInstance(declared_parameters[0], Parameter) self.assertIsInstance(declared_parameters[1], Parameter) self.assertIsInstance(declared_parameters[2], Parameter) self.assertIsInstance(declared_parameters[3], Parameter) self.assertIsInstance(declared_parameters[4], Parameter) self.assertEqual(declared_parameters[0].value, 0) self.assertEqual(declared_parameters[1].value, 10) self.assertEqual(declared_parameters[2].value, 4) self.assertEqual(declared_parameters[3].value, 'I am no integer') self.assertAlmostEqual(declared_parameters[4].value, 123.0) self.assertEqual(self.node.get_parameter('from_value').value, 0) self.assertEqual(self.node.get_parameter('to_value').value, 10) self.assertEqual(self.node.get_parameter('in_range').value, 4) self.assertEqual(self.node.get_parameter('str_value').value, 'I am no integer') self.assertAlmostEqual(self.node.get_parameter('float_value').value, 123.0) # Try to set a parameter out of range. result = self.node.set_parameters([Parameter('in_range', value=12)]) self.assertIsInstance(result, list) self.assertIsInstance(result[0], SetParametersResult) self.assertFalse(result[0].successful) self.assertEqual(self.node.get_parameter('in_range').value, 4) # Try to set a parameter out of range (bad step). result = self.node.set_parameters([Parameter('in_range', value=5)]) self.assertIsInstance(result, list) self.assertIsInstance(result[0], SetParametersResult) self.assertFalse(result[0].successful) self.assertEqual(self.node.get_parameter('in_range').value, 4) # From and to are always valid. # Parameters that don't comply with the description will raise an exception. integer_range = IntegerRange(from_value=-10, to_value=0, step=30) parameters = [ ('from_value_2', -10, ParameterDescriptor(integer_range=[integer_range])), ('to_value_2', 0, ParameterDescriptor(integer_range=[integer_range])), ('in_range_bad_step', -4, ParameterDescriptor(integer_range=[integer_range])), ('out_of_range', 30, ParameterDescriptor(integer_range=[integer_range])) ] with self.assertRaises(InvalidParameterValueException): self.node.declare_parameters('', parameters) self.assertEqual(self.node.get_parameter('from_value_2').value, -10) self.assertEqual(self.node.get_parameter('to_value_2').value, 0) self.assertFalse(self.node.has_parameter('in_range_bad_step')) self.assertFalse(self.node.has_parameter('out_of_range')) # Try some more parameters with no step. integer_range = IntegerRange(from_value=-10, to_value=10, step=0) parameters = [ ('from_value_no_step', -10, ParameterDescriptor(integer_range=[integer_range])), ('to_value_no_step', 10, ParameterDescriptor(integer_range=[integer_range])), ('in_range_no_step', 5, ParameterDescriptor(integer_range=[integer_range])), ] result = self.node.declare_parameters('', parameters) self.assertIsInstance(result, list) self.assertIsInstance(result[0], Parameter) self.assertIsInstance(result[1], Parameter) self.assertIsInstance(result[2], Parameter) self.assertEqual(result[0].value, -10) self.assertEqual(result[1].value, 10) self.assertEqual(result[2].value, 5) self.assertEqual(self.node.get_parameter('from_value_no_step').value, -10) self.assertEqual(self.node.get_parameter('to_value_no_step').value, 10) self.assertEqual(self.node.get_parameter('in_range_no_step').value, 5) def test_static_dynamic_typing(self) -> None: parameters: List[Union[ Tuple[str, int], Tuple[str, None, ParameterDescriptor] ]] = [ ('int_param', 0), ('int_param_no_default', Parameter.Type.INTEGER), ('dynamic_param', None, ParameterDescriptor(dynamic_typing=True)), ] self.node.declare_parameters('', parameters) # Try getting parameters before setting values int_param = self.node.get_parameter('int_param') self.assertEqual(int_param.type_, Parameter.Type.INTEGER) self.assertEqual(int_param.value, 0) with pytest.raises(ParameterUninitializedException): self.node.get_parameter('int_param_no_default') self.assertEqual(self.node.get_parameter('dynamic_param').type_, Parameter.Type.NOT_SET) result = self.node.set_parameters([Parameter('int_param', value='asd')])[0] self.assertFalse(result.successful) self.assertTrue(result.reason.startswith('Wrong parameter type')) self.assertTrue(self.node.set_parameters([Parameter('int_param', value=3)])[0].successful) result = self.node.set_parameters([Parameter('int_param_no_default', value='asd')])[0] self.assertFalse(result.successful) self.assertTrue(result.reason.startswith('Wrong parameter type')) self.assertTrue( self.node.set_parameters([Parameter('int_param_no_default', value=3)])[0].successful) self.assertEqual(self.node.get_parameter('int_param_no_default').value, 3) result = self.node.set_parameters([Parameter('int_param_no_default', value=None)])[0] self.assertFalse(result.successful) self.assertTrue(result.reason.startswith('Static parameter cannot be undeclared')) self.assertTrue( self.node.set_parameters([Parameter('dynamic_param', value='asd')])[0].successful) self.assertTrue( self.node.set_parameters([Parameter('dynamic_param', value=3)])[0].successful) result = self.node.set_parameters_atomically([ Parameter('dynamic_param', value=3), Parameter('int_param', value='asd')]) self.assertFalse(result.successful) self.assertTrue(result.reason.startswith('Wrong parameter type')) self.assertTrue(self.node.set_parameters_atomically([ Parameter('dynamic_param', value=None), Parameter('int_param', value=4)]).successful) self.assertEqual(self.node.get_parameter('int_param').value, 4) self.assertFalse(self.node.has_parameter('dynamic_param')) def test_wait_for_node(self) -> None: node = rclpy.create_node( 'waiting_for_this_node', namespace=TEST_NAMESPACE, context=self.context) try: self.assertTrue(self.node.wait_for_node('/my_ns/waiting_for_this_node', 3.0)) finally: node.destroy_node() def test_wait_for_node_timeout(self) -> None: self.assertFalse(self.node.wait_for_node('node_does_not_exist', 0.1)) class TestCreateNode(unittest.TestCase): def test_use_global_arguments(self) -> None: context = rclpy.context.Context() rclpy.init( args=['process_name', '--ros-args', '-r', '__node:=global_node_name'], context=context ) try: node1 = rclpy.create_node( TEST_NODE, namespace=TEST_NAMESPACE, use_global_arguments=True, context=context) try: node2 = rclpy.create_node( TEST_NODE, namespace=TEST_NAMESPACE, use_global_arguments=False, context=context ) try: self.assertEqual('global_node_name', node1.get_name()) self.assertEqual(TEST_NODE, node2.get_name()) finally: node2.destroy_node() finally: node1.destroy_node() finally: rclpy.shutdown(context=context) def test_node_arguments(self) -> None: context = rclpy.context.Context() rclpy.init(context=context) try: node = rclpy.create_node( TEST_NODE, namespace=TEST_NAMESPACE, cli_args=['--ros-args', '-r', '__ns:=/foo/bar'], context=context ) try: self.assertEqual('/foo/bar', node.get_namespace()) finally: node.destroy_node() finally: rclpy.shutdown(context=context) def test_bad_node_arguments(self) -> None: context = rclpy.context.Context() rclpy.init(context=context) try: from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy invalid_ros_args_pattern = r'Failed to parse ROS arguments:.*not-a-remap.*' with self.assertRaisesRegex(_rclpy.RCLInvalidROSArgsError, invalid_ros_args_pattern): rclpy.create_node( TEST_NODE, namespace=TEST_NAMESPACE, cli_args=['--ros-args', '-r', 'not-a-remap'], context=context) unknown_ros_args_pattern = r'\[\'--my-custom-flag\'\]' with self.assertRaisesRegex(_rclpy.UnknownROSArgsError, unknown_ros_args_pattern): rclpy.create_node( TEST_NODE, namespace=TEST_NAMESPACE, cli_args=['--ros-args', '--my-custom-flag'], context=context) finally: rclpy.shutdown(context=context) def test_node_get_fully_qualified_name(self) -> None: context = rclpy.context.Context() rclpy.init(context=context) try: node = rclpy.create_node(TEST_NODE, namespace=TEST_NAMESPACE, context=context) try: assert node.get_fully_qualified_name() == '{}/{}'.format(TEST_NAMESPACE, TEST_NODE) finally: node.destroy_node() # When ns is not specified, a leading / should be added node_without_ns = rclpy.create_node(TEST_NODE, context=context) try: assert node_without_ns.get_fully_qualified_name() == '/' + TEST_NODE finally: node_without_ns.destroy_node() remapped_ns = '/another_ns' remapped_name = 'another_node' node_with_remapped_ns = rclpy.create_node( TEST_NODE, namespace=TEST_NAMESPACE, context=context, cli_args=['--ros-args', '-r', '__ns:=' + remapped_ns] ) try: expected_name = '{}/{}'.format(remapped_ns, TEST_NODE) assert node_with_remapped_ns.get_fully_qualified_name() == expected_name finally: node_with_remapped_ns.destroy_node() node_with_remapped_name = rclpy.create_node( TEST_NODE, namespace=TEST_NAMESPACE, context=context, cli_args=['--ros-args', '-r', '__node:=' + remapped_name] ) try: expected_name = '{}/{}'.format(TEST_NAMESPACE, remapped_name) assert node_with_remapped_name.get_fully_qualified_name() == expected_name finally: node_with_remapped_name.destroy_node() node_with_remapped_ns_name = rclpy.create_node( TEST_NODE, namespace=TEST_NAMESPACE, context=context, cli_args=[ '--ros-args', '-r', '__node:=' + remapped_name, '-r', '__ns:=' + remapped_ns] ) try: expected_name = '{}/{}'.format(remapped_ns, remapped_name) assert node_with_remapped_ns_name.get_fully_qualified_name() == expected_name finally: node_with_remapped_ns_name.destroy_node() finally: rclpy.shutdown(context=context) def test_node_get_fully_qualified_name_global_remap(self) -> None: g_context = rclpy.context.Context() global_remap_name = 'global_node_name' rclpy.init( args=['--ros-args', '-r', '__node:=' + global_remap_name], context=g_context, ) try: node_with_global_arguments = rclpy.create_node( TEST_NODE, namespace=TEST_NAMESPACE, context=g_context, ) try: expected_name = '{}/{}'.format(TEST_NAMESPACE, global_remap_name) assert node_with_global_arguments.get_fully_qualified_name() == expected_name finally: node_with_global_arguments.destroy_node() node_skip_global_params = rclpy.create_node( TEST_NODE, namespace=TEST_NAMESPACE, context=g_context, use_global_arguments=False ) try: expected_name = '{}/{}'.format(TEST_NAMESPACE, TEST_NODE) assert node_skip_global_params.get_fully_qualified_name() == expected_name finally: node_skip_global_params.destroy_node() finally: rclpy.shutdown(context=g_context) def test_no_use_sim_time(self) -> None: context = rclpy.context.Context() rclpy.init(context=context) try: no_sim_node = rclpy.create_node('test_node_no_sim', context=context) try: self.assertTrue(no_sim_node.has_parameter(USE_SIM_TIME_NAME)) self.assertFalse(no_sim_node.get_parameter(USE_SIM_TIME_NAME).value) finally: no_sim_node.destroy_node() finally: rclpy.shutdown(context=context) def test_use_sim_time(self) -> None: context = rclpy.context.Context() rclpy.init(context=context) try: sim_time_node = rclpy.create_node( 'test_node_sim', namespace=TEST_NAMESPACE, context=context, parameter_overrides=[ Parameter(USE_SIM_TIME_NAME, value=True), ], automatically_declare_parameters_from_overrides=False ) try: # use_sim_time is declared automatically; in this case using override value. self.assertTrue(sim_time_node.has_parameter(USE_SIM_TIME_NAME)) self.assertTrue(sim_time_node.get_parameter(USE_SIM_TIME_NAME).value) finally: sim_time_node.destroy_node() finally: rclpy.shutdown(context=context) def test_node_context_manager(self) -> None: context = rclpy.context.Context() rclpy.init(context=context) try: with rclpy.create_node('test_node_no_sim', context=context) as node: self.assertTrue(node.has_parameter(USE_SIM_TIME_NAME)) self.assertFalse(node.get_parameter(USE_SIM_TIME_NAME).value) finally: rclpy.shutdown(context=context) def test_node_resolve_name() -> None: context = rclpy.Context() rclpy.init( args=['--ros-args', '-r', 'foo:=bar'], context=context, ) try: node = rclpy.create_node( 'test_rclpy_node_resolve_name', namespace=TEST_NAMESPACE, context=context ) try: assert node.resolve_topic_name('foo') == '/my_ns/bar' assert node.resolve_topic_name('/abs') == '/abs' assert node.resolve_topic_name('foo', only_expand=True) == '/my_ns/foo' assert node.resolve_service_name('foo') == '/my_ns/bar' assert node.resolve_service_name('/abs') == '/abs' assert node.resolve_service_name('foo', only_expand=True) == '/my_ns/foo' finally: node.destroy_node() finally: rclpy.shutdown(context=context) class TestNodeParamsFile(unittest.TestCase): @classmethod def setUpClass(cls) -> None: rclpy.init() @classmethod def tearDownClass(cls) -> None: rclpy.shutdown() def test_node_ns_params_file_with_wildcards(self) -> None: node = rclpy.create_node( 'node2', namespace='/ns', cli_args=[ '--ros-args', '--params-file', str(TEST_RESOURCES_DIR / 'wildcards.yaml') ], automatically_declare_parameters_from_overrides=True) try: self.assertEqual('full_wild', node.get_parameter('full_wild').value) self.assertEqual('namespace_wild', node.get_parameter('namespace_wild').value) self.assertEqual( 'namespace_wild_another', node.get_parameter('namespace_wild_another').value) self.assertEqual( 'namespace_wild_one_star', node.get_parameter('namespace_wild_one_star').value) self.assertEqual('node_wild_in_ns', node.get_parameter('node_wild_in_ns').value) self.assertEqual( 'node_wild_in_ns_another', node.get_parameter('node_wild_in_ns_another').value) self.assertEqual('explicit_in_ns', node.get_parameter('explicit_in_ns').value) with self.assertRaises(ParameterNotDeclaredException): node.get_parameter('node_wild_no_ns') with self.assertRaises(ParameterNotDeclaredException): node.get_parameter('explicit_no_ns') with self.assertRaises(ParameterNotDeclaredException): node.get_parameter('should_not_appear') finally: node.destroy_node() def test_node_params_file_with_wildcards(self) -> None: node = rclpy.create_node( 'node2', cli_args=[ '--ros-args', '--params-file', str(TEST_RESOURCES_DIR / 'wildcards.yaml') ], automatically_declare_parameters_from_overrides=True) try: self.assertEqual('full_wild', node.get_parameter('full_wild').value) self.assertEqual('namespace_wild', node.get_parameter('namespace_wild').value) self.assertEqual( 'namespace_wild_another', node.get_parameter('namespace_wild_another').value) with self.assertRaises(ParameterNotDeclaredException): node.get_parameter('namespace_wild_one_star') with self.assertRaises(ParameterNotDeclaredException): node.get_parameter('node_wild_in_ns') with self.assertRaises(ParameterNotDeclaredException): node.get_parameter('node_wild_in_ns_another') with self.assertRaises(ParameterNotDeclaredException): node.get_parameter('explicit_in_ns') self.assertEqual('node_wild_no_ns', node.get_parameter('node_wild_no_ns').value) self.assertEqual('explicit_no_ns', node.get_parameter('explicit_no_ns').value) with self.assertRaises(ParameterNotDeclaredException): node.get_parameter('should_not_appear') finally: node.destroy_node() def test_node_ns_params_file_by_order(self) -> None: node = rclpy.create_node( 'node2', namespace='/ns', cli_args=[ '--ros-args', '--params-file', str(TEST_RESOURCES_DIR / 'params_by_order.yaml') ], automatically_declare_parameters_from_overrides=True) try: self.assertEqual('last_one_win', node.get_parameter('a_value').value) self.assertEqual('foo', node.get_parameter('foo').value) self.assertEqual('bar', node.get_parameter('bar').value) finally: node.destroy_node() def test_node_ns_params_file_with_complicated_wildcards(self) -> None: # regex matched: /**/foo/*/bar node = rclpy.create_node( 'node2', namespace='/a/b/c/foo/d/bar', cli_args=[ '--ros-args', '--params-file', str(TEST_RESOURCES_DIR / 'complicated_wildcards.yaml') ], automatically_declare_parameters_from_overrides=True) try: self.assertEqual('foo', node.get_parameter('foo').value) self.assertEqual('bar', node.get_parameter('bar').value) finally: node.destroy_node() if __name__ == '__main__': unittest.main()
rclpy
python
# Copyright 2024 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy from typing_extensions import TypeAlias ClockType: TypeAlias = _rclpy.ClockType
# Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import threading import time from typing import Generator import unittest from unittest.mock import Mock import pytest import rclpy from rclpy.clock import Clock from rclpy.clock import JumpHandle from rclpy.clock import JumpThreshold from rclpy.clock import ROSClock from rclpy.clock_type import ClockType from rclpy.context import Context from rclpy.duration import Duration from rclpy.exceptions import NotInitializedException from rclpy.time import Time from rclpy.utilities import get_default_context A_SMALL_AMOUNT_OF_TIME = Duration(seconds=0.5) def test_invalid_jump_threshold() -> None: with pytest.raises(ValueError, match='.*min_forward.*'): JumpThreshold( min_forward=Duration(nanoseconds=0), min_backward=Duration(nanoseconds=-1)) with pytest.raises(ValueError, match='.*min_forward.*'): JumpThreshold( min_forward=Duration(nanoseconds=-1), min_backward=Duration(nanoseconds=-1)) with pytest.raises(ValueError, match='.*min_backward.*'): JumpThreshold( min_forward=Duration(nanoseconds=1), min_backward=Duration(nanoseconds=0)) with pytest.raises(ValueError, match='.*min_backward.*'): JumpThreshold( min_forward=Duration(nanoseconds=1), min_backward=Duration(nanoseconds=1)) with pytest.raises(ValueError, match='.*must be enabled.*'): JumpThreshold( min_forward=None, min_backward=None, on_clock_change=False) class TestClock(unittest.TestCase): def test_clock_construction(self) -> None: clock = Clock() with self.assertRaises(TypeError): clock = Clock(clock_type='STEADY_TIME') # type: ignore[call-overload] clock = Clock(clock_type=ClockType.STEADY_TIME) assert clock.clock_type == ClockType.STEADY_TIME clock = Clock(clock_type=ClockType.SYSTEM_TIME) assert clock.clock_type == ClockType.SYSTEM_TIME # A subclass ROSClock is returned if ROS_TIME is specified. clock = Clock(clock_type=ClockType.ROS_TIME) assert clock.clock_type == ClockType.ROS_TIME assert isinstance(clock, ROSClock) # Direct instantiation of a ROSClock is also possible. clock = ROSClock() assert clock.clock_type == ClockType.ROS_TIME def test_clock_now(self) -> None: # System time should be roughly equal to time.time() # There will still be differences between them, with the bound depending on the scheduler. clock = Clock(clock_type=ClockType.SYSTEM_TIME) now = clock.now() python_time_sec = time.time() assert isinstance(now, Time) assert abs(now.nanoseconds * 1e-9 - python_time_sec) < 5 # Unless there is a date change during the test, system time have increased between these # calls. now2 = clock.now() assert now2 > now # Steady time should always return increasing values clock = Clock(clock_type=ClockType.STEADY_TIME) now = clock.now() now2 = now for i in range(10): now2 = clock.now() assert now2 > now now = now2 def test_ros_time_is_active(self) -> None: clock = ROSClock() clock._set_ros_time_is_active(True) assert clock.ros_time_is_active clock._set_ros_time_is_active(False) assert not clock.ros_time_is_active def test_triggered_time_jump_callbacks(self) -> None: one_second = Duration(seconds=1) half_second = Duration(seconds=0.5) negative_half_second = Duration(seconds=-0.5) negative_one_second = Duration(seconds=-1) threshold1 = JumpThreshold( min_forward=one_second, min_backward=negative_half_second, on_clock_change=False) threshold2 = JumpThreshold( min_forward=half_second, min_backward=negative_one_second, on_clock_change=False) pre_callback1 = Mock() post_callback1 = Mock() pre_callback2 = Mock() post_callback2 = Mock() clock = ROSClock() handler1 = clock.create_jump_callback( threshold1, pre_callback=pre_callback1, post_callback=post_callback1) handler2 = clock.create_jump_callback( threshold2, pre_callback=pre_callback2, post_callback=post_callback2) clock.set_ros_time_override(Time(seconds=1)) clock._set_ros_time_is_active(True) pre_callback1.assert_not_called() post_callback1.assert_not_called() pre_callback2.assert_not_called() post_callback2.assert_not_called() # forward jump clock.set_ros_time_override(Time(seconds=1.75)) pre_callback1.assert_not_called() post_callback1.assert_not_called() pre_callback2.assert_called() post_callback2.assert_called() pre_callback1.reset_mock() post_callback1.reset_mock() pre_callback2.reset_mock() post_callback2.reset_mock() # backwards jump clock.set_ros_time_override(Time(seconds=1)) pre_callback1.assert_called() post_callback1.assert_called() pre_callback2.assert_not_called() post_callback2.assert_not_called() handler1.unregister() handler2.unregister() def test_triggered_clock_change_callbacks(self) -> None: one_second = Duration(seconds=1) negative_one_second = Duration(seconds=-1) threshold1 = JumpThreshold( min_forward=one_second, min_backward=negative_one_second, on_clock_change=False) threshold2 = JumpThreshold(min_forward=None, min_backward=None, on_clock_change=True) threshold3 = JumpThreshold( min_forward=one_second, min_backward=negative_one_second, on_clock_change=True) pre_callback1 = Mock() post_callback1 = Mock() pre_callback2 = Mock() post_callback2 = Mock() pre_callback3 = Mock() post_callback3 = Mock() clock = ROSClock() handler1 = clock.create_jump_callback( threshold1, pre_callback=pre_callback1, post_callback=post_callback1) handler2 = clock.create_jump_callback( threshold2, pre_callback=pre_callback2, post_callback=post_callback2) handler3 = clock.create_jump_callback( threshold3, pre_callback=pre_callback3, post_callback=post_callback3) clock._set_ros_time_is_active(True) pre_callback1.assert_not_called() post_callback1.assert_not_called() pre_callback2.assert_called() post_callback2.assert_called() pre_callback3.assert_called() post_callback3.assert_called() pre_callback1.reset_mock() post_callback1.reset_mock() pre_callback2.reset_mock() post_callback2.reset_mock() pre_callback3.reset_mock() post_callback3.reset_mock() clock._set_ros_time_is_active(True) pre_callback1.assert_not_called() post_callback1.assert_not_called() pre_callback2.assert_not_called() post_callback2.assert_not_called() pre_callback3.assert_not_called() post_callback3.assert_not_called() handler1.unregister() handler2.unregister() handler3.unregister() @pytest.fixture() def default_context() -> Generator[Context, None, None]: rclpy.init() yield get_default_context() rclpy.shutdown() @pytest.fixture() def non_default_context() -> Generator[Context, None, None]: context = Context() context.init() yield context context.try_shutdown() def test_sleep_until_mismatched_clock_type(default_context: Context) -> None: clock = Clock(clock_type=ClockType.SYSTEM_TIME) with pytest.raises(ValueError, match='.*clock type does not match.*'): clock.sleep_until(Time(clock_type=ClockType.STEADY_TIME)) def test_sleep_until_non_default_context(non_default_context: Context) -> None: clock = Clock() assert clock.sleep_until(clock.now() + Duration(seconds=0.1), context=non_default_context) def test_sleep_for_non_default_context(non_default_context: Context) -> None: clock = Clock() assert clock.sleep_for(Duration(seconds=0.1), context=non_default_context) def test_sleep_until_invalid_context() -> None: clock = Clock() with pytest.raises(NotInitializedException): clock.sleep_until(clock.now() + Duration(seconds=0.1), context=Context()) def test_sleep_for_invalid_context() -> None: clock = Clock() with pytest.raises(NotInitializedException): clock.sleep_for(Duration(seconds=0.1), context=Context()) @pytest.mark.parametrize( 'clock_type', (ClockType.SYSTEM_TIME, ClockType.STEADY_TIME, ClockType.ROS_TIME)) def test_sleep_until_basic(default_context: Context, clock_type: ClockType) -> None: clock = Clock(clock_type=clock_type) sleep_duration = Duration(seconds=0.1) start = clock.now() assert clock.sleep_until(clock.now() + sleep_duration) stop = clock.now() assert stop - start >= sleep_duration @pytest.mark.parametrize( 'clock_type', (ClockType.SYSTEM_TIME, ClockType.STEADY_TIME, ClockType.ROS_TIME)) def test_sleep_for_basic(default_context: Context, clock_type: ClockType) -> None: clock = Clock(clock_type=clock_type) sleep_duration = Duration(seconds=0.1) start = clock.now() assert clock.sleep_for(sleep_duration) stop = clock.now() assert stop - start >= sleep_duration @pytest.mark.parametrize( 'clock_type', (ClockType.SYSTEM_TIME, ClockType.STEADY_TIME, ClockType.ROS_TIME)) def test_sleep_until_time_in_past(default_context: Context, clock_type: ClockType) -> None: clock = Clock(clock_type=clock_type) sleep_duration = Duration(seconds=-1) start = clock.now() assert clock.sleep_until(clock.now() + sleep_duration) stop = clock.now() assert stop - start < A_SMALL_AMOUNT_OF_TIME @pytest.mark.parametrize( 'clock_type', (ClockType.SYSTEM_TIME, ClockType.STEADY_TIME, ClockType.ROS_TIME)) def test_sleep_for_negative_duration(default_context: Context, clock_type: ClockType) -> None: clock = Clock(clock_type=clock_type) sleep_duration = Duration(seconds=-1) start = clock.now() assert clock.sleep_for(sleep_duration) stop = clock.now() assert stop - start < A_SMALL_AMOUNT_OF_TIME @pytest.mark.parametrize('ros_time_enabled', (True, False)) def test_sleep_until_ros_time_toggled(default_context: Context, ros_time_enabled: bool) -> None: clock = ROSClock() clock._set_ros_time_is_active(not ros_time_enabled) retval = None def run() -> None: nonlocal retval retval = clock.sleep_until(clock.now() + Duration(seconds=10)) t = threading.Thread(target=run) t.start() # wait for thread to get inside sleep_until call time.sleep(0.2) clock._set_ros_time_is_active(ros_time_enabled) # wait for thread to exit start = clock.now() t.join() stop = clock.now() assert stop - start < A_SMALL_AMOUNT_OF_TIME assert retval is False @pytest.mark.parametrize('ros_time_enabled', (True, False)) def test_sleep_for_ros_time_toggled(default_context: Context, ros_time_enabled: bool) -> None: clock = ROSClock() clock._set_ros_time_is_active(not ros_time_enabled) retval = None def run() -> None: nonlocal retval retval = clock.sleep_for(Duration(seconds=10)) t = threading.Thread(target=run) t.start() # wait for thread to get inside sleep_for call time.sleep(0.2) clock._set_ros_time_is_active(ros_time_enabled) # wait for thread to exit start = clock.now() t.join() stop = clock.now() assert stop - start < A_SMALL_AMOUNT_OF_TIME assert retval is False def test_sleep_until_context_shut_down(non_default_context: Context) -> None: clock = Clock() retval = None def run() -> None: nonlocal retval retval = clock.sleep_until( clock.now() + Duration(seconds=10), context=non_default_context) t = threading.Thread(target=run) t.start() # wait for thread to get inside sleep_until call time.sleep(0.2) non_default_context.shutdown() # wait for thread to exit start = clock.now() t.join() stop = clock.now() assert stop - start < A_SMALL_AMOUNT_OF_TIME assert retval is False def test_sleep_for_context_shut_down(non_default_context: Context) -> None: clock = Clock() retval = None def run() -> None: nonlocal retval retval = clock.sleep_for(Duration(seconds=10), context=non_default_context) t = threading.Thread(target=run) t.start() # wait for thread to get inside sleep_for call time.sleep(0.2) non_default_context.shutdown() # wait for thread to exit start = clock.now() t.join() stop = clock.now() assert stop - start < A_SMALL_AMOUNT_OF_TIME assert retval is False def test_sleep_until_ros_time_enabled(default_context: Context) -> None: clock = ROSClock() clock._set_ros_time_is_active(True) start_time = Time(seconds=1, clock_type=ClockType.ROS_TIME) stop_time = start_time + Duration(seconds=10) clock.set_ros_time_override(start_time) retval = None def run() -> None: nonlocal retval retval = clock.sleep_until(stop_time) t = threading.Thread(target=run) t.start() # wait for thread to get inside sleep_until call time.sleep(0.2) clock.set_ros_time_override(stop_time) # wait for thread to exit start = clock.now() t.join() stop = clock.now() assert stop - start < A_SMALL_AMOUNT_OF_TIME assert retval def test_sleep_for_ros_time_enabled(default_context: Context) -> None: clock = ROSClock() clock._set_ros_time_is_active(True) start_time = Time(seconds=1, clock_type=ClockType.ROS_TIME) sleep_duration = Duration(seconds=10) stop_time = start_time + sleep_duration clock.set_ros_time_override(start_time) retval = None def run() -> None: nonlocal retval retval = clock.sleep_for(sleep_duration) t = threading.Thread(target=run) t.start() # wait for thread to get inside sleep_for call time.sleep(0.2) clock.set_ros_time_override(stop_time) # wait for thread to exit start = clock.now() t.join() stop = clock.now() assert stop - start < A_SMALL_AMOUNT_OF_TIME assert retval def test_with_jump_handle() -> None: clock = ROSClock() clock._set_ros_time_is_active(False) post_callback = Mock() threshold = JumpThreshold(min_forward=None, min_backward=None, on_clock_change=True) with clock.create_jump_callback(threshold, post_callback=post_callback) as jump_handler: assert isinstance(jump_handler, JumpHandle) clock._set_ros_time_is_active(True) post_callback.assert_called_once() post_callback.reset_mock() clock._set_ros_time_is_active(False) post_callback.assert_not_called()
rclpy
python
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Literal from rclpy.exceptions import InvalidServiceNameException from rclpy.exceptions import InvalidTopicNameException from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy def validate_full_topic_name(name: str, *, is_service: bool = False) -> Literal[True]: """ Validate a given topic or service name, and raise an exception if invalid. The name must be fully-qualified and already expanded. If the name is invalid then rclpy.exceptions.InvalidTopicNameException will be raised. :param name: topic or service name to be validated :param is_service: if true, InvalidServiceNameException is raised :returns: True when it is valid :raises: InvalidTopicNameException: when the name is invalid """ result = _rclpy.rclpy_get_validation_error_for_full_topic_name(name) if result is None: return True error_msg, invalid_index = result if is_service: raise InvalidServiceNameException(name, error_msg, invalid_index) else: raise InvalidTopicNameException(name, error_msg, invalid_index)
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from rclpy.exceptions import InvalidServiceNameException from rclpy.exceptions import InvalidTopicNameException from rclpy.validate_full_topic_name import validate_full_topic_name class TestValidateFullTopicName(unittest.TestCase): def test_validate_full_topic_name(self) -> None: tests = [ '/chatter', '/node_name/chatter', '/ns/node_name/chatter', ] for topic in tests: # Will raise if invalid validate_full_topic_name(topic) def test_validate_full_topic_name_failures(self) -> None: # topic name may not contain '?' with self.assertRaisesRegex(InvalidTopicNameException, 'must not contain characters'): validate_full_topic_name('/invalid_topic?') # topic name must start with / with self.assertRaisesRegex(InvalidTopicNameException, 'must be absolute'): validate_full_topic_name('invalid_topic') def test_validate_full_topic_name_failures_services(self) -> None: # service name may not contain '?' with self.assertRaisesRegex(InvalidServiceNameException, 'must not contain characters'): validate_full_topic_name('/invalid_service?', is_service=True) # service name must start with / with self.assertRaisesRegex(InvalidServiceNameException, 'must be absolute'): validate_full_topic_name('invalid_service', is_service=True) if __name__ == '__main__': unittest.main()
rclpy
python
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Literal from rclpy.exceptions import InvalidNodeNameException from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy def validate_node_name(node_name: str) -> Literal[True]: """ Validate a given node_name, and raise an exception if it is invalid. If the node_name is invalid then rclpy.exceptions.InvalidNodeNameException will be raised. :param node_name: node_name to be validated :returns: True when it is valid :raises: InvalidNodeNameException: when the node_name is invalid """ result = _rclpy.rclpy_get_validation_error_for_node_name(node_name) if result is None: return True error_msg, invalid_index = result raise InvalidNodeNameException(node_name, error_msg, invalid_index)
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from rclpy.exceptions import InvalidNodeNameException from rclpy.validate_node_name import validate_node_name class TestValidateNodeName(unittest.TestCase): def test_validate_node_name(self) -> None: tests = [ 'my_node', ] for topic in tests: # Will raise if invalid validate_node_name(topic) def test_validate_node_name_failures(self) -> None: # node name must not be empty with self.assertRaisesRegex(InvalidNodeNameException, 'must not be empty'): validate_node_name('') # node name may not contain '.' with self.assertRaisesRegex(InvalidNodeNameException, 'must not contain characters'): validate_node_name('invalid_node.') # node name may not contain '?' with self.assertRaisesRegex(InvalidNodeNameException, 'must not contain characters'): validate_node_name('invalid_node?') # node name must not contain / with self.assertRaisesRegex(InvalidNodeNameException, 'must not contain characters'): validate_node_name('/invalid_node') if __name__ == '__main__': unittest.main()
rclpy
python
# Copyright 2022 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time from typing import Any, Callable, List, Optional, Sequence, Union from rcl_interfaces.msg import Parameter as ParameterMsg from rcl_interfaces.msg import ParameterEvent from rcl_interfaces.srv import DescribeParameters from rcl_interfaces.srv import GetParameters from rcl_interfaces.srv import GetParameterTypes from rcl_interfaces.srv import ListParameters from rcl_interfaces.srv import SetParameters from rcl_interfaces.srv import SetParametersAtomically from rclpy.callback_groups import CallbackGroup from rclpy.client import Client from rclpy.event_handler import SubscriptionEventCallbacks from rclpy.node import Node from rclpy.parameter import Parameter as Parameter from rclpy.parameter import parameter_dict_from_yaml_file from rclpy.qos import qos_profile_parameter_events from rclpy.qos import qos_profile_services_default from rclpy.qos import QoSProfile from rclpy.qos_overriding_options import QoSOverridingOptions from rclpy.subscription import MessageInfo from rclpy.subscription import Subscription from rclpy.task import Future class AsyncParameterClient: def __init__( self, node: Node, remote_node_name: str, qos_profile: QoSProfile = qos_profile_services_default, callback_group: Optional[CallbackGroup] = None, ) -> None: """ Create an AsyncParameterClient. An AsyncParameterClient that uses services offered by a remote node to query and modify parameters in a streamlined way. Usage example: .. code-block:: python import rclpy from rclpy.parameter import Parameter node = rclpy.create_node('my_node') client = AsyncParameterClient(node, 'example_node') # set parameters on example node future = client.set_parameters([ Parameter('int_param', Parameter.Type.INTEGER, 88), Parameter('string/param', Parameter.Type.STRING, 'hello world').to_parameter_msg(), ]) self.executor.spin_until_future_complete(future) results = future.result() # rcl_interfaces.srv.SetParameters.Response For more on service names, see: `ROS 2 docs`_. .. _ROS 2 docs: https://docs.ros.org/en/rolling/Concepts/About-ROS-2-Parameters.html#interacting-with-parameters # noqa E501 :param node: Node used to create clients that will interact with the remote node :param remote_node_name: Name of remote node for which the parameters will be managed """ self.remote_node_name = remote_node_name self.node = node self._get_parameter_client: Client[GetParameters.Request, GetParameters.Response] = self.node.create_client( GetParameters, f'{remote_node_name}/get_parameters', qos_profile=qos_profile, callback_group=callback_group ) self._list_parameter_client: Client[ListParameters.Request, ListParameters.Response] = self.node.create_client( ListParameters, f'{remote_node_name}/list_parameters', qos_profile=qos_profile, callback_group=callback_group ) self._set_parameter_client: Client[SetParameters.Request, SetParameters.Response] = self.node.create_client( SetParameters, f'{remote_node_name}/set_parameters', qos_profile=qos_profile, callback_group=callback_group ) self._get_parameter_types_client: Client[GetParameterTypes.Request, GetParameterTypes.Response] = \ self.node.create_client( GetParameterTypes, f'{remote_node_name}/get_parameter_types', qos_profile=qos_profile, callback_group=callback_group ) self._describe_parameters_client: Client[DescribeParameters.Request, DescribeParameters.Response] = \ self.node.create_client( DescribeParameters, f'{remote_node_name}/describe_parameters', qos_profile=qos_profile, callback_group=callback_group ) self._set_parameters_atomically_client: Client[SetParametersAtomically.Request, SetParametersAtomically.Response] = \ self.node.create_client( SetParametersAtomically, f'{remote_node_name}/set_parameters_atomically', qos_profile=qos_profile, callback_group=callback_group ) def services_are_ready(self) -> bool: """ Check if all services are ready. :return: ``True`` if all services are available, False otherwise. """ return all([ self._list_parameter_client.service_is_ready(), self._set_parameter_client.service_is_ready(), self._get_parameter_client.service_is_ready(), self._get_parameter_types_client.service_is_ready(), self._describe_parameters_client.service_is_ready(), self._set_parameters_atomically_client.service_is_ready(), ]) def wait_for_services(self, timeout_sec: Optional[float] = None) -> bool: """ Wait for all parameter services to be available. :param timeout_sec: Seconds to wait. If ``None``, then wait forever. :return: ``True`` if all services becomes available, ``False`` otherwise. """ # TODO(ihasdapie) See: rclpy.Client.wait_for_service sleep_time = 0.25 if timeout_sec is None: timeout_sec = float('inf') while not self.services_are_ready() and timeout_sec > 0.0: time.sleep(sleep_time) timeout_sec -= sleep_time return self.services_are_ready() def list_parameters( self, prefixes: Optional[List[str]] = None, depth: Optional[int] = None, callback: Optional[Callable[[Future[ListParameters.Response]], None]] = None ) -> Future[ListParameters.Response]: """ List all parameters with given prefixes. :param prefixes: List of prefixes to filter by. :param depth: Depth of the parameter tree to list. ``None`` means unlimited. :param callback: Callback function to call when the request is complete. :return: ``Future`` with the result of the request. """ request = ListParameters.Request() if prefixes: request.prefixes = prefixes if depth: request.depth = depth future = self._list_parameter_client.call_async(request) if callback: future.add_done_callback(callback) return future def get_parameters(self, names: List[str], callback: Optional[Callable[[Future[GetParameters.Response]], None]] = None ) -> Future[GetParameters.Response]: """ Get parameters given names. :param names: List of parameter names to get. :param callback: Callback function to call when the request is complete. :return: ``Future`` with the result of the request. """ request = GetParameters.Request() request.names = names future = self._get_parameter_client.call_async(request) if callback: future.add_done_callback(callback) return future def set_parameters( self, parameters: Sequence[Union[Parameter[Any], ParameterMsg]], callback: Optional[Callable[[Future[SetParameters.Response]], None]] = None ) -> Future[SetParameters.Response]: """ Set parameters given a list of parameters. The result after the returned future is complete will be of type ``rcl_interfaces.srv.SetParameters.Response``. :param parameters: Sequence of parameters to set. :param callback: Callback function to call when the request is complete. :return: ``Future`` with the result of the request. """ request = SetParameters.Request() request.parameters = [ param.to_parameter_msg() if isinstance(param, Parameter) else param for param in parameters ] future = self._set_parameter_client.call_async(request) if callback: future.add_done_callback(callback) return future def describe_parameters( self, names: List[str], callback: Optional[Callable[[Future[DescribeParameters.Response]], None]] = None ) -> Future[DescribeParameters.Response]: """ Describe parameters given names. The result after the returned future is complete will be of type ``rcl_interfaces.srv.DescribeParameters.Response``. :param names: List of parameter names to describe :param callback: Callback function to call when the request is complete. :return: ``Future`` with the result of the request. """ request = DescribeParameters.Request() request.names = names future = self._describe_parameters_client.call_async(request) if callback: future.add_done_callback(callback) return future def get_parameter_types( self, names: List[str], callback: Optional[Callable[[Future[GetParameterTypes.Response]], None]] = None ) -> Future[GetParameterTypes.Response]: """ Get parameter types given names. The result after the returned future is complete will be of type ``rcl_interfaces.srv.GetParameterTypes.Response``. Parameter type definitions are given in Parameter.Type :param names: List of parameter names to get types for. :param callback: Callback function to call when the request is complete. :return: ``Future`` with the result of the request. """ request = GetParameterTypes.Request() request.names = names future = self._get_parameter_types_client.call_async(request) if callback: future.add_done_callback(callback) return future def set_parameters_atomically( self, parameters: Sequence[Union[Parameter[Any], ParameterMsg]], callback: Optional[Callable[[Future[SetParametersAtomically.Response]], None]] = None ) -> Future[SetParametersAtomically.Response]: """ Set parameters atomically. The result after the returned future is complete will be of type ``rcl_interfaces.srv.SetParametersAtomically.Response``. :param parameters: Sequence of parameters to set. :param callback: Callback function to call when the request is complete. :return: ``Future`` with the result of the request. """ request = SetParametersAtomically.Request() request.parameters = [ param.to_parameter_msg() if isinstance(param, Parameter) else param for param in parameters ] future = self._set_parameters_atomically_client.call_async(request) if callback: future.add_done_callback(callback) return future def delete_parameters( self, names: List[str], callback: Optional[Callable[[Future[SetParameters.Response]], None]] = None ) -> Future[SetParameters.Response]: """ Unset parameters with given names. The result after the returned future is complete will be of type ``rcl_interfaces.srv.SetParameters.Response``. Note: Only parameters that have been declared as dynamically typed can be unset. :param names: List of parameter names to unset. :param callback: Callback function to call when the request is complete. :return: ``Future`` with the result of the request. """ request = SetParameters.Request() request.parameters = [Parameter(name=i).to_parameter_msg() for i in names] future = self._set_parameter_client.call_async(request) if callback: future.add_done_callback(callback) return future def load_parameter_file( self, parameter_file: str, use_wildcard: bool = False, callback: Optional[Callable[[Future[SetParameters.Response]], None]] = None ) -> Future[SetParameters.Response]: """ Load parameters from a yaml file. Wrapper around `rclpy.parameter.parameter_dict_from_yaml_file`. The result after the returned future is complete will be of type ``rcl_interfaces.srv.SetParameters.Response``. :param parameter_file: Path to the parameter file. :param use_wildcard: Whether to use wildcard expansion. :return: Future with the result from the set_parameters call. """ param_dict = parameter_dict_from_yaml_file( parameter_file, use_wildcard, target_nodes=[self.remote_node_name]) future = self.set_parameters(list(param_dict.values()), callback=callback) return future def load_parameter_file_atomically( self, parameter_file: str, use_wildcard: bool = False, callback: Optional[Callable[[Future[SetParametersAtomically.Response]], None]] = None ) -> Future[SetParametersAtomically.Response]: """ Load parameters from a yaml file atomically. Wrapper around `rclpy.parameter.parameter_dict_from_yaml_file`. The result after the returned future is complete will be of type ``rcl_interfaces.srv.SetParametersAtomically.Response``. :param parameter_file: Path to the parameter file. :param use_wildcard: Whether to use wildcard expansion. :return: Future with the result from the set_parameters_atomically call. """ param_dict = parameter_dict_from_yaml_file( parameter_file, use_wildcard, target_nodes=[self.remote_node_name]) future = self.set_parameters_atomically(list(param_dict.values()), callback=callback) return future def on_parameter_event( self, callback: Union[Callable[[ParameterEvent], None], Callable[[ParameterEvent, MessageInfo], None]], qos_profile: QoSProfile = qos_profile_parameter_events, *, callback_group: Optional[CallbackGroup] = None, event_callbacks: Optional[SubscriptionEventCallbacks] = None, qos_overriding_options: Optional[QoSOverridingOptions] = None, raw: bool = False ) -> Subscription[ParameterEvent]: return self.node.create_subscription( ParameterEvent, '/parameter_events', callback, qos_profile, callback_group=callback_group, event_callbacks=event_callbacks, qos_overriding_options=qos_overriding_options, raw=raw)
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import platform import threading import time import traceback from typing import List from typing import Optional from typing import Tuple from typing import TYPE_CHECKING import unittest from unittest.mock import Mock from rcl_interfaces.srv import GetParameters import rclpy from rclpy.client import Client import rclpy.context import rclpy.executors import rclpy.node from rclpy.service import Service from rclpy.utilities import get_rmw_implementation_identifier from test_msgs.srv import Empty from typing_extensions import TypeAlias # TODO(sloretz) Reduce fudge once wait_for_service uses node graph events TIME_FUDGE = 0.3 ClientGetParameters: TypeAlias = Client[GetParameters.Request, GetParameters.Response] ServiceGetParameters: TypeAlias = Service[GetParameters.Request, GetParameters.Response] TestServiceName: TypeAlias = List[Tuple[str, Optional[str], Optional[List[str]], str]] class TestClient(unittest.TestCase): if TYPE_CHECKING: context: rclpy.context.Context node: rclpy.node.Node @classmethod def setUpClass(cls) -> None: cls.context = rclpy.context.Context() rclpy.init(context=cls.context) cls.node = rclpy.create_node('TestClient', context=cls.context) @classmethod def tearDownClass(cls) -> None: cls.node.destroy_node() rclpy.shutdown(context=cls.context) @classmethod def do_test_service_name(cls, test_service_name_list: TestServiceName) -> None: for service_name, ns, cli_args, target_service_name in test_service_name_list: node = rclpy.create_node( node_name='node_name', context=cls.context, namespace=ns, cli_args=cli_args, start_parameter_services=False) client: Client[Empty.Request, Empty.Response] = node.create_client( srv_type=Empty, srv_name=service_name ) assert client.service_name == target_service_name client.destroy() node.destroy_node() @staticmethod def _spin_rclpy_node( rclpy_node: rclpy.node.Node, rclpy_executor: rclpy.executors.SingleThreadedExecutor ) -> None: try: rclpy_executor.spin() except rclpy.executors.ExternalShutdownException: pass except Exception as err: traceback.print_exc() print(rclpy_node.get_name() + ': ' + str(err)) print(rclpy_node.get_name() + ': rclpy_node exit') # rclpy_node.destroy_node() def test_wait_for_service_5sec(self) -> None: cli: ClientGetParameters = self.node.create_client(GetParameters, 'get/parameters') try: start = time.monotonic() self.assertFalse(cli.wait_for_service(timeout_sec=5.0)) end = time.monotonic() self.assertGreater(5.0, end - start - TIME_FUDGE) self.assertLess(5.0, end - start + TIME_FUDGE) finally: self.node.destroy_client(cli) def test_wait_for_service_nowait(self) -> None: cli: ClientGetParameters = self.node.create_client(GetParameters, 'get/parameters') try: start = time.monotonic() self.assertFalse(cli.wait_for_service(timeout_sec=0)) end = time.monotonic() self.assertGreater(0, end - start - TIME_FUDGE) self.assertLess(0, end - start + TIME_FUDGE) finally: self.node.destroy_client(cli) def test_wait_for_service_exists(self) -> None: cli: ClientGetParameters = self.node.create_client(GetParameters, 'test_wfs_exists') srv: ServiceGetParameters = self.node.create_service(GetParameters, 'test_wfs_exists', lambda request, response: None) try: start = time.monotonic() self.assertTrue(cli.wait_for_service(timeout_sec=1.0)) end = time.monotonic() self.assertGreater(0, end - start - TIME_FUDGE) self.assertLess(0, end - start + TIME_FUDGE) finally: self.node.destroy_client(cli) self.node.destroy_service(srv) def test_concurrent_calls_to_service(self) -> None: cli: ClientGetParameters = self.node.create_client(GetParameters, 'get/parameters') srv: ServiceGetParameters = self.node.create_service( GetParameters, 'get/parameters', lambda request, response: response) try: self.assertTrue(cli.wait_for_service(timeout_sec=20)) future1 = cli.call_async(GetParameters.Request()) future2 = cli.call_async(GetParameters.Request()) executor = rclpy.executors.SingleThreadedExecutor(context=self.context) rclpy.spin_until_future_complete(self.node, future1, executor=executor) rclpy.spin_until_future_complete(self.node, future2, executor=executor) self.assertTrue(future1.result() is not None) self.assertTrue(future2.result() is not None) finally: self.node.destroy_client(cli) self.node.destroy_service(srv) @unittest.skipIf( get_rmw_implementation_identifier() == 'rmw_connextdds' and platform.system() == 'Windows', reason='Source timestamp not implemented for Connext on Windows') def test_service_timestamps(self) -> None: cli: ClientGetParameters = self.node.create_client(GetParameters, 'get/parameters') srv: ServiceGetParameters = self.node.create_service( GetParameters, 'get/parameters', lambda request, response: response) try: self.assertTrue(cli.wait_for_service(timeout_sec=20)) cli.call_async(GetParameters.Request()) for i in range(5): with srv.handle: result = srv.handle.service_take_request(srv.srv_type.Request) if result != (None, None): request, header = result assert header is not None self.assertTrue(header is not None) self.assertNotEqual(0, header.source_timestamp) return else: time.sleep(0.2) self.fail('Did not get a request in time') finally: self.node.destroy_client(cli) self.node.destroy_service(srv) def test_different_type_raises(self) -> None: cli: ClientGetParameters = self.node.create_client(GetParameters, 'get/parameters') srv: ServiceGetParameters = self.node.create_service( GetParameters, 'get/parameters', lambda request, response: 'different response type') try: with self.assertRaises(TypeError): cli.call('different request type') with self.assertRaises(TypeError): cli.call_async('different request type') self.assertTrue(cli.wait_for_service(timeout_sec=20)) future = cli.call_async(GetParameters.Request()) executor = rclpy.executors.SingleThreadedExecutor(context=self.context) with self.assertRaises(TypeError): rclpy.spin_until_future_complete(self.node, future, executor=executor) finally: self.node.destroy_client(cli) self.node.destroy_service(srv) def test_get_service_name(self) -> None: test_service_name_list: TestServiceName = [ # test_service_name, namespace, cli_args for remap, expected service name # No namespaces ('service', None, None, '/service'), ('example/service', None, None, '/example/service'), # Using service names with namespaces ('service', 'ns', None, '/ns/service'), ('example/service', 'ns', None, '/ns/example/service'), ('example/service', 'my/ns', None, '/my/ns/example/service'), ('example/service', '/my/ns', None, '/my/ns/example/service'), # Global service name ('/service', 'ns', None, '/service'), ('/example/service', 'ns', None, '/example/service') ] TestClient.do_test_service_name(test_service_name_list) def test_get_service_name_after_remapping(self) -> None: test_service_name_list: TestServiceName = [ ('service', None, ['--ros-args', '--remap', 'service:=new_service'], '/new_service'), ('service', 'ns', ['--ros-args', '--remap', 'service:=new_service'], '/ns/new_service'), ('service', 'ns', ['--ros-args', '--remap', 'service:=example/new_service'], '/ns/example/new_service'), ('example/service', 'ns', ['--ros-args', '--remap', 'example/service:=new_service'], '/ns/new_service') ] TestClient.do_test_service_name(test_service_name_list) def test_sync_call(self) -> None: def _service(request: GetParameters.Request, response: GetParameters.Response) -> GetParameters.Response: return response cli: ClientGetParameters = self.node.create_client(GetParameters, 'get/parameters') srv = self.node.create_service(GetParameters, 'get/parameters', _service) try: self.assertTrue(cli.wait_for_service(timeout_sec=20)) executor = rclpy.executors.SingleThreadedExecutor(context=self.context) executor.add_node(self.node) executor_thread = threading.Thread( target=TestClient._spin_rclpy_node, args=(self.node, executor)) executor_thread.start() # make sure thread has started to avoid exception via join() self.assertTrue(executor_thread.is_alive()) result = cli.call(GetParameters.Request(), 0.5) self.assertTrue(result is not None) executor.shutdown() executor_thread.join() finally: self.node.destroy_client(cli) self.node.destroy_service(srv) def test_sync_call_timeout(self) -> None: def _service(request: GetParameters.Request, response: GetParameters.Response) -> GetParameters.Response: time.sleep(1) return response cli: ClientGetParameters = self.node.create_client(GetParameters, 'get/parameters') srv = self.node.create_service(GetParameters, 'get/parameters', _service) try: self.assertTrue(cli.wait_for_service(timeout_sec=20)) executor = rclpy.executors.SingleThreadedExecutor(context=self.context) executor.add_node(self.node) executor_thread = threading.Thread( target=TestClient._spin_rclpy_node, args=(self.node, executor)) executor_thread.start() # make sure thread has started to avoid exception via join() self.assertTrue(executor_thread.is_alive()) with self.assertRaises(TimeoutError): cli.call(GetParameters.Request(), 0.5) finally: executor.shutdown() executor_thread.join() self.node.destroy_client(cli) self.node.destroy_service(srv) def test_sync_call_context_manager(self) -> None: def _service(request: GetParameters.Request, response: GetParameters.Response) -> GetParameters.Response: return response cli: ClientGetParameters with self.node.create_client(GetParameters, 'get/parameters') as cli: with self.node.create_service(GetParameters, 'get/parameters', _service): self.assertTrue(cli.wait_for_service(timeout_sec=20)) executor = rclpy.executors.SingleThreadedExecutor(context=self.context) executor.add_node(self.node) executor_thread = threading.Thread( target=TestClient._spin_rclpy_node, args=(self.node, executor)) executor_thread.start() # make sure thread has started to avoid exception via join() self.assertTrue(executor_thread.is_alive()) result = cli.call(GetParameters.Request(), 0.5) self.assertTrue(result is not None) executor.shutdown() executor_thread.join() def test_logger_name_is_equal_to_node_name(self) -> None: with self.node.create_client(GetParameters, 'get/parameters') as cli: self.assertEqual(cli.logger_name, 'TestClient') def test_on_new_response_callback(self) -> None: def _service(request, response): return response with self.node.create_client(Empty, '/service') as cli: with self.node.create_service(Empty, '/service', _service): executor = rclpy.executors.SingleThreadedExecutor(context=self.context) try: self.assertTrue(cli.wait_for_service(timeout_sec=20)) executor.add_node(self.node) cb = Mock() cli.handle.set_on_new_response_callback(cb) cb.assert_not_called() cli.call_async(Empty.Request()) executor.spin_once(0) cb.assert_called_once_with(1) cli.handle.clear_on_new_response_callback() cli.call_async(Empty.Request()) executor.spin_once(0) cb.assert_called_once() finally: executor.shutdown() if __name__ == '__main__': unittest.main()
rclpy
python
# Copyright 2023 Sony Group Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from rcl_interfaces.msg import LoggerLevel, SetLoggerLevelsResult from rcl_interfaces.srv import GetLoggerLevels from rcl_interfaces.srv import SetLoggerLevels import rclpy from rclpy.impl.logging_severity import LoggingSeverity from rclpy.qos import qos_profile_services_default from rclpy.validate_topic_name import TOPIC_SEPARATOR_STRING if TYPE_CHECKING: from rclpy.node import Node class LoggingService: def __init__(self, node: 'Node'): node_name = node.get_name() get_logger_name_service_name = \ TOPIC_SEPARATOR_STRING.join((node_name, 'get_logger_levels')) node.create_service( GetLoggerLevels, get_logger_name_service_name, self._get_logger_levels, qos_profile=qos_profile_services_default ) set_logger_name_service_name = \ TOPIC_SEPARATOR_STRING.join((node_name, 'set_logger_levels')) node.create_service( SetLoggerLevels, set_logger_name_service_name, self._set_logger_levels, qos_profile=qos_profile_services_default ) def _get_logger_levels(self, request: GetLoggerLevels.Request, response: GetLoggerLevels.Response) -> GetLoggerLevels.Response: for name in request.names: logger_level = LoggerLevel() logger_level.name = name try: ret_level = rclpy.logging.get_logger_level(name) except RuntimeError: ret_level = LoggingSeverity.UNSET logger_level.level = ret_level response.levels.append(logger_level) return response def _set_logger_levels(self, request: SetLoggerLevels.Request, response: SetLoggerLevels.Response) -> SetLoggerLevels.Response: for level in request.levels: result = SetLoggerLevelsResult() result.successful = False try: rclpy.logging.set_logger_level(level.name, level.level, detailed_error=True) result.successful = True except ValueError: result.reason = 'Failed reason: Invalid logger level.' except RuntimeError as e: result.reason = str(e) response.results.append(result) return response
# Copyright 2023 Sony Group Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import threading import unittest from rcl_interfaces.msg import LoggerLevel from rcl_interfaces.srv import GetLoggerLevels from rcl_interfaces.srv import SetLoggerLevels import rclpy from rclpy.client import Client import rclpy.context from rclpy.executors import SingleThreadedExecutor from typing_extensions import TypeAlias ClientGetLoggerLevels: TypeAlias = Client[GetLoggerLevels.Request, GetLoggerLevels.Response] ClientSetLoggerLevels: TypeAlias = Client[SetLoggerLevels.Request, SetLoggerLevels.Response] class TestLoggingService(unittest.TestCase): def setUp(self) -> None: self.context = rclpy.context.Context() rclpy.init(context=self.context) self.test_node_with_logger_service = rclpy.create_node( 'test_node_with_logger_service_enabled', namespace='/rclpy', context=self.context, enable_logger_service=True) self.test_node = rclpy.create_node( 'test_logger_service', namespace='/rclpy', context=self.context) self.executor1 = SingleThreadedExecutor(context=self.context) self.executor1.add_node(self.test_node_with_logger_service) self.executor2 = SingleThreadedExecutor(context=self.context) self.executor2.add_node(self.test_node) self.thread = threading.Thread(target=self.executor1.spin, daemon=True) self.thread.start() def tearDown(self) -> None: self.executor1.shutdown() self.thread.join() self.executor2.shutdown() self.test_node.destroy_node() self.test_node_with_logger_service.destroy_node() rclpy.shutdown(context=self.context) def test_connect_get_logging_service(self) -> None: client: ClientGetLoggerLevels = self.test_node.create_client( GetLoggerLevels, '/rclpy/test_node_with_logger_service_enabled/get_logger_levels') try: self.assertTrue(client.wait_for_service(2)) finally: self.test_node.destroy_client(client) def test_connect_set_logging_service(self) -> None: client: ClientSetLoggerLevels = self.test_node.create_client( SetLoggerLevels, '/rclpy/test_node_with_logger_service_enabled/set_logger_levels' ) try: self.assertTrue(client.wait_for_service(2)) finally: self.test_node.destroy_client(client) def test_set_and_get_one_logging_level(self) -> None: test_log_name = 'rcl' test_log_level = 10 # Set debug level set_client: ClientSetLoggerLevels = self.test_node.create_client( SetLoggerLevels, '/rclpy/test_node_with_logger_service_enabled/set_logger_levels') self.assertTrue(set_client.wait_for_service(2)) request = SetLoggerLevels.Request() set_level = LoggerLevel() set_level.name = test_log_name set_level.level = test_log_level request.levels.append(set_level) future = set_client.call_async(request) self.executor2.spin_until_future_complete(future, 10) self.assertTrue(future.done()) response = future.result() assert response is not None self.assertEqual(len(response.results), 1) self.assertTrue(response.results[0].successful) self.assertEqual(response.results[0].reason, '') # reason should be empty if successful self.test_node.destroy_client(set_client) # Get set level get_client: ClientGetLoggerLevels = self.test_node.create_client( GetLoggerLevels, '/rclpy/test_node_with_logger_service_enabled/get_logger_levels') self.assertTrue(get_client.wait_for_service(2)) request = GetLoggerLevels.Request() request.names = [test_log_name] future = get_client.call_async(request) self.executor2.spin_until_future_complete(future, 10) self.assertTrue(future.done()) response = future.result() assert response is not None self.assertEqual(len(response.levels), 1) self.assertEqual(response.levels[0].name, test_log_name) self.assertEqual(response.levels[0].level, test_log_level) self.test_node.destroy_client(get_client) def test_set_and_get_multi_logging_level(self) -> None: test_log_name1 = 'rcl' test_log_level1 = 20 test_log_name2 = 'rclpy' test_log_level2 = 30 test_log_name3 = 'test_node_with_logger_service_enabled' test_log_level3 = 40 # Set multi log levels request = SetLoggerLevels.Request() set_level = LoggerLevel() set_level.name = test_log_name1 set_level.level = test_log_level1 request.levels.append(set_level) set_level = LoggerLevel() set_level.name = test_log_name2 set_level.level = test_log_level2 request.levels.append(set_level) set_level = LoggerLevel() set_level.name = test_log_name3 set_level.level = test_log_level3 request.levels.append(set_level) set_client: ClientSetLoggerLevels = self.test_node.create_client( SetLoggerLevels, '/rclpy/test_node_with_logger_service_enabled/set_logger_levels') self.assertTrue(set_client.wait_for_service(2)) future = set_client.call_async(request) self.executor2.spin_until_future_complete(future, 10) self.assertTrue(future.done()) response = future.result() assert response is not None self.assertEqual(len(response.results), 3) for result in response.results: self.assertTrue(result.successful) self.assertEqual(result.reason, str()) self.test_node.destroy_client(set_client) # Get multi log levels get_client: ClientGetLoggerLevels = self.test_node.create_client( GetLoggerLevels, '/rclpy/test_node_with_logger_service_enabled/get_logger_levels') self.assertTrue(get_client.wait_for_service(2)) request = GetLoggerLevels.Request() request.names = [test_log_name1, test_log_name2, test_log_name3] future = get_client.call_async(request) self.executor2.spin_until_future_complete(future, 10) self.assertTrue(future.done()) response = future.result() assert response is not None self.assertEqual(len(response.levels), 3) self.assertEqual(response.levels[0].name, test_log_name1) self.assertEqual(response.levels[0].level, test_log_level1) self.assertEqual(response.levels[1].name, test_log_name2) self.assertEqual(response.levels[1].level, test_log_level2) self.assertEqual(response.levels[2].name, test_log_name3) self.assertEqual(response.levels[2].level, test_log_level3) self.test_node.destroy_client(get_client) def test_set_logging_level_with_invalid_param(self) -> None: set_client: ClientSetLoggerLevels = self.test_node.create_client( SetLoggerLevels, '/rclpy/test_node_with_logger_service_enabled/set_logger_levels') self.assertTrue(set_client.wait_for_service(2)) request = SetLoggerLevels.Request() set_level = LoggerLevel() set_level.name = 'test_node_with_logger_service_enabled' set_level.level = 22 request.levels.append(set_level) set_level = LoggerLevel() set_level.name = 'rcl' set_level.level = 12 request.levels.append(set_level) future = set_client.call_async(request) self.executor2.spin_until_future_complete(future, 10) self.assertTrue(future.done()) response = future.result() assert response is not None self.assertEqual(len(response.results), 2) self.assertFalse(response.results[0].successful) self.assertEqual(response.results[0].reason, 'Failed reason: Invalid logger level.') self.assertFalse(response.results[1].successful) self.assertEqual(response.results[1].reason, 'Failed reason: Invalid logger level.') self.test_node.destroy_client(set_client) def test_set_logging_level_with_partial_invalid_param(self) -> None: set_client: ClientSetLoggerLevels = self.test_node.create_client( SetLoggerLevels, '/rclpy/test_node_with_logger_service_enabled/set_logger_levels') self.assertTrue(set_client.wait_for_service(2)) request = SetLoggerLevels.Request() set_level = LoggerLevel() set_level.name = 'rcl' set_level.level = 10 request.levels.append(set_level) set_level = LoggerLevel() set_level.name = 'rclpy' set_level.level = 22 # Invalid logger level request.levels.append(set_level) set_level = LoggerLevel() set_level.name = 'test_node_with_logger_service_enabled' set_level.level = 30 request.levels.append(set_level) future = set_client.call_async(request) self.executor2.spin_until_future_complete(future, 10) self.assertTrue(future.done()) response = future.result() assert response is not None self.assertEqual(len(response.results), 3) self.assertTrue(response.results[0].successful) self.assertEqual(response.results[0].reason, '') self.assertFalse(response.results[1].successful) self.assertEqual(response.results[1].reason, 'Failed reason: Invalid logger level.') self.assertTrue(response.results[2].successful) self.assertEqual(response.results[2].reason, '') self.test_node.destroy_client(set_client) if __name__ == '__main__': unittest.main()
rclpy
python
# Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from types import TracebackType from typing import Any, Generic, List, Optional, Type, TYPE_CHECKING, TypeVar from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy T = TypeVar('T') if TYPE_CHECKING: from rclpy.callback_groups import CallbackGroup from rclpy.task import Future class NumberOfEntities: __slots__ = [ 'num_subscriptions', 'num_guard_conditions', 'num_timers', 'num_clients', 'num_services', 'num_events'] def __init__( self, num_subs: int = 0, num_gcs: int = 0, num_timers: int = 0, num_clients: int = 0, num_services: int = 0, num_events: int = 0 ): self.num_subscriptions = num_subs self.num_guard_conditions = num_gcs self.num_timers = num_timers self.num_clients = num_clients self.num_services = num_services self.num_events = num_events def __add__(self, other: 'NumberOfEntities') -> 'NumberOfEntities': result = self.__class__() result.num_subscriptions = self.num_subscriptions + other.num_subscriptions result.num_guard_conditions = self.num_guard_conditions + other.num_guard_conditions result.num_timers = self.num_timers + other.num_timers result.num_clients = self.num_clients + other.num_clients result.num_services = self.num_services + other.num_services result.num_events = self.num_events + other.num_events return result def __iadd__(self, other: 'NumberOfEntities') -> 'NumberOfEntities': self.num_subscriptions += other.num_subscriptions self.num_guard_conditions += other.num_guard_conditions self.num_timers += other.num_timers self.num_clients += other.num_clients self.num_services += other.num_services self.num_events += other.num_events return self def __repr__(self) -> str: return '<{0}({1}, {2}, {3}, {4}, {5}, {6})>'.format( self.__class__.__name__, self.num_subscriptions, self.num_guard_conditions, self.num_timers, self.num_clients, self.num_services, self.num_events) class Waitable(Generic[T]): """ Add something to a wait set and execute it. This class wraps a collection of entities which can be added to a wait set. """ def __init__(self, callback_group: 'CallbackGroup'): # A callback group to control when this entity can execute (used by Executor) self.callback_group = callback_group self.callback_group.add_entity(self) # Flag set by executor when a handler has been created but not executed (used by Executor) self._executor_event = False # List of Futures that have callbacks needing execution self._futures: List[Future[Any]] = [] def __enter__(self) -> None: """Implement to mark entities as in-use to prevent destruction while waiting on them.""" raise NotImplementedError('Must be implemented by subclass') def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: """Implement to mark entities as not-in-use to allow destruction after waiting on them.""" raise NotImplementedError('Must be implemented by subclass') def add_future(self, future: 'Future[Any]') -> None: self._futures.append(future) def remove_future(self, future: 'Future[Any]') -> None: self._futures.remove(future) def is_ready(self, wait_set: _rclpy.WaitSet) -> bool: """Return True if entities are ready in the wait set.""" raise NotImplementedError('Must be implemented by subclass') def take_data(self) -> T: """Take stuff from lower level so the wait set doesn't immediately wake again.""" raise NotImplementedError('Must be implemented by subclass') async def execute(self, taken_data: T) -> None: """Execute work after data has been taken from a ready wait set.""" raise NotImplementedError('Must be implemented by subclass') def get_num_entities(self) -> NumberOfEntities: """Return number of each type of entity used.""" raise NotImplementedError('Must be implemented by subclass') def add_to_wait_set(self, wait_set: _rclpy.WaitSet) -> None: """Add entities to wait set.""" raise NotImplementedError('Must be implemented by subclass')
# Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import threading import time from typing import TYPE_CHECKING import unittest import rclpy from rclpy.callback_groups import MutuallyExclusiveCallbackGroup, ReentrantCallbackGroup from rclpy.clock import Clock from rclpy.clock_type import ClockType import rclpy.context from rclpy.executors import SingleThreadedExecutor from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy from rclpy.qos import QoSProfile from rclpy.task import Future from rclpy.type_support import check_for_type_support from rclpy.waitable import NumberOfEntities from rclpy.waitable import Waitable from test_msgs.msg import Empty as EmptyMsg from test_msgs.srv import Empty as EmptySrv check_for_type_support(EmptyMsg) check_for_type_support(EmptySrv) class ClientWaitable(Waitable): def __init__(self, node): super().__init__(ReentrantCallbackGroup()) with node.handle: self.client = _rclpy.Client( node.handle, EmptySrv, 'test_client', QoSProfile(depth=10).get_c_qos_profile()) self.client_index = None self.client_is_ready = False self.node = node self.future = None def __enter__(self) -> None: pass def __exit__(self, exc_type, exc_val, exc_tb) -> None: pass def is_ready(self, wait_set): """Return True if entities are ready in the wait set.""" if wait_set.is_ready('client', self.client_index): self.client_is_ready = True return self.client_is_ready def take_data(self): """Take stuff from lower level so the wait set doesn't immediately wake again.""" if self.client_is_ready: self.client_is_ready = False return self.client.take_response(EmptySrv.Response) return None async def execute(self, taken_data): """Execute work after data has been taken from a ready wait set.""" test_data = {} if isinstance(taken_data[1], EmptySrv.Response): test_data['client'] = taken_data[1] self.future.set_result(test_data) def get_num_entities(self): """Return number of each type of entity used.""" return NumberOfEntities(0, 0, 0, 1, 0) def add_to_wait_set(self, wait_set): """Add entities to wait set.""" self.client_index = wait_set.add_client(self.client) class ServerWaitable(Waitable): def __init__(self, node): super().__init__(ReentrantCallbackGroup()) with node.handle: self.server = _rclpy.Service( node.handle, EmptySrv, 'test_server', QoSProfile(depth=10).get_c_qos_profile()) self.server_index = None self.server_is_ready = False self.node = node self.future = None def __enter__(self) -> None: pass def __exit__(self, exc_type, exc_val, exc_tb) -> None: pass def is_ready(self, wait_set): """Return True if entities are ready in the wait set.""" if wait_set.is_ready('service', self.server_index): self.server_is_ready = True return self.server_is_ready def take_data(self): """Take stuff from lower level so the wait set doesn't immediately wake again.""" if self.server_is_ready: self.server_is_ready = False return self.server.service_take_request(EmptySrv.Request) return None async def execute(self, taken_data): """Execute work after data has been taken from a ready wait set.""" test_data = {} if isinstance(taken_data[0], EmptySrv.Request): test_data['server'] = taken_data[0] self.future.set_result(test_data) def get_num_entities(self): """Return number of each type of entity used.""" return NumberOfEntities(0, 0, 0, 0, 1) def add_to_wait_set(self, wait_set): """Add entities to wait set.""" self.server_index = wait_set.add_service(self.server) class TimerWaitable(Waitable): def __init__(self, node): super().__init__(ReentrantCallbackGroup()) self._clock = Clock(clock_type=ClockType.STEADY_TIME) period_nanoseconds = 10000 with self._clock.handle, node.context.handle: self.timer = _rclpy.Timer( self._clock.handle, node.context.handle, period_nanoseconds, True) self.timer_index = None self.timer_is_ready = False self.node = node self.future = None def __enter__(self) -> None: pass def __exit__(self, exc_type, exc_val, exc_tb) -> None: pass def is_ready(self, wait_set): """Return True if entities are ready in the wait set.""" if wait_set.is_ready('timer', self.timer_index): self.timer_is_ready = True return self.timer_is_ready def take_data(self): """Take stuff from lower level so the wait set doesn't immediately wake again.""" if self.timer_is_ready: self.timer_is_ready = False self.timer.call_timer_with_info() return 'timer' return None async def execute(self, taken_data): """Execute work after data has been taken from a ready wait set.""" test_data = {} if 'timer' == taken_data: test_data['timer'] = taken_data self.future.set_result(test_data) def get_num_entities(self): """Return number of each type of entity used.""" return NumberOfEntities(0, 0, 1, 0, 0) def add_to_wait_set(self, wait_set): """Add entities to wait set.""" self.timer_index = wait_set.add_timer(self.timer) class SubscriptionWaitable(Waitable): def __init__(self, node): super().__init__(ReentrantCallbackGroup()) with node.handle: self.subscription = _rclpy.Subscription( node.handle, EmptyMsg, 'test_topic', QoSProfile(depth=10).get_c_qos_profile()) self.subscription_index = None self.subscription_is_ready = False self.node = node self.future = None def __enter__(self) -> None: pass def __exit__(self, exc_type, exc_val, exc_tb) -> None: pass def is_ready(self, wait_set): """Return True if entities are ready in the wait set.""" if wait_set.is_ready('subscription', self.subscription_index): self.subscription_is_ready = True return self.subscription_is_ready def take_data(self): """Take stuff from lower level so the wait set doesn't immediately wake again.""" if self.subscription_is_ready: self.subscription_is_ready = False msg_info = self.subscription.take_message(EmptyMsg, False) if msg_info is not None: return msg_info[0] return None async def execute(self, taken_data): """Execute work after data has been taken from a ready wait set.""" test_data = {} if isinstance(taken_data, EmptyMsg): test_data['subscription'] = taken_data self.future.set_result(test_data) def get_num_entities(self): """Return number of each type of entity used.""" return NumberOfEntities(1, 0, 0, 0, 0) def add_to_wait_set(self, wait_set): """Add entities to wait set.""" self.subscription_index = wait_set.add_subscription( self.subscription) class GuardConditionWaitable(Waitable): def __init__(self, node): super().__init__(ReentrantCallbackGroup()) with node.context.handle: self.guard_condition = _rclpy.GuardCondition(node.context.handle) self.guard_condition_index = None self.guard_is_ready = False self.node = node self.future = None def __enter__(self) -> None: pass def __exit__(self, exc_type, exc_val, exc_tb) -> None: pass def is_ready(self, wait_set): """Return True if entities are ready in the wait set.""" if wait_set.is_ready('guard_condition', self.guard_condition_index): self.guard_is_ready = True return self.guard_is_ready def take_data(self): """Take stuff from lower level so the wait set doesn't immediately wake again.""" if self.guard_is_ready: self.guard_is_ready = False return 'guard_condition' return None async def execute(self, taken_data): """Execute work after data has been taken from a ready wait set.""" test_data = {} if 'guard_condition' == taken_data: test_data['guard_condition'] = True self.future.set_result(test_data) def get_num_entities(self): """Return number of each type of entity used.""" return NumberOfEntities(0, 1, 0, 0, 0) def add_to_wait_set(self, wait_set): """Add entities to wait set.""" self.guard_condition_index = wait_set.add_guard_condition(self.guard_condition) class MutuallyExclusiveWaitable(Waitable): def __init__(self) -> None: super().__init__(MutuallyExclusiveCallbackGroup()) def __enter__(self) -> None: pass def __exit__(self, exc_type, exc_val, exc_tb) -> None: pass def is_ready(self, wait_set): return False def take_data(self) -> None: return None async def execute(self, taken_data): pass def get_num_entities(self): return NumberOfEntities(0, 0, 0, 0, 0) def add_to_wait_set(self, wait_set): pass class TestWaitable(unittest.TestCase): if TYPE_CHECKING: node: rclpy.node.Node context: rclpy.context.Context executor: SingleThreadedExecutor @classmethod def setUpClass(cls): cls.context = rclpy.context.Context() rclpy.init(context=cls.context) cls.node = rclpy.create_node( 'TestWaitable', namespace='/rclpy/test', context=cls.context, allow_undeclared_parameters=True) cls.executor = SingleThreadedExecutor(context=cls.context) cls.executor.add_node(cls.node) @classmethod def tearDownClass(cls): cls.executor.shutdown() cls.node.destroy_node() rclpy.shutdown(context=cls.context) def start_spin_thread(self, waitable): waitable.future = Future(executor=self.executor) self.thr = threading.Thread( target=self.executor.spin_until_future_complete, args=(waitable.future,), daemon=True) self.thr.start() return self.thr def setUp(self) -> None: pass def tearDown(self) -> None: self.node.remove_waitable(self.waitable) # Ensure resources inside the waitable are destroyed before the node in tearDownClass del self.waitable def test_waitable_with_client(self) -> None: self.waitable = ClientWaitable(self.node) self.node.add_waitable(self.waitable) server = self.node.create_service(EmptySrv, 'test_client', lambda req, resp: resp) while not self.waitable.client.service_server_is_available(): time.sleep(0.1) thr = self.start_spin_thread(self.waitable) self.waitable.client.send_request(EmptySrv.Request()) thr.join() assert self.waitable.future.done() assert isinstance(self.waitable.future.result()['client'], EmptySrv.Response) self.node.destroy_service(server) def test_waitable_with_server(self) -> None: self.waitable = ServerWaitable(self.node) self.node.add_waitable(self.waitable) client = self.node.create_client(EmptySrv, 'test_server') thr = self.start_spin_thread(self.waitable) client.call_async(EmptySrv.Request()) thr.join() assert self.waitable.future.done() assert isinstance(self.waitable.future.result()['server'], EmptySrv.Request) self.node.destroy_client(client) def test_waitable_with_timer(self) -> None: self.waitable = TimerWaitable(self.node) self.node.add_waitable(self.waitable) thr = self.start_spin_thread(self.waitable) thr.join() assert self.waitable.future.done() assert self.waitable.future.result()['timer'] def test_waitable_with_subscription(self) -> None: self.waitable = SubscriptionWaitable(self.node) self.node.add_waitable(self.waitable) pub = self.node.create_publisher(EmptyMsg, 'test_topic', 1) thr = self.start_spin_thread(self.waitable) pub.publish(EmptyMsg()) thr.join() assert self.waitable.future.done() assert isinstance(self.waitable.future.result()['subscription'], EmptyMsg) self.node.destroy_publisher(pub) def test_waitable_with_guard_condition(self) -> None: self.waitable = GuardConditionWaitable(self.node) self.node.add_waitable(self.waitable) thr = self.start_spin_thread(self.waitable) self.waitable.guard_condition.trigger_guard_condition() thr.join() assert self.waitable.future.done() assert self.waitable.future.result()['guard_condition'] # Test that waitable doesn't crash with MutuallyExclusiveCallbackGroup # https://github.com/ros2/rclpy/issues/264 def test_waitable_with_mutually_exclusive_callback_group(self) -> None: self.waitable = MutuallyExclusiveWaitable() self.node.add_waitable(self.waitable) self.executor.spin_once(timeout_sec=0.1) class TestNumberOfEntities(unittest.TestCase): def test_add(self) -> None: n1 = NumberOfEntities(1, 2, 3, 4, 5, 6) n2 = NumberOfEntities(10, 20, 30, 40, 50, 60) n = n1 + n2 assert n.num_subscriptions == 11 assert n.num_guard_conditions == 22 assert n.num_timers == 33 assert n.num_clients == 44 assert n.num_services == 55 assert n.num_events == 66 def test_add_assign(self) -> None: n1 = NumberOfEntities(1, 2, 3, 4, 5, 6) n2 = NumberOfEntities(10, 20, 30, 40, 50, 60) n1 += n2 assert n1.num_subscriptions == 11 assert n1.num_guard_conditions == 22 assert n1.num_timers == 33 assert n1.num_clients == 44 assert n1.num_services == 55 assert n1.num_events == 66
rclpy
python
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pathlib import Path from typing import Union from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy from rclpy.impl.logging_severity import LoggingSeverity as LoggingSeverity from rclpy.impl.rcutils_logger import RcutilsLogger _root_logger = RcutilsLogger() def get_logger(name: str) -> RcutilsLogger: if not name: raise ValueError('Logger name must not be empty.') return _root_logger.get_child(name) def initialize() -> None: _rclpy.rclpy_logging_initialize() def shutdown() -> None: _rclpy.rclpy_logging_shutdown() def clear_config() -> None: """Clear the configuration of the logging system, e.g. logger levels.""" shutdown() initialize() def set_logger_level(name: str, level: Union[int, LoggingSeverity], detailed_error: bool = False) -> None: level = LoggingSeverity(level) _rclpy.rclpy_logging_set_logger_level(name, level, detailed_error) def get_logger_effective_level(name: str) -> LoggingSeverity: logger_level = _rclpy.rclpy_logging_get_logger_effective_level(name) return LoggingSeverity(logger_level) def get_logger_level(name: str) -> LoggingSeverity: logger_level = _rclpy.rclpy_logging_get_logger_level(name) return LoggingSeverity(logger_level) def get_logging_severity_from_string(log_severity: str) -> LoggingSeverity: return LoggingSeverity( _rclpy.rclpy_logging_severity_level_from_string(log_severity)) def get_logging_directory() -> Path: """ Return the current logging directory being used. For more details, :func:`~rcl_logging_interface.rcl_logging_get_logging_directory` """ return Path(_rclpy.rclpy_logging_get_logging_directory())
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect import os from pathlib import Path import time import unittest import rclpy from rclpy.clock import Clock, ROSClock from rclpy.logging import LoggingSeverity from rclpy.time import Time from rclpy.time_source import TimeSource class TestLogging(unittest.TestCase): def test_root_logger_level(self) -> None: original_severity = rclpy.logging._root_logger.get_effective_level() for severity in LoggingSeverity: rclpy.logging._root_logger.set_level(severity) self.assertEqual( severity, rclpy.logging._root_logger.get_effective_level()) rclpy.logging._root_logger.set_level(original_severity) def test_logger_level(self) -> None: # We should be able to set the threshold of a nonexistent logger / one that doesn't # correspond to a python object, e.g. an RMW internal logger. name = 'my_internal_logger_name' original_severity = rclpy.logging.get_logger_effective_level(name) for severity in LoggingSeverity: if severity is not LoggingSeverity.UNSET: # unset causes the hierarchy to be traversed rclpy.logging.set_logger_level(name, severity) self.assertEqual( severity, rclpy.logging.get_logger_effective_level(name)) rclpy.logging.set_logger_level(name, original_severity) def test_logger_object_level(self) -> None: logger = rclpy.logging.get_logger('test_logger') for severity in LoggingSeverity: if severity is not LoggingSeverity.UNSET: # unset causes the hierarchy to be traversed logger.set_level(severity) self.assertEqual(severity, logger.get_effective_level()) def test_logger_effective_level(self) -> None: name = 'my_nonexistent_logger_name' self.assertEqual( rclpy.logging._root_logger.get_effective_level(), rclpy.logging.get_logger_effective_level(name)) # Check that the effective threshold for a logger with manually unset severity is default rclpy.logging.set_logger_level(name, LoggingSeverity.UNSET) self.assertEqual( rclpy.logging._root_logger.get_effective_level(), rclpy.logging.get_logger_effective_level(name)) # Check that the effective threshold for a logger with set severity rclpy.logging.set_logger_level(name, LoggingSeverity.ERROR) self.assertEqual( LoggingSeverity.ERROR, rclpy.logging.get_logger_effective_level(name)) def test_log_threshold(self) -> None: rclpy.logging._root_logger.set_level(LoggingSeverity.INFO) # Logging below threshold not expected to be logged self.assertFalse(rclpy.logging._root_logger.debug('message_debug')) # Logging at or above threshold expected to be logged self.assertTrue(rclpy.logging._root_logger.info('message_info')) self.assertTrue(rclpy.logging._root_logger.warning('message_warn')) self.assertTrue(rclpy.logging._root_logger.error('message_error')) self.assertTrue(rclpy.logging._root_logger.fatal('message_fatal')) def test_log_once(self) -> None: message_was_logged = [] for i in range(5): message_was_logged.append(rclpy.logging._root_logger.log( 'message_' + inspect.stack()[0][3] + '_' + str(i), LoggingSeverity.INFO, once=True, )) self.assertEqual(message_was_logged, [True] + [False] * 4) # If the argument is specified as false it shouldn't impact the logging. message_was_logged = [] for i in range(5): message_was_logged.append(rclpy.logging._root_logger.log( 'message2_' + inspect.stack()[0][3] + '_false_' + str(i), LoggingSeverity.INFO, once=False, )) self.assertEqual(message_was_logged, [True] * 5) def test_log_throttle(self) -> None: message_was_logged = [] system_clock = Clock() for i in range(5): message_was_logged.append(rclpy.logging._root_logger.log( 'message_' + inspect.stack()[0][3] + '_' + str(i), LoggingSeverity.INFO, throttle_duration_sec=1, throttle_time_source_type=system_clock, )) time.sleep(0.4) self.assertEqual( message_was_logged, [ True, # t=0, not throttled False, # t=0.4, throttled False, # t=0.8, throttled True, # t=1.2, not throttled False # t=1.6, throttled ]) def test_log_throttle_ros_clock(self) -> None: message_was_logged = [] ros_clock = ROSClock() time_source = TimeSource() time_source.attach_clock(ros_clock) time_source.ros_time_is_active = True for i in range(5): message_was_logged.append(rclpy.logging._root_logger.log( 'message_' + inspect.stack()[0][3] + '_' + str(i), LoggingSeverity.INFO, throttle_duration_sec=1, throttle_time_source_type=ros_clock, )) time.sleep(0.4) self.assertEqual( message_was_logged, [ False, # t=0, throttled False, # t=0.4, throttled False, # t=0.8, throttled False, # t=1.2, throttled False # t=1.6, throttled ]) message_was_logged = [] for i in range(5): message_was_logged.append(rclpy.logging._root_logger.log( 'message_' + inspect.stack()[0][3] + '_' + str(i), LoggingSeverity.INFO, throttle_duration_sec=2, throttle_time_source_type=ros_clock, )) ros_clock.set_ros_time_override(Time( seconds=i + 1, nanoseconds=0, clock_type=ros_clock.clock_type, )) self.assertEqual( message_was_logged, [ False, # t=0, throttled False, # t=1.0, throttled True, # t=2.0, not throttled False, # t=3.0, throttled True # t=4.0, not throttled ]) def test_log_skip_first(self) -> None: message_was_logged = [] for i in range(5): message_was_logged.append(rclpy.logging._root_logger.log( 'message_' + inspect.stack()[0][3] + '_' + str(i), LoggingSeverity.INFO, skip_first=True, )) self.assertEqual(message_was_logged, [False] + [True] * 4) def test_log_skip_first_throttle(self) -> None: # Because of the ordering of supported_filters, first the throttle condition will be # evaluated/updated, then the skip_first condition message_was_logged = [] system_clock = Clock() for i in range(5): message_was_logged.append(rclpy.logging._root_logger.log( 'message_' + inspect.stack()[0][3] + '_' + str(i), LoggingSeverity.INFO, skip_first=True, throttle_duration_sec=1, throttle_time_source_type=system_clock, )) time.sleep(0.4) self.assertEqual( message_was_logged, [ False, # t=0, not throttled, but skipped because first False, # t=0.4, throttled False, # t=0.8, throttled True, # t=1.2, not throttled False # t=1.6, throttled ]) def test_log_skip_first_once(self) -> None: # Because of the ordering of supported_filters, first the skip_first condition will be # evaluated/updated, then the once condition message_was_logged = [] for i in range(5): message_was_logged.append(rclpy.logging._root_logger.log( 'message_' + inspect.stack()[0][3] + '_' + str(i), LoggingSeverity.INFO, once=True, skip_first=True, )) time.sleep(0.3) self.assertEqual(message_was_logged, [False, True] + [False] * 3) def test_log_arguments(self) -> None: system_clock = Clock() # Check half-specified filter not allowed if a required parameter is missing with self.assertRaisesRegex(TypeError, 'required parameter .* not specified'): rclpy.logging._root_logger.log( 'message', LoggingSeverity.INFO, throttle_time_source_type=system_clock, ) # Check half-specified filter is allowed if an optional parameter is missing rclpy.logging._root_logger.log( 'message', LoggingSeverity.INFO, throttle_duration_sec=0.1, ) # Check unused kwarg is not allowed with self.assertRaisesRegex(TypeError, 'parameter .* is not one of the recognized'): rclpy.logging._root_logger.log( # type: ignore[call-arg] 'message', LoggingSeverity.INFO, name='my_name', skip_first=True, unused_kwarg='unused_kwarg', ) def test_log_parameters_changing(self) -> None: # Check changing log call parameters is not allowed with self.assertRaisesRegex(ValueError, 'parameters cannot be changed between'): # Start at 1 because a throttle_duration_sec of 0 causes the filter to be ignored. for i in range(1, 3): rclpy.logging._root_logger.log( 'message_' + inspect.stack()[0][3] + '_' + str(i), LoggingSeverity.INFO, throttle_duration_sec=i, ) with self.assertRaisesRegex(ValueError, 'name cannot be changed between'): for i in range(2): rclpy.logging._root_logger.log( 'message_' + inspect.stack()[0][3] + '_' + str(i), LoggingSeverity.INFO, name='name_' + str(i), ) with self.assertRaisesRegex(ValueError, 'severity cannot be changed between'): for severity in LoggingSeverity: rclpy.logging._root_logger.log( 'message_' + inspect.stack()[0][3] + '_' + str(severity), severity, ) def test_named_logger(self) -> None: my_logger = rclpy.logging.get_logger('my_logger') my_logger.set_level(LoggingSeverity.INFO) # Test convenience functions # Logging below threshold not expected to be logged self.assertFalse(my_logger.debug('message_debug')) # Logging at or above threshold expected to be logged self.assertTrue(my_logger.warning('message_warn')) self.assertTrue(my_logger.error('message_err')) self.assertTrue(my_logger.fatal('message_fatal')) # Check that specifying a different severity isn't allowed with self.assertRaisesRegex(TypeError, "got multiple values for argument 'severity'"): my_logger.fatal( # type: ignore[call-arg] 'message_fatal', severity=LoggingSeverity.DEBUG) # Check that this logger's context is independent of the root logger's context loggers = [my_logger, rclpy.logging._root_logger] for logger in loggers: message_was_logged = [] for i in range(5): message_was_logged.append(logger.log( 'message_' + inspect.stack()[0][3] + '_' + str(i), LoggingSeverity.INFO, once=True, )) self.assertEqual(message_was_logged, [True] + [False] * 4) def test_named_logger_hierarchy(self) -> None: # Create a logger that implicitly is a child of the un-named root logger with self.assertRaisesRegex(ValueError, 'Logger name must not be empty'): my_logger = rclpy.logging.get_logger('') my_logger = rclpy.logging.get_logger('my_logger') self.assertEqual('my_logger', my_logger.name) # Check that any logger gets the level of the root logger by default self.assertEqual( rclpy.logging._root_logger.get_effective_level(), my_logger.get_effective_level()) with self.assertRaisesRegex(ValueError, 'Child logger name must not be empty'): my_logger_child = my_logger.get_child('') with self.assertRaisesRegex(ValueError, 'Child logger name must not be empty'): my_logger_child = my_logger.get_child(None) # type: ignore[arg-type] my_logger_child = my_logger.get_child('child') self.assertEqual(my_logger.name + '.child', my_logger_child.name) original_severity = rclpy.logging._root_logger.get_effective_level() default_severity = LoggingSeverity.INFO rclpy.logging._root_logger.set_level(default_severity) # Check that children get the default severity if parent's threshold is unset self.assertEqual(default_severity, my_logger.get_effective_level()) self.assertEqual(default_severity, my_logger_child.get_effective_level()) # Check that children inherit their parent's threshold my_logger_severity = LoggingSeverity.ERROR my_logger.set_level(my_logger_severity) self.assertEqual(my_logger_severity, my_logger.get_effective_level()) self.assertEqual(my_logger_severity, my_logger_child.get_effective_level()) # Check that child's threshold has preference over their parent's, if set my_logger_child_severity = LoggingSeverity.DEBUG my_logger_child.set_level(my_logger_child_severity) self.assertEqual(my_logger_severity, my_logger.get_effective_level()) self.assertEqual( my_logger_child_severity, my_logger_child.get_effective_level()) # Check that severity inheritance returns if the child's threshold is cleared my_logger_child_severity = LoggingSeverity.UNSET my_logger_child.set_level(my_logger_child_severity) self.assertEqual(my_logger_severity, my_logger.get_effective_level()) self.assertEqual(my_logger_severity, my_logger_child.get_effective_level()) rclpy.logging._root_logger.set_level(original_severity) def test_clear_config(self) -> None: my_logger = rclpy.logging.get_logger('my_temp_logger') my_logger.set_level(LoggingSeverity.WARN) self.assertEqual(LoggingSeverity.WARN, my_logger.get_effective_level()) rclpy.logging.clear_config() self.assertNotEqual(LoggingSeverity.WARN, my_logger.get_effective_level()) self.assertEqual( rclpy.logging._root_logger.get_effective_level(), my_logger.get_effective_level()) def test_logging_severity_from_string(self) -> None: for severity in rclpy.logging.LoggingSeverity: self.assertEqual( rclpy.logging.get_logging_severity_from_string(severity.name), severity) def test_nonexistent_logging_severity_from_string(self) -> None: with self.assertRaises(RuntimeError): rclpy.logging.get_logging_severity_from_string('non_existent_severity') def test_get_logging_directory(self) -> None: os.environ['HOME'] = '/fake_home_dir' os.environ.pop('USERPROFILE', None) os.environ.pop('ROS_LOG_DIR', None) os.environ.pop('ROS_HOME', None) log_dir = rclpy.logging.get_logging_directory() assert isinstance(log_dir, Path) assert log_dir == Path('/fake_home_dir') / '.ros' / 'log' if __name__ == '__main__': unittest.main()
rclpy
python
# Copyright 2020 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Any from typing import Callable from typing import Iterable from typing import List from typing import Optional from typing import Text from typing import Type from typing import TYPE_CHECKING from typing import Union from rcl_interfaces.msg import ParameterDescriptor from rcl_interfaces.msg import SetParametersResult import rclpy from rclpy.duration import Duration from rclpy.exceptions import ParameterAlreadyDeclaredException from rclpy.parameter import Parameter from rclpy.publisher import Publisher from rclpy.qos import QoSDurabilityPolicy from rclpy.qos import QoSHistoryPolicy from rclpy.qos import QoSLivelinessPolicy from rclpy.qos import QoSPolicyKind from rclpy.qos import QoSProfile from rclpy.qos import QoSReliabilityPolicy from rclpy.subscription import Subscription from typing_extensions import TypeAlias if TYPE_CHECKING: from rclpy.node import Node class InvalidQosOverridesError(Exception): pass # Return type of qos validation callbacks QosCallbackResult: TypeAlias = SetParametersResult # Qos callback type annotation QosCallbackType = Callable[[QoSProfile], QosCallbackResult] class QoSOverridingOptions: """Options to customize QoS parameter overrides.""" def __init__( self, policy_kinds: Iterable[QoSPolicyKind], *, callback: Optional[QosCallbackType] = None, entity_id: Optional[Text] = None ): """ Construct a QoSOverridingOptions object. :param policy_kinds: QoS kinds that will have a declared parameter. :param callback: Callback that will be used to validate the QoS profile after the paramter overrides get applied. :param entity_id: Optional identifier, to disambiguate in the case that different QoS policies for the same topic are desired. """ self._policy_kinds = policy_kinds self._callback = callback self._entity_id = entity_id @property def policy_kinds(self) -> Iterable[QoSPolicyKind]: """Get QoS policy kinds that will have a parameter override.""" return self._policy_kinds @property def callback(self) -> Optional[QosCallbackType]: """Get the validation callback.""" return self._callback @property def entity_id(self) -> Optional[Text]: """Get the optional entity ID.""" return self._entity_id @classmethod def with_default_policies( cls, *, callback: Optional[QosCallbackType] = None, entity_id: Optional[Text] = None ) -> 'QoSOverridingOptions': return cls( policy_kinds=(QoSPolicyKind.HISTORY, QoSPolicyKind.DEPTH, QoSPolicyKind.RELIABILITY), callback=callback, entity_id=entity_id, ) def _declare_qos_parameters( entity_type: Union[Type[Publisher[Any]], Type[Subscription[Any]]], node: 'Node', topic_name: Text, qos: QoSProfile, options: QoSOverridingOptions ) -> None: """ Declare QoS parameters for a Publisher or a Subscription. :param entity_type: Either `rclpy.node.Publisher` or `rclpy.node.Subscription`. :param node: Node used to declare the parameters. :param topic_name: Topic name of the entity being created. :param qos: Default QoS settings of the entity being created, that will be overridden with the user provided QoS parameter overrides. :param options: Options that indicates which parameters are going to be declared. """ if not issubclass(entity_type, (Publisher, Subscription)): raise TypeError('Argument `entity_type` should be a subclass of Publisher or Subscription') entity_type_str = 'publisher' if issubclass(entity_type, Publisher) else 'subscription' id_suffix = '' if options.entity_id is None else f'_{options.entity_id}' name = f'qos_overrides.{topic_name}.{entity_type_str}{id_suffix}.' '{}' description = '{}' f' for {entity_type_str} `{topic_name}` with id `{options.entity_id}`' allowed_policies = _get_allowed_policies(entity_type) for policy in options.policy_kinds: if policy not in allowed_policies: continue policy_name = policy.name.lower() descriptor = ParameterDescriptor() descriptor.description = description.format(policy_name) descriptor.read_only = True try: param: Parameter[Any] = node.declare_parameter( name.format(policy_name), _get_qos_policy_parameter(qos, policy), descriptor) except ParameterAlreadyDeclaredException: param = node.get_parameter(name.format(policy_name)) _override_qos_policy_with_param(qos, policy, param) if options.callback is not None: result = options.callback(qos) if not result.successful: raise InvalidQosOverridesError( f"{description.format('Provided QoS overrides')}, are not valid: {result.reason}") def _get_allowed_policies(entity_type: Union[Type[Publisher[Any]], Type[Subscription[Any]]]) -> List[QoSPolicyKind]: allowed_policies = list(QoSPolicyKind.__members__.values()) if issubclass(entity_type, Subscription): allowed_policies.remove(QoSPolicyKind.LIFESPAN) return allowed_policies QoSProfileAttributes = Union[QoSHistoryPolicy, int, QoSReliabilityPolicy, QoSDurabilityPolicy, Duration, QoSLivelinessPolicy, bool] def _get_qos_policy_parameter(qos: QoSProfile, policy: QoSPolicyKind) -> Union[str, int, bool]: value: QoSProfileAttributes = getattr(qos, policy.name.lower()) if isinstance(value, (QoSHistoryPolicy, QoSReliabilityPolicy, QoSDurabilityPolicy, QoSLivelinessPolicy)): return_value: Union[str, int, bool] = value.name.lower() if return_value == 'unknown': raise ValueError('User provided QoS profile is invalid') elif isinstance(value, Duration): return_value = value.nanoseconds else: return_value = value return return_value def _override_qos_policy_with_param(qos: QoSProfile, policy: QoSPolicyKind, param: Parameter[Any]) -> None: value = param.value policy_name = policy.name.lower() if policy in ( QoSPolicyKind.LIVELINESS, QoSPolicyKind.RELIABILITY, QoSPolicyKind.HISTORY, QoSPolicyKind.DURABILITY ): def capitalize_first_letter(x: str) -> str: return x[0].upper() + x[1:] # e.g. `policy=QosPolicyKind.LIVELINESS` -> `policy_enum_class=rclpy.qos.LivelinessPolicy` policy_enum_class = getattr( rclpy.qos, f'{capitalize_first_letter(policy_name)}Policy') try: value = policy_enum_class[value.upper()] except KeyError: raise RuntimeError( f'Unexpected QoS override for policy `{policy.name.lower()}`: `{value}`') if policy in ( QoSPolicyKind.LIFESPAN, QoSPolicyKind.DEADLINE, QoSPolicyKind.LIVELINESS_LEASE_DURATION ): value = Duration(nanoseconds=value) setattr(qos, policy.name.lower(), value)
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import warnings from rclpy.duration import Duration from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy from rclpy.qos import InvalidQoSProfileException from rclpy.qos import qos_check_compatible from rclpy.qos import qos_profile_system_default from rclpy.qos import QoSCompatibility from rclpy.qos import QoSDurabilityPolicy from rclpy.qos import QoSHistoryPolicy from rclpy.qos import QoSLivelinessPolicy from rclpy.qos import QoSPresetProfiles from rclpy.qos import QoSProfile from rclpy.qos import QoSReliabilityPolicy class TestQosProfile(unittest.TestCase): def convert_and_assert_equality(self, qos_profile: QoSProfile) -> None: c_qos_profile = qos_profile.get_c_qos_profile() converted_profile = QoSProfile(**c_qos_profile.to_dict()) self.assertEqual(qos_profile, converted_profile) def test_depth_only_constructor(self) -> None: qos = QoSProfile(depth=1) assert qos.depth == 1 assert qos.history == QoSHistoryPolicy.KEEP_LAST def test_eq_operator(self) -> None: profile_1 = QoSProfile(history=QoSHistoryPolicy.KEEP_LAST, depth=1) profile_same = QoSProfile( history=QoSHistoryPolicy.KEEP_LAST, depth=1) profile_different_depth = QoSProfile( history=QoSHistoryPolicy.KEEP_LAST, depth=2) profile_different_duration = QoSProfile( history=QoSHistoryPolicy.KEEP_LAST, depth=1, deadline=Duration(seconds=2)) profile_equal_duration = QoSProfile( history=QoSHistoryPolicy.KEEP_LAST, depth=1, deadline=Duration(seconds=2)) self.assertEqual(profile_1, profile_same) self.assertNotEqual(profile_1, profile_different_depth) self.assertNotEqual(profile_1, profile_different_duration) self.assertEqual(profile_different_duration, profile_equal_duration) def test_simple_round_trip(self) -> None: source_profile = QoSProfile(history=QoSHistoryPolicy.KEEP_ALL) self.convert_and_assert_equality(source_profile) def test_big_nanoseconds(self) -> None: # Under 31 bits no_problem = QoSProfile( history=QoSHistoryPolicy.KEEP_ALL, lifespan=Duration(seconds=2)) self.convert_and_assert_equality(no_problem) # Total nanoseconds in duration is too large to store in 32 bit signed int int32_problem = QoSProfile( history=QoSHistoryPolicy.KEEP_ALL, lifespan=Duration(seconds=4)) self.convert_and_assert_equality(int32_problem) # Total nanoseconds in duration is too large to store in 32 bit unsigned int uint32_problem = QoSProfile( history=QoSHistoryPolicy.KEEP_ALL, lifespan=Duration(seconds=5)) self.convert_and_assert_equality(uint32_problem) def test_alldata_round_trip(self) -> None: source_profile = QoSProfile( history=QoSHistoryPolicy.KEEP_ALL, depth=12, reliability=QoSReliabilityPolicy.BEST_EFFORT, durability=QoSDurabilityPolicy.VOLATILE, lifespan=Duration(seconds=4), deadline=Duration(nanoseconds=1e6), liveliness=QoSLivelinessPolicy.MANUAL_BY_TOPIC, liveliness_lease_duration=Duration(nanoseconds=12), avoid_ros_namespace_conventions=True ) self.convert_and_assert_equality(source_profile) def test_invalid_qos(self) -> None: with self.assertRaises(InvalidQoSProfileException): # No history or depth settings provided QoSProfile() with self.assertRaises(InvalidQoSProfileException): # History is KEEP_LAST, but no depth is provided QoSProfile(history=QoSHistoryPolicy.KEEP_LAST) def test_policy_short_names(self) -> None: # Full test on History to show the mechanism works assert ( QoSHistoryPolicy.short_keys() == ['system_default', 'keep_last', 'keep_all', 'unknown']) assert ( QoSHistoryPolicy.get_from_short_key('system_default') == QoSHistoryPolicy.SYSTEM_DEFAULT.value) assert ( QoSHistoryPolicy.get_from_short_key('KEEP_ALL') == QoSHistoryPolicy.KEEP_ALL.value) assert ( QoSHistoryPolicy.get_from_short_key('KEEP_last') == QoSHistoryPolicy.KEEP_LAST.value) def test_preset_profiles(self) -> None: # Make sure the Enum does what we expect assert QoSPresetProfiles.SYSTEM_DEFAULT.value == qos_profile_system_default assert ( QoSPresetProfiles.SYSTEM_DEFAULT.value == QoSPresetProfiles.get_from_short_key('system_default')) def test_keep_last_zero_depth_constructor(self) -> None: with warnings.catch_warnings(record=True) as caught_warnings: warnings.simplefilter('always', category=UserWarning) qos = QoSProfile(history=QoSHistoryPolicy.KEEP_LAST, depth=0) assert len(caught_warnings) == 1 assert issubclass(caught_warnings[0].category, UserWarning) assert "A zero depth with KEEP_LAST doesn't make sense" in str(caught_warnings[0]) assert qos.history == QoSHistoryPolicy.KEEP_LAST def test_keep_last_zero_depth_set(self) -> None: qos = QoSProfile(history=QoSHistoryPolicy.KEEP_LAST, depth=1) assert qos.depth == 1 with warnings.catch_warnings(record=True) as caught_warnings: warnings.simplefilter('always', category=UserWarning) qos.depth = 0 assert len(caught_warnings) == 1 assert issubclass(caught_warnings[0].category, UserWarning) assert "A zero depth with KEEP_LAST doesn't make sense" in str(caught_warnings[0]) class TestCheckQosCompatibility(unittest.TestCase): def test_compatible(self) -> None: qos = QoSProfile( depth=1, reliability=QoSReliabilityPolicy.RELIABLE, durability=QoSDurabilityPolicy.VOLATILE, lifespan=Duration(seconds=1), deadline=Duration(seconds=1), liveliness=QoSLivelinessPolicy.AUTOMATIC, liveliness_lease_duration=Duration(seconds=1), ) compatibility, reason = qos_check_compatible( qos, qos ) assert compatibility == QoSCompatibility.OK assert reason == '' def test_incompatible(self) -> None: """ This test is assuming a DDS implementation. It's possible that a "best effort" publisher and "reliable" subscription is a valid match in a non-DDS implementation. """ pub_qos = QoSProfile( depth=1, reliability=QoSReliabilityPolicy.BEST_EFFORT, ) sub_qos = QoSProfile( depth=1, reliability=QoSReliabilityPolicy.RELIABLE, ) compatibility, reason = qos_check_compatible( pub_qos, sub_qos ) if _rclpy.rclpy_get_rmw_implementation_identifier() != 'rmw_zenoh_cpp': assert compatibility == QoSCompatibility.ERROR assert reason != '' else: assert compatibility == QoSCompatibility.OK assert reason == '' def test_warn_of_possible_incompatibility(self) -> None: """ This test is assuming a DDS implementation. It's possible that a "best effort" publisher and "reliable" subscription is a valid match in a non-DDS implementation. """ pub_qos = QoSPresetProfiles.SYSTEM_DEFAULT.value sub_qos = QoSProfile( depth=1, reliability=QoSReliabilityPolicy.RELIABLE, ) compatibility, reason = qos_check_compatible( pub_qos, sub_qos ) if _rclpy.rclpy_get_rmw_implementation_identifier() != 'rmw_zenoh_cpp': assert compatibility == QoSCompatibility.WARNING assert reason != '' else: assert compatibility == QoSCompatibility.OK assert reason == ''
rclpy
python
# Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from enum import Enum import inspect import sys import threading from typing import (Any, Callable, cast, Coroutine, Dict, Generator, Generic, List, Optional, overload, Tuple, TYPE_CHECKING, TypeVar, Union) import warnings import weakref if TYPE_CHECKING: from rclpy.executors import Executor T = TypeVar('T') def _fake_weakref() -> None: """Return None when called to simulate a weak reference that has been garbage collected.""" return None class FutureState(Enum): """States defining the lifecycle of a future.""" PENDING = 'PENDING' CANCELLED = 'CANCELLED' FINISHED = 'FINISHED' class Future(Generic[T]): """Represent the outcome of a task in the future.""" def __init__(self, *, executor: Optional['Executor'] = None) -> None: self._state = FutureState.PENDING # the final return value of the handler self._result: Optional[T] = None # An exception raised by the handler when called self._exception: Optional[Exception] = None self._exception_fetched = False # callbacks to be scheduled after this task completes self._callbacks: List[Callable[['Future[T]'], None]] = [] # Lock for threadsafety self._lock = threading.Lock() # An executor to use when scheduling done callbacks self._executor: Optional[Union[weakref.ReferenceType['Executor'], Callable[[], None]]] = None self._set_executor(executor) def __del__(self) -> None: if self._exception is not None and not self._exception_fetched: print( 'The following exception was never retrieved: ' + str(self._exception), file=sys.stderr) def __await__(self) -> Generator['Future[T]', None, Optional[T]]: # Yield if the task is not finished if self._pending(): # This tells the task to suspend until the future is done yield self if self._pending(): raise RuntimeError('Future awaited a second time before it was done') return self.result() def _pending(self) -> bool: return self._state == FutureState.PENDING def cancel(self) -> None: """Request cancellation of the running task if it is not done already.""" with self._lock: if not self._pending(): return self._state = FutureState.CANCELLED self._schedule_or_invoke_done_callbacks() def cancelled(self) -> bool: """ Indicate if the task has been cancelled. :return: True if the task was cancelled """ return self._state == FutureState.CANCELLED def done(self) -> bool: """ Indicate if the task has finished executing. :return: True if the task is finished or raised while it was executing """ return self._state == FutureState.FINISHED def result(self) -> Optional[T]: """ Get the result of a done task. :raises: Exception if one was set during the task. :return: The result set by the task, or None if no result was set. """ exception = self.exception() if exception: raise exception return self._result def exception(self) -> Optional[Exception]: """ Get an exception raised by a done task. :return: The exception raised by the task """ self._exception_fetched = True return self._exception def set_result(self, result: T) -> None: """ Set the result returned by a task. :param result: The output of a long running task. """ with self._lock: self._result = result self._state = FutureState.FINISHED self._schedule_or_invoke_done_callbacks() def set_exception(self, exception: Exception) -> None: """ Set the exception raised by the task. :param result: The output of a long running task. """ with self._lock: self._exception = exception self._exception_fetched = False self._state = FutureState.FINISHED self._schedule_or_invoke_done_callbacks() def _schedule_or_invoke_done_callbacks(self) -> None: """ Schedule done callbacks on the executor if possible, else run them directly. This function assumes self._lock is not held. """ with self._lock: assert self._executor is not None executor = self._executor() callbacks = self._callbacks self._callbacks = [] if executor is not None: # Have the executor take care of the callbacks for callback in callbacks: executor.create_task(callback, self) else: # No executor, call right away for callback in callbacks: try: callback(self) except Exception as e: # Don't let exceptions be raised because there may be more callbacks to call warnings.warn('Unhandled exception in done callback: {}'.format(e)) def _set_executor(self, executor: Optional['Executor']) -> None: """Set the executor this future is associated with.""" with self._lock: if executor is None: self._executor = _fake_weakref else: self._executor = weakref.ref(executor) def add_done_callback(self, callback: Callable[['Future[T]'], None]) -> None: """ Add a callback to be executed when the task is done. Callbacks should not raise exceptions. The callback may be called immediately by this method if the future is already done. If this happens and the callback raises, the exception will be raised by this method. :param callback: a callback taking the future as an argument to be run when completed """ invoke = False with self._lock: if not self._pending(): assert self._executor is not None executor = self._executor() if executor is not None: executor.create_task(callback, self) else: invoke = True else: self._callbacks.append(callback) # Invoke when not holding self._lock if invoke: callback(self) def remove_done_callback(self, callback: Callable[['Future[T]'], None]) -> bool: """ Remove a previously-added done callback. Returns true if the given callback was found and removed. Always fails if the Future was already complete. """ with self._lock: try: self._callbacks.remove(callback) except ValueError: return False return True class Task(Future[T]): """ Execute a function or coroutine. This executes either a normal function or a coroutine to completion. On completion it creates tasks for any 'done' callbacks. This class should only be instantiated by :class:`rclpy.executors.Executor`. """ @overload def __init__(self, handler: Callable[..., Coroutine[Any, Any, T]], args: Optional[Tuple[Any, ...]] = None, kwargs: Optional[Dict[str, Any]] = None, executor: Optional['Executor'] = None) -> None: ... @overload def __init__(self, handler: Callable[..., T], args: Optional[Tuple[Any, ...]] = None, kwargs: Optional[Dict[str, Any]] = None, executor: Optional['Executor'] = None) -> None: ... def __init__(self, handler: Callable[..., Any], args: Optional[Tuple[Any, ...]] = None, kwargs: Optional[Dict[str, Any]] = None, executor: Optional['Executor'] = None) -> None: super().__init__(executor=executor) # Arguments passed into the function if args is None: args = () self._args: Optional[Tuple[Any, ...]] = args if kwargs is None: kwargs = {} self._kwargs: Optional[Dict[str, Any]] = kwargs # _handler is either a normal function or a coroutine if inspect.iscoroutinefunction(handler): self._handler: Union[ Coroutine[Any, Any, T], Callable[[], T], None ] = cast(Coroutine[Any, Any, T], handler(*args, **kwargs)) self._args = None self._kwargs = None else: handler = cast(Callable[[], T], handler) self._handler = handler # True while the task is being executed self._executing = False # Lock acquired to prevent task from executing in parallel with itself self._task_lock = threading.Lock() def __call__(self) -> None: """ Run or resume a task. This attempts to execute a handler. If the handler is a coroutine it will attempt to await it. If there are done callbacks it will schedule them with the executor. The return value of the handler is stored as the task result. """ if ( not self._pending() or self._executing or not self._task_lock.acquire(blocking=False) ): return try: if not self._pending(): return self._executing = True if inspect.iscoroutine(self._handler): self._execute_coroutine_step(self._handler) else: # Execute a normal function try: assert self._handler is not None and callable(self._handler) self.set_result(self._handler(*self._args, **self._kwargs)) except Exception as e: self.set_exception(e) self._complete_task() self._executing = False finally: self._task_lock.release() def _execute_coroutine_step(self, coro: Coroutine[Any, Any, T]) -> None: """Execute or resume a coroutine task.""" try: result = coro.send(None) except StopIteration as e: # The coroutine finished; store the result self.set_result(e.value) self._complete_task() except Exception as e: # The coroutine raised; store the exception self.set_exception(e) self._complete_task() else: # The coroutine yielded; suspend the task until it is resumed executor = self._executor() if executor is None: raise RuntimeError( 'Task tried to reschedule but no executor was set: ' 'tasks should only be initialized through executor.create_task()') elif isinstance(result, Future): # Schedule the task to resume when the future is done self._add_resume_callback(result, executor) elif result is None: # The coroutine yielded None, schedule the task to resume in the next spin executor._call_task_in_next_spin(self) else: raise TypeError( f'Expected coroutine to yield a Future or None, got: {type(result)}') def _add_resume_callback(self, future: Future[T], executor: 'Executor') -> None: future_executor = future._executor() if future_executor is None: # The future is not associated with an executor yet, so associate it with ours future._set_executor(executor) elif future_executor is not executor: raise RuntimeError('A task can only await futures associated with the same executor') # The future is associated with the same executor, so we can resume the task directly # in the done callback future.add_done_callback(lambda _: self.__call__()) def _complete_task(self) -> None: """Cleanup after task finished.""" self._handler = None self._args = None self._kwargs = None def executing(self) -> bool: """ Check if the task is currently being executed. :return: True if the task is currently executing. """ return self._executing def cancel(self) -> None: if self._pending() and inspect.iscoroutine(self._handler): self._handler.close() super().cancel()
# Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Any from typing import Callable from typing import List from typing import Tuple import unittest from rclpy.task import Future from rclpy.task import Task class DummyExecutor: def __init__(self) -> None: self.done_callbacks: List[Tuple[Callable[..., Any], Any]] = [] def create_task(self, cb: Callable[..., Any], *args: Any) -> None: self.done_callbacks.append((cb, args)) class TestTask(unittest.TestCase): def test_task_normal_callable(self) -> None: def func() -> str: return 'Sentinel Result' t = Task(func) t() self.assertTrue(t.done()) self.assertEqual('Sentinel Result', t.result()) def test_task_lambda(self) -> None: def func() -> str: return 'Sentinel Result' t = Task(lambda: func()) t() self.assertTrue(t.done()) self.assertEqual('Sentinel Result', t.result()) def test_done_callback_scheduled(self) -> None: executor = DummyExecutor() t = Task(lambda: None, executor=executor) # type: ignore[call-overload] t.add_done_callback('Sentinel Value') t() self.assertTrue(t.done()) self.assertEqual(1, len(executor.done_callbacks)) self.assertEqual('Sentinel Value', executor.done_callbacks[0][0]) args = executor.done_callbacks[0][1] self.assertEqual(1, len(args)) self.assertEqual(t, args[0]) def test_done_task_done_callback_scheduled(self) -> None: executor = DummyExecutor() t = Task(lambda: None, executor=executor) # type: ignore[call-overload] t() self.assertTrue(t.done()) t.add_done_callback('Sentinel Value') self.assertEqual(1, len(executor.done_callbacks)) self.assertEqual('Sentinel Value', executor.done_callbacks[0][0]) args = executor.done_callbacks[0][1] self.assertEqual(1, len(args)) self.assertEqual(t, args[0]) def test_done_task_called(self) -> None: called = False def func() -> None: nonlocal called called = True t = Task(func) t() self.assertTrue(called) self.assertTrue(t.done()) called = False t() self.assertFalse(called) self.assertTrue(t.done()) def test_cancelled(self) -> None: t = Task(lambda: None) t.cancel() self.assertTrue(t.cancelled()) def test_done_task_cancelled(self) -> None: t = Task(lambda: None) t() t.cancel() self.assertFalse(t.cancelled()) def test_exception(self) -> None: def func() -> None: e = Exception() e.sentinel_value = 'Sentinel Exception' # type: ignore[attr-defined] raise e t = Task(func) t() self.assertTrue(t.done()) self.assertEqual('Sentinel Exception', t.exception().sentinel_value) # type: ignore[union-attr] with self.assertRaises(Exception): t.result() def test_coroutine_exception(self) -> None: async def coro() -> None: e = Exception() e.sentinel_value = 'Sentinel Exception' # type: ignore[attr-defined] raise e t = Task(coro) t() self.assertTrue(t.done()) self.assertEqual('Sentinel Exception', t.exception().sentinel_value) # type: ignore[union-attr] with self.assertRaises(Exception): t.result() def test_task_normal_callable_args(self) -> None: arg_in = 'Sentinel Arg' def func(arg: Any) -> Any: return arg t = Task(func, args=(arg_in,)) t() self.assertEqual('Sentinel Arg', t.result()) def test_coroutine_args(self) -> None: arg_in = 'Sentinel Arg' async def coro(arg: Any) -> Any: return arg t = Task(coro, args=(arg_in,)) t() self.assertEqual('Sentinel Arg', t.result()) def test_task_normal_callable_kwargs(self) -> None: arg_in = 'Sentinel Arg' def func(kwarg: Any = None) -> Any: return kwarg t = Task(func, kwargs={'kwarg': arg_in}) t() self.assertEqual('Sentinel Arg', t.result()) def test_coroutine_kwargs(self) -> None: arg_in = 'Sentinel Arg' async def coro(kwarg: Any = None) -> Any: return kwarg t = Task(coro, kwargs={'kwarg': arg_in}) t() self.assertEqual('Sentinel Arg', t.result()) def test_executing(self) -> None: t = Task(lambda: None) self.assertFalse(t.executing()) class TestFuture(unittest.TestCase): def test_cancelled(self) -> None: f: Future[Any] = Future() f.cancel() self.assertTrue(f.cancelled()) def test_done(self) -> None: f: Future[None] = Future() self.assertFalse(f.done()) f.set_result(None) self.assertTrue(f.done()) def test_set_result(self) -> None: f: Future[str] = Future() f.set_result('Sentinel Result') self.assertEqual('Sentinel Result', f.result()) self.assertTrue(f.done()) def test_set_exception(self) -> None: f: Future[Any] = Future() f.set_exception('Sentinel Exception') # type: ignore[arg-type] self.assertEqual('Sentinel Exception', f.exception()) self.assertTrue(f.done()) def test_await(self) -> None: f: Future[str] = Future() async def coro() -> Any: nonlocal f return await f c = coro() c.send(None) f.set_result('Sentinel Result') try: c.send(None) except StopIteration as e: self.assertEqual('Sentinel Result', e.value) def test_await_exception(self) -> None: f: Future[Any] = Future() async def coro() -> Any: nonlocal f return await f c = coro() c.send(None) f.set_exception(RuntimeError('test exception')) with self.assertRaises(RuntimeError): c.send(None) def test_cancel_schedules_callbacks(self) -> None: executor = DummyExecutor() f: Future[Any] = Future(executor=executor) # type: ignore[arg-type] f.add_done_callback(lambda f: None) f.cancel() self.assertTrue(executor.done_callbacks) def test_set_result_schedules_callbacks(self) -> None: executor = DummyExecutor() f: Future[str] = Future(executor=executor) # type: ignore[arg-type] f.add_done_callback(lambda f: None) f.set_result('Anything') self.assertTrue(executor.done_callbacks) def test_set_exception_schedules_callbacks(self) -> None: executor = DummyExecutor() f: Future[Any] = Future(executor=executor) # type: ignore[arg-type] f.add_done_callback(lambda f: None) f.set_exception(Exception('Anything')) self.assertTrue(executor.done_callbacks) def test_cancel_invokes_callbacks(self) -> None: called = False def cb(fut: Future[Any]) -> None: nonlocal called called = True f: Future[Any] = Future() f.add_done_callback(cb) f.cancel() assert called def test_set_result_invokes_callbacks(self) -> None: called = False def cb(fut: Future[Any]) -> None: nonlocal called called = True f: Future[str] = Future() f.add_done_callback(cb) f.set_result('Anything') assert called def test_set_exception_invokes_callbacks(self) -> None: called = False def cb(fut: Future[Any]) -> None: nonlocal called called = True f: Future[Any] = Future() f.add_done_callback(cb) f.set_exception(Exception('Anything')) assert called def test_add_done_callback_invokes_callback(self) -> None: called = False def cb(fut: Future[Any]) -> None: nonlocal called called = True f: Future[str] = Future() f.set_result('Anything') f.add_done_callback(cb) assert called def test_set_result_on_done_future_without_exception(self) -> None: f: Future[None] = Future() f.set_result(None) self.assertTrue(f.done()) self.assertFalse(f.cancelled()) f.set_result(None) self.assertTrue(f.done()) self.assertFalse(f.cancelled()) def test_set_result_on_cancelled_future_without_exception(self) -> None: f: Future[None] = Future() f.cancel() self.assertTrue(f.cancelled()) self.assertFalse(f.done()) f.set_result(None) self.assertTrue(f.done()) def test_set_exception_on_done_future_without_exception(self) -> None: f: Future[None] = Future() f.set_result(None) self.assertIsNone(f.exception()) f.set_exception(Exception()) f.set_result(None) self.assertIsNotNone(f.exception()) def test_set_exception_on_cancelled_future_without_exception(self) -> None: f: Future[Any] = Future() f.cancel() self.assertTrue(f.cancelled()) self.assertIsNone(f.exception()) f.set_exception(Exception()) self.assertIsNotNone(f.exception()) if __name__ == '__main__': unittest.main()
rclpy
python
# Copyright 2016 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import threading from types import TracebackType from typing import Callable from typing import Coroutine from typing import Optional from typing import Type from typing import Union from rclpy.callback_groups import CallbackGroup from rclpy.clock import Clock from rclpy.clock_type import ClockType from rclpy.context import Context from rclpy.exceptions import InvalidHandle, ROSInterruptException from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy from rclpy.time import Time from rclpy.utilities import get_default_context from typing_extensions import TypeAlias class TimerInfo: """ Represents a timer call information. A ``TimerInfo`` object encapsulate the timer information when called. """ def __init__( self, *, expected_call_time: int = 0, actual_call_time: int = 0, clock_type: ClockType = ClockType.SYSTEM_TIME, ) -> None: if not isinstance(clock_type, ClockType): raise TypeError('Clock type must be a ClockType enum') if expected_call_time < 0 or actual_call_time < 0: raise ValueError('call time values must not be negative') self._expected_call_time: Time = Time( nanoseconds=expected_call_time, clock_type=clock_type) self._actual_call_time: Time = Time( nanoseconds=actual_call_time, clock_type=clock_type) @property def expected_call_time(self) -> Time: """:return: the expected_call_time.""" return self._expected_call_time @property def actual_call_time(self) -> Time: """:return: the actual_call_time.""" return self._actual_call_time TimerCallbackType: TypeAlias = Union[Callable[[], None], Callable[[TimerInfo], None], Callable[[], Coroutine[None, None, None]]] class Timer: def __init__( self, callback: Optional[TimerCallbackType], callback_group: Optional[CallbackGroup], timer_period_ns: int, clock: Clock, *, context: Optional[Context] = None, autostart: bool = True ) -> None: """ Create a Timer. If autostart is ``True`` (the default), the timer will be started and every ``timer_period_sec`` number of seconds the provided callback function will be called. If autostart is ``False``, the timer will be created but not started; it can then be started by calling ``reset()`` on the timer object. .. warning:: Users should not create a timer with this constructor, instead they should call :meth:`.Node.create_timer`. :param callback: A user-defined callback function that is called when the timer expires. :param callback_group: The callback group for the timer. If ``None``, then the default callback group for the node is used. :param timer_period_ns: The period (in nanoseconds) of the timer. :param clock: The clock which the timer gets time from. :param context: The context to be associated with. :param autostart: Whether to automatically start the timer after creation; defaults to ``True``. """ self._context = get_default_context() if context is None else context self._clock = clock if self._context.handle is None: raise RuntimeError('Context must be initialized before create a _rclpy.Timer.') with self._clock.handle, self._context.handle: self.__timer = _rclpy.Timer( self._clock.handle, self._context.handle, timer_period_ns, autostart) self.timer_period_ns = timer_period_ns self.callback = callback self.callback_group = callback_group # True when the callback is ready to fire but has not been "taken" by an executor self._executor_event = False @property def handle(self) -> _rclpy.Timer: return self.__timer def destroy(self) -> None: """ Destroy a container for a ROS timer. .. warning:: Users should not destroy a timer with this method, instead they should call :meth:`.Node.destroy_timer`. """ self.__timer.destroy_when_not_in_use() @property def clock(self) -> Clock: return self._clock @property def timer_period_ns(self) -> int: with self.__timer: val = self.__timer.get_timer_period() self.__timer_period_ns = val return val @timer_period_ns.setter def timer_period_ns(self, value: int) -> None: val = int(value) with self.__timer: self.__timer.change_timer_period(val) self.__timer_period_ns = val def is_ready(self) -> bool: with self.__timer: return self.__timer.is_timer_ready() def is_canceled(self) -> bool: with self.__timer: return self.__timer.is_timer_canceled() def cancel(self) -> None: with self.__timer: self.__timer.cancel_timer() def reset(self) -> None: with self.__timer: self.__timer.reset_timer() def time_since_last_call(self) -> int: with self.__timer: return self.__timer.time_since_last_call() def time_until_next_call(self) -> Optional[int]: with self.__timer: return self.__timer.time_until_next_call() def __enter__(self) -> 'Timer': return self def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: self.destroy() class Rate: """A utility for sleeping at a fixed rate.""" def __init__(self, timer: Timer, *, context: Context) -> None: """ Create a Rate. .. warning:: Users should not create a rate with this constructor, instead they should call :meth:`.Node.create_rate`. """ # Rate is a wrapper around a timer self._timer = timer self._is_shutdown = False self._is_destroyed = False # This event is set to wake sleepers self._event = threading.Event() self._lock = threading.Lock() self._num_sleepers = 0 # Set event when timer fires self._timer.callback = self._event.set # Set event when ROS is shutdown context.on_shutdown(self._on_shutdown) def _on_shutdown(self) -> None: self._is_shutdown = True self.destroy() def destroy(self) -> None: """ Destroy a container for a ROS rate. .. warning:: Users should not destroy a rate with this method, instead they should call :meth:`.Node.destroy_rate`. """ self._is_destroyed = True self._event.set() def _presleep(self) -> None: if self._is_shutdown: raise ROSInterruptException() if self._is_destroyed: raise RuntimeError('Rate cannot sleep because it has been destroyed') if not self._timer.handle: self.destroy() raise InvalidHandle('Rate cannot sleep because the timer has been destroyed') with self._lock: self._num_sleepers += 1 def _postsleep(self) -> None: with self._lock: self._num_sleepers -= 1 if self._num_sleepers == 0: self._event.clear() if self._is_shutdown: self.destroy() raise ROSInterruptException() def sleep(self) -> None: """ Block until timer triggers. Care should be taken when calling this from a callback. This may block forever if called in a callback in a SingleThreadedExecutor. """ self._presleep() try: self._event.wait() finally: self._postsleep()
# Copyright 2016 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import functools import os import platform import time from typing import List from typing import Optional from unittest.mock import Mock import pytest import rclpy from rclpy.clock_type import ClockType from rclpy.constants import S_TO_NS from rclpy.executors import SingleThreadedExecutor from rclpy.timer import TimerInfo @pytest.fixture def context() -> None: return rclpy.context.Context() @pytest.fixture def setup_ros(context) -> None: rclpy.init(context=context) yield rclpy.shutdown(context=context) @pytest.fixture def test_node(context, setup_ros): node = rclpy.create_node('test_node', context=context) yield node node.destroy_node() TEST_PERIODS = ( 0.1, pytest.param( 0.01, marks=( pytest.mark.skipif(os.name == 'nt', reason='Flaky on windows'), ) ), pytest.param( 0.001, marks=( pytest.mark.skipif(os.name == 'nt', reason='Flaky on windows'), pytest.mark.skipif(platform.machine() == 'aarch64', reason='Flaky on arm') ) ) ) @pytest.mark.parametrize('period', TEST_PERIODS) def test_zero_callback(period: float) -> None: context = rclpy.context.Context() rclpy.init(context=context) try: node = rclpy.create_node('test_timer_no_callback', context=context) try: executor = SingleThreadedExecutor(context=context) try: executor.add_node(node) # The first spin_once() takes long enough for 1ms timer tests to fail executor.spin_once(timeout_sec=0) callbacks: List[int] = [] timer = node.create_timer(period, lambda: callbacks.append(len(callbacks))) try: executor.spin_once(timeout_sec=(period / 2)) assert len(callbacks) == 0 finally: node.destroy_timer(timer) finally: executor.shutdown() finally: node.destroy_node() finally: rclpy.shutdown(context=context) @pytest.mark.parametrize('period', TEST_PERIODS) def test_number_callbacks(period: float) -> None: context = rclpy.context.Context() rclpy.init(context=context) try: node = rclpy.create_node('test_timer_number_callbacks', context=context) try: executor = SingleThreadedExecutor(context=context) try: executor.add_node(node) # The first spin_once() takes long enough for 1ms timer tests to fail executor.spin_once(timeout_sec=0) callbacks: List[int] = [] timer = node.create_timer(period, lambda: callbacks.append(len(callbacks))) try: begin_time = time.time() while rclpy.ok(context=context) and time.time() - begin_time < 4.5 * period: executor.spin_once(timeout_sec=period / 10) assert len(callbacks) == 4 finally: node.destroy_timer(timer) finally: executor.shutdown() finally: node.destroy_node() finally: rclpy.shutdown(context=context) @pytest.mark.parametrize('period', TEST_PERIODS) def test_cancel_reset(period: float) -> None: context = rclpy.context.Context() rclpy.init(context=context) try: node = rclpy.create_node('test_timer_cancel_reset', context=context) try: executor = SingleThreadedExecutor(context=context) try: executor.add_node(node) # The first spin_once() takes long enough for 1ms timer tests to fail executor.spin_once(timeout_sec=0) callbacks: List[int] = [] timer = node.create_timer(period, lambda: callbacks.append(len(callbacks))) try: # Make sure callbacks can be received assert not timer.is_canceled() begin_time = time.time() while rclpy.ok(context=context) and time.time() - begin_time < 2.5 * period: executor.spin_once(timeout_sec=period / 10) assert len(callbacks) == 2 # Cancel timer and make sure no callbacks are received assert not timer.is_canceled() timer.cancel() assert timer.is_canceled() callbacks = [] begin_time = time.time() while rclpy.ok(context=context) and time.time() - begin_time < 2.5 * period: executor.spin_once(timeout_sec=period / 10) assert [] == callbacks # Reenable timer and make sure callbacks are received again timer.reset() assert not timer.is_canceled() begin_time = time.time() while rclpy.ok(context=context) and time.time() - begin_time < 2.5 * period: executor.spin_once(timeout_sec=period / 10) assert len(callbacks) == 2 finally: node.destroy_timer(timer) finally: executor.shutdown() finally: node.destroy_node() finally: rclpy.shutdown(context=context) def test_time_until_next_call() -> None: node = None executor = None timer = None context = rclpy.context.Context() rclpy.init(context=context) try: node = rclpy.create_node('test_time_until_next_call', context=context) executor = SingleThreadedExecutor(context=context) executor.add_node(node) executor.spin_once(timeout_sec=0) timer = node.create_timer(1, lambda: None) assert not timer.is_canceled() executor.spin_once(0.1) time_until_next_call = timer.time_until_next_call() assert time_until_next_call is not None assert time_until_next_call <= (1 * S_TO_NS) timer.reset() assert not timer.is_canceled() time_until_next_call = timer.time_until_next_call() assert time_until_next_call is not None assert time_until_next_call <= (1 * S_TO_NS) timer.cancel() assert timer.is_canceled() assert timer.time_until_next_call() is None finally: if executor is not None: executor.shutdown() if node is not None: if timer is not None: node.destroy_timer(timer) node.destroy_node() rclpy.shutdown(context=context) def test_timer_without_autostart() -> None: node = None timer = None rclpy.init() try: node = rclpy.create_node('test_timer_without_autostart') timer = node.create_timer(1, lambda: None, autostart=False) assert timer.is_canceled() timer.reset() assert not timer.is_canceled() timer.cancel() assert timer.is_canceled() finally: if node is not None: if timer is not None: node.destroy_timer(timer) node.destroy_node() rclpy.shutdown() def test_timer_context_manager() -> None: rclpy.init() try: with rclpy.create_node('test_timer_without_autostart') as node: with node.create_timer(1, lambda: None, autostart=False) as timer: assert timer.is_canceled() timer.reset() assert not timer.is_canceled() timer.cancel() assert timer.is_canceled() finally: rclpy.shutdown() def test_timer_info_construction() -> None: timer_info = TimerInfo() assert timer_info.expected_call_time.nanoseconds == 0 assert timer_info.actual_call_time.nanoseconds == 0 assert timer_info.expected_call_time.clock_type == ClockType.SYSTEM_TIME assert timer_info.actual_call_time.clock_type == ClockType.SYSTEM_TIME timer_info = TimerInfo( expected_call_time=123456789, actual_call_time=987654321, clock_type=ClockType.STEADY_TIME ) assert timer_info.expected_call_time.nanoseconds == 123456789 assert timer_info.actual_call_time.nanoseconds == 987654321 assert timer_info.expected_call_time.clock_type == ClockType.STEADY_TIME assert timer_info.actual_call_time.clock_type == ClockType.STEADY_TIME timer_info_copy = timer_info assert timer_info_copy.expected_call_time.nanoseconds == 123456789 assert timer_info_copy.actual_call_time.nanoseconds == 987654321 assert timer_info_copy.expected_call_time.clock_type == ClockType.STEADY_TIME assert timer_info_copy.actual_call_time.clock_type == ClockType.STEADY_TIME def test_timer_with_info() -> None: node = None executor = None timer = None timer_info: Optional[TimerInfo] = None context = rclpy.context.Context() rclpy.init(context=context) try: node = rclpy.create_node('test_timer_with_info', context=context) executor = SingleThreadedExecutor(context=context) executor.add_node(node) executor.spin_once(timeout_sec=0) def timer_callback(info: TimerInfo) -> None: nonlocal timer_info timer_info = info timer = node.create_timer(1, timer_callback) assert not timer.is_canceled() executor.spin_once(3) timer.cancel() assert timer.is_canceled() assert timer_info is not None assert timer_info.actual_call_time.clock_type == timer.clock.clock_type assert timer_info.expected_call_time.clock_type == timer.clock.clock_type assert timer_info.actual_call_time.nanoseconds > 0 assert timer_info.expected_call_time.nanoseconds > 0 finally: if executor is not None: executor.shutdown() if node is not None: if timer is not None: node.destroy_timer(timer) node.destroy_node() rclpy.shutdown(context=context) def test_timer_info_with_partial() -> None: node = None executor = None timer = None timer_info: Optional[TimerInfo] = None timer_called = False context = rclpy.context.Context() rclpy.init(context=context) try: node = rclpy.create_node('test_timer_with_partial', context=context) executor = SingleThreadedExecutor(context=context) executor.add_node(node) executor.spin_once(timeout_sec=0) def timer_callback(info: TimerInfo) -> None: nonlocal timer_info timer_info = info nonlocal timer_called if timer_called is False: timer_called = True timer = node.create_timer(1, functools.partial(timer_callback)) assert not timer.is_canceled() executor.spin_once(3) timer.cancel() assert timer.is_canceled() assert timer_called is True assert timer_info is not None assert timer_info.actual_call_time.clock_type == timer.clock.clock_type assert timer_info.expected_call_time.clock_type == timer.clock.clock_type assert timer_info.actual_call_time.nanoseconds > 0 assert timer_info.expected_call_time.nanoseconds > 0 finally: if executor is not None: executor.shutdown() if node is not None: if timer is not None: node.destroy_timer(timer) node.destroy_node() rclpy.shutdown(context=context) def test_on_reset_callback(test_node): tmr = test_node.create_timer(1, lambda: None) cb = Mock() tmr.handle.set_on_reset_callback(cb) cb.assert_not_called() tmr.reset() cb.assert_called_once_with(1) tmr.handle.clear_on_reset_callback() tmr.reset() cb.assert_called_once()
rclpy
python
# Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. from sensor_msgs.msg import PointCloud2 from sensor_msgs.point_cloud2 import read_points, create_cloud import PyKDL import rospy import tf2_ros def to_msg_msg(msg): return msg tf2_ros.ConvertRegistration().add_to_msg(PointCloud2, to_msg_msg) def from_msg_msg(msg): return msg tf2_ros.ConvertRegistration().add_from_msg(PointCloud2, from_msg_msg) def transform_to_kdl(t): return PyKDL.Frame(PyKDL.Rotation.Quaternion(t.transform.rotation.x, t.transform.rotation.y, t.transform.rotation.z, t.transform.rotation.w), PyKDL.Vector(t.transform.translation.x, t.transform.translation.y, t.transform.translation.z)) # PointStamped def do_transform_cloud(cloud, transform): t_kdl = transform_to_kdl(transform) points_out = [] for p_in in read_points(cloud): p_out = t_kdl * PyKDL.Vector(p_in[0], p_in[1], p_in[2]) points_out.append((p_out[0], p_out[1], p_out[2]) + p_in[3:]) res = create_cloud(transform.header, cloud.fields, points_out) return res tf2_ros.TransformRegistration().add(PointCloud2, do_transform_cloud)
#!/usr/bin/env python from __future__ import print_function import unittest import struct import tf2_sensor_msgs from sensor_msgs import point_cloud2 from sensor_msgs.msg import PointField from tf2_ros import TransformStamped import copy ## A sample python unit test class PointCloudConversions(unittest.TestCase): def setUp(self): self.point_cloud_in = point_cloud2.PointCloud2() self.point_cloud_in.fields = [PointField('x', 0, PointField.FLOAT32, 1), PointField('y', 4, PointField.FLOAT32, 1), PointField('z', 8, PointField.FLOAT32, 1)] self.point_cloud_in.point_step = 4 * 3 self.point_cloud_in.height = 1 # we add two points (with x, y, z to the cloud) self.point_cloud_in.width = 2 self.point_cloud_in.row_step = self.point_cloud_in.point_step * self.point_cloud_in.width points = [1, 2, 0, 10, 20, 30] self.point_cloud_in.data = struct.pack('%sf' % len(points), *points) self.transform_translate_xyz_300 = TransformStamped() self.transform_translate_xyz_300.transform.translation.x = 300 self.transform_translate_xyz_300.transform.translation.y = 300 self.transform_translate_xyz_300.transform.translation.z = 300 self.transform_translate_xyz_300.transform.rotation.w = 1 # no rotation so we only set w assert(list(point_cloud2.read_points(self.point_cloud_in)) == [(1.0, 2.0, 0.0), (10.0, 20.0, 30.0)]) def test_simple_transform(self): old_data = copy.deepcopy(self.point_cloud_in.data) # deepcopy is not required here because we have a str for now point_cloud_transformed = tf2_sensor_msgs.do_transform_cloud(self.point_cloud_in, self.transform_translate_xyz_300) k = 300 expected_coordinates = [(1+k, 2+k, 0+k), (10+k, 20+k, 30+k)] new_points = list(point_cloud2.read_points(point_cloud_transformed)) print("new_points are %s" % new_points) assert(expected_coordinates == new_points) assert(old_data == self.point_cloud_in.data) # checking no modification in input cloud ## A simple unit test for tf2_sensor_msgs.do_transform_cloud (multi channel version) class PointCloudConversionsMultichannel(unittest.TestCase): TRANSFORM_OFFSET_DISTANCE = 300 def setUp(self): self.point_cloud_in = point_cloud2.PointCloud2() self.point_cloud_in.fields = [PointField('x', 0, PointField.FLOAT32, 1), PointField('y', 4, PointField.FLOAT32, 1), PointField('z', 8, PointField.FLOAT32, 1), PointField('index', 12, PointField.INT32, 1)] self.point_cloud_in.point_step = 4 * 4 self.point_cloud_in.height = 1 # we add two points (with x, y, z to the cloud) self.point_cloud_in.width = 2 self.point_cloud_in.row_step = self.point_cloud_in.point_step * self.point_cloud_in.width self.points = [(1.0, 2.0, 0.0, 123), (10.0, 20.0, 30.0, 456)] for point in self.points: self.point_cloud_in.data += struct.pack('3fi', *point) self.transform_translate_xyz_300 = TransformStamped() self.transform_translate_xyz_300.transform.translation.x = self.TRANSFORM_OFFSET_DISTANCE self.transform_translate_xyz_300.transform.translation.y = self.TRANSFORM_OFFSET_DISTANCE self.transform_translate_xyz_300.transform.translation.z = self.TRANSFORM_OFFSET_DISTANCE self.transform_translate_xyz_300.transform.rotation.w = 1 # no rotation so we only set w assert(list(point_cloud2.read_points(self.point_cloud_in)) == self.points) def test_simple_transform_multichannel(self): old_data = copy.deepcopy(self.point_cloud_in.data) # deepcopy is not required here because we have a str for now point_cloud_transformed = tf2_sensor_msgs.do_transform_cloud(self.point_cloud_in, self.transform_translate_xyz_300) expected_coordinates = [] for point in self.points: expected_coordinates += [( point[0] + self.TRANSFORM_OFFSET_DISTANCE, point[1] + self.TRANSFORM_OFFSET_DISTANCE, point[2] + self.TRANSFORM_OFFSET_DISTANCE, point[3] # index channel must be kept same )] new_points = list(point_cloud2.read_points(point_cloud_transformed)) print("new_points are %s" % new_points) assert(expected_coordinates == new_points) assert(old_data == self.point_cloud_in.data) # checking no modification in input cloud if __name__ == '__main__': import rosunit rosunit.unitrun("test_tf2_sensor_msgs", "test_point_cloud_conversion", PointCloudConversions) rosunit.unitrun("test_tf2_sensor_msgs", "test_point_cloud_conversion", PointCloudConversionsMultichannel)
geometry2
python
#! /usr/bin/python #*********************************************************** #* Software License Agreement (BSD License) #* #* Copyright (c) 2009, Willow Garage, Inc. #* All rights reserved. #* #* Redistribution and use in source and binary forms, with or without #* modification, are permitted provided that the following conditions #* are met: #* #* * Redistributions of source code must retain the above copyright #* notice, this list of conditions and the following disclaimer. #* * Redistributions in binary form must reproduce the above #* copyright notice, this list of conditions and the following #* disclaimer in the documentation and/or other materials provided #* with the distribution. #* * Neither the name of Willow Garage, Inc. nor the names of its #* contributors may be used to endorse or promote products derived #* from this software without specific prior written permission. #* #* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS #* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT #* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS #* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE #* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, #* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, #* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; #* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER #* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT #* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN #* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #* POSSIBILITY OF SUCH DAMAGE. #* #* Author: Eitan Marder-Eppstein #*********************************************************** import rospy import actionlib import tf2_py as tf2 import tf2_ros from tf2_msgs.msg import LookupTransformAction, LookupTransformGoal from actionlib_msgs.msg import GoalStatus class BufferClient(tf2_ros.BufferInterface): """ Action client-based implementation of BufferInterface. """ def __init__(self, ns, check_frequency = None, timeout_padding = rospy.Duration.from_sec(2.0)): """ .. function:: __init__(ns, check_frequency = None, timeout_padding = rospy.Duration.from_sec(2.0)) Constructor. :param ns: The namespace in which to look for a BufferServer. :param check_frequency: How frequently to check for updates to known transforms. :param timeout_padding: A constant timeout to add to blocking calls. """ tf2_ros.BufferInterface.__init__(self) self.client = actionlib.SimpleActionClient(ns, LookupTransformAction) self.timeout_padding = timeout_padding if check_frequency is not None: rospy.logwarn('Argument check_frequency is deprecated and should not be used.') def wait_for_server(self, timeout = rospy.Duration()): """ Block until the action server is ready to respond to requests. :param timeout: Time to wait for the server. :return: True if the server is ready, false otherwise. :rtype: bool """ return self.client.wait_for_server(timeout) # lookup, simple api def lookup_transform(self, target_frame, source_frame, time, timeout=rospy.Duration(0.0)): """ Get the transform from the source frame to the target frame. :param target_frame: Name of the frame to transform into. :param source_frame: Name of the input frame. :param time: The time at which to get the transform. (0 will get the latest) :param timeout: (Optional) Time to wait for the target frame to become available. :return: The transform between the frames. :rtype: :class:`geometry_msgs.msg.TransformStamped` """ goal = LookupTransformGoal() goal.target_frame = target_frame; goal.source_frame = source_frame; goal.source_time = time; goal.timeout = timeout; goal.advanced = False; return self.__process_goal(goal) # lookup, advanced api def lookup_transform_full(self, target_frame, target_time, source_frame, source_time, fixed_frame, timeout=rospy.Duration(0.0)): """ Get the transform from the source frame to the target frame using the advanced API. :param target_frame: Name of the frame to transform into. :param target_time: The time to transform to. (0 will get the latest) :param source_frame: Name of the input frame. :param source_time: The time at which source_frame will be evaluated. (0 will get the latest) :param fixed_frame: Name of the frame to consider constant in time. :param timeout: (Optional) Time to wait for the target frame to become available. :return: The transform between the frames. :rtype: :class:`geometry_msgs.msg.TransformStamped` """ goal = LookupTransformGoal() goal.target_frame = target_frame; goal.source_frame = source_frame; goal.source_time = source_time; goal.timeout = timeout; goal.target_time = target_time; goal.fixed_frame = fixed_frame; goal.advanced = True; return self.__process_goal(goal) # can, simple api def can_transform(self, target_frame, source_frame, time, timeout=rospy.Duration(0.0)): """ Check if a transform from the source frame to the target frame is possible. :param target_frame: Name of the frame to transform into. :param source_frame: Name of the input frame. :param time: The time at which to get the transform. (0 will get the latest) :param timeout: (Optional) Time to wait for the target frame to become available. :param return_debug_type: (Optional) If true, return a tuple representing debug information. :return: True if the transform is possible, false otherwise. :rtype: bool """ try: self.lookup_transform(target_frame, source_frame, time, timeout) return True except tf2.TransformException: return False # can, advanced api def can_transform_full(self, target_frame, target_time, source_frame, source_time, fixed_frame, timeout=rospy.Duration(0.0)): """ Check if a transform from the source frame to the target frame is possible (advanced API). Must be implemented by a subclass of BufferInterface. :param target_frame: Name of the frame to transform into. :param target_time: The time to transform to. (0 will get the latest) :param source_frame: Name of the input frame. :param source_time: The time at which source_frame will be evaluated. (0 will get the latest) :param fixed_frame: Name of the frame to consider constant in time. :param timeout: (Optional) Time to wait for the target frame to become available. :param return_debug_type: (Optional) If true, return a tuple representing debug information. :return: True if the transform is possible, false otherwise. :rtype: bool """ try: self.lookup_transform_full(target_frame, target_time, source_frame, source_time, fixed_frame, timeout) return True except tf2.TransformException: return False def __process_goal(self, goal): self.client.send_goal(goal) if not self.client.wait_for_result(goal.timeout + self.timeout_padding): #This shouldn't happen, but could in rare cases where the server hangs raise tf2.TimeoutException("The LookupTransform goal sent to the BufferServer did not come back in the specified time. Something is likely wrong with the server") if self.client.get_state() != GoalStatus.SUCCEEDED: raise tf2.TimeoutException("The LookupTransform goal sent to the BufferServer did not come back with SUCCEEDED status. Something is likely wrong with the server.") return self.__process_result(self.client.get_result()) def __process_result(self, result): if not result: raise tf2.TransformException("The BufferServer returned None for result! Something is likely wrong with the server.") if not result.error: raise tf2.TransformException("The BufferServer returned None for result.error! Something is likely wrong with the server.") if result.error.error != result.error.NO_ERROR: if result.error.error == result.error.LOOKUP_ERROR: raise tf2.LookupException(result.error.error_string) if result.error.error == result.error.CONNECTIVITY_ERROR: raise tf2.ConnectivityException(result.error.error_string) if result.error.error == result.error.EXTRAPOLATION_ERROR: raise tf2.ExtrapolationException(result.error.error_string) if result.error.error == result.error.INVALID_ARGUMENT_ERROR: raise tf2.InvalidArgumentException(result.error.error_string) if result.error.error == result.error.TIMEOUT_ERROR: raise tf2.TimeoutException(result.error.error_string) raise tf2.TransformException(result.error.error_string) return result.transform
#! /usr/bin/env python #*********************************************************** #* Software License Agreement (BSD License) #* #* Copyright (c) 2009, Willow Garage, Inc. #* All rights reserved. #* #* Redistribution and use in source and binary forms, with or without #* modification, are permitted provided that the following conditions #* are met: #* #* * Redistributions of source code must retain the above copyright #* notice, this list of conditions and the following disclaimer. #* * Redistributions in binary form must reproduce the above #* copyright notice, this list of conditions and the following #* disclaimer in the documentation and/or other materials provided #* with the distribution. #* * Neither the name of Willow Garage, Inc. nor the names of its #* contributors may be used to endorse or promote products derived #* from this software without specific prior written permission. #* #* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS #* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT #* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS #* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE #* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, #* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, #* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; #* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER #* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT #* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN #* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #* POSSIBILITY OF SUCH DAMAGE. #* #* Author: Eitan Marder-Eppstein #*********************************************************** PKG = 'test_tf2' import sys import unittest import tf2_py as tf2 import tf2_ros import tf2_kdl import tf2_geometry_msgs from geometry_msgs.msg import PointStamped import rospy import PyKDL class TestBufferClient(unittest.TestCase): def test_buffer_client(self): client = tf2_ros.BufferClient("tf_action") client.wait_for_server() p1 = PointStamped() p1.header.frame_id = "a" p1.header.stamp = rospy.Time(0.0) p1.point.x = 0.0 p1.point.y = 0.0 p1.point.z = 0.0 try: p2 = client.transform(p1, "b") rospy.loginfo("p1: %s, p2: %s" % (p1, p2)) except tf2.TransformException as e: rospy.logerr("%s" % e) def test_transform_type(self): client = tf2_ros.BufferClient("tf_action") client.wait_for_server() p1 = PointStamped() p1.header.frame_id = "a" p1.header.stamp = rospy.Time(0.0) p1.point.x = 0.0 p1.point.y = 0.0 p1.point.z = 0.0 try: p2 = client.transform(p1, "b", new_type = PyKDL.Vector) rospy.loginfo("p1: %s, p2: %s" % (str(p1), str(p2))) except tf2.TransformException as e: rospy.logerr("%s" % e) if __name__ == '__main__': rospy.init_node("test_buffer_client") import rostest rostest.rosrun(PKG, 'test_buffer_client', TestBufferClient)
geometry2
python
""" requests.structures ~~~~~~~~~~~~~~~~~~~ Data structures that power Requests. """ from collections import OrderedDict from .compat import Mapping, MutableMapping class CaseInsensitiveDict(MutableMapping): """A case-insensitive ``dict``-like object. Implements all methods and operations of ``MutableMapping`` as well as dict's ``copy``. Also provides ``lower_items``. All keys are expected to be strings. The structure remembers the case of the last key to be set, and ``iter(instance)``, ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()`` will contain case-sensitive keys. However, querying and contains testing is case insensitive:: cid = CaseInsensitiveDict() cid['Accept'] = 'application/json' cid['aCCEPT'] == 'application/json' # True list(cid) == ['Accept'] # True For example, ``headers['content-encoding']`` will return the value of a ``'Content-Encoding'`` response header, regardless of how the header name was originally stored. If the constructor, ``.update``, or equality comparison operations are given keys that have equal ``.lower()``s, the behavior is undefined. """ def __init__(self, data=None, **kwargs): self._store = OrderedDict() if data is None: data = {} self.update(data, **kwargs) def __setitem__(self, key, value): # Use the lowercased key for lookups, but store the actual # key alongside the value. self._store[key.lower()] = (key, value) def __getitem__(self, key): return self._store[key.lower()][1] def __delitem__(self, key): del self._store[key.lower()] def __iter__(self): return (casedkey for casedkey, mappedvalue in self._store.values()) def __len__(self): return len(self._store) def lower_items(self): """Like iteritems(), but with all lowercase keys.""" return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items()) def __eq__(self, other): if isinstance(other, Mapping): other = CaseInsensitiveDict(other) else: return NotImplemented # Compare insensitively return dict(self.lower_items()) == dict(other.lower_items()) # Copy is required def copy(self): return CaseInsensitiveDict(self._store.values()) def __repr__(self): return str(dict(self.items())) class LookupDict(dict): """Dictionary lookup object.""" def __init__(self, name=None): self.name = name super().__init__() def __repr__(self): return f"<lookup '{self.name}'>" def __getitem__(self, key): # We allow fall-through here, so values default to None return self.__dict__.get(key, None) def get(self, key, default=None): return self.__dict__.get(key, default)
import pytest from requests.structures import CaseInsensitiveDict, LookupDict class TestCaseInsensitiveDict: @pytest.fixture(autouse=True) def setup(self): """CaseInsensitiveDict instance with "Accept" header.""" self.case_insensitive_dict = CaseInsensitiveDict() self.case_insensitive_dict["Accept"] = "application/json" def test_list(self): assert list(self.case_insensitive_dict) == ["Accept"] possible_keys = pytest.mark.parametrize( "key", ("accept", "ACCEPT", "aCcEpT", "Accept") ) @possible_keys def test_getitem(self, key): assert self.case_insensitive_dict[key] == "application/json" @possible_keys def test_delitem(self, key): del self.case_insensitive_dict[key] assert key not in self.case_insensitive_dict def test_lower_items(self): assert list(self.case_insensitive_dict.lower_items()) == [ ("accept", "application/json") ] def test_repr(self): assert repr(self.case_insensitive_dict) == "{'Accept': 'application/json'}" def test_copy(self): copy = self.case_insensitive_dict.copy() assert copy is not self.case_insensitive_dict assert copy == self.case_insensitive_dict @pytest.mark.parametrize( "other, result", ( ({"AccePT": "application/json"}, True), ({}, False), (None, False), ), ) def test_instance_equality(self, other, result): assert (self.case_insensitive_dict == other) is result class TestLookupDict: @pytest.fixture(autouse=True) def setup(self): """LookupDict instance with "bad_gateway" attribute.""" self.lookup_dict = LookupDict("test") self.lookup_dict.bad_gateway = 502 def test_repr(self): assert repr(self.lookup_dict) == "<lookup 'test'>" get_item_parameters = pytest.mark.parametrize( "key, value", ( ("bad_gateway", 502), ("not_a_key", None), ), ) @get_item_parameters def test_getitem(self, key, value): assert self.lookup_dict[key] == value @get_item_parameters def test_get(self, key, value): assert self.lookup_dict.get(key) == value
requests
python
""" requests.utils ~~~~~~~~~~~~~~ This module provides utility functions that are used within Requests that are also useful for external consumption. """ import codecs import contextlib import io import os import re import socket import struct import sys import tempfile import warnings import zipfile from collections import OrderedDict from urllib3.util import make_headers, parse_url from . import certs from .__version__ import __version__ # to_native_string is unused here, but imported here for backwards compatibility from ._internal_utils import ( # noqa: F401 _HEADER_VALIDATORS_BYTE, _HEADER_VALIDATORS_STR, HEADER_VALIDATORS, to_native_string, ) from .compat import ( Mapping, basestring, bytes, getproxies, getproxies_environment, integer_types, is_urllib3_1, ) from .compat import parse_http_list as _parse_list_header from .compat import ( proxy_bypass, proxy_bypass_environment, quote, str, unquote, urlparse, urlunparse, ) from .cookies import cookiejar_from_dict from .exceptions import ( FileModeWarning, InvalidHeader, InvalidURL, UnrewindableBodyError, ) from .structures import CaseInsensitiveDict NETRC_FILES = (".netrc", "_netrc") DEFAULT_CA_BUNDLE_PATH = certs.where() DEFAULT_PORTS = {"http": 80, "https": 443} # Ensure that ', ' is used to preserve previous delimiter behavior. DEFAULT_ACCEPT_ENCODING = ", ".join( re.split(r",\s*", make_headers(accept_encoding=True)["accept-encoding"]) ) if sys.platform == "win32": # provide a proxy_bypass version on Windows without DNS lookups def proxy_bypass_registry(host): try: import winreg except ImportError: return False try: internetSettings = winreg.OpenKey( winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Internet Settings", ) # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it proxyEnable = int(winreg.QueryValueEx(internetSettings, "ProxyEnable")[0]) # ProxyOverride is almost always a string proxyOverride = winreg.QueryValueEx(internetSettings, "ProxyOverride")[0] except (OSError, ValueError): return False if not proxyEnable or not proxyOverride: return False # make a check value list from the registry entry: replace the # '<local>' string by the localhost entry and the corresponding # canonical entry. proxyOverride = proxyOverride.split(";") # filter out empty strings to avoid re.match return true in the following code. proxyOverride = filter(None, proxyOverride) # now check if we match one of the registry values. for test in proxyOverride: if test == "<local>": if "." not in host: return True test = test.replace(".", r"\.") # mask dots test = test.replace("*", r".*") # change glob sequence test = test.replace("?", r".") # change glob char if re.match(test, host, re.I): return True return False def proxy_bypass(host): # noqa """Return True, if the host should be bypassed. Checks proxy settings gathered from the environment, if specified, or the registry. """ if getproxies_environment(): return proxy_bypass_environment(host) else: return proxy_bypass_registry(host) def dict_to_sequence(d): """Returns an internal sequence dictionary update.""" if hasattr(d, "items"): d = d.items() return d def super_len(o): total_length = None current_position = 0 if not is_urllib3_1 and isinstance(o, str): # urllib3 2.x+ treats all strings as utf-8 instead # of latin-1 (iso-8859-1) like http.client. o = o.encode("utf-8") if hasattr(o, "__len__"): total_length = len(o) elif hasattr(o, "len"): total_length = o.len elif hasattr(o, "fileno"): try: fileno = o.fileno() except (io.UnsupportedOperation, AttributeError): # AttributeError is a surprising exception, seeing as how we've just checked # that `hasattr(o, 'fileno')`. It happens for objects obtained via # `Tarfile.extractfile()`, per issue 5229. pass else: total_length = os.fstat(fileno).st_size # Having used fstat to determine the file length, we need to # confirm that this file was opened up in binary mode. if "b" not in o.mode: warnings.warn( ( "Requests has determined the content-length for this " "request using the binary size of the file: however, the " "file has been opened in text mode (i.e. without the 'b' " "flag in the mode). This may lead to an incorrect " "content-length. In Requests 3.0, support will be removed " "for files in text mode." ), FileModeWarning, ) if hasattr(o, "tell"): try: current_position = o.tell() except OSError: # This can happen in some weird situations, such as when the file # is actually a special file descriptor like stdin. In this # instance, we don't know what the length is, so set it to zero and # let requests chunk it instead. if total_length is not None: current_position = total_length else: if hasattr(o, "seek") and total_length is None: # StringIO and BytesIO have seek but no usable fileno try: # seek to end of file o.seek(0, 2) total_length = o.tell() # seek back to current position to support # partially read file-like objects o.seek(current_position or 0) except OSError: total_length = 0 if total_length is None: total_length = 0 return max(0, total_length - current_position) def get_netrc_auth(url, raise_errors=False): """Returns the Requests tuple auth for a given url from netrc.""" netrc_file = os.environ.get("NETRC") if netrc_file is not None: netrc_locations = (netrc_file,) else: netrc_locations = (f"~/{f}" for f in NETRC_FILES) try: from netrc import NetrcParseError, netrc netrc_path = None for f in netrc_locations: loc = os.path.expanduser(f) if os.path.exists(loc): netrc_path = loc break # Abort early if there isn't one. if netrc_path is None: return ri = urlparse(url) host = ri.hostname try: _netrc = netrc(netrc_path).authenticators(host) if _netrc: # Return with login / password login_i = 0 if _netrc[0] else 1 return (_netrc[login_i], _netrc[2]) except (NetrcParseError, OSError): # If there was a parsing error or a permissions issue reading the file, # we'll just skip netrc auth unless explicitly asked to raise errors. if raise_errors: raise # App Engine hackiness. except (ImportError, AttributeError): pass def guess_filename(obj): """Tries to guess the filename of the given object.""" name = getattr(obj, "name", None) if name and isinstance(name, basestring) and name[0] != "<" and name[-1] != ">": return os.path.basename(name) def extract_zipped_paths(path): """Replace nonexistent paths that look like they refer to a member of a zip archive with the location of an extracted copy of the target, or else just return the provided path unchanged. """ if os.path.exists(path): # this is already a valid path, no need to do anything further return path # find the first valid part of the provided path and treat that as a zip archive # assume the rest of the path is the name of a member in the archive archive, member = os.path.split(path) while archive and not os.path.exists(archive): archive, prefix = os.path.split(archive) if not prefix: # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split), # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users break member = "/".join([prefix, member]) if not zipfile.is_zipfile(archive): return path zip_file = zipfile.ZipFile(archive) if member not in zip_file.namelist(): return path # we have a valid zip archive and a valid member of that archive tmp = tempfile.gettempdir() extracted_path = os.path.join(tmp, member.split("/")[-1]) if not os.path.exists(extracted_path): # use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition with atomic_open(extracted_path) as file_handler: file_handler.write(zip_file.read(member)) return extracted_path @contextlib.contextmanager def atomic_open(filename): """Write a file to the disk in an atomic fashion""" tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename)) try: with os.fdopen(tmp_descriptor, "wb") as tmp_handler: yield tmp_handler os.replace(tmp_name, filename) except BaseException: os.remove(tmp_name) raise def from_key_val_list(value): """Take an object and test to see if it can be represented as a dictionary. Unless it can not be represented as such, return an OrderedDict, e.g., :: >>> from_key_val_list([('key', 'val')]) OrderedDict([('key', 'val')]) >>> from_key_val_list('string') Traceback (most recent call last): ... ValueError: cannot encode objects that are not 2-tuples >>> from_key_val_list({'key': 'val'}) OrderedDict([('key', 'val')]) :rtype: OrderedDict """ if value is None: return None if isinstance(value, (str, bytes, bool, int)): raise ValueError("cannot encode objects that are not 2-tuples") return OrderedDict(value) def to_key_val_list(value): """Take an object and test to see if it can be represented as a dictionary. If it can be, return a list of tuples, e.g., :: >>> to_key_val_list([('key', 'val')]) [('key', 'val')] >>> to_key_val_list({'key': 'val'}) [('key', 'val')] >>> to_key_val_list('string') Traceback (most recent call last): ... ValueError: cannot encode objects that are not 2-tuples :rtype: list """ if value is None: return None if isinstance(value, (str, bytes, bool, int)): raise ValueError("cannot encode objects that are not 2-tuples") if isinstance(value, Mapping): value = value.items() return list(value) # From mitsuhiko/werkzeug (used with permission). def parse_list_header(value): """Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed automatically after parsing. It basically works like :func:`parse_set_header` just that items may appear multiple times and case sensitivity is preserved. The return value is a standard :class:`list`: >>> parse_list_header('token, "quoted value"') ['token', 'quoted value'] To create a header from the :class:`list` again, use the :func:`dump_header` function. :param value: a string with a list header. :return: :class:`list` :rtype: list """ result = [] for item in _parse_list_header(value): if item[:1] == item[-1:] == '"': item = unquote_header_value(item[1:-1]) result.append(item) return result # From mitsuhiko/werkzeug (used with permission). def parse_dict_header(value): """Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict: >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] If there is no value for a key it will be `None`: >>> parse_dict_header('key_without_value') {'key_without_value': None} To create a header from the :class:`dict` again, use the :func:`dump_header` function. :param value: a string with a dict header. :return: :class:`dict` :rtype: dict """ result = {} for item in _parse_list_header(value): if "=" not in item: result[item] = None continue name, value = item.split("=", 1) if value[:1] == value[-1:] == '"': value = unquote_header_value(value[1:-1]) result[name] = value return result # From mitsuhiko/werkzeug (used with permission). def unquote_header_value(value, is_filename=False): r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). This does not use the real unquoting but what browsers are actually using for quoting. :param value: the header value to unquote. :rtype: str """ if value and value[0] == value[-1] == '"': # this is not the real unquoting, but fixing this so that the # RFC is met will result in bugs with internet explorer and # probably some other browsers as well. IE for example is # uploading files with "C:\foo\bar.txt" as filename value = value[1:-1] # if this is a filename and the starting characters look like # a UNC path, then just return the value without quotes. Using the # replace sequence below on a UNC path has the effect of turning # the leading double slash into a single slash and then # _fix_ie_filename() doesn't work correctly. See #458. if not is_filename or value[:2] != "\\\\": return value.replace("\\\\", "\\").replace('\\"', '"') return value def dict_from_cookiejar(cj): """Returns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from. :rtype: dict """ cookie_dict = {cookie.name: cookie.value for cookie in cj} return cookie_dict def add_dict_to_cookiejar(cj, cookie_dict): """Returns a CookieJar from a key/value dictionary. :param cj: CookieJar to insert cookies into. :param cookie_dict: Dict of key/values to insert into CookieJar. :rtype: CookieJar """ return cookiejar_from_dict(cookie_dict, cj) def get_encodings_from_content(content): """Returns encodings from given content string. :param content: bytestring to extract encodings from. """ warnings.warn( ( "In requests 3.0, get_encodings_from_content will be removed. For " "more information, please see the discussion on issue #2266. (This" " warning should only appear once.)" ), DeprecationWarning, ) charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I) pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I) xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]') return ( charset_re.findall(content) + pragma_re.findall(content) + xml_re.findall(content) ) def _parse_content_type_header(header): """Returns content type and parameters from given header :param header: string :return: tuple containing content type and dictionary of parameters """ tokens = header.split(";") content_type, params = tokens[0].strip(), tokens[1:] params_dict = {} items_to_strip = "\"' " for param in params: param = param.strip() if param: key, value = param, True index_of_equals = param.find("=") if index_of_equals != -1: key = param[:index_of_equals].strip(items_to_strip) value = param[index_of_equals + 1 :].strip(items_to_strip) params_dict[key.lower()] = value return content_type, params_dict def get_encoding_from_headers(headers): """Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from. :rtype: str """ content_type = headers.get("content-type") if not content_type: return None content_type, params = _parse_content_type_header(content_type) if "charset" in params: return params["charset"].strip("'\"") if "text" in content_type: return "ISO-8859-1" if "application/json" in content_type: # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset return "utf-8" def stream_decode_response_unicode(iterator, r): """Stream decodes an iterator.""" if r.encoding is None: yield from iterator return decoder = codecs.getincrementaldecoder(r.encoding)(errors="replace") for chunk in iterator: rv = decoder.decode(chunk) if rv: yield rv rv = decoder.decode(b"", final=True) if rv: yield rv def iter_slices(string, slice_length): """Iterate over slices of a string.""" pos = 0 if slice_length is None or slice_length <= 0: slice_length = len(string) while pos < len(string): yield string[pos : pos + slice_length] pos += slice_length def get_unicode_from_response(r): """Returns the requested content back in unicode. :param r: Response object to get unicode content from. Tried: 1. charset from content-type 2. fall back and replace all unicode characters :rtype: str """ warnings.warn( ( "In requests 3.0, get_unicode_from_response will be removed. For " "more information, please see the discussion on issue #2266. (This" " warning should only appear once.)" ), DeprecationWarning, ) tried_encodings = [] # Try charset from content-type encoding = get_encoding_from_headers(r.headers) if encoding: try: return str(r.content, encoding) except UnicodeError: tried_encodings.append(encoding) # Fall back: try: return str(r.content, encoding, errors="replace") except TypeError: return r.content # The unreserved URI characters (RFC 3986) UNRESERVED_SET = frozenset( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~" ) def unquote_unreserved(uri): """Un-escape any percent-escape sequences in a URI that are unreserved characters. This leaves all reserved, illegal and non-ASCII bytes encoded. :rtype: str """ parts = uri.split("%") for i in range(1, len(parts)): h = parts[i][0:2] if len(h) == 2 and h.isalnum(): try: c = chr(int(h, 16)) except ValueError: raise InvalidURL(f"Invalid percent-escape sequence: '{h}'") if c in UNRESERVED_SET: parts[i] = c + parts[i][2:] else: parts[i] = f"%{parts[i]}" else: parts[i] = f"%{parts[i]}" return "".join(parts) def requote_uri(uri): """Re-quote the given URI. This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. :rtype: str """ safe_with_percent = "!#$%&'()*+,/:;=?@[]~" safe_without_percent = "!#$&'()*+,/:;=?@[]~" try: # Unquote only the unreserved characters # Then quote only illegal characters (do not quote reserved, # unreserved, or '%') return quote(unquote_unreserved(uri), safe=safe_with_percent) except InvalidURL: # We couldn't unquote the given URI, so let's try quoting it, but # there may be unquoted '%'s in the URI. We need to make sure they're # properly quoted so they do not cause issues elsewhere. return quote(uri, safe=safe_without_percent) def address_in_network(ip, net): """This function allows you to check if an IP belongs to a network subnet Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 :rtype: bool """ ipaddr = struct.unpack("=L", socket.inet_aton(ip))[0] netaddr, bits = net.split("/") netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0] network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask return (ipaddr & netmask) == (network & netmask) def dotted_netmask(mask): """Converts mask from /xx format to xxx.xxx.xxx.xxx Example: if mask is 24 function returns 255.255.255.0 :rtype: str """ bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1 return socket.inet_ntoa(struct.pack(">I", bits)) def is_ipv4_address(string_ip): """ :rtype: bool """ try: socket.inet_aton(string_ip) except OSError: return False return True def is_valid_cidr(string_network): """ Very simple check of the cidr format in no_proxy variable. :rtype: bool """ if string_network.count("/") == 1: try: mask = int(string_network.split("/")[1]) except ValueError: return False if mask < 1 or mask > 32: return False try: socket.inet_aton(string_network.split("/")[0]) except OSError: return False else: return False return True @contextlib.contextmanager def set_environ(env_name, value): """Set the environment variable 'env_name' to 'value' Save previous value, yield, and then restore the previous value stored in the environment variable 'env_name'. If 'value' is None, do nothing""" value_changed = value is not None if value_changed: old_value = os.environ.get(env_name) os.environ[env_name] = value try: yield finally: if value_changed: if old_value is None: del os.environ[env_name] else: os.environ[env_name] = old_value def should_bypass_proxies(url, no_proxy): """ Returns whether we should bypass proxies or not. :rtype: bool """ # Prioritize lowercase environment variables over uppercase # to keep a consistent behaviour with other http projects (curl, wget). def get_proxy(key): return os.environ.get(key) or os.environ.get(key.upper()) # First check whether no_proxy is defined. If it is, check that the URL # we're getting isn't in the no_proxy list. no_proxy_arg = no_proxy if no_proxy is None: no_proxy = get_proxy("no_proxy") parsed = urlparse(url) if parsed.hostname is None: # URLs don't always have hostnames, e.g. file:/// urls. return True if no_proxy: # We need to check whether we match here. We need to see if we match # the end of the hostname, both with and without the port. no_proxy = (host for host in no_proxy.replace(" ", "").split(",") if host) if is_ipv4_address(parsed.hostname): for proxy_ip in no_proxy: if is_valid_cidr(proxy_ip): if address_in_network(parsed.hostname, proxy_ip): return True elif parsed.hostname == proxy_ip: # If no_proxy ip was defined in plain IP notation instead of cidr notation & # matches the IP of the index return True else: host_with_port = parsed.hostname if parsed.port: host_with_port += f":{parsed.port}" for host in no_proxy: if parsed.hostname.endswith(host) or host_with_port.endswith(host): # The URL does match something in no_proxy, so we don't want # to apply the proxies on this URL. return True with set_environ("no_proxy", no_proxy_arg): # parsed.hostname can be `None` in cases such as a file URI. try: bypass = proxy_bypass(parsed.hostname) except (TypeError, socket.gaierror): bypass = False if bypass: return True return False def get_environ_proxies(url, no_proxy=None): """ Return a dict of environment proxies. :rtype: dict """ if should_bypass_proxies(url, no_proxy=no_proxy): return {} else: return getproxies() def select_proxy(url, proxies): """Select a proxy for the url, if applicable. :param url: The url being for the request :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs """ proxies = proxies or {} urlparts = urlparse(url) if urlparts.hostname is None: return proxies.get(urlparts.scheme, proxies.get("all")) proxy_keys = [ urlparts.scheme + "://" + urlparts.hostname, urlparts.scheme, "all://" + urlparts.hostname, "all", ] proxy = None for proxy_key in proxy_keys: if proxy_key in proxies: proxy = proxies[proxy_key] break return proxy def resolve_proxies(request, proxies, trust_env=True): """This method takes proxy information from a request and configuration input to resolve a mapping of target proxies. This will consider settings such as NO_PROXY to strip proxy configurations. :param request: Request or PreparedRequest :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs :param trust_env: Boolean declaring whether to trust environment configs :rtype: dict """ proxies = proxies if proxies is not None else {} url = request.url scheme = urlparse(url).scheme no_proxy = proxies.get("no_proxy") new_proxies = proxies.copy() if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy): environ_proxies = get_environ_proxies(url, no_proxy=no_proxy) proxy = environ_proxies.get(scheme, environ_proxies.get("all")) if proxy: new_proxies.setdefault(scheme, proxy) return new_proxies def default_user_agent(name="python-requests"): """ Return a string representing the default user agent. :rtype: str """ return f"{name}/{__version__}" def default_headers(): """ :rtype: requests.structures.CaseInsensitiveDict """ return CaseInsensitiveDict( { "User-Agent": default_user_agent(), "Accept-Encoding": DEFAULT_ACCEPT_ENCODING, "Accept": "*/*", "Connection": "keep-alive", } ) def parse_header_links(value): """Return a list of parsed link headers proxies. i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg" :rtype: list """ links = [] replace_chars = " '\"" value = value.strip(replace_chars) if not value: return links for val in re.split(", *<", value): try: url, params = val.split(";", 1) except ValueError: url, params = val, "" link = {"url": url.strip("<> '\"")} for param in params.split(";"): try: key, value = param.split("=") except ValueError: break link[key.strip(replace_chars)] = value.strip(replace_chars) links.append(link) return links # Null bytes; no need to recreate these on each call to guess_json_utf _null = "\x00".encode("ascii") # encoding to ASCII for Python 3 _null2 = _null * 2 _null3 = _null * 3 def guess_json_utf(data): """ :rtype: str """ # JSON always starts with two ASCII characters, so detection is as # easy as counting the nulls and from their location and count # determine the encoding. Also detect a BOM, if present. sample = data[:4] if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE): return "utf-32" # BOM included if sample[:3] == codecs.BOM_UTF8: return "utf-8-sig" # BOM included, MS style (discouraged) if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE): return "utf-16" # BOM included nullcount = sample.count(_null) if nullcount == 0: return "utf-8" if nullcount == 2: if sample[::2] == _null2: # 1st and 3rd are null return "utf-16-be" if sample[1::2] == _null2: # 2nd and 4th are null return "utf-16-le" # Did not detect 2 valid UTF-16 ascii-range characters if nullcount == 3: if sample[:3] == _null3: return "utf-32-be" if sample[1:] == _null3: return "utf-32-le" # Did not detect a valid UTF-32 ascii-range character return None def prepend_scheme_if_needed(url, new_scheme): """Given a URL that may or may not have a scheme, prepend the given scheme. Does not replace a present scheme with the one provided as an argument. :rtype: str """ parsed = parse_url(url) scheme, auth, host, port, path, query, fragment = parsed # A defect in urlparse determines that there isn't a netloc present in some # urls. We previously assumed parsing was overly cautious, and swapped the # netloc and path. Due to a lack of tests on the original defect, this is # maintained with parse_url for backwards compatibility. netloc = parsed.netloc if not netloc: netloc, path = path, netloc if auth: # parse_url doesn't provide the netloc with auth # so we'll add it ourselves. netloc = "@".join([auth, netloc]) if scheme is None: scheme = new_scheme if path is None: path = "" return urlunparse((scheme, netloc, path, "", query, fragment)) def get_auth_from_url(url): """Given a url with authentication components, extract them into a tuple of username,password. :rtype: (str,str) """ parsed = urlparse(url) try: auth = (unquote(parsed.username), unquote(parsed.password)) except (AttributeError, TypeError): auth = ("", "") return auth def check_header_validity(header): """Verifies that header parts don't contain leading whitespace reserved characters, or return characters. :param header: tuple, in the format (name, value). """ name, value = header _validate_header_part(header, name, 0) _validate_header_part(header, value, 1) def _validate_header_part(header, header_part, header_validator_index): if isinstance(header_part, str): validator = _HEADER_VALIDATORS_STR[header_validator_index] elif isinstance(header_part, bytes): validator = _HEADER_VALIDATORS_BYTE[header_validator_index] else: raise InvalidHeader( f"Header part ({header_part!r}) from {header} " f"must be of type str or bytes, not {type(header_part)}" ) if not validator.match(header_part): header_kind = "name" if header_validator_index == 0 else "value" raise InvalidHeader( f"Invalid leading whitespace, reserved character(s), or return " f"character(s) in header {header_kind}: {header_part!r}" ) def urldefragauth(url): """ Given a url remove the fragment and the authentication part. :rtype: str """ scheme, netloc, path, params, query, fragment = urlparse(url) # see func:`prepend_scheme_if_needed` if not netloc: netloc, path = path, netloc netloc = netloc.rsplit("@", 1)[-1] return urlunparse((scheme, netloc, path, params, query, "")) def rewind_body(prepared_request): """Move file pointer back to its recorded starting position so it can be read again on redirect. """ body_seek = getattr(prepared_request.body, "seek", None) if body_seek is not None and isinstance( prepared_request._body_position, integer_types ): try: body_seek(prepared_request._body_position) except OSError: raise UnrewindableBodyError( "An error occurred when rewinding request body for redirect." ) else: raise UnrewindableBodyError("Unable to rewind request body for redirect.")
import copy import filecmp import os import tarfile import zipfile from collections import deque from io import BytesIO from unittest import mock import pytest from requests import compat from requests._internal_utils import unicode_is_ascii from requests.cookies import RequestsCookieJar from requests.structures import CaseInsensitiveDict from requests.utils import ( _parse_content_type_header, add_dict_to_cookiejar, address_in_network, dotted_netmask, extract_zipped_paths, get_auth_from_url, get_encoding_from_headers, get_encodings_from_content, get_environ_proxies, get_netrc_auth, guess_filename, guess_json_utf, is_ipv4_address, is_valid_cidr, iter_slices, parse_dict_header, parse_header_links, prepend_scheme_if_needed, requote_uri, select_proxy, set_environ, should_bypass_proxies, super_len, to_key_val_list, to_native_string, unquote_header_value, unquote_unreserved, urldefragauth, ) from .compat import StringIO, cStringIO class TestSuperLen: @pytest.mark.parametrize( "stream, value", ( (StringIO.StringIO, "Test"), (BytesIO, b"Test"), pytest.param( cStringIO, "Test", marks=pytest.mark.skipif("cStringIO is None") ), ), ) def test_io_streams(self, stream, value): """Ensures that we properly deal with different kinds of IO streams.""" assert super_len(stream()) == 0 assert super_len(stream(value)) == 4 def test_super_len_correctly_calculates_len_of_partially_read_file(self): """Ensure that we handle partially consumed file like objects.""" s = StringIO.StringIO() s.write("foobarbogus") assert super_len(s) == 0 @pytest.mark.parametrize("error", [IOError, OSError]) def test_super_len_handles_files_raising_weird_errors_in_tell(self, error): """If tell() raises errors, assume the cursor is at position zero.""" class BoomFile: def __len__(self): return 5 def tell(self): raise error() assert super_len(BoomFile()) == 0 @pytest.mark.parametrize("error", [IOError, OSError]) def test_super_len_tell_ioerror(self, error): """Ensure that if tell gives an IOError super_len doesn't fail""" class NoLenBoomFile: def tell(self): raise error() def seek(self, offset, whence): pass assert super_len(NoLenBoomFile()) == 0 def test_string(self): assert super_len("Test") == 4 @pytest.mark.parametrize( "mode, warnings_num", ( ("r", 1), ("rb", 0), ), ) def test_file(self, tmpdir, mode, warnings_num, recwarn): file_obj = tmpdir.join("test.txt") file_obj.write("Test") with file_obj.open(mode) as fd: assert super_len(fd) == 4 assert len(recwarn) == warnings_num def test_tarfile_member(self, tmpdir): file_obj = tmpdir.join("test.txt") file_obj.write("Test") tar_obj = str(tmpdir.join("test.tar")) with tarfile.open(tar_obj, "w") as tar: tar.add(str(file_obj), arcname="test.txt") with tarfile.open(tar_obj) as tar: member = tar.extractfile("test.txt") assert super_len(member) == 4 def test_super_len_with__len__(self): foo = [1, 2, 3, 4] len_foo = super_len(foo) assert len_foo == 4 def test_super_len_with_no__len__(self): class LenFile: def __init__(self): self.len = 5 assert super_len(LenFile()) == 5 def test_super_len_with_tell(self): foo = StringIO.StringIO("12345") assert super_len(foo) == 5 foo.read(2) assert super_len(foo) == 3 def test_super_len_with_fileno(self): with open(__file__, "rb") as f: length = super_len(f) file_data = f.read() assert length == len(file_data) def test_super_len_with_no_matches(self): """Ensure that objects without any length methods default to 0""" assert super_len(object()) == 0 class TestGetNetrcAuth: def test_works(self, tmp_path, monkeypatch): netrc_path = tmp_path / ".netrc" monkeypatch.setenv("NETRC", str(netrc_path)) with open(netrc_path, "w") as f: f.write("machine example.com login aaaa password bbbb\n") auth = get_netrc_auth("http://example.com/thing") assert auth == ("aaaa", "bbbb") def test_not_vulnerable_to_bad_url_parsing(self, tmp_path, monkeypatch): netrc_path = tmp_path / ".netrc" monkeypatch.setenv("NETRC", str(netrc_path)) with open(netrc_path, "w") as f: f.write("machine example.com login aaaa password bbbb\n") auth = get_netrc_auth("http://example.com:@evil.com/&apos;") assert auth is None class TestToKeyValList: @pytest.mark.parametrize( "value, expected", ( ([("key", "val")], [("key", "val")]), ((("key", "val"),), [("key", "val")]), ({"key": "val"}, [("key", "val")]), (None, None), ), ) def test_valid(self, value, expected): assert to_key_val_list(value) == expected def test_invalid(self): with pytest.raises(ValueError): to_key_val_list("string") class TestUnquoteHeaderValue: @pytest.mark.parametrize( "value, expected", ( (None, None), ("Test", "Test"), ('"Test"', "Test"), ('"Test\\\\"', "Test\\"), ('"\\\\Comp\\Res"', "\\Comp\\Res"), ), ) def test_valid(self, value, expected): assert unquote_header_value(value) == expected def test_is_filename(self): assert unquote_header_value('"\\\\Comp\\Res"', True) == "\\\\Comp\\Res" class TestGetEnvironProxies: """Ensures that IP addresses are correctly matches with ranges in no_proxy variable. """ @pytest.fixture(autouse=True, params=["no_proxy", "NO_PROXY"]) def no_proxy(self, request, monkeypatch): monkeypatch.setenv( request.param, "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1" ) @pytest.mark.parametrize( "url", ( "http://192.168.0.1:5000/", "http://192.168.0.1/", "http://172.16.1.1/", "http://172.16.1.1:5000/", "http://localhost.localdomain:5000/v1.0/", ), ) def test_bypass(self, url): assert get_environ_proxies(url, no_proxy=None) == {} @pytest.mark.parametrize( "url", ( "http://192.168.1.1:5000/", "http://192.168.1.1/", "http://www.requests.com/", ), ) def test_not_bypass(self, url): assert get_environ_proxies(url, no_proxy=None) != {} @pytest.mark.parametrize( "url", ( "http://192.168.1.1:5000/", "http://192.168.1.1/", "http://www.requests.com/", ), ) def test_bypass_no_proxy_keyword(self, url): no_proxy = "192.168.1.1,requests.com" assert get_environ_proxies(url, no_proxy=no_proxy) == {} @pytest.mark.parametrize( "url", ( "http://192.168.0.1:5000/", "http://192.168.0.1/", "http://172.16.1.1/", "http://172.16.1.1:5000/", "http://localhost.localdomain:5000/v1.0/", ), ) def test_not_bypass_no_proxy_keyword(self, url, monkeypatch): # This is testing that the 'no_proxy' argument overrides the # environment variable 'no_proxy' monkeypatch.setenv("http_proxy", "http://proxy.example.com:3128/") no_proxy = "192.168.1.1,requests.com" assert get_environ_proxies(url, no_proxy=no_proxy) != {} class TestIsIPv4Address: def test_valid(self): assert is_ipv4_address("8.8.8.8") @pytest.mark.parametrize("value", ("8.8.8.8.8", "localhost.localdomain")) def test_invalid(self, value): assert not is_ipv4_address(value) class TestIsValidCIDR: def test_valid(self): assert is_valid_cidr("192.168.1.0/24") @pytest.mark.parametrize( "value", ( "8.8.8.8", "192.168.1.0/a", "192.168.1.0/128", "192.168.1.0/-1", "192.168.1.999/24", ), ) def test_invalid(self, value): assert not is_valid_cidr(value) class TestAddressInNetwork: def test_valid(self): assert address_in_network("192.168.1.1", "192.168.1.0/24") def test_invalid(self): assert not address_in_network("172.16.0.1", "192.168.1.0/24") class TestGuessFilename: @pytest.mark.parametrize( "value", (1, type("Fake", (object,), {"name": 1})()), ) def test_guess_filename_invalid(self, value): assert guess_filename(value) is None @pytest.mark.parametrize( "value, expected_type", ( (b"value", compat.bytes), (b"value".decode("utf-8"), compat.str), ), ) def test_guess_filename_valid(self, value, expected_type): obj = type("Fake", (object,), {"name": value})() result = guess_filename(obj) assert result == value assert isinstance(result, expected_type) class TestExtractZippedPaths: @pytest.mark.parametrize( "path", ( "/", __file__, pytest.__file__, "/etc/invalid/location", ), ) def test_unzipped_paths_unchanged(self, path): assert path == extract_zipped_paths(path) def test_zipped_paths_extracted(self, tmpdir): zipped_py = tmpdir.join("test.zip") with zipfile.ZipFile(zipped_py.strpath, "w") as f: f.write(__file__) _, name = os.path.splitdrive(__file__) zipped_path = os.path.join(zipped_py.strpath, name.lstrip(r"\/")) extracted_path = extract_zipped_paths(zipped_path) assert extracted_path != zipped_path assert os.path.exists(extracted_path) assert filecmp.cmp(extracted_path, __file__) def test_invalid_unc_path(self): path = r"\\localhost\invalid\location" assert extract_zipped_paths(path) == path class TestContentEncodingDetection: def test_none(self): encodings = get_encodings_from_content("") assert not len(encodings) @pytest.mark.parametrize( "content", ( # HTML5 meta charset attribute '<meta charset="UTF-8">', # HTML4 pragma directive '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">', # XHTML 1.x served with text/html MIME type '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />', # XHTML 1.x served as XML '<?xml version="1.0" encoding="UTF-8"?>', ), ) def test_pragmas(self, content): encodings = get_encodings_from_content(content) assert len(encodings) == 1 assert encodings[0] == "UTF-8" def test_precedence(self): content = """ <?xml version="1.0" encoding="XML"?> <meta charset="HTML5"> <meta http-equiv="Content-type" content="text/html;charset=HTML4" /> """.strip() assert get_encodings_from_content(content) == ["HTML5", "HTML4", "XML"] class TestGuessJSONUTF: @pytest.mark.parametrize( "encoding", ( "utf-32", "utf-8-sig", "utf-16", "utf-8", "utf-16-be", "utf-16-le", "utf-32-be", "utf-32-le", ), ) def test_encoded(self, encoding): data = "{}".encode(encoding) assert guess_json_utf(data) == encoding def test_bad_utf_like_encoding(self): assert guess_json_utf(b"\x00\x00\x00\x00") is None @pytest.mark.parametrize( ("encoding", "expected"), ( ("utf-16-be", "utf-16"), ("utf-16-le", "utf-16"), ("utf-32-be", "utf-32"), ("utf-32-le", "utf-32"), ), ) def test_guess_by_bom(self, encoding, expected): data = "\ufeff{}".encode(encoding) assert guess_json_utf(data) == expected USER = PASSWORD = "%!*'();:@&=+$,/?#[] " ENCODED_USER = compat.quote(USER, "") ENCODED_PASSWORD = compat.quote(PASSWORD, "") @pytest.mark.parametrize( "url, auth", ( ( f"http://{ENCODED_USER}:{ENCODED_PASSWORD}@request.com/url.html#test", (USER, PASSWORD), ), ("http://user:[email protected]/path?query=yes", ("user", "pass")), ( "http://user:pass%[email protected]/path?query=yes", ("user", "pass pass"), ), ("http://user:pass [email protected]/path?query=yes", ("user", "pass pass")), ( "http://user%25user:[email protected]/path?query=yes", ("user%user", "pass"), ), ( "http://user:pass%[email protected]/path?query=yes", ("user", "pass#pass"), ), ("http://complex.url.com/path?query=yes", ("", "")), ), ) def test_get_auth_from_url(url, auth): assert get_auth_from_url(url) == auth @pytest.mark.parametrize( "uri, expected", ( ( # Ensure requoting doesn't break expectations "http://example.com/fiz?buz=%25ppicture", "http://example.com/fiz?buz=%25ppicture", ), ( # Ensure we handle unquoted percent signs in redirects "http://example.com/fiz?buz=%ppicture", "http://example.com/fiz?buz=%25ppicture", ), ), ) def test_requote_uri_with_unquoted_percents(uri, expected): """See: https://github.com/psf/requests/issues/2356""" assert requote_uri(uri) == expected @pytest.mark.parametrize( "uri, expected", ( ( # Illegal bytes "http://example.com/?a=%--", "http://example.com/?a=%--", ), ( # Reserved characters "http://example.com/?a=%300", "http://example.com/?a=00", ), ), ) def test_unquote_unreserved(uri, expected): assert unquote_unreserved(uri) == expected @pytest.mark.parametrize( "mask, expected", ( (8, "255.0.0.0"), (24, "255.255.255.0"), (25, "255.255.255.128"), ), ) def test_dotted_netmask(mask, expected): assert dotted_netmask(mask) == expected http_proxies = { "http": "http://http.proxy", "http://some.host": "http://some.host.proxy", } all_proxies = { "all": "socks5://http.proxy", "all://some.host": "socks5://some.host.proxy", } mixed_proxies = { "http": "http://http.proxy", "http://some.host": "http://some.host.proxy", "all": "socks5://http.proxy", } @pytest.mark.parametrize( "url, expected, proxies", ( ("hTTp://u:[email protected]/path", "http://some.host.proxy", http_proxies), ("hTTp://u:[email protected]/path", "http://http.proxy", http_proxies), ("hTTp:///path", "http://http.proxy", http_proxies), ("hTTps://Other.Host", None, http_proxies), ("file:///etc/motd", None, http_proxies), ("hTTp://u:[email protected]/path", "socks5://some.host.proxy", all_proxies), ("hTTp://u:[email protected]/path", "socks5://http.proxy", all_proxies), ("hTTp:///path", "socks5://http.proxy", all_proxies), ("hTTps://Other.Host", "socks5://http.proxy", all_proxies), ("http://u:[email protected]/path", "http://http.proxy", mixed_proxies), ("http://u:[email protected]/path", "http://some.host.proxy", mixed_proxies), ("https://u:[email protected]/path", "socks5://http.proxy", mixed_proxies), ("https://u:[email protected]/path", "socks5://http.proxy", mixed_proxies), ("https://", "socks5://http.proxy", mixed_proxies), # XXX: unsure whether this is reasonable behavior ("file:///etc/motd", "socks5://http.proxy", all_proxies), ), ) def test_select_proxies(url, expected, proxies): """Make sure we can select per-host proxies correctly.""" assert select_proxy(url, proxies) == expected @pytest.mark.parametrize( "value, expected", ( ('foo="is a fish", bar="as well"', {"foo": "is a fish", "bar": "as well"}), ("key_without_value", {"key_without_value": None}), ), ) def test_parse_dict_header(value, expected): assert parse_dict_header(value) == expected @pytest.mark.parametrize( "value, expected", ( ("application/xml", ("application/xml", {})), ( "application/json ; charset=utf-8", ("application/json", {"charset": "utf-8"}), ), ( "application/json ; Charset=utf-8", ("application/json", {"charset": "utf-8"}), ), ("text/plain", ("text/plain", {})), ( "multipart/form-data; boundary = something ; boundary2='something_else' ; no_equals ", ( "multipart/form-data", { "boundary": "something", "boundary2": "something_else", "no_equals": True, }, ), ), ( 'multipart/form-data; boundary = something ; boundary2="something_else" ; no_equals ', ( "multipart/form-data", { "boundary": "something", "boundary2": "something_else", "no_equals": True, }, ), ), ( "multipart/form-data; boundary = something ; 'boundary2=something_else' ; no_equals ", ( "multipart/form-data", { "boundary": "something", "boundary2": "something_else", "no_equals": True, }, ), ), ( 'multipart/form-data; boundary = something ; "boundary2=something_else" ; no_equals ', ( "multipart/form-data", { "boundary": "something", "boundary2": "something_else", "no_equals": True, }, ), ), ("application/json ; ; ", ("application/json", {})), ), ) def test__parse_content_type_header(value, expected): assert _parse_content_type_header(value) == expected @pytest.mark.parametrize( "value, expected", ( (CaseInsensitiveDict(), None), ( CaseInsensitiveDict({"content-type": "application/json; charset=utf-8"}), "utf-8", ), (CaseInsensitiveDict({"content-type": "text/plain"}), "ISO-8859-1"), ), ) def test_get_encoding_from_headers(value, expected): assert get_encoding_from_headers(value) == expected @pytest.mark.parametrize( "value, length", ( ("", 0), ("T", 1), ("Test", 4), ("Cont", 0), ("Other", -5), ("Content", None), ), ) def test_iter_slices(value, length): if length is None or (length <= 0 and len(value) > 0): # Reads all content at once assert len(list(iter_slices(value, length))) == 1 else: assert len(list(iter_slices(value, 1))) == length @pytest.mark.parametrize( "value, expected", ( ( '<http:/.../front.jpeg>; rel=front; type="image/jpeg"', [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}], ), ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]), ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]), ( '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;', [ {"url": "http:/.../front.jpeg", "type": "image/jpeg"}, {"url": "http://.../back.jpeg"}, ], ), ("", []), ), ) def test_parse_header_links(value, expected): assert parse_header_links(value) == expected @pytest.mark.parametrize( "value, expected", ( ("example.com/path", "http://example.com/path"), ("//example.com/path", "http://example.com/path"), ("example.com:80", "http://example.com:80"), ( "http://user:[email protected]/path?query", "http://user:[email protected]/path?query", ), ("http://[email protected]/path?query", "http://[email protected]/path?query"), ), ) def test_prepend_scheme_if_needed(value, expected): assert prepend_scheme_if_needed(value, "http") == expected @pytest.mark.parametrize( "value, expected", ( ("T", "T"), (b"T", "T"), ("T", "T"), ), ) def test_to_native_string(value, expected): assert to_native_string(value) == expected @pytest.mark.parametrize( "url, expected", ( ("http://u:[email protected]/path?a=1#test", "http://example.com/path?a=1"), ("http://example.com/path", "http://example.com/path"), ("//u:[email protected]/path", "//example.com/path"), ("//example.com/path", "//example.com/path"), ("example.com/path", "//example.com/path"), ("scheme:u:[email protected]/path", "scheme://example.com/path"), ), ) def test_urldefragauth(url, expected): assert urldefragauth(url) == expected @pytest.mark.parametrize( "url, expected", ( ("http://192.168.0.1:5000/", True), ("http://192.168.0.1/", True), ("http://172.16.1.1/", True), ("http://172.16.1.1:5000/", True), ("http://localhost.localdomain:5000/v1.0/", True), ("http://google.com:6000/", True), ("http://172.16.1.12/", False), ("http://172.16.1.12:5000/", False), ("http://google.com:5000/v1.0/", False), ("file:///some/path/on/disk", True), ), ) def test_should_bypass_proxies(url, expected, monkeypatch): """Tests for function should_bypass_proxies to check if proxy can be bypassed or not """ monkeypatch.setenv( "no_proxy", "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000", ) monkeypatch.setenv( "NO_PROXY", "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000", ) assert should_bypass_proxies(url, no_proxy=None) == expected @pytest.mark.parametrize( "url, expected", ( ("http://172.16.1.1/", "172.16.1.1"), ("http://172.16.1.1:5000/", "172.16.1.1"), ("http://user:[email protected]", "172.16.1.1"), ("http://user:[email protected]:5000", "172.16.1.1"), ("http://hostname/", "hostname"), ("http://hostname:5000/", "hostname"), ("http://user:pass@hostname", "hostname"), ("http://user:pass@hostname:5000", "hostname"), ), ) def test_should_bypass_proxies_pass_only_hostname(url, expected): """The proxy_bypass function should be called with a hostname or IP without a port number or auth credentials. """ with mock.patch("requests.utils.proxy_bypass") as proxy_bypass: should_bypass_proxies(url, no_proxy=None) proxy_bypass.assert_called_once_with(expected) @pytest.mark.parametrize( "cookiejar", ( compat.cookielib.CookieJar(), RequestsCookieJar(), ), ) def test_add_dict_to_cookiejar(cookiejar): """Ensure add_dict_to_cookiejar works for non-RequestsCookieJar CookieJars """ cookiedict = {"test": "cookies", "good": "cookies"} cj = add_dict_to_cookiejar(cookiejar, cookiedict) cookies = {cookie.name: cookie.value for cookie in cj} assert cookiedict == cookies @pytest.mark.parametrize( "value, expected", ( ("test", True), ("æíöû", False), ("ジェーピーニック", False), ), ) def test_unicode_is_ascii(value, expected): assert unicode_is_ascii(value) is expected @pytest.mark.parametrize( "url, expected", ( ("http://192.168.0.1:5000/", True), ("http://192.168.0.1/", True), ("http://172.16.1.1/", True), ("http://172.16.1.1:5000/", True), ("http://localhost.localdomain:5000/v1.0/", True), ("http://172.16.1.12/", False), ("http://172.16.1.12:5000/", False), ("http://google.com:5000/v1.0/", False), ), ) def test_should_bypass_proxies_no_proxy(url, expected, monkeypatch): """Tests for function should_bypass_proxies to check if proxy can be bypassed or not using the 'no_proxy' argument """ no_proxy = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1" # Test 'no_proxy' argument assert should_bypass_proxies(url, no_proxy=no_proxy) == expected @pytest.mark.skipif(os.name != "nt", reason="Test only on Windows") @pytest.mark.parametrize( "url, expected, override", ( ("http://192.168.0.1:5000/", True, None), ("http://192.168.0.1/", True, None), ("http://172.16.1.1/", True, None), ("http://172.16.1.1:5000/", True, None), ("http://localhost.localdomain:5000/v1.0/", True, None), ("http://172.16.1.22/", False, None), ("http://172.16.1.22:5000/", False, None), ("http://google.com:5000/v1.0/", False, None), ("http://mylocalhostname:5000/v1.0/", True, "<local>"), ("http://192.168.0.1/", False, ""), ), ) def test_should_bypass_proxies_win_registry(url, expected, override, monkeypatch): """Tests for function should_bypass_proxies to check if proxy can be bypassed or not with Windows registry settings """ if override is None: override = "192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1" import winreg class RegHandle: def Close(self): pass ie_settings = RegHandle() proxyEnableValues = deque([1, "1"]) def OpenKey(key, subkey): return ie_settings def QueryValueEx(key, value_name): if key is ie_settings: if value_name == "ProxyEnable": # this could be a string (REG_SZ) or a 32-bit number (REG_DWORD) proxyEnableValues.rotate() return [proxyEnableValues[0]] elif value_name == "ProxyOverride": return [override] monkeypatch.setenv("http_proxy", "") monkeypatch.setenv("https_proxy", "") monkeypatch.setenv("ftp_proxy", "") monkeypatch.setenv("no_proxy", "") monkeypatch.setenv("NO_PROXY", "") monkeypatch.setattr(winreg, "OpenKey", OpenKey) monkeypatch.setattr(winreg, "QueryValueEx", QueryValueEx) assert should_bypass_proxies(url, None) == expected @pytest.mark.skipif(os.name != "nt", reason="Test only on Windows") def test_should_bypass_proxies_win_registry_bad_values(monkeypatch): """Tests for function should_bypass_proxies to check if proxy can be bypassed or not with Windows invalid registry settings. """ import winreg class RegHandle: def Close(self): pass ie_settings = RegHandle() def OpenKey(key, subkey): return ie_settings def QueryValueEx(key, value_name): if key is ie_settings: if value_name == "ProxyEnable": # Invalid response; Should be an int or int-y value return [""] elif value_name == "ProxyOverride": return ["192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1"] monkeypatch.setenv("http_proxy", "") monkeypatch.setenv("https_proxy", "") monkeypatch.setenv("no_proxy", "") monkeypatch.setenv("NO_PROXY", "") monkeypatch.setattr(winreg, "OpenKey", OpenKey) monkeypatch.setattr(winreg, "QueryValueEx", QueryValueEx) assert should_bypass_proxies("http://172.16.1.1/", None) is False @pytest.mark.parametrize( "env_name, value", ( ("no_proxy", "192.168.0.0/24,127.0.0.1,localhost.localdomain"), ("no_proxy", None), ("a_new_key", "192.168.0.0/24,127.0.0.1,localhost.localdomain"), ("a_new_key", None), ), ) def test_set_environ(env_name, value): """Tests set_environ will set environ values and will restore the environ.""" environ_copy = copy.deepcopy(os.environ) with set_environ(env_name, value): assert os.environ.get(env_name) == value assert os.environ == environ_copy def test_set_environ_raises_exception(): """Tests set_environ will raise exceptions in context when the value parameter is None.""" with pytest.raises(Exception) as exception: with set_environ("test1", None): raise Exception("Expected exception") assert "Expected exception" in str(exception.value) @pytest.mark.skipif(os.name != "nt", reason="Test only on Windows") def test_should_bypass_proxies_win_registry_ProxyOverride_value(monkeypatch): """Tests for function should_bypass_proxies to check if proxy can be bypassed or not with Windows ProxyOverride registry value ending with a semicolon. """ import winreg class RegHandle: def Close(self): pass ie_settings = RegHandle() def OpenKey(key, subkey): return ie_settings def QueryValueEx(key, value_name): if key is ie_settings: if value_name == "ProxyEnable": return [1] elif value_name == "ProxyOverride": return [ "192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1;<-loopback>;" ] monkeypatch.setenv("NO_PROXY", "") monkeypatch.setenv("no_proxy", "") monkeypatch.setattr(winreg, "OpenKey", OpenKey) monkeypatch.setattr(winreg, "QueryValueEx", QueryValueEx) assert should_bypass_proxies("http://example.com/", None) is False
requests
python
""" requests.hooks ~~~~~~~~~~~~~~ This module provides the capabilities for the Requests hooks system. Available hooks: ``response``: The response generated from a Request. """ HOOKS = ["response"] def default_hooks(): return {event: [] for event in HOOKS} # TODO: response is the only one def dispatch_hook(key, hooks, hook_data, **kwargs): """Dispatches a hook dictionary on a given piece of data.""" hooks = hooks or {} hooks = hooks.get(key) if hooks: if hasattr(hooks, "__call__"): hooks = [hooks] for hook in hooks: _hook_data = hook(hook_data, **kwargs) if _hook_data is not None: hook_data = _hook_data return hook_data
import pytest from requests import hooks def hook(value): return value[1:] @pytest.mark.parametrize( "hooks_list, result", ( (hook, "ata"), ([hook, lambda x: None, hook], "ta"), ), ) def test_hooks(hooks_list, result): assert hooks.dispatch_hook("response", {"response": hooks_list}, "Data") == result def test_default_hooks(): assert hooks.default_hooks() == {"response": []}
requests
python
"""Module containing bug report helper(s).""" import json import platform import ssl import sys import idna import urllib3 from . import __version__ as requests_version try: import charset_normalizer except ImportError: charset_normalizer = None try: import chardet except ImportError: chardet = None try: from urllib3.contrib import pyopenssl except ImportError: pyopenssl = None OpenSSL = None cryptography = None else: import cryptography import OpenSSL def _implementation(): """Return a dict with the Python implementation and version. Provide both the name and the version of the Python implementation currently running. For example, on CPython 3.10.3 it will return {'name': 'CPython', 'version': '3.10.3'}. This function works best on CPython and PyPy: in particular, it probably doesn't work for Jython or IronPython. Future investigation should be done to work out the correct shape of the code for those platforms. """ implementation = platform.python_implementation() if implementation == "CPython": implementation_version = platform.python_version() elif implementation == "PyPy": implementation_version = "{}.{}.{}".format( sys.pypy_version_info.major, sys.pypy_version_info.minor, sys.pypy_version_info.micro, ) if sys.pypy_version_info.releaselevel != "final": implementation_version = "".join( [implementation_version, sys.pypy_version_info.releaselevel] ) elif implementation == "Jython": implementation_version = platform.python_version() # Complete Guess elif implementation == "IronPython": implementation_version = platform.python_version() # Complete Guess else: implementation_version = "Unknown" return {"name": implementation, "version": implementation_version} def info(): """Generate information for a bug report.""" try: platform_info = { "system": platform.system(), "release": platform.release(), } except OSError: platform_info = { "system": "Unknown", "release": "Unknown", } implementation_info = _implementation() urllib3_info = {"version": urllib3.__version__} charset_normalizer_info = {"version": None} chardet_info = {"version": None} if charset_normalizer: charset_normalizer_info = {"version": charset_normalizer.__version__} if chardet: chardet_info = {"version": chardet.__version__} pyopenssl_info = { "version": None, "openssl_version": "", } if OpenSSL: pyopenssl_info = { "version": OpenSSL.__version__, "openssl_version": f"{OpenSSL.SSL.OPENSSL_VERSION_NUMBER:x}", } cryptography_info = { "version": getattr(cryptography, "__version__", ""), } idna_info = { "version": getattr(idna, "__version__", ""), } system_ssl = ssl.OPENSSL_VERSION_NUMBER system_ssl_info = {"version": f"{system_ssl:x}" if system_ssl is not None else ""} return { "platform": platform_info, "implementation": implementation_info, "system_ssl": system_ssl_info, "using_pyopenssl": pyopenssl is not None, "using_charset_normalizer": chardet is None, "pyOpenSSL": pyopenssl_info, "urllib3": urllib3_info, "chardet": chardet_info, "charset_normalizer": charset_normalizer_info, "cryptography": cryptography_info, "idna": idna_info, "requests": { "version": requests_version, }, } def main(): """Pretty-print the bug information as JSON.""" print(json.dumps(info(), sort_keys=True, indent=2)) if __name__ == "__main__": main()
from unittest import mock from requests.help import info def test_system_ssl(): """Verify we're actually setting system_ssl when it should be available.""" assert info()["system_ssl"]["version"] != "" class VersionedPackage: def __init__(self, version): self.__version__ = version def test_idna_without_version_attribute(): """Older versions of IDNA don't provide a __version__ attribute, verify that if we have such a package, we don't blow up. """ with mock.patch("requests.help.idna", new=None): assert info()["idna"] == {"version": ""} def test_idna_with_version_attribute(): """Verify we're actually setting idna version when it should be available.""" with mock.patch("requests.help.idna", new=VersionedPackage("2.6")): assert info()["idna"] == {"version": "2.6"}
requests
python
""" Built-in, globally-available admin actions. """ from django.contrib import messages from django.contrib.admin import helpers from django.contrib.admin.decorators import action from django.contrib.admin.utils import model_ngettext from django.core.exceptions import PermissionDenied from django.template.response import TemplateResponse from django.utils.translation import gettext as _ from django.utils.translation import gettext_lazy @action( permissions=["delete"], description=gettext_lazy("Delete selected %(verbose_name_plural)s"), ) def delete_selected(modeladmin, request, queryset): """ Default action which deletes the selected objects. This action first displays a confirmation page which shows all the deletable objects, or, if the user has no permission one of the related childs (foreignkeys), a "permission denied" message. Next, it deletes all selected objects and redirects back to the change list. """ opts = modeladmin.model._meta app_label = opts.app_label # Populate deletable_objects, a data structure of all related objects that # will also be deleted. ( deletable_objects, model_count, perms_needed, protected, ) = modeladmin.get_deleted_objects(queryset, request) # The user has already confirmed the deletion. # Do the deletion and return None to display the change list view again. if request.POST.get("post") and not protected: if perms_needed: raise PermissionDenied n = len(queryset) if n: modeladmin.log_deletions(request, queryset) modeladmin.delete_queryset(request, queryset) modeladmin.message_user( request, _("Successfully deleted %(count)d %(items)s.") % {"count": n, "items": model_ngettext(modeladmin.opts, n)}, messages.SUCCESS, ) # Return None to display the change list page again. return None objects_name = model_ngettext(queryset) if perms_needed or protected: title = _("Cannot delete %(name)s") % {"name": objects_name} else: title = _("Delete multiple objects") context = { **modeladmin.admin_site.each_context(request), "title": title, "subtitle": None, "objects_name": str(objects_name), "deletable_objects": [deletable_objects], "model_count": dict(model_count).items(), "queryset": queryset, "perms_lacking": perms_needed, "protected": protected, "opts": opts, "action_checkbox_name": helpers.ACTION_CHECKBOX_NAME, "media": modeladmin.media, } request.current_app = modeladmin.admin_site.name # Display the confirmation page return TemplateResponse( request, modeladmin.delete_selected_confirmation_template or [ "admin/%s/%s/delete_selected_confirmation.html" % (app_label, opts.model_name), "admin/%s/delete_selected_confirmation.html" % app_label, "admin/delete_selected_confirmation.html", ], context, )
from django.contrib import admin from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.models import ContentType from django.test import TestCase from .models import Band class AdminActionsTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) content_type = ContentType.objects.get_for_model(Band) Permission.objects.create( name="custom", codename="custom_band", content_type=content_type ) for user_type in ("view", "add", "change", "delete", "custom"): username = "%suser" % user_type user = User.objects.create_user( username=username, password="secret", is_staff=True ) permission = Permission.objects.get( codename="%s_band" % user_type, content_type=content_type ) user.user_permissions.add(permission) setattr(cls, username, user) def test_get_actions_respects_permissions(self): class MockRequest: pass class BandAdmin(admin.ModelAdmin): actions = ["custom_action"] @admin.action def custom_action(modeladmin, request, queryset): pass def has_custom_permission(self, request): return request.user.has_perm("%s.custom_band" % self.opts.app_label) ma = BandAdmin(Band, admin.AdminSite()) mock_request = MockRequest() mock_request.GET = {} cases = [ (None, self.viewuser, ["custom_action"]), ("view", self.superuser, ["delete_selected", "custom_action"]), ("view", self.viewuser, ["custom_action"]), ("add", self.adduser, ["custom_action"]), ("change", self.changeuser, ["custom_action"]), ("delete", self.deleteuser, ["delete_selected", "custom_action"]), ("custom", self.customuser, ["custom_action"]), ] for permission, user, expected in cases: with self.subTest(permission=permission, user=user): if permission is None: if hasattr(BandAdmin.custom_action, "allowed_permissions"): del BandAdmin.custom_action.allowed_permissions else: BandAdmin.custom_action.allowed_permissions = (permission,) mock_request.user = user actions = ma.get_actions(mock_request) self.assertEqual(list(actions.keys()), expected) def test_actions_inheritance(self): class AdminBase(admin.ModelAdmin): actions = ["custom_action"] @admin.action def custom_action(modeladmin, request, queryset): pass class AdminA(AdminBase): pass class AdminB(AdminBase): actions = None ma1 = AdminA(Band, admin.AdminSite()) action_names = [name for _, name, _ in ma1._get_base_actions()] self.assertEqual(action_names, ["delete_selected", "custom_action"]) # `actions = None` removes actions from superclasses. ma2 = AdminB(Band, admin.AdminSite()) action_names = [name for _, name, _ in ma2._get_base_actions()] self.assertEqual(action_names, ["delete_selected"]) def test_global_actions_description(self): @admin.action(description="Site-wide admin action 1.") def global_action_1(modeladmin, request, queryset): pass @admin.action def global_action_2(modeladmin, request, queryset): pass admin_site = admin.AdminSite() admin_site.add_action(global_action_1) admin_site.add_action(global_action_2) class BandAdmin(admin.ModelAdmin): pass ma = BandAdmin(Band, admin_site) self.assertEqual( [description for _, _, description in ma._get_base_actions()], [ "Delete selected %(verbose_name_plural)s", "Site-wide admin action 1.", "Global action 2", ], ) def test_actions_replace_global_action(self): @admin.action(description="Site-wide admin action 1.") def global_action_1(modeladmin, request, queryset): pass @admin.action(description="Site-wide admin action 2.") def global_action_2(modeladmin, request, queryset): pass admin.site.add_action(global_action_1, name="custom_action_1") admin.site.add_action(global_action_2, name="custom_action_2") @admin.action(description="Local admin action 1.") def custom_action_1(modeladmin, request, queryset): pass class BandAdmin(admin.ModelAdmin): actions = [custom_action_1, "custom_action_2"] @admin.action(description="Local admin action 2.") def custom_action_2(self, request, queryset): pass ma = BandAdmin(Band, admin.site) self.assertEqual(ma.check(), []) self.assertEqual( [ desc for _, name, desc in ma._get_base_actions() if name.startswith("custom_action") ], [ "Local admin action 1.", "Local admin action 2.", ], )
django
python
urlpatterns = [] handler404 = "csrf_tests.views.csrf_token_error_handler"
from unittest import mock from django.template import TemplateDoesNotExist from django.test import Client, RequestFactory, SimpleTestCase, override_settings from django.utils.translation import override from django.views.csrf import CSRF_FAILURE_TEMPLATE_NAME, csrf_failure @override_settings(ROOT_URLCONF="view_tests.urls") class CsrfViewTests(SimpleTestCase): def setUp(self): super().setUp() self.client = Client(enforce_csrf_checks=True) @override_settings( USE_I18N=True, MIDDLEWARE=[ "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", ], ) def test_translation(self): """An invalid request is rejected with a localized error message.""" response = self.client.post("/") self.assertContains(response, "Forbidden", status_code=403) self.assertContains( response, "CSRF verification failed. Request aborted.", status_code=403 ) with self.settings(LANGUAGE_CODE="nl"), override("en-us"): response = self.client.post("/") self.assertContains(response, "Verboden", status_code=403) self.assertContains( response, "CSRF-verificatie mislukt. Verzoek afgebroken.", status_code=403, ) @override_settings(SECURE_PROXY_SSL_HEADER=("HTTP_X_FORWARDED_PROTO", "https")) def test_no_referer(self): """ Referer header is strictly checked for POST over HTTPS. Trigger the exception by sending an incorrect referer. """ response = self.client.post("/", headers={"x-forwarded-proto": "https"}) self.assertContains( response, "You are seeing this message because this HTTPS site requires a " "“Referer header” to be sent by your web browser, but " "none was sent.", status_code=403, ) self.assertContains( response, "If you have configured your browser to disable “Referer” " "headers, please re-enable them, at least for this site, or for " "HTTPS connections, or for “same-origin” requests.", status_code=403, ) self.assertContains( response, "If you are using the &lt;meta name=&quot;referrer&quot; " "content=&quot;no-referrer&quot;&gt; tag or including the " "“Referrer-Policy: no-referrer” header, please remove them.", status_code=403, ) def test_no_cookies(self): """ The CSRF cookie is checked for POST. Failure to send this cookie should provide a nice error message. """ response = self.client.post("/") self.assertContains( response, "You are seeing this message because this site requires a CSRF " "cookie when submitting forms. This cookie is required for " "security reasons, to ensure that your browser is not being " "hijacked by third parties.", status_code=403, ) @override_settings(TEMPLATES=[]) def test_no_django_template_engine(self): """ The CSRF view doesn't depend on the TEMPLATES configuration (#24388). """ response = self.client.post("/") self.assertContains(response, "Forbidden", status_code=403) @override_settings( TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "OPTIONS": { "loaders": [ ( "django.template.loaders.locmem.Loader", { CSRF_FAILURE_TEMPLATE_NAME: ( "Test template for CSRF failure" ) }, ), ], }, } ] ) def test_custom_template(self): """A custom CSRF_FAILURE_TEMPLATE_NAME is used.""" response = self.client.post("/") self.assertContains(response, "Test template for CSRF failure", status_code=403) self.assertIs(response.wsgi_request, response.context.request) def test_custom_template_does_not_exist(self): """An exception is raised if a nonexistent template is supplied.""" factory = RequestFactory() request = factory.post("/") with self.assertRaises(TemplateDoesNotExist): csrf_failure(request, template_name="nonexistent.html") def test_template_encoding(self): """ The template is loaded directly, not via a template loader, and should be opened as utf-8 charset as is the default specified on template engines. """ from django.views.csrf import Path with mock.patch.object(Path, "open") as m: csrf_failure(mock.MagicMock(), mock.Mock()) m.assert_called_once_with(encoding="utf-8") @override_settings(DEBUG=True) @mock.patch("django.views.csrf.get_docs_version", return_value="4.2") def test_doc_links(self, mocked_get_complete_version): response = self.client.post("/") self.assertContains(response, "Forbidden", status_code=403) self.assertNotContains( response, "https://docs.djangoproject.com/en/dev/", status_code=403 ) self.assertContains( response, "https://docs.djangoproject.com/en/4.2/", status_code=403 )
django
python
from django import template register = template.Library() @register.simple_tag def go_boom(): raise Exception("boom")
import importlib import inspect import os import re import sys import tempfile import threading from io import StringIO from pathlib import Path from unittest import mock, skipIf from asgiref.sync import async_to_sync, iscoroutinefunction from django.core import mail from django.core.files.uploadedfile import SimpleUploadedFile from django.db import DatabaseError, connection from django.http import Http404, HttpRequest, HttpResponse from django.shortcuts import render from django.template import TemplateDoesNotExist from django.test import RequestFactory, SimpleTestCase, override_settings from django.test.utils import LoggingCaptureMixin from django.urls import path, reverse from django.urls.converters import IntConverter from django.utils.functional import SimpleLazyObject from django.utils.regex_helper import _lazy_re_compile from django.utils.safestring import mark_safe from django.views.debug import ( CallableSettingWrapper, ExceptionCycleWarning, ExceptionReporter, ) from django.views.debug import Path as DebugPath from django.views.debug import ( SafeExceptionReporterFilter, default_urlconf, get_default_exception_reporter_filter, technical_404_response, technical_500_response, ) from django.views.decorators.debug import sensitive_post_parameters, sensitive_variables from ..views import ( async_sensitive_method_view, async_sensitive_method_view_nested, async_sensitive_view, async_sensitive_view_nested, custom_exception_reporter_filter_view, index_page, multivalue_dict_key_error, non_sensitive_view, paranoid_view, sensitive_args_function_caller, sensitive_kwargs_function_caller, sensitive_method_view, sensitive_view, ) class User: def __str__(self): return "jacob" class WithoutEmptyPathUrls: urlpatterns = [path("url/", index_page, name="url")] class CallableSettingWrapperTests(SimpleTestCase): """Unittests for CallableSettingWrapper""" def test_repr(self): class WrappedCallable: def __repr__(self): return "repr from the wrapped callable" def __call__(self): pass actual = repr(CallableSettingWrapper(WrappedCallable())) self.assertEqual(actual, "repr from the wrapped callable") @override_settings(DEBUG=True, ROOT_URLCONF="view_tests.urls") class DebugViewTests(SimpleTestCase): def test_files(self): with self.assertLogs("django.request", "ERROR"): response = self.client.get("/raises/") self.assertEqual(response.status_code, 500) data = { "file_data.txt": SimpleUploadedFile("file_data.txt", b"haha"), } with self.assertLogs("django.request", "ERROR"): response = self.client.post("/raises/", data) self.assertContains(response, "file_data.txt", status_code=500) self.assertNotContains(response, "haha", status_code=500) def test_400(self): # When DEBUG=True, technical_500_template() is called. with self.assertLogs("django.security", "WARNING"): response = self.client.get("/raises400/") self.assertContains(response, '<div class="context" id="', status_code=400) def test_400_bad_request(self): # When DEBUG=True, technical_500_template() is called. with self.assertLogs("django.request", "WARNING") as cm: response = self.client.get("/raises400_bad_request/") self.assertContains(response, '<div class="context" id="', status_code=400) self.assertEqual( cm.records[0].getMessage(), "Malformed request syntax: /raises400_bad_request/", ) # Ensure no 403.html template exists to test the default case. @override_settings( TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", } ] ) def test_403(self): response = self.client.get("/raises403/") self.assertContains(response, "<h1>403 Forbidden</h1>", status_code=403) # Set up a test 403.html template. @override_settings( TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "OPTIONS": { "loaders": [ ( "django.template.loaders.locmem.Loader", { "403.html": ( "This is a test template for a 403 error " "({{ exception }})." ), }, ), ], }, } ] ) def test_403_template(self): response = self.client.get("/raises403/") self.assertContains(response, "test template", status_code=403) self.assertContains(response, "(Insufficient Permissions).", status_code=403) def test_404(self): response = self.client.get("/raises404/") self.assertNotContains( response, '<pre class="exception_value">', status_code=404, ) self.assertContains( response, "<p>The current path, <code>not-in-urls</code>, didn’t match any " "of these.</p>", status_code=404, html=True, ) def test_404_not_in_urls(self): response = self.client.get("/not-in-urls") self.assertNotContains(response, "Raised by:", status_code=404) self.assertNotContains( response, '<pre class="exception_value">', status_code=404, ) self.assertContains( response, "Django tried these URL patterns", status_code=404 ) self.assertContains( response, "<code>technical404/ [name='my404']</code>", status_code=404, html=True, ) self.assertContains( response, "<p>The current path, <code>not-in-urls</code>, didn’t match any " "of these.</p>", status_code=404, html=True, ) # Pattern and view name of a RegexURLPattern appear. self.assertContains( response, r"^regex-post/(?P&lt;pk&gt;[0-9]+)/$", status_code=404 ) self.assertContains(response, "[name='regex-post']", status_code=404) # Pattern and view name of a RoutePattern appear. self.assertContains(response, r"path-post/&lt;int:pk&gt;/", status_code=404) self.assertContains(response, "[name='path-post']", status_code=404) @override_settings(ROOT_URLCONF=WithoutEmptyPathUrls) def test_404_empty_path_not_in_urls(self): response = self.client.get("/") self.assertContains( response, "<p>The empty path didn’t match any of these.</p>", status_code=404, html=True, ) def test_technical_404(self): response = self.client.get("/technical404/") self.assertContains(response, '<header id="summary">', status_code=404) self.assertContains(response, '<main id="info">', status_code=404) self.assertContains(response, '<footer id="explanation">', status_code=404) self.assertContains( response, '<pre class="exception_value">Testing technical 404.</pre>', status_code=404, html=True, ) self.assertContains(response, "Raised by:", status_code=404) self.assertContains( response, "<td>view_tests.views.technical404</td>", status_code=404, ) self.assertContains( response, "<p>The current path, <code>technical404/</code>, matched the " "last one.</p>", status_code=404, html=True, ) def test_classbased_technical_404(self): response = self.client.get("/classbased404/") self.assertContains( response, '<th scope="row">Raised by:</th><td>view_tests.views.Http404View</td>', status_code=404, html=True, ) def test_technical_500(self): with self.assertLogs("django.request", "ERROR"): response = self.client.get("/raises500/") self.assertContains(response, '<header id="summary">', status_code=500) self.assertContains(response, '<main id="info">', status_code=500) self.assertContains(response, '<footer id="explanation">', status_code=500) self.assertContains( response, '<th scope="row">Raised during:</th><td>view_tests.views.raises500</td>', status_code=500, html=True, ) with self.assertLogs("django.request", "ERROR"): response = self.client.get("/raises500/", headers={"accept": "text/plain"}) self.assertContains( response, "Raised during: view_tests.views.raises500", status_code=500, ) def test_technical_500_content_type_negotiation(self): for accepts, content_type in [ ("text/plain", "text/plain; charset=utf-8"), ("text/html", "text/html"), ("text/html,text/plain;q=0.9", "text/html"), ("text/plain,text/html;q=0.9", "text/plain; charset=utf-8"), ("text/*", "text/html"), ]: with self.subTest(accepts=accepts): with self.assertLogs("django.request", "ERROR"): response = self.client.get( "/raises500/", headers={"accept": accepts} ) self.assertEqual(response.status_code, 500) self.assertEqual(response["Content-Type"], content_type) def test_classbased_technical_500(self): with self.assertLogs("django.request", "ERROR"): response = self.client.get("/classbased500/") self.assertContains( response, '<th scope="row">Raised during:</th>' "<td>view_tests.views.Raises500View</td>", status_code=500, html=True, ) with self.assertLogs("django.request", "ERROR"): response = self.client.get( "/classbased500/", headers={"accept": "text/plain"} ) self.assertContains( response, "Raised during: view_tests.views.Raises500View", status_code=500, ) def test_non_l10ned_numeric_ids(self): """ Numeric IDs and fancy traceback context blocks line numbers shouldn't be localized. """ with self.settings(DEBUG=True): with self.assertLogs("django.request", "ERROR"): response = self.client.get("/raises500/") # We look for a HTML fragment of the form # '<div class="context" id="c38123208">', # not '<div class="context" id="c38,123,208"'. self.assertContains(response, '<div class="context" id="', status_code=500) match = re.search( b'<div class="context" id="(?P<id>[^"]+)">', response.content ) self.assertIsNotNone(match) id_repr = match["id"] self.assertFalse( re.search(b"[^c0-9]", id_repr), "Numeric IDs in debug response HTML page shouldn't be localized " "(value: %s)." % id_repr.decode(), ) def test_template_exceptions(self): with self.assertLogs("django.request", "ERROR"): try: self.client.get(reverse("template_exception")) except Exception: raising_loc = inspect.trace()[-1][-2][0].strip() self.assertNotEqual( raising_loc.find('raise Exception("boom")'), -1, "Failed to find 'raise Exception' in last frame of " "traceback, instead found: %s" % raising_loc, ) @skipIf( sys.platform == "win32", "Raises OSError instead of TemplateDoesNotExist on Windows.", ) def test_safestring_in_exception(self): with self.assertLogs("django.request", "ERROR"): response = self.client.get("/safestring_exception/") self.assertNotContains( response, "<script>alert(1);</script>", status_code=500, html=True, ) self.assertContains( response, "&lt;script&gt;alert(1);&lt;/script&gt;", count=3, status_code=500, html=True, ) def test_template_loader_postmortem(self): """Tests for not existing file""" template_name = "notfound.html" with tempfile.NamedTemporaryFile(prefix=template_name) as tmpfile: tempdir = os.path.dirname(tmpfile.name) template_path = os.path.join(tempdir, template_name) with ( override_settings( TEMPLATES=[ { "BACKEND": ( "django.template.backends.django.DjangoTemplates" ), "DIRS": [tempdir], } ] ), self.assertLogs("django.request", "ERROR"), ): response = self.client.get( reverse( "raises_template_does_not_exist", kwargs={"path": template_name} ) ) self.assertContains( response, "%s (Source does not exist)" % template_path, status_code=500, count=2, ) # Assert as HTML. self.assertContains( response, "<li><code>django.template.loaders.filesystem.Loader</code>: " "%s (Source does not exist)</li>" % os.path.join(tempdir, "notfound.html"), status_code=500, html=True, ) def test_no_template_source_loaders(self): """ Make sure if you don't specify a template, the debug view doesn't blow up. """ with self.assertLogs("django.request", "ERROR"): with self.assertRaises(TemplateDoesNotExist): self.client.get("/render_no_template/") @override_settings(ROOT_URLCONF="view_tests.default_urls") def test_default_urlconf_template(self): """ Make sure that the default URLconf template is shown instead of the technical 404 page, if the user has not altered their URLconf yet. """ response = self.client.get("/") self.assertContains( response, "<h1>The install worked successfully! Congratulations!</h1>" ) @override_settings( ROOT_URLCONF="view_tests.default_urls", FORCE_SCRIPT_NAME="/FORCED_PREFIX" ) def test_default_urlconf_script_name(self): response = self.client.request(**{"path": "/FORCED_PREFIX/"}) self.assertContains( response, "<h1>The install worked successfully! Congratulations!</h1>" ) @override_settings(ROOT_URLCONF="view_tests.default_urls") def test_default_urlconf_technical_404(self): response = self.client.get("/favicon.ico") self.assertContains( response, "<code>\nadmin/\n[namespace='admin']\n</code>", status_code=404, html=True, ) @override_settings(ROOT_URLCONF="view_tests.regression_21530_urls") def test_regression_21530(self): """ Regression test for bug #21530. If the admin app include is replaced with exactly one url pattern, then the technical 404 template should be displayed. The bug here was that an AttributeError caused a 500 response. """ response = self.client.get("/") self.assertContains( response, "Page not found <small>(404)</small>", status_code=404 ) def test_template_encoding(self): """ The templates are loaded directly, not via a template loader, and should be opened as utf-8 charset as is the default specified on template engines. """ with mock.patch.object(DebugPath, "open") as m: default_urlconf(None) m.assert_called_once_with(encoding="utf-8") m.reset_mock() technical_404_response(mock.MagicMock(), mock.Mock()) m.assert_called_once_with(encoding="utf-8") def test_technical_404_converter_raise_404(self): with mock.patch.object(IntConverter, "to_python", side_effect=Http404): response = self.client.get("/path-post/1/") self.assertContains(response, "Page not found", status_code=404) def test_exception_reporter_from_request(self): with self.assertLogs("django.request", "ERROR"): response = self.client.get("/custom_reporter_class_view/") self.assertContains(response, "custom traceback text", status_code=500) @override_settings( DEFAULT_EXCEPTION_REPORTER="view_tests.views.CustomExceptionReporter" ) def test_exception_reporter_from_settings(self): with self.assertLogs("django.request", "ERROR"): response = self.client.get("/raises500/") self.assertContains(response, "custom traceback text", status_code=500) @override_settings( DEFAULT_EXCEPTION_REPORTER="view_tests.views.TemplateOverrideExceptionReporter" ) def test_template_override_exception_reporter(self): with self.assertLogs("django.request", "ERROR"): response = self.client.get("/raises500/") self.assertContains( response, "<h1>Oh no, an error occurred!</h1>", status_code=500, html=True, ) with self.assertLogs("django.request", "ERROR"): response = self.client.get("/raises500/", headers={"accept": "text/plain"}) self.assertContains(response, "Oh dear, an error occurred!", status_code=500) class DebugViewQueriesAllowedTests(SimpleTestCase): # May need a query to initialize MySQL connection databases = {"default"} def test_handle_db_exception(self): """ Ensure the debug view works when a database exception is raised by performing an invalid query and passing the exception to the debug view. """ with connection.cursor() as cursor: try: cursor.execute("INVALID SQL") except DatabaseError: exc_info = sys.exc_info() rf = RequestFactory() response = technical_500_response(rf.get("/"), *exc_info) self.assertContains(response, "OperationalError at /", status_code=500) @override_settings( DEBUG=True, ROOT_URLCONF="view_tests.urls", # No template directories are configured, so no templates will be found. TEMPLATES=[ { "BACKEND": "django.template.backends.dummy.TemplateStrings", } ], ) class NonDjangoTemplatesDebugViewTests(SimpleTestCase): def test_400(self): # When DEBUG=True, technical_500_template() is called. with self.assertLogs("django.security", "WARNING"): response = self.client.get("/raises400/") self.assertContains(response, '<div class="context" id="', status_code=400) def test_400_bad_request(self): # When DEBUG=True, technical_500_template() is called. with self.assertLogs("django.request", "WARNING") as cm: response = self.client.get("/raises400_bad_request/") self.assertContains(response, '<div class="context" id="', status_code=400) self.assertEqual( cm.records[0].getMessage(), "Malformed request syntax: /raises400_bad_request/", ) def test_403(self): response = self.client.get("/raises403/") self.assertContains(response, "<h1>403 Forbidden</h1>", status_code=403) def test_404(self): response = self.client.get("/raises404/") self.assertEqual(response.status_code, 404) def test_template_not_found_error(self): # Raises a TemplateDoesNotExist exception and shows the debug view. url = reverse( "raises_template_does_not_exist", kwargs={"path": "notfound.html"} ) with self.assertLogs("django.request", "ERROR"): response = self.client.get(url) self.assertContains(response, '<div class="context" id="', status_code=500) class ExceptionReporterTests(SimpleTestCase): rf = RequestFactory() def test_request_and_exception(self): "A simple exception report can be generated" try: request = self.rf.get("/test_view/") request.user = User() raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML("<h1>ValueError at /test_view/</h1>", html) self.assertIn( '<pre class="exception_value">Can&#x27;t find my keys</pre>', html ) self.assertIn('<th scope="row">Request Method:</th>', html) self.assertIn('<th scope="row">Request URL:</th>', html) self.assertIn('<h3 id="user-info">USER</h3>', html) self.assertIn("<p>jacob</p>", html) self.assertIn('<th scope="row">Exception Type:</th>', html) self.assertIn('<th scope="row">Exception Value:</th>', html) self.assertIn("<h2>Traceback ", html) self.assertIn("<h2>Request information</h2>", html) self.assertNotIn("<p>Request data not supplied</p>", html) self.assertIn("<p>No POST data</p>", html) def test_no_request(self): "An exception report can be generated without request" try: raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML("<h1>ValueError</h1>", html) self.assertIn( '<pre class="exception_value">Can&#x27;t find my keys</pre>', html ) self.assertNotIn('<th scope="row">Request Method:</th>', html) self.assertNotIn('<th scope="row">Request URL:</th>', html) self.assertNotIn('<h3 id="user-info">USER</h3>', html) self.assertIn('<th scope="row">Exception Type:</th>', html) self.assertIn('<th scope="row">Exception Value:</th>', html) self.assertIn("<h2>Traceback ", html) self.assertIn("<h2>Request information</h2>", html) self.assertIn("<p>Request data not supplied</p>", html) def test_sharing_traceback(self): try: raise ValueError("Oops") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn( '<form action="https://dpaste.com/" name="pasteform" ' 'id="pasteform" method="post">', html, ) def test_eol_support(self): """ The ExceptionReporter supports Unix, Windows and Macintosh EOL markers """ LINES = ["print %d" % i for i in range(1, 6)] reporter = ExceptionReporter(None, None, None, None) for newline in ["\n", "\r\n", "\r"]: fd, filename = tempfile.mkstemp(text=False) os.write(fd, (newline.join(LINES) + newline).encode()) os.close(fd) try: self.assertEqual( reporter._get_lines_from_file(filename, 3, 2), (1, LINES[1:3], LINES[3], LINES[4:]), ) finally: os.unlink(filename) def test_no_exception(self): "An exception report can be generated for just a request" request = self.rf.get("/test_view/") reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML("<h1>Report at /test_view/</h1>", html) self.assertIn( '<pre class="exception_value">No exception message supplied</pre>', html ) self.assertIn('<th scope="row">Request Method:</th>', html) self.assertIn('<th scope="row">Request URL:</th>', html) self.assertNotIn('<th scope="row">Exception Type:</th>', html) self.assertNotIn('<th scope="row">Exception Value:</th>', html) self.assertNotIn("<h2>Traceback ", html) self.assertIn("<h2>Request information</h2>", html) self.assertNotIn("<p>Request data not supplied</p>", html) def test_suppressed_context(self): try: try: raise RuntimeError("Can't find my keys") except RuntimeError: raise ValueError("Can't find my keys") from None except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML("<h1>ValueError</h1>", html) self.assertIn( '<pre class="exception_value">Can&#x27;t find my keys</pre>', html ) self.assertIn('<th scope="row">Exception Type:</th>', html) self.assertIn('<th scope="row">Exception Value:</th>', html) self.assertIn("<h2>Traceback ", html) self.assertIn("<h2>Request information</h2>", html) self.assertIn("<p>Request data not supplied</p>", html) self.assertNotIn("During handling of the above exception", html) def test_innermost_exception_without_traceback(self): try: try: raise RuntimeError("Oops") except Exception as exc: new_exc = RuntimeError("My context") exc.__context__ = new_exc raise except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) frames = reporter.get_traceback_frames() self.assertEqual(len(frames), 2) html = reporter.get_traceback_html() self.assertInHTML("<h1>RuntimeError</h1>", html) self.assertIn('<pre class="exception_value">Oops</pre>', html) self.assertIn('<th scope="row">Exception Type:</th>', html) self.assertIn('<th scope="row">Exception Value:</th>', html) self.assertIn("<h2>Traceback ", html) self.assertIn("<h2>Request information</h2>", html) self.assertIn("<p>Request data not supplied</p>", html) self.assertIn( "During handling of the above exception (My context), another " "exception occurred", html, ) self.assertInHTML('<li class="frame user">None</li>', html) self.assertIn("Traceback (most recent call last):\n None", html) text = reporter.get_traceback_text() self.assertIn("Exception Type: RuntimeError", text) self.assertIn("Exception Value: Oops", text) self.assertIn("Traceback (most recent call last):\n None", text) self.assertIn( "During handling of the above exception (My context), another " "exception occurred", text, ) def test_exception_with_notes(self): request = self.rf.get("/test_view/") try: try: raise RuntimeError("Oops") except Exception as err: err.add_note("First Note") err.add_note("Second Note") err.add_note(mark_safe("<script>alert(1);</script>")) raise err except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn( '<pre class="exception_value">Oops\nFirst Note\nSecond Note\n' "&lt;script&gt;alert(1);&lt;/script&gt;</pre>", html, ) self.assertIn( "Exception Value: Oops\nFirst Note\nSecond Note\n" "&lt;script&gt;alert(1);&lt;/script&gt;", html, ) text = reporter.get_traceback_text() self.assertIn( "Exception Value: Oops\nFirst Note\nSecond Note\n" "<script>alert(1);</script>", text, ) def test_mid_stack_exception_without_traceback(self): try: try: raise RuntimeError("Inner Oops") except Exception as exc: new_exc = RuntimeError("My context") new_exc.__context__ = exc raise RuntimeError("Oops") from new_exc except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML("<h1>RuntimeError</h1>", html) self.assertIn('<pre class="exception_value">Oops</pre>', html) self.assertIn('<th scope="row">Exception Type:</th>', html) self.assertIn('<th scope="row">Exception Value:</th>', html) self.assertIn("<h2>Traceback ", html) self.assertInHTML('<li class="frame user">Traceback: None</li>', html) self.assertIn( "During handling of the above exception (Inner Oops), another " "exception occurred:\n Traceback: None", html, ) text = reporter.get_traceback_text() self.assertIn("Exception Type: RuntimeError", text) self.assertIn("Exception Value: Oops", text) self.assertIn("Traceback (most recent call last):", text) self.assertIn( "During handling of the above exception (Inner Oops), another " "exception occurred:\n Traceback: None", text, ) def test_reporting_of_nested_exceptions(self): request = self.rf.get("/test_view/") try: try: raise AttributeError(mark_safe("<p>Top level</p>")) except AttributeError as explicit: try: raise ValueError(mark_safe("<p>Second exception</p>")) from explicit except ValueError: raise IndexError(mark_safe("<p>Final exception</p>")) except Exception: # Custom exception handler, just pass it into ExceptionReporter exc_type, exc_value, tb = sys.exc_info() explicit_exc = ( "The above exception ({0}) was the direct cause of the following exception:" ) implicit_exc = ( "During handling of the above exception ({0}), another exception occurred:" ) reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() # Both messages are twice on page -- one rendered as html, # one as plain text (for pastebin) self.assertEqual( 2, html.count(explicit_exc.format("&lt;p&gt;Top level&lt;/p&gt;")) ) self.assertEqual( 2, html.count(implicit_exc.format("&lt;p&gt;Second exception&lt;/p&gt;")) ) self.assertEqual(10, html.count("&lt;p&gt;Final exception&lt;/p&gt;")) text = reporter.get_traceback_text() self.assertIn(explicit_exc.format("<p>Top level</p>"), text) self.assertIn(implicit_exc.format("<p>Second exception</p>"), text) self.assertEqual(3, text.count("<p>Final exception</p>")) @skipIf( sys._xoptions.get("no_debug_ranges", False) or os.environ.get("PYTHONNODEBUGRANGES", False), "Fine-grained error locations are disabled.", ) def test_highlight_error_position(self): request = self.rf.get("/test_view/") try: try: raise AttributeError("Top level") except AttributeError as explicit: try: raise ValueError(mark_safe("<p>2nd exception</p>")) from explicit except ValueError: raise IndexError("Final exception") except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn( "<pre> raise AttributeError(&quot;Top level&quot;)\n" " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre>", html, ) self.assertIn( "<pre> raise ValueError(mark_safe(" "&quot;&lt;p&gt;2nd exception&lt;/p&gt;&quot;)) from explicit\n" " " "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre>", html, ) self.assertIn( "<pre> raise IndexError(&quot;Final exception&quot;)\n" " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre>", html, ) # Pastebin. self.assertIn( " raise AttributeError(&quot;Top level&quot;)\n" " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", html, ) self.assertIn( " raise ValueError(mark_safe(" "&quot;&lt;p&gt;2nd exception&lt;/p&gt;&quot;)) from explicit\n" " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", html, ) self.assertIn( " raise IndexError(&quot;Final exception&quot;)\n" " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", html, ) # Text traceback. text = reporter.get_traceback_text() self.assertIn( ' raise AttributeError("Top level")\n' " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", text, ) self.assertIn( ' raise ValueError(mark_safe("<p>2nd exception</p>")) from explicit\n' " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", text, ) self.assertIn( ' raise IndexError("Final exception")\n' " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", text, ) def test_reporting_frames_without_source(self): try: source = "def funcName():\n raise Error('Whoops')\nfuncName()" namespace = {} code = compile(source, "generated", "exec") exec(code, namespace) except Exception: exc_type, exc_value, tb = sys.exc_info() request = self.rf.get("/test_view/") reporter = ExceptionReporter(request, exc_type, exc_value, tb) frames = reporter.get_traceback_frames() last_frame = frames[-1] self.assertEqual(last_frame["context_line"], "<source code not available>") self.assertEqual(last_frame["filename"], "generated") self.assertEqual(last_frame["function"], "funcName") self.assertEqual(last_frame["lineno"], 2) html = reporter.get_traceback_html() self.assertIn( '<span class="fname">generated</span>, line 2, in funcName', html, ) self.assertIn( '<code class="fname">generated</code>, line 2, in funcName', html, ) self.assertIn( '"generated", line 2, in funcName\n &lt;source code not available&gt;', html, ) text = reporter.get_traceback_text() self.assertIn( '"generated", line 2, in funcName\n <source code not available>', text, ) def test_reporting_frames_source_not_match(self): try: source = "def funcName():\n raise Error('Whoops')\nfuncName()" namespace = {} code = compile(source, "generated", "exec") exec(code, namespace) except Exception: exc_type, exc_value, tb = sys.exc_info() with mock.patch( "django.views.debug.ExceptionReporter._get_source", return_value=["wrong source"], ): request = self.rf.get("/test_view/") reporter = ExceptionReporter(request, exc_type, exc_value, tb) frames = reporter.get_traceback_frames() last_frame = frames[-1] self.assertEqual(last_frame["context_line"], "<source code not available>") self.assertEqual(last_frame["filename"], "generated") self.assertEqual(last_frame["function"], "funcName") self.assertEqual(last_frame["lineno"], 2) html = reporter.get_traceback_html() self.assertIn( '<span class="fname">generated</span>, line 2, in funcName', html, ) self.assertIn( '<code class="fname">generated</code>, line 2, in funcName', html, ) self.assertIn( '"generated", line 2, in funcName\n' " &lt;source code not available&gt;", html, ) text = reporter.get_traceback_text() self.assertIn( '"generated", line 2, in funcName\n <source code not available>', text, ) def test_reporting_frames_for_cyclic_reference(self): try: def test_func(): try: raise RuntimeError("outer") from RuntimeError("inner") except RuntimeError as exc: raise exc.__cause__ test_func() except Exception: exc_type, exc_value, tb = sys.exc_info() request = self.rf.get("/test_view/") reporter = ExceptionReporter(request, exc_type, exc_value, tb) def generate_traceback_frames(*args, **kwargs): nonlocal tb_frames tb_frames = reporter.get_traceback_frames() tb_frames = None tb_generator = threading.Thread(target=generate_traceback_frames, daemon=True) msg = ( "Cycle in the exception chain detected: exception 'inner' " "encountered again." ) with self.assertWarnsMessage(ExceptionCycleWarning, msg): tb_generator.start() tb_generator.join(timeout=5) if tb_generator.is_alive(): # tb_generator is a daemon that runs until the main thread/process # exits. This is resource heavy when running the full test suite. # Setting the following values to None makes # reporter.get_traceback_frames() exit early. exc_value.__traceback__ = exc_value.__context__ = exc_value.__cause__ = None tb_generator.join() self.fail("Cyclic reference in Exception Reporter.get_traceback_frames()") if tb_frames is None: # can happen if the thread generating traceback got killed # or exception while generating the traceback self.fail("Traceback generation failed") last_frame = tb_frames[-1] self.assertIn("raise exc.__cause__", last_frame["context_line"]) self.assertEqual(last_frame["filename"], __file__) self.assertEqual(last_frame["function"], "test_func") def test_request_and_message(self): "A message can be provided in addition to a request" request = self.rf.get("/test_view/") reporter = ExceptionReporter(request, None, "I'm a little teapot", None) html = reporter.get_traceback_html() self.assertInHTML("<h1>Report at /test_view/</h1>", html) self.assertIn( '<pre class="exception_value">I&#x27;m a little teapot</pre>', html ) self.assertIn('<th scope="row">Request Method:</th>', html) self.assertIn('<th scope="row">Request URL:</th>', html) self.assertNotIn('<th scope="row">Exception Type:</th>', html) self.assertNotIn('<th scope="row">Exception Value:</th>', html) self.assertIn("<h2>Traceback ", html) self.assertIn("<h2>Request information</h2>", html) self.assertNotIn("<p>Request data not supplied</p>", html) def test_message_only(self): reporter = ExceptionReporter(None, None, "I'm a little teapot", None) html = reporter.get_traceback_html() self.assertInHTML("<h1>Report</h1>", html) self.assertIn( '<pre class="exception_value">I&#x27;m a little teapot</pre>', html ) self.assertNotIn('<th scope="row">Request Method:</th>', html) self.assertNotIn('<th scope="row">Request URL:</th>', html) self.assertNotIn('<th scope="row">Exception Type:</th>', html) self.assertNotIn('<th scope="row">Exception Value:</th>', html) self.assertIn("<h2>Traceback ", html) self.assertIn("<h2>Request information</h2>", html) self.assertIn("<p>Request data not supplied</p>", html) def test_non_utf8_values_handling(self): """ Non-UTF-8 exceptions/values should not make the output generation choke. """ try: class NonUtf8Output(Exception): def __repr__(self): return b"EXC\xe9EXC" somevar = b"VAL\xe9VAL" # NOQA raise NonUtf8Output() except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn("VAL\\xe9VAL", html) self.assertIn("EXC\\xe9EXC", html) def test_local_variable_escaping(self): """Safe strings in local variables are escaped.""" try: local = mark_safe("<p>Local variable</p>") raise ValueError(local) except Exception: exc_type, exc_value, tb = sys.exc_info() html = ExceptionReporter(None, exc_type, exc_value, tb).get_traceback_html() self.assertIn( '<td class="code"><pre>&#x27;&lt;p&gt;Local variable&lt;/p&gt;&#x27;</pre>' "</td>", html, ) def test_unprintable_values_handling(self): "Unprintable values should not make the output generation choke." try: class OomOutput: def __repr__(self): raise MemoryError("OOM") oomvalue = OomOutput() # NOQA raise ValueError() except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn('<td class="code"><pre>Error in formatting', html) def test_too_large_values_handling(self): "Large values should not create a large HTML." large = 256 * 1024 repr_of_str_adds = len(repr("")) try: class LargeOutput: def __repr__(self): return repr("A" * large) largevalue = LargeOutput() # NOQA raise ValueError() except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertEqual(len(html) // 1024 // 128, 0) # still fit in 128Kb self.assertIn( "&lt;trimmed %d bytes string&gt;" % (large + repr_of_str_adds,), html ) def test_encoding_error(self): """ A UnicodeError displays a portion of the problematic string. HTML in safe strings is escaped. """ try: mark_safe("abcdefghijkl<p>mnὀp</p>qrstuwxyz").encode("ascii") except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn("<h2>Unicode error hint</h2>", html) self.assertIn("The string that could not be encoded/decoded was: ", html) self.assertIn("<strong>&lt;p&gt;mnὀp&lt;/p&gt;</strong>", html) def test_unfrozen_importlib(self): """ importlib is not a frozen app, but its loader thinks it's frozen which results in an ImportError. Refs #21443. """ try: request = self.rf.get("/test_view/") importlib.import_module("abc.def.invalid.name") except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML("<h1>ModuleNotFoundError at /test_view/</h1>", html) def test_ignore_traceback_evaluation_exceptions(self): """ Don't trip over exceptions generated by crafted objects when evaluating them while cleansing (#24455). """ class BrokenEvaluation(Exception): pass def broken_setup(): raise BrokenEvaluation request = self.rf.get("/test_view/") broken_lazy = SimpleLazyObject(broken_setup) try: bool(broken_lazy) except BrokenEvaluation: exc_type, exc_value, tb = sys.exc_info() self.assertIn( "BrokenEvaluation", ExceptionReporter(request, exc_type, exc_value, tb).get_traceback_html(), "Evaluation exception reason not mentioned in traceback", ) @override_settings(ALLOWED_HOSTS="example.com") def test_disallowed_host(self): "An exception report can be generated even for a disallowed host." request = self.rf.get("/", headers={"host": "evil.com"}) reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertIn("http://evil.com/", html) def test_request_with_items_key(self): """ An exception report can be generated for requests with 'items' in request GET, POST, FILES, or COOKIES QueryDicts. """ value = '<td>items</td><td class="code"><pre>&#x27;Oops&#x27;</pre></td>' # GET request = self.rf.get("/test_view/?items=Oops") reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML(value, html) # POST request = self.rf.post("/test_view/", data={"items": "Oops"}) reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML(value, html) # FILES fp = StringIO("filecontent") request = self.rf.post("/test_view/", data={"name": "filename", "items": fp}) reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML( '<td>items</td><td class="code"><pre>&lt;InMemoryUploadedFile: ' "items (application/octet-stream)&gt;</pre></td>", html, ) # COOKIES rf = RequestFactory() rf.cookies["items"] = "Oops" request = rf.get("/test_view/") reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML( '<td>items</td><td class="code"><pre>&#x27;Oops&#x27;</pre></td>', html ) def test_exception_fetching_user(self): """ The error page can be rendered if the current user can't be retrieved (such as when the database is unavailable). """ class ExceptionUser: def __str__(self): raise Exception() request = self.rf.get("/test_view/") request.user = ExceptionUser() try: raise ValueError("Oops") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML("<h1>ValueError at /test_view/</h1>", html) self.assertIn('<pre class="exception_value">Oops</pre>', html) self.assertIn('<h3 id="user-info">USER</h3>', html) self.assertIn("<p>[unable to retrieve the current user]</p>", html) text = reporter.get_traceback_text() self.assertIn("USER: [unable to retrieve the current user]", text) def test_template_encoding(self): """ The templates are loaded directly, not via a template loader, and should be opened as utf-8 charset as is the default specified on template engines. """ reporter = ExceptionReporter(None, None, None, None) with mock.patch.object(DebugPath, "open") as m: reporter.get_traceback_html() m.assert_called_once_with(encoding="utf-8") m.reset_mock() reporter.get_traceback_text() m.assert_called_once_with(encoding="utf-8") @override_settings(ALLOWED_HOSTS=["example.com"]) def test_get_raw_insecure_uri(self): factory = RequestFactory(headers={"host": "evil.com"}) tests = [ ("////absolute-uri", "http://evil.com//absolute-uri"), ("/?foo=bar", "http://evil.com/?foo=bar"), ("/path/with:colons", "http://evil.com/path/with:colons"), ] for url, expected in tests: with self.subTest(url=url): request = factory.get(url) reporter = ExceptionReporter(request, None, None, None) self.assertEqual(reporter._get_raw_insecure_uri(), expected) class PlainTextReportTests(SimpleTestCase): rf = RequestFactory() def test_request_and_exception(self): "A simple exception report can be generated" try: request = self.rf.get("/test_view/") request.user = User() raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) text = reporter.get_traceback_text() self.assertIn("ValueError at /test_view/", text) self.assertIn("Can't find my keys", text) self.assertIn("Request Method:", text) self.assertIn("Request URL:", text) self.assertIn("USER: jacob", text) self.assertIn("Exception Type:", text) self.assertIn("Exception Value:", text) self.assertIn("Traceback (most recent call last):", text) self.assertIn("Request information:", text) self.assertNotIn("Request data not supplied", text) def test_no_request(self): "An exception report can be generated without request" try: raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) text = reporter.get_traceback_text() self.assertIn("ValueError", text) self.assertIn("Can't find my keys", text) self.assertNotIn("Request Method:", text) self.assertNotIn("Request URL:", text) self.assertNotIn("USER:", text) self.assertIn("Exception Type:", text) self.assertIn("Exception Value:", text) self.assertIn("Traceback (most recent call last):", text) self.assertIn("Request data not supplied", text) def test_no_exception(self): "An exception report can be generated for just a request" request = self.rf.get("/test_view/") reporter = ExceptionReporter(request, None, None, None) reporter.get_traceback_text() def test_request_and_message(self): "A message can be provided in addition to a request" request = self.rf.get("/test_view/") reporter = ExceptionReporter(request, None, "I'm a little teapot", None) reporter.get_traceback_text() @override_settings(DEBUG=True) def test_template_exception(self): request = self.rf.get("/test_view/") try: render(request, "debug/template_error.html") except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) text = reporter.get_traceback_text() templ_path = Path( Path(__file__).parents[1], "templates", "debug", "template_error.html" ) self.assertIn( "Template error:\n" "In template %(path)s, error at line 2\n" " 'cycle' tag requires at least two arguments\n" " 1 : Template with error:\n" " 2 : {%% cycle %%} \n" " 3 : " % {"path": templ_path}, text, ) def test_request_with_items_key(self): """ An exception report can be generated for requests with 'items' in request GET, POST, FILES, or COOKIES QueryDicts. """ # GET request = self.rf.get("/test_view/?items=Oops") reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) # POST request = self.rf.post("/test_view/", data={"items": "Oops"}) reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) # FILES fp = StringIO("filecontent") request = self.rf.post("/test_view/", data={"name": "filename", "items": fp}) reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = <InMemoryUploadedFile:", text) # COOKIES rf = RequestFactory() rf.cookies["items"] = "Oops" request = rf.get("/test_view/") reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) def test_message_only(self): reporter = ExceptionReporter(None, None, "I'm a little teapot", None) reporter.get_traceback_text() @override_settings(ALLOWED_HOSTS="example.com") def test_disallowed_host(self): "An exception report can be generated even for a disallowed host." request = self.rf.get("/", headers={"host": "evil.com"}) reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("http://evil.com/", text) class ExceptionReportTestMixin: # Mixin used in the ExceptionReporterFilterTests and # AjaxResponseExceptionReporterFilter tests below breakfast_data = { "sausage-key": "sausage-value", "baked-beans-key": "baked-beans-value", "hash-brown-key": "hash-brown-value", "bacon-key": "bacon-value", } def verify_unsafe_response( self, view, check_for_vars=True, check_for_POST_params=True ): """ Asserts that potentially sensitive info are displayed in the response. """ request = self.rf.post("/some_url/", self.breakfast_data) if iscoroutinefunction(view): response = async_to_sync(view)(request) else: response = view(request) if check_for_vars: # All variables are shown. self.assertContains(response, "cooked_eggs", status_code=500) self.assertContains(response, "scrambled", status_code=500) self.assertContains(response, "sauce", status_code=500) self.assertContains(response, "worcestershire", status_code=500) if check_for_POST_params: for k, v in self.breakfast_data.items(): # All POST parameters are shown. self.assertContains(response, k, status_code=500) self.assertContains(response, v, status_code=500) def verify_safe_response( self, view, check_for_vars=True, check_for_POST_params=True ): """ Asserts that certain sensitive info are not displayed in the response. """ request = self.rf.post("/some_url/", self.breakfast_data) if iscoroutinefunction(view): response = async_to_sync(view)(request) else: response = view(request) if check_for_vars: # Non-sensitive variable's name and value are shown. self.assertContains(response, "cooked_eggs", status_code=500) self.assertContains(response, "scrambled", status_code=500) # Sensitive variable's name is shown but not its value. self.assertContains(response, "sauce", status_code=500) self.assertNotContains(response, "worcestershire", status_code=500) if check_for_POST_params: for k in self.breakfast_data: # All POST parameters' names are shown. self.assertContains(response, k, status_code=500) # Non-sensitive POST parameters' values are shown. self.assertContains(response, "baked-beans-value", status_code=500) self.assertContains(response, "hash-brown-value", status_code=500) # Sensitive POST parameters' values are not shown. self.assertNotContains(response, "sausage-value", status_code=500) self.assertNotContains(response, "bacon-value", status_code=500) def verify_paranoid_response( self, view, check_for_vars=True, check_for_POST_params=True ): """ Asserts that no variables or POST parameters are displayed in the response. """ request = self.rf.post("/some_url/", self.breakfast_data) response = view(request) if check_for_vars: # Show variable names but not their values. self.assertContains(response, "cooked_eggs", status_code=500) self.assertNotContains(response, "scrambled", status_code=500) self.assertContains(response, "sauce", status_code=500) self.assertNotContains(response, "worcestershire", status_code=500) if check_for_POST_params: for k, v in self.breakfast_data.items(): # All POST parameters' names are shown. self.assertContains(response, k, status_code=500) # No POST parameters' values are shown. self.assertNotContains(response, v, status_code=500) def verify_unsafe_email(self, view, check_for_POST_params=True): """ Asserts that potentially sensitive info are displayed in the email report. """ with self.settings(ADMINS=["[email protected]"]): mail.outbox = [] # Empty outbox request = self.rf.post("/some_url/", self.breakfast_data) if iscoroutinefunction(view): async_to_sync(view)(request) else: view(request) self.assertEqual(len(mail.outbox), 1) email = mail.outbox[0] # Frames vars are never shown in plain text email reports. body_plain = str(email.body) self.assertNotIn("cooked_eggs", body_plain) self.assertNotIn("scrambled", body_plain) self.assertNotIn("sauce", body_plain) self.assertNotIn("worcestershire", body_plain) # Frames vars are shown in html email reports. body_html = str(email.alternatives[0].content) self.assertIn("cooked_eggs", body_html) self.assertIn("scrambled", body_html) self.assertIn("sauce", body_html) self.assertIn("worcestershire", body_html) if check_for_POST_params: for k, v in self.breakfast_data.items(): # All POST parameters are shown. self.assertIn(k, body_plain) self.assertIn(v, body_plain) self.assertIn(k, body_html) self.assertIn(v, body_html) def verify_safe_email(self, view, check_for_POST_params=True): """ Asserts that certain sensitive info are not displayed in the email report. """ with self.settings(ADMINS=["[email protected]"]): mail.outbox = [] # Empty outbox request = self.rf.post("/some_url/", self.breakfast_data) if iscoroutinefunction(view): async_to_sync(view)(request) else: view(request) self.assertEqual(len(mail.outbox), 1) email = mail.outbox[0] # Frames vars are never shown in plain text email reports. body_plain = str(email.body) self.assertNotIn("cooked_eggs", body_plain) self.assertNotIn("scrambled", body_plain) self.assertNotIn("sauce", body_plain) self.assertNotIn("worcestershire", body_plain) # Frames vars are shown in html email reports. body_html = str(email.alternatives[0].content) self.assertIn("cooked_eggs", body_html) self.assertIn("scrambled", body_html) self.assertIn("sauce", body_html) self.assertNotIn("worcestershire", body_html) if check_for_POST_params: for k in self.breakfast_data: # All POST parameters' names are shown. self.assertIn(k, body_plain) # Non-sensitive POST parameters' values are shown. self.assertIn("baked-beans-value", body_plain) self.assertIn("hash-brown-value", body_plain) self.assertIn("baked-beans-value", body_html) self.assertIn("hash-brown-value", body_html) # Sensitive POST parameters' values are not shown. self.assertNotIn("sausage-value", body_plain) self.assertNotIn("bacon-value", body_plain) self.assertNotIn("sausage-value", body_html) self.assertNotIn("bacon-value", body_html) def verify_paranoid_email(self, view): """ Asserts that no variables or POST parameters are displayed in the email report. """ with self.settings(ADMINS=["[email protected]"]): mail.outbox = [] # Empty outbox request = self.rf.post("/some_url/", self.breakfast_data) view(request) self.assertEqual(len(mail.outbox), 1) email = mail.outbox[0] # Frames vars are never shown in plain text email reports. body = str(email.body) self.assertNotIn("cooked_eggs", body) self.assertNotIn("scrambled", body) self.assertNotIn("sauce", body) self.assertNotIn("worcestershire", body) for k, v in self.breakfast_data.items(): # All POST parameters' names are shown. self.assertIn(k, body) # No POST parameters' values are shown. self.assertNotIn(v, body) @override_settings(ROOT_URLCONF="view_tests.urls") class ExceptionReporterFilterTests( ExceptionReportTestMixin, LoggingCaptureMixin, SimpleTestCase ): """ Sensitive information can be filtered out of error reports (#14614). """ rf = RequestFactory() sensitive_settings = [ "SECRET_KEY", "SECRET_KEY_FALLBACKS", "PASSWORD", "API_KEY", "SOME_TOKEN", "MY_AUTH", ] def test_non_sensitive_request(self): """ Everything (request info and frame variables) can bee seen in the default error reports for non-sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(non_sensitive_view) self.verify_unsafe_email(non_sensitive_view) with self.settings(DEBUG=False): self.verify_unsafe_response(non_sensitive_view) self.verify_unsafe_email(non_sensitive_view) def test_sensitive_request(self): """ Sensitive POST parameters and frame variables cannot be seen in the default error reports for sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_view) self.verify_unsafe_email(sensitive_view) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_view) self.verify_safe_email(sensitive_view) def test_async_sensitive_request(self): with self.settings(DEBUG=True): self.verify_unsafe_response(async_sensitive_view) self.verify_unsafe_email(async_sensitive_view) with self.settings(DEBUG=False): self.verify_safe_response(async_sensitive_view) self.verify_safe_email(async_sensitive_view) def test_async_sensitive_nested_request(self): with self.settings(DEBUG=True): self.verify_unsafe_response(async_sensitive_view_nested) self.verify_unsafe_email(async_sensitive_view_nested) with self.settings(DEBUG=False): self.verify_safe_response(async_sensitive_view_nested) self.verify_safe_email(async_sensitive_view_nested) def test_paranoid_request(self): """ No POST parameters and frame variables can be seen in the default error reports for "paranoid" requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(paranoid_view) self.verify_unsafe_email(paranoid_view) with self.settings(DEBUG=False): self.verify_paranoid_response(paranoid_view) self.verify_paranoid_email(paranoid_view) def test_multivalue_dict_key_error(self): """ #21098 -- Sensitive POST parameters cannot be seen in the error reports for if request.POST['nonexistent_key'] throws an error. """ with self.settings(DEBUG=True): self.verify_unsafe_response(multivalue_dict_key_error) self.verify_unsafe_email(multivalue_dict_key_error) with self.settings(DEBUG=False): self.verify_safe_response(multivalue_dict_key_error) self.verify_safe_email(multivalue_dict_key_error) def test_custom_exception_reporter_filter(self): """ It's possible to assign an exception reporter filter to the request to bypass the one set in DEFAULT_EXCEPTION_REPORTER_FILTER. """ with self.settings(DEBUG=True): self.verify_unsafe_response(custom_exception_reporter_filter_view) self.verify_unsafe_email(custom_exception_reporter_filter_view) with self.settings(DEBUG=False): self.verify_unsafe_response(custom_exception_reporter_filter_view) self.verify_unsafe_email(custom_exception_reporter_filter_view) def test_sensitive_method(self): """ The sensitive_variables decorator works with object methods. """ with self.settings(DEBUG=True): self.verify_unsafe_response( sensitive_method_view, check_for_POST_params=False ) self.verify_unsafe_email(sensitive_method_view, check_for_POST_params=False) with self.settings(DEBUG=False): self.verify_safe_response( sensitive_method_view, check_for_POST_params=False ) self.verify_safe_email(sensitive_method_view, check_for_POST_params=False) def test_async_sensitive_method(self): """ The sensitive_variables decorator works with async object methods. """ with self.settings(DEBUG=True): self.verify_unsafe_response( async_sensitive_method_view, check_for_POST_params=False ) self.verify_unsafe_email( async_sensitive_method_view, check_for_POST_params=False ) with self.settings(DEBUG=False): self.verify_safe_response( async_sensitive_method_view, check_for_POST_params=False ) self.verify_safe_email( async_sensitive_method_view, check_for_POST_params=False ) def test_async_sensitive_method_nested(self): """ The sensitive_variables decorator works with async object methods. """ with self.settings(DEBUG=True): self.verify_unsafe_response( async_sensitive_method_view_nested, check_for_POST_params=False ) self.verify_unsafe_email( async_sensitive_method_view_nested, check_for_POST_params=False ) with self.settings(DEBUG=False): self.verify_safe_response( async_sensitive_method_view_nested, check_for_POST_params=False ) self.verify_safe_email( async_sensitive_method_view_nested, check_for_POST_params=False ) def test_sensitive_function_arguments(self): """ Sensitive variables don't leak in the sensitive_variables decorator's frame, when those variables are passed as arguments to the decorated function. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_args_function_caller) self.verify_unsafe_email(sensitive_args_function_caller) with self.settings(DEBUG=False): self.verify_safe_response( sensitive_args_function_caller, check_for_POST_params=False ) self.verify_safe_email( sensitive_args_function_caller, check_for_POST_params=False ) def test_sensitive_function_keyword_arguments(self): """ Sensitive variables don't leak in the sensitive_variables decorator's frame, when those variables are passed as keyword arguments to the decorated function. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_kwargs_function_caller) self.verify_unsafe_email(sensitive_kwargs_function_caller) with self.settings(DEBUG=False): self.verify_safe_response( sensitive_kwargs_function_caller, check_for_POST_params=False ) self.verify_safe_email( sensitive_kwargs_function_caller, check_for_POST_params=False ) def test_callable_settings(self): """ Callable settings should not be evaluated in the debug page (#21345). """ def callable_setting(): return "This should not be displayed" with self.settings(DEBUG=True, FOOBAR=callable_setting): response = self.client.get("/raises500/") self.assertNotContains( response, "This should not be displayed", status_code=500 ) def test_callable_settings_forbidding_to_set_attributes(self): """ Callable settings which forbid to set attributes should not break the debug page (#23070). """ class CallableSettingWithSlots: __slots__ = [] def __call__(self): return "This should not be displayed" with self.settings(DEBUG=True, WITH_SLOTS=CallableSettingWithSlots()): response = self.client.get("/raises500/") self.assertNotContains( response, "This should not be displayed", status_code=500 ) def test_dict_setting_with_non_str_key(self): """ A dict setting containing a non-string key should not break the debug page (#12744). """ with self.settings(DEBUG=True, FOOBAR={42: None}): response = self.client.get("/raises500/") self.assertContains(response, "FOOBAR", status_code=500) def test_sensitive_settings(self): """ The debug page should not show some sensitive settings (password, secret key, ...). """ for setting in self.sensitive_settings: with self.subTest(setting=setting): with self.settings(DEBUG=True, **{setting: "should not be displayed"}): response = self.client.get("/raises500/") self.assertNotContains( response, "should not be displayed", status_code=500 ) def test_settings_with_sensitive_keys(self): """ The debug page should filter out some sensitive information found in dict settings. """ for setting in self.sensitive_settings: FOOBAR = { setting: "should not be displayed", "recursive": {setting: "should not be displayed"}, } with self.subTest(setting=setting): with self.settings(DEBUG=True, FOOBAR=FOOBAR): response = self.client.get("/raises500/") self.assertNotContains( response, "should not be displayed", status_code=500 ) def test_cleanse_setting_basic(self): reporter_filter = SafeExceptionReporterFilter() self.assertEqual(reporter_filter.cleanse_setting("TEST", "TEST"), "TEST") self.assertEqual( reporter_filter.cleanse_setting("PASSWORD", "super_secret"), reporter_filter.cleansed_substitute, ) def test_cleanse_setting_ignore_case(self): reporter_filter = SafeExceptionReporterFilter() self.assertEqual( reporter_filter.cleanse_setting("password", "super_secret"), reporter_filter.cleansed_substitute, ) def test_cleanse_setting_recurses_in_dictionary(self): reporter_filter = SafeExceptionReporterFilter() initial = {"login": "cooper", "password": "secret"} self.assertEqual( reporter_filter.cleanse_setting("SETTING_NAME", initial), {"login": "cooper", "password": reporter_filter.cleansed_substitute}, ) def test_cleanse_setting_recurses_in_dictionary_with_non_string_key(self): reporter_filter = SafeExceptionReporterFilter() initial = {("localhost", 8000): {"login": "cooper", "password": "secret"}} self.assertEqual( reporter_filter.cleanse_setting("SETTING_NAME", initial), { ("localhost", 8000): { "login": "cooper", "password": reporter_filter.cleansed_substitute, }, }, ) def test_cleanse_setting_recurses_in_list_tuples(self): reporter_filter = SafeExceptionReporterFilter() initial = [ { "login": "cooper", "password": "secret", "apps": ( {"name": "app1", "api_key": "a06b-c462cffae87a"}, {"name": "app2", "api_key": "a9f4-f152e97ad808"}, ), "tokens": ["98b37c57-ec62-4e39", "8690ef7d-8004-4916"], }, {"SECRET_KEY": "c4d77c62-6196-4f17-a06b-c462cffae87a"}, ] cleansed = [ { "login": "cooper", "password": reporter_filter.cleansed_substitute, "apps": ( {"name": "app1", "api_key": reporter_filter.cleansed_substitute}, {"name": "app2", "api_key": reporter_filter.cleansed_substitute}, ), "tokens": reporter_filter.cleansed_substitute, }, {"SECRET_KEY": reporter_filter.cleansed_substitute}, ] self.assertEqual( reporter_filter.cleanse_setting("SETTING_NAME", initial), cleansed, ) self.assertEqual( reporter_filter.cleanse_setting("SETTING_NAME", tuple(initial)), tuple(cleansed), ) def test_request_meta_filtering(self): headers = { "API_URL": "super secret", "A_SIGNATURE_VALUE": "super secret", "MY_KEY": "super secret", "PASSWORD": "super secret", "SECRET_VALUE": "super secret", "SOME_TOKEN": "super secret", "THE_AUTH": "super secret", } request = self.rf.get("/", headers=headers) reporter_filter = SafeExceptionReporterFilter() cleansed_headers = reporter_filter.get_safe_request_meta(request) for header in headers: with self.subTest(header=header): self.assertEqual( cleansed_headers[f"HTTP_{header}"], reporter_filter.cleansed_substitute, ) self.assertEqual( cleansed_headers["HTTP_COOKIE"], reporter_filter.cleansed_substitute, ) def test_exception_report_uses_meta_filtering(self): response = self.client.get( "/raises500/", headers={"secret-header": "super_secret"} ) self.assertNotIn(b"super_secret", response.content) response = self.client.get( "/raises500/", headers={"secret-header": "super_secret", "accept": "application/json"}, ) self.assertNotIn(b"super_secret", response.content) @override_settings(SESSION_COOKIE_NAME="djangosession") def test_cleanse_session_cookie_value(self): self.client.cookies.load({"djangosession": "should not be displayed"}) response = self.client.get("/raises500/") self.assertNotContains(response, "should not be displayed", status_code=500) class CustomExceptionReporterFilter(SafeExceptionReporterFilter): cleansed_substitute = "XXXXXXXXXXXXXXXXXXXX" hidden_settings = _lazy_re_compile("PASS|DATABASE", flags=re.I) @override_settings( ROOT_URLCONF="view_tests.urls", DEFAULT_EXCEPTION_REPORTER_FILTER="%s.CustomExceptionReporterFilter" % __name__, ) class CustomExceptionReporterFilterTests(SimpleTestCase): def setUp(self): get_default_exception_reporter_filter.cache_clear() self.addCleanup(get_default_exception_reporter_filter.cache_clear) def test_setting_allows_custom_subclass(self): self.assertIsInstance( get_default_exception_reporter_filter(), CustomExceptionReporterFilter, ) def test_cleansed_substitute_override(self): reporter_filter = get_default_exception_reporter_filter() self.assertEqual( reporter_filter.cleanse_setting("password", "super_secret"), reporter_filter.cleansed_substitute, ) def test_hidden_settings_override(self): reporter_filter = get_default_exception_reporter_filter() self.assertEqual( reporter_filter.cleanse_setting("database_url", "super_secret"), reporter_filter.cleansed_substitute, ) class NonHTMLResponseExceptionReporterFilter( ExceptionReportTestMixin, LoggingCaptureMixin, SimpleTestCase ): """ Sensitive information can be filtered out of error reports. The plain text 500 debug-only error page is served when it has been detected the request doesn't accept HTML content. Don't check for (non)existence of frames vars in the traceback information section of the response content because they're not included in these error pages. Refs #14614. """ rf = RequestFactory(headers={"accept": "application/json"}) def test_non_sensitive_request(self): """ Request info can bee seen in the default error reports for non-sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(non_sensitive_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_unsafe_response(non_sensitive_view, check_for_vars=False) def test_sensitive_request(self): """ Sensitive POST parameters cannot be seen in the default error reports for sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_view, check_for_vars=False) def test_async_sensitive_request(self): """ Sensitive POST parameters cannot be seen in the default error reports for sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(async_sensitive_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_safe_response(async_sensitive_view, check_for_vars=False) def test_async_sensitive_request_nested(self): """ Sensitive POST parameters cannot be seen in the default error reports for sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response( async_sensitive_view_nested, check_for_vars=False ) with self.settings(DEBUG=False): self.verify_safe_response(async_sensitive_view_nested, check_for_vars=False) def test_paranoid_request(self): """ No POST parameters can be seen in the default error reports for "paranoid" requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(paranoid_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_paranoid_response(paranoid_view, check_for_vars=False) def test_custom_exception_reporter_filter(self): """ It's possible to assign an exception reporter filter to the request to bypass the one set in DEFAULT_EXCEPTION_REPORTER_FILTER. """ with self.settings(DEBUG=True): self.verify_unsafe_response( custom_exception_reporter_filter_view, check_for_vars=False ) with self.settings(DEBUG=False): self.verify_unsafe_response( custom_exception_reporter_filter_view, check_for_vars=False ) @override_settings(DEBUG=True, ROOT_URLCONF="view_tests.urls") def test_non_html_response_encoding(self): response = self.client.get( "/raises500/", headers={"accept": "application/json"} ) self.assertEqual(response.headers["Content-Type"], "text/plain; charset=utf-8") class DecoratorsTests(SimpleTestCase): def test_sensitive_variables_not_called(self): msg = ( "sensitive_variables() must be called to use it as a decorator, " "e.g., use @sensitive_variables(), not @sensitive_variables." ) with self.assertRaisesMessage(TypeError, msg): @sensitive_variables def test_func(password): pass def test_sensitive_post_parameters_not_called(self): msg = ( "sensitive_post_parameters() must be called to use it as a " "decorator, e.g., use @sensitive_post_parameters(), not " "@sensitive_post_parameters." ) with self.assertRaisesMessage(TypeError, msg): @sensitive_post_parameters def test_func(request): return index_page(request) def test_sensitive_post_parameters_http_request(self): class MyClass: @sensitive_post_parameters() def a_view(self, request): return HttpResponse() msg = ( "sensitive_post_parameters didn't receive an HttpRequest object. " "If you are decorating a classmethod, make sure to use " "@method_decorator." ) with self.assertRaisesMessage(TypeError, msg): MyClass().a_view(HttpRequest())
django
python
from django.conf.urls.i18n import i18n_patterns from django.urls import path from django.utils.translation import gettext_lazy as _ urlpatterns = i18n_patterns( path(_("translated/"), lambda x: x, name="i18n_prefixed"), )
import gettext import json from os import path from unittest import mock from django.conf import settings from django.test import ( RequestFactory, SimpleTestCase, TestCase, modify_settings, override_settings, ) from django.test.selenium import SeleniumTestCase from django.urls import reverse from django.utils.translation import get_language, override from django.views.i18n import JavaScriptCatalog, get_formats from ..urls import locale_dir @override_settings(ROOT_URLCONF="view_tests.urls") class SetLanguageTests(TestCase): """Test the django.views.i18n.set_language view.""" def _get_inactive_language_code(self): """Return language code for a language which is not activated.""" current_language = get_language() return [code for code, name in settings.LANGUAGES if code != current_language][ 0 ] def test_setlang(self): """ The set_language view can be used to change the session language. The user is redirected to the 'next' argument if provided. """ lang_code = self._get_inactive_language_code() post_data = {"language": lang_code, "next": "/"} response = self.client.post( "/i18n/setlang/", post_data, headers={"referer": "/i_should_not_be_used/"} ) self.assertRedirects(response, "/") # The language is set in a cookie. language_cookie = self.client.cookies[settings.LANGUAGE_COOKIE_NAME] self.assertEqual(language_cookie.value, lang_code) self.assertEqual(language_cookie["domain"], "") self.assertEqual(language_cookie["path"], "/") self.assertEqual(language_cookie["max-age"], "") self.assertEqual(language_cookie["httponly"], "") self.assertEqual(language_cookie["samesite"], "") self.assertEqual(language_cookie["secure"], "") def test_setlang_unsafe_next(self): """ The set_language view only redirects to the 'next' argument if it is "safe". """ lang_code = self._get_inactive_language_code() post_data = {"language": lang_code, "next": "//unsafe/redirection/"} response = self.client.post("/i18n/setlang/", data=post_data) self.assertEqual(response.url, "/") self.assertEqual( self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code ) def test_setlang_http_next(self): """ The set_language view only redirects to the 'next' argument if it is "safe" and its scheme is HTTPS if the request was sent over HTTPS. """ lang_code = self._get_inactive_language_code() non_https_next_url = "http://testserver/redirection/" post_data = {"language": lang_code, "next": non_https_next_url} # Insecure URL in POST data. response = self.client.post("/i18n/setlang/", data=post_data, secure=True) self.assertEqual(response.url, "/") self.assertEqual( self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code ) # Insecure URL in HTTP referer. response = self.client.post( "/i18n/setlang/", secure=True, headers={"referer": non_https_next_url} ) self.assertEqual(response.url, "/") self.assertEqual( self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code ) def test_setlang_redirect_to_referer(self): """ The set_language view redirects to the URL in the referer header when there isn't a "next" parameter. """ lang_code = self._get_inactive_language_code() post_data = {"language": lang_code} response = self.client.post( "/i18n/setlang/", post_data, headers={"referer": "/i18n/"} ) self.assertRedirects(response, "/i18n/", fetch_redirect_response=False) self.assertEqual( self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code ) def test_setlang_default_redirect(self): """ The set_language view redirects to '/' when there isn't a referer or "next" parameter. """ lang_code = self._get_inactive_language_code() post_data = {"language": lang_code} response = self.client.post("/i18n/setlang/", post_data) self.assertRedirects(response, "/") self.assertEqual( self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code ) def test_setlang_performs_redirect_for_ajax_if_explicitly_requested(self): """ The set_language view redirects to the "next" parameter for requests not accepting HTML response content. """ lang_code = self._get_inactive_language_code() post_data = {"language": lang_code, "next": "/"} response = self.client.post( "/i18n/setlang/", post_data, headers={"accept": "application/json"} ) self.assertRedirects(response, "/") self.assertEqual( self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code ) def test_setlang_doesnt_perform_a_redirect_to_referer_for_ajax(self): """ The set_language view doesn't redirect to the HTTP referer header if the request doesn't accept HTML response content. """ lang_code = self._get_inactive_language_code() post_data = {"language": lang_code} headers = {"HTTP_REFERER": "/", "HTTP_ACCEPT": "application/json"} response = self.client.post("/i18n/setlang/", post_data, **headers) self.assertEqual(response.status_code, 204) self.assertEqual( self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code ) def test_setlang_doesnt_perform_a_default_redirect_for_ajax(self): """ The set_language view returns 204 by default for requests not accepting HTML response content. """ lang_code = self._get_inactive_language_code() post_data = {"language": lang_code} response = self.client.post( "/i18n/setlang/", post_data, headers={"accept": "application/json"} ) self.assertEqual(response.status_code, 204) self.assertEqual( self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code ) def test_setlang_unsafe_next_for_ajax(self): """ The fallback to root URL for the set_language view works for requests not accepting HTML response content. """ lang_code = self._get_inactive_language_code() post_data = {"language": lang_code, "next": "//unsafe/redirection/"} response = self.client.post( "/i18n/setlang/", post_data, headers={"accept": "application/json"} ) self.assertEqual(response.url, "/") self.assertEqual( self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code ) def test_setlang_reversal(self): self.assertEqual(reverse("set_language"), "/i18n/setlang/") def test_setlang_cookie(self): # we force saving language to a cookie rather than a session # by excluding session middleware and those which do require it test_settings = { "MIDDLEWARE": ["django.middleware.common.CommonMiddleware"], "LANGUAGE_COOKIE_NAME": "mylanguage", "LANGUAGE_COOKIE_AGE": 3600 * 7 * 2, "LANGUAGE_COOKIE_DOMAIN": ".example.com", "LANGUAGE_COOKIE_PATH": "/test/", "LANGUAGE_COOKIE_HTTPONLY": True, "LANGUAGE_COOKIE_SAMESITE": "Strict", "LANGUAGE_COOKIE_SECURE": True, } with self.settings(**test_settings): post_data = {"language": "pl", "next": "/views/"} response = self.client.post("/i18n/setlang/", data=post_data) language_cookie = response.cookies.get("mylanguage") self.assertEqual(language_cookie.value, "pl") self.assertEqual(language_cookie["domain"], ".example.com") self.assertEqual(language_cookie["path"], "/test/") self.assertEqual(language_cookie["max-age"], 3600 * 7 * 2) self.assertIs(language_cookie["httponly"], True) self.assertEqual(language_cookie["samesite"], "Strict") self.assertIs(language_cookie["secure"], True) def test_setlang_decodes_http_referer_url(self): """ The set_language view decodes the HTTP_REFERER URL and preserves an encoded query string. """ # The URL & view must exist for this to work as a regression test. self.assertEqual( reverse("with_parameter", kwargs={"parameter": "x"}), "/test-setlang/x/" ) lang_code = self._get_inactive_language_code() # %C3%A4 decodes to ä, %26 to &. encoded_url = "/test-setlang/%C3%A4/?foo=bar&baz=alpha%26omega" response = self.client.post( "/i18n/setlang/", {"language": lang_code}, headers={"referer": encoded_url} ) self.assertRedirects(response, encoded_url, fetch_redirect_response=False) self.assertEqual( self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code ) @modify_settings( MIDDLEWARE={ "append": "django.middleware.locale.LocaleMiddleware", } ) def test_lang_from_translated_i18n_pattern(self): response = self.client.post( "/i18n/setlang/", data={"language": "nl"}, follow=True, headers={"referer": "/en/translated/"}, ) self.assertEqual(self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, "nl") self.assertRedirects(response, "/nl/vertaald/") # And reverse response = self.client.post( "/i18n/setlang/", data={"language": "en"}, follow=True, headers={"referer": "/nl/vertaald/"}, ) self.assertRedirects(response, "/en/translated/") @override_settings(ROOT_URLCONF="view_tests.urls") class I18NViewTests(SimpleTestCase): """Test django.views.i18n views other than set_language.""" @override_settings(LANGUAGE_CODE="de") def test_get_formats(self): formats = get_formats() # Test 3 possible types in get_formats: integer, string, and list. self.assertEqual(formats["FIRST_DAY_OF_WEEK"], 1) self.assertEqual(formats["DECIMAL_SEPARATOR"], ",") self.assertEqual( formats["TIME_INPUT_FORMATS"], ["%H:%M:%S", "%H:%M:%S.%f", "%H:%M"] ) def test_jsi18n(self): """The javascript_catalog can be deployed with language settings""" for lang_code in ["es", "fr", "ru"]: with override(lang_code): catalog = gettext.translation("djangojs", locale_dir, [lang_code]) trans_txt = catalog.gettext("this is to be translated") response = self.client.get("/jsi18n/") self.assertEqual( response.headers["Content-Type"], 'text/javascript; charset="utf-8"' ) # response content must include a line like: # "this is to be translated": <value of trans_txt Python # variable> json.dumps() is used to be able to check Unicode # strings. self.assertContains(response, json.dumps(trans_txt), 1) if lang_code == "fr": # Message with context (msgctxt) self.assertContains(response, '"month name\\u0004May": "mai"', 1) @override_settings(USE_I18N=False) def test_jsi18n_USE_I18N_False(self): response = self.client.get("/jsi18n/") # default plural function self.assertContains( response, "django.pluralidx = function(count) { return (count == 1) ? 0 : 1; };", ) self.assertNotContains(response, "var newcatalog =") def test_jsoni18n(self): """ The json_catalog returns the language catalog and settings as JSON. """ with override("de"): response = self.client.get("/jsoni18n/") data = json.loads(response.text) self.assertIn("catalog", data) self.assertIn("formats", data) self.assertEqual( data["formats"]["TIME_INPUT_FORMATS"], ["%H:%M:%S", "%H:%M:%S.%f", "%H:%M"], ) self.assertEqual(data["formats"]["FIRST_DAY_OF_WEEK"], 1) self.assertIn("plural", data) self.assertEqual(data["catalog"]["month name\x04May"], "Mai") self.assertIn("DATETIME_FORMAT", data["formats"]) self.assertEqual(data["plural"], "(n != 1)") def test_jsi18n_with_missing_en_files(self): """ The javascript_catalog shouldn't load the fallback language in the case that the current selected language is actually the one translated from, and hence missing translation files completely. This happens easily when you're translating from English to other languages and you've set settings.LANGUAGE_CODE to some other language than English. """ with self.settings(LANGUAGE_CODE="es"), override("en-us"): response = self.client.get("/jsi18n/") self.assertNotContains(response, "esto tiene que ser traducido") def test_jsoni18n_with_missing_en_files(self): """ Same as above for the json_catalog view. Here we also check for the expected JSON format. """ with self.settings(LANGUAGE_CODE="es"), override("en-us"): response = self.client.get("/jsoni18n/") data = json.loads(response.text) self.assertIn("catalog", data) self.assertIn("formats", data) self.assertIn("plural", data) self.assertEqual(data["catalog"], {}) self.assertIn("DATETIME_FORMAT", data["formats"]) self.assertIsNone(data["plural"]) def test_jsi18n_fallback_language(self): """ Let's make sure that the fallback language is still working properly in cases where the selected language cannot be found. """ with self.settings(LANGUAGE_CODE="fr"), override("fi"): response = self.client.get("/jsi18n/") self.assertContains(response, "il faut le traduire") self.assertNotContains(response, "Untranslated string") def test_jsi18n_fallback_language_with_custom_locale_dir(self): """ The fallback language works when there are several levels of fallback translation catalogs. """ locale_paths = [ path.join( path.dirname(path.dirname(path.abspath(__file__))), "custom_locale_path", ), ] with self.settings(LOCALE_PATHS=locale_paths), override("es_MX"): response = self.client.get("/jsi18n/") self.assertContains( response, "custom_locale_path: esto tiene que ser traducido" ) response = self.client.get("/jsi18n_no_packages/") self.assertContains( response, "custom_locale_path: esto tiene que ser traducido" ) def test_i18n_fallback_language_plural(self): """ The fallback to a language with less plural forms maintains the real language's number of plural forms and correct translations. """ with self.settings(LANGUAGE_CODE="pt"), override("ru"): response = self.client.get("/jsi18n/") self.assertEqual( response.context["catalog"]["{count} plural3"], ["{count} plural3 p3", "{count} plural3 p3s", "{count} plural3 p3t"], ) self.assertEqual( response.context["catalog"]["{count} plural2"], ["{count} plural2", "{count} plural2s", ""], ) with self.settings(LANGUAGE_CODE="ru"), override("pt"): response = self.client.get("/jsi18n/") self.assertEqual( response.context["catalog"]["{count} plural3"], ["{count} plural3", "{count} plural3s"], ) self.assertEqual( response.context["catalog"]["{count} plural2"], ["{count} plural2", "{count} plural2s"], ) def test_i18n_english_variant(self): with override("en-gb"): response = self.client.get("/jsi18n/") self.assertIn( '"this color is to be translated": "this colour is to be translated"', response.context["catalog_str"], ) def test_i18n_language_non_english_default(self): """ Check if the JavaScript i18n view returns an empty language catalog if the default language is non-English, the selected language is English and there is not 'en' translation available. See #13388, #3594 and #13726 for more details. """ with self.settings(LANGUAGE_CODE="fr"), override("en-us"): response = self.client.get("/jsi18n/") self.assertNotContains(response, "Choisir une heure") @modify_settings(INSTALLED_APPS={"append": "view_tests.app0"}) def test_non_english_default_english_userpref(self): """ Same as above with the difference that there IS an 'en' translation available. The JavaScript i18n view must return a NON empty language catalog with the proper English translations. See #13726 for more details. """ with self.settings(LANGUAGE_CODE="fr"), override("en-us"): response = self.client.get("/jsi18n_english_translation/") self.assertContains(response, "this app0 string is to be translated") def test_i18n_language_non_english_fallback(self): """ Makes sure that the fallback language is still working properly in cases where the selected language cannot be found. """ with self.settings(LANGUAGE_CODE="fr"), override("none"): response = self.client.get("/jsi18n/") self.assertContains(response, "Choisir une heure") def test_escaping(self): # Force a language via GET otherwise the gettext functions are a noop! response = self.client.get("/jsi18n_admin/?language=de") self.assertContains(response, "\\x04") @modify_settings(INSTALLED_APPS={"append": ["view_tests.app5"]}) def test_non_BMP_char(self): """ Non-BMP characters should not break the javascript_catalog (#21725). """ with self.settings(LANGUAGE_CODE="en-us"), override("fr"): response = self.client.get("/jsi18n/app5/") self.assertContains(response, "emoji") self.assertContains(response, "\\ud83d\\udca9") @modify_settings(INSTALLED_APPS={"append": ["view_tests.app1", "view_tests.app2"]}) def test_i18n_language_english_default(self): """ Check if the JavaScript i18n view returns a complete language catalog if the default language is en-us, the selected language has a translation available and a catalog composed by djangojs domain translations of multiple Python packages is requested. See #13388, #3594 and #13514 for more details. """ base_trans_string = ( "il faut traduire cette cha\\u00eene de caract\\u00e8res de " ) app1_trans_string = base_trans_string + "app1" app2_trans_string = base_trans_string + "app2" with self.settings(LANGUAGE_CODE="en-us"), override("fr"): response = self.client.get("/jsi18n_multi_packages1/") self.assertContains(response, app1_trans_string) self.assertContains(response, app2_trans_string) response = self.client.get("/jsi18n/app1/") self.assertContains(response, app1_trans_string) self.assertNotContains(response, app2_trans_string) response = self.client.get("/jsi18n/app2/") self.assertNotContains(response, app1_trans_string) self.assertContains(response, app2_trans_string) @modify_settings(INSTALLED_APPS={"append": ["view_tests.app3", "view_tests.app4"]}) def test_i18n_different_non_english_languages(self): """ Similar to above but with neither default or requested language being English. """ with self.settings(LANGUAGE_CODE="fr"), override("es-ar"): response = self.client.get("/jsi18n_multi_packages2/") self.assertContains(response, "este texto de app3 debe ser traducido") def test_i18n_with_locale_paths(self): extended_locale_paths = settings.LOCALE_PATHS + [ path.join( path.dirname(path.dirname(path.abspath(__file__))), "app3", "locale", ), ] with self.settings(LANGUAGE_CODE="es-ar", LOCALE_PATHS=extended_locale_paths): with override("es-ar"): response = self.client.get("/jsi18n/") self.assertContains(response, "este texto de app3 debe ser traducido") def test_i18n_unknown_package_error(self): view = JavaScriptCatalog.as_view() request = RequestFactory().get("/") msg = "Invalid package(s) provided to JavaScriptCatalog: unknown_package" with self.assertRaisesMessage(ValueError, msg): view(request, packages="unknown_package") msg += ",unknown_package2" with self.assertRaisesMessage(ValueError, msg): view(request, packages="unknown_package+unknown_package2") def test_template_encoding(self): """ The template is loaded directly, not via a template loader, and should be opened as utf-8 charset as is the default specified on template engines. """ from django.views.i18n import Path view = JavaScriptCatalog.as_view() request = RequestFactory().get("/") with mock.patch.object(Path, "open") as m: view(request) m.assert_called_once_with(encoding="utf-8") @override_settings(ROOT_URLCONF="view_tests.urls") class I18nSeleniumTests(SeleniumTestCase): # The test cases use fixtures & translations from these apps. available_apps = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "view_tests", ] @override_settings(LANGUAGE_CODE="de") def test_javascript_gettext(self): from selenium.webdriver.common.by import By self.selenium.get(self.live_server_url + "/jsi18n_template/") elem = self.selenium.find_element(By.ID, "gettext") self.assertEqual(elem.text, "Entfernen") elem = self.selenium.find_element(By.ID, "ngettext_sing") self.assertEqual(elem.text, "1 Element") elem = self.selenium.find_element(By.ID, "ngettext_plur") self.assertEqual(elem.text, "455 Elemente") elem = self.selenium.find_element(By.ID, "ngettext_onnonplural") self.assertEqual(elem.text, "Bild") elem = self.selenium.find_element(By.ID, "pgettext") self.assertEqual(elem.text, "Kann") elem = self.selenium.find_element(By.ID, "npgettext_sing") self.assertEqual(elem.text, "1 Resultat") elem = self.selenium.find_element(By.ID, "npgettext_plur") self.assertEqual(elem.text, "455 Resultate") elem = self.selenium.find_element(By.ID, "formats") self.assertEqual( elem.text, "DATE_INPUT_FORMATS is an object; DECIMAL_SEPARATOR is a string; " "FIRST_DAY_OF_WEEK is a number;", ) @modify_settings(INSTALLED_APPS={"append": ["view_tests.app1", "view_tests.app2"]}) @override_settings(LANGUAGE_CODE="fr") def test_multiple_catalogs(self): from selenium.webdriver.common.by import By self.selenium.get(self.live_server_url + "/jsi18n_multi_catalogs/") elem = self.selenium.find_element(By.ID, "app1string") self.assertEqual( elem.text, "il faut traduire cette chaîne de caractères de app1" ) elem = self.selenium.find_element(By.ID, "app2string") self.assertEqual( elem.text, "il faut traduire cette chaîne de caractères de app2" )
django
python
from django.contrib.staticfiles.apps import StaticFilesConfig class IgnorePatternsAppConfig(StaticFilesConfig): ignore_patterns = ["*.css", "*/vendor/*.js"]
import mimetypes import unittest from os import path from unittest import mock from urllib.parse import quote from django.conf.urls.static import static from django.core.exceptions import ImproperlyConfigured from django.http import FileResponse, HttpResponseNotModified from django.test import SimpleTestCase, override_settings from django.utils.http import http_date from django.views.static import directory_index, was_modified_since from .. import urls from ..urls import media_dir @override_settings(DEBUG=True, ROOT_URLCONF="view_tests.urls") class StaticTests(SimpleTestCase): """Tests django views in django/views/static.py""" prefix = "site_media" def test_serve(self): "The static view can serve static media" media_files = ["file.txt", "file.txt.gz", "%2F.txt"] for filename in media_files: response = self.client.get("/%s/%s" % (self.prefix, quote(filename))) response_content = b"".join(response) file_path = path.join(media_dir, filename) with open(file_path, "rb") as fp: self.assertEqual(fp.read(), response_content) self.assertEqual( len(response_content), int(response.headers["Content-Length"]) ) self.assertEqual( mimetypes.guess_type(file_path)[1], response.get("Content-Encoding", None), ) def test_chunked(self): """ The static view should stream files in chunks to avoid large memory usage """ response = self.client.get("/%s/%s" % (self.prefix, "long-line.txt")) response_iterator = iter(response) first_chunk = next(response_iterator) self.assertEqual(len(first_chunk), FileResponse.block_size) second_chunk = next(response_iterator) response.close() # strip() to prevent OS line endings from causing differences self.assertEqual(len(second_chunk.strip()), 1449) def test_unknown_mime_type(self): response = self.client.get("/%s/file.unknown" % self.prefix) self.assertEqual("application/octet-stream", response.headers["Content-Type"]) response.close() def test_copes_with_empty_path_component(self): file_name = "file.txt" response = self.client.get("/%s//%s" % (self.prefix, file_name)) response_content = b"".join(response) with open(path.join(media_dir, file_name), "rb") as fp: self.assertEqual(fp.read(), response_content) def test_is_modified_since(self): file_name = "file.txt" response = self.client.get( "/%s/%s" % (self.prefix, file_name), headers={"if-modified-since": "Thu, 1 Jan 1970 00:00:00 GMT"}, ) response_content = b"".join(response) with open(path.join(media_dir, file_name), "rb") as fp: self.assertEqual(fp.read(), response_content) def test_not_modified_since(self): file_name = "file.txt" response = self.client.get( "/%s/%s" % (self.prefix, file_name), headers={ # This is 24h before max Unix time. Remember to fix Django and # update this test well before 2038 :) "if-modified-since": "Mon, 18 Jan 2038 05:14:07 GMT" }, ) self.assertIsInstance(response, HttpResponseNotModified) def test_invalid_if_modified_since(self): """Handle bogus If-Modified-Since values gracefully Assume that a file is modified since an invalid timestamp as per RFC 9110 Section 13.1.3. """ file_name = "file.txt" invalid_date = "Mon, 28 May 999999999999 28:25:26 GMT" response = self.client.get( "/%s/%s" % (self.prefix, file_name), headers={"if-modified-since": invalid_date}, ) response_content = b"".join(response) with open(path.join(media_dir, file_name), "rb") as fp: self.assertEqual(fp.read(), response_content) self.assertEqual(len(response_content), int(response.headers["Content-Length"])) def test_invalid_if_modified_since2(self): """Handle even more bogus If-Modified-Since values gracefully Assume that a file is modified since an invalid timestamp as per RFC 9110 Section 13.1.3. """ file_name = "file.txt" invalid_date = ": 1291108438, Wed, 20 Oct 2010 14:05:00 GMT" response = self.client.get( "/%s/%s" % (self.prefix, file_name), headers={"if-modified-since": invalid_date}, ) response_content = b"".join(response) with open(path.join(media_dir, file_name), "rb") as fp: self.assertEqual(fp.read(), response_content) self.assertEqual(len(response_content), int(response.headers["Content-Length"])) def test_404(self): response = self.client.get("/%s/nonexistent_resource" % self.prefix) self.assertEqual(404, response.status_code) def test_index(self): response = self.client.get("/%s/" % self.prefix) self.assertContains(response, "Index of ./") # Directories have a trailing slash. self.assertIn("subdir/", response.context["file_list"]) def test_index_subdir(self): response = self.client.get("/%s/subdir/" % self.prefix) self.assertContains(response, "Index of subdir/") # File with a leading dot (e.g. .hidden) aren't displayed. self.assertEqual(response.context["file_list"], ["visible"]) @override_settings( TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "OPTIONS": { "loaders": [ ( "django.template.loaders.locmem.Loader", { "static/directory_index.html": "Test index", }, ), ], }, } ] ) def test_index_custom_template(self): response = self.client.get("/%s/" % self.prefix) self.assertEqual(response.content, b"Test index") def test_template_encoding(self): """ The template is loaded directly, not via a template loader, and should be opened as utf-8 charset as is the default specified on template engines. """ from django.views.static import Path with mock.patch.object(Path, "open") as m: directory_index(mock.MagicMock(), mock.MagicMock()) m.assert_called_once_with(encoding="utf-8") class StaticHelperTest(StaticTests): """ Test case to make sure the static URL pattern helper works as expected """ def setUp(self): super().setUp() self._old_views_urlpatterns = urls.urlpatterns[:] urls.urlpatterns += static("media/", document_root=media_dir) def tearDown(self): super().tearDown() urls.urlpatterns = self._old_views_urlpatterns def test_prefix(self): self.assertEqual(static("test")[0].pattern.regex.pattern, "^test(?P<path>.*)$") @override_settings(DEBUG=False) def test_debug_off(self): """No URLs are served if DEBUG=False.""" self.assertEqual(static("test"), []) def test_empty_prefix(self): with self.assertRaisesMessage( ImproperlyConfigured, "Empty static prefix not permitted" ): static("") def test_special_prefix(self): """No URLs are served if prefix contains a netloc part.""" self.assertEqual(static("http://example.org"), []) self.assertEqual(static("//example.org"), []) class StaticUtilsTests(unittest.TestCase): def test_was_modified_since_fp(self): """ A floating point mtime does not disturb was_modified_since (#18675). """ mtime = 1343416141.107817 header = http_date(mtime) self.assertFalse(was_modified_since(header, mtime)) def test_was_modified_since_empty_string(self): self.assertTrue(was_modified_since(header="", mtime=1))
django
python
from pathlib import Path import jinja2 from django.conf import settings from django.template import TemplateDoesNotExist, TemplateSyntaxError from django.utils.functional import cached_property from django.utils.module_loading import import_string from .base import BaseEngine from .utils import csrf_input_lazy, csrf_token_lazy class Jinja2(BaseEngine): app_dirname = "jinja2" def __init__(self, params): params = params.copy() options = params.pop("OPTIONS").copy() super().__init__(params) self.context_processors = options.pop("context_processors", []) environment = options.pop("environment", "jinja2.Environment") environment_cls = import_string(environment) if "loader" not in options: options["loader"] = jinja2.FileSystemLoader(self.template_dirs) options.setdefault("autoescape", True) options.setdefault("auto_reload", settings.DEBUG) options.setdefault( "undefined", jinja2.DebugUndefined if settings.DEBUG else jinja2.Undefined ) self.env = environment_cls(**options) def from_string(self, template_code): return Template(self.env.from_string(template_code), self) def get_template(self, template_name): try: return Template(self.env.get_template(template_name), self) except jinja2.TemplateNotFound as exc: raise TemplateDoesNotExist(exc.name, backend=self) from exc except jinja2.TemplateSyntaxError as exc: new = TemplateSyntaxError(exc.args) new.template_debug = get_exception_info(exc) raise new from exc @cached_property def template_context_processors(self): return [import_string(path) for path in self.context_processors] class Template: def __init__(self, template, backend): self.template = template self.backend = backend self.origin = Origin( name=template.filename, template_name=template.name, ) def render(self, context=None, request=None): if context is None: context = {} if request is not None: context["request"] = request context["csrf_input"] = csrf_input_lazy(request) context["csrf_token"] = csrf_token_lazy(request) for context_processor in self.backend.template_context_processors: context.update(context_processor(request)) try: return self.template.render(context) except jinja2.TemplateSyntaxError as exc: new = TemplateSyntaxError(exc.args) new.template_debug = get_exception_info(exc) raise new from exc class Origin: """ A container to hold debug information as described in the template API documentation. """ def __init__(self, name, template_name): self.name = name self.template_name = template_name def get_exception_info(exception): """ Format exception information for display on the debug page using the structure described in the template API documentation. """ context_lines = 10 lineno = exception.lineno source = exception.source if source is None: exception_file = Path(exception.filename) if exception_file.exists(): source = exception_file.read_text() if source is not None: lines = list(enumerate(source.strip().split("\n"), start=1)) during = lines[lineno - 1][1] total = len(lines) top = max(0, lineno - context_lines - 1) bottom = min(total, lineno + context_lines) else: during = "" lines = [] total = top = bottom = 0 return { "name": exception.filename, "message": exception.message, "source_lines": lines[top:bottom], "line": lineno, "before": "", "during": during, "after": "", "total": total, "top": top, "bottom": bottom, }
from pathlib import Path from unittest import mock, skipIf from django.contrib.auth.models import User from django.template import TemplateSyntaxError from django.test import RequestFactory, TestCase from .test_dummy import TemplateStringsTests try: import jinja2 except ImportError: jinja2 = None Jinja2 = None else: from django.template.backends.jinja2 import Jinja2 @skipIf(jinja2 is None, "this test requires jinja2") class Jinja2Tests(TemplateStringsTests): engine_class = Jinja2 backend_name = "jinja2" options = { "keep_trailing_newline": True, "context_processors": [ "django.template.context_processors.static", ], } def test_origin(self): template = self.engine.get_template("template_backends/hello.html") self.assertTrue(template.origin.name.endswith("hello.html")) self.assertEqual(template.origin.template_name, "template_backends/hello.html") def test_origin_from_string(self): template = self.engine.from_string("Hello!\n") self.assertEqual(template.origin.name, "<template>") self.assertIsNone(template.origin.template_name) def test_self_context(self): """ Using 'self' in the context should not throw errors (#24538). """ # self will be overridden to be a TemplateReference, so the self # variable will not come through. Attempting to use one though should # not throw an error. template = self.engine.from_string("hello {{ foo }}!") content = template.render(context={"self": "self", "foo": "world"}) self.assertEqual(content, "hello world!") def test_exception_debug_info_min_context(self): with self.assertRaises(TemplateSyntaxError) as e: self.engine.get_template("template_backends/syntax_error.html") debug = e.exception.template_debug self.assertEqual(debug["after"], "") self.assertEqual(debug["before"], "") self.assertEqual(debug["during"], "{% block %}") self.assertEqual(debug["bottom"], 1) self.assertEqual(debug["top"], 0) self.assertEqual(debug["line"], 1) self.assertEqual(debug["total"], 1) self.assertEqual(len(debug["source_lines"]), 1) self.assertTrue(debug["name"].endswith("syntax_error.html")) self.assertIn("message", debug) def test_exception_debug_info_max_context(self): with self.assertRaises(TemplateSyntaxError) as e: self.engine.get_template("template_backends/syntax_error2.html") debug = e.exception.template_debug self.assertEqual(debug["after"], "") self.assertEqual(debug["before"], "") self.assertEqual(debug["during"], "{% block %}") self.assertEqual(debug["bottom"], 26) self.assertEqual(debug["top"], 5) self.assertEqual(debug["line"], 16) self.assertEqual(debug["total"], 31) self.assertEqual(len(debug["source_lines"]), 21) self.assertTrue(debug["name"].endswith("syntax_error2.html")) self.assertIn("message", debug) def test_context_processors(self): request = RequestFactory().get("/") template = self.engine.from_string("Static URL: {{ STATIC_URL }}") content = template.render(request=request) self.assertEqual(content, "Static URL: /static/") with self.settings(STATIC_URL="/s/"): content = template.render(request=request) self.assertEqual(content, "Static URL: /s/") def test_dirs_pathlib(self): engine = Jinja2( { "DIRS": [Path(__file__).parent / "templates" / "template_backends"], "APP_DIRS": False, "NAME": "jinja2", "OPTIONS": {}, } ) template = engine.get_template("hello.html") self.assertEqual(template.render({"name": "Joe"}), "Hello Joe!") def test_template_render_nested_error(self): template = self.engine.get_template( "template_backends/syntax_error_include.html" ) with self.assertRaises(TemplateSyntaxError) as e: template.render(context={}) debug = e.exception.template_debug self.assertEqual(debug["after"], "") self.assertEqual(debug["before"], "") self.assertEqual(debug["during"], "{% block %}") self.assertEqual(debug["bottom"], 1) self.assertEqual(debug["top"], 0) self.assertEqual(debug["line"], 1) self.assertEqual(debug["total"], 1) self.assertEqual(len(debug["source_lines"]), 1) self.assertTrue(debug["name"].endswith("syntax_error.html")) self.assertIn("message", debug) def test_template_render_error_nonexistent_source(self): template = self.engine.get_template("template_backends/hello.html") with mock.patch( "jinja2.environment.Template.render", side_effect=jinja2.TemplateSyntaxError("", 1, filename="nonexistent.html"), ): with self.assertRaises(TemplateSyntaxError) as e: template.render(context={}) debug = e.exception.template_debug self.assertEqual(debug["after"], "") self.assertEqual(debug["before"], "") self.assertEqual(debug["during"], "") self.assertEqual(debug["bottom"], 0) self.assertEqual(debug["top"], 0) self.assertEqual(debug["line"], 1) self.assertEqual(debug["total"], 0) self.assertEqual(len(debug["source_lines"]), 0) self.assertTrue(debug["name"].endswith("nonexistent.html")) self.assertIn("message", debug) @skipIf(jinja2 is None, "this test requires jinja2") class Jinja2SandboxTests(TestCase): engine_class = Jinja2 backend_name = "jinja2" options = {"environment": "jinja2.sandbox.SandboxedEnvironment"} @classmethod def setUpClass(cls): super().setUpClass() params = { "DIRS": [], "APP_DIRS": True, "NAME": cls.backend_name, "OPTIONS": cls.options, } cls.engine = cls.engine_class(params) def test_set_alters_data(self): template = self.engine.from_string( "{% set test = User.objects.create_superuser(" "username='evil', email='[email protected]', password='xxx') %}" "{{ test }}" ) with self.assertRaises(jinja2.exceptions.SecurityError): template.render(context={"User": User}) self.assertEqual(User.objects.count(), 0)
django
python
""" YAML serializer. Requires PyYaml (https://pyyaml.org/), but that's checked for in __init__. """ import collections import datetime import decimal import yaml from django.core.serializers.base import DeserializationError from django.core.serializers.python import Deserializer as PythonDeserializer from django.core.serializers.python import Serializer as PythonSerializer # Use the C (faster) implementation if possible try: from yaml import CSafeDumper as SafeDumper from yaml import CSafeLoader as SafeLoader except ImportError: from yaml import SafeDumper, SafeLoader class DjangoSafeDumper(SafeDumper): def represent_decimal(self, data): return self.represent_scalar("tag:yaml.org,2002:str", str(data)) def represent_ordered_dict(self, data): return self.represent_mapping("tag:yaml.org,2002:map", data.items()) DjangoSafeDumper.add_representer(decimal.Decimal, DjangoSafeDumper.represent_decimal) DjangoSafeDumper.add_representer( collections.OrderedDict, DjangoSafeDumper.represent_ordered_dict ) # Workaround to represent dictionaries in insertion order. # See https://github.com/yaml/pyyaml/pull/143. DjangoSafeDumper.add_representer(dict, DjangoSafeDumper.represent_ordered_dict) class Serializer(PythonSerializer): """Convert a queryset to YAML.""" internal_use_only = False def _value_from_field(self, obj, field): # A nasty special case: base YAML doesn't support serialization of time # types (as opposed to dates or datetimes, which it does support). # Since we want to use the "safe" serializer for better # interoperability, we need to do something with those pesky times. # Converting 'em to strings isn't perfect, but it's better than a # "!!python/time" type which would halt deserialization under any other # language. value = super()._value_from_field(obj, field) if isinstance(value, datetime.time): value = str(value) return value def end_serialization(self): self.options.setdefault("allow_unicode", True) yaml.dump(self.objects, self.stream, Dumper=DjangoSafeDumper, **self.options) def getvalue(self): # Grandparent super return super(PythonSerializer, self).getvalue() class Deserializer(PythonDeserializer): """Deserialize a stream or string of YAML data.""" def __init__(self, stream_or_string, **options): stream = stream_or_string if isinstance(stream_or_string, bytes): stream = stream_or_string.decode() try: objects = yaml.load(stream, Loader=SafeLoader) except Exception as exc: raise DeserializationError() from exc super().__init__(objects, **options) def _handle_object(self, obj): try: yield from super()._handle_object(obj) except (GeneratorExit, DeserializationError): raise except Exception as exc: raise DeserializationError(f"Error deserializing object: {exc}") from exc
import importlib import unittest from io import StringIO from django.core import management, serializers from django.core.serializers.base import DeserializationError from django.test import SimpleTestCase, TestCase, TransactionTestCase from .models import Author from .tests import SerializersTestBase, SerializersTransactionTestBase try: import yaml HAS_YAML = True except ImportError: HAS_YAML = False YAML_IMPORT_ERROR_MESSAGE = r"No module named yaml" class YamlImportModuleMock: """Provides a wrapped import_module function to simulate yaml ImportError In order to run tests that verify the behavior of the YAML serializer when run on a system that has yaml installed (like the django CI server), mock import_module, so that it raises an ImportError when the yaml serializer is being imported. The importlib.import_module() call is being made in the serializers.register_serializer(). Refs: #12756 """ def __init__(self): self._import_module = importlib.import_module def import_module(self, module_path): if module_path == serializers.BUILTIN_SERIALIZERS["yaml"]: raise ImportError(YAML_IMPORT_ERROR_MESSAGE) return self._import_module(module_path) class NoYamlSerializerTestCase(SimpleTestCase): """Not having pyyaml installed provides a misleading error Refs: #12756 """ @classmethod def setUpClass(cls): """Removes imported yaml and stubs importlib.import_module""" super().setUpClass() cls._import_module_mock = YamlImportModuleMock() importlib.import_module = cls._import_module_mock.import_module # clear out cached serializers to emulate yaml missing serializers._serializers = {} @classmethod def tearDownClass(cls): """Puts yaml back if necessary""" super().tearDownClass() importlib.import_module = cls._import_module_mock._import_module # clear out cached serializers to clean out BadSerializer instances serializers._serializers = {} def test_serializer_pyyaml_error_message(self): """Using yaml serializer without pyyaml raises ImportError""" jane = Author(name="Jane") with self.assertRaises(ImportError): serializers.serialize("yaml", [jane]) def test_deserializer_pyyaml_error_message(self): """Using yaml deserializer without pyyaml raises ImportError""" with self.assertRaises(ImportError): serializers.deserialize("yaml", "") def test_dumpdata_pyyaml_error_message(self): """Calling dumpdata produces an error when yaml package missing""" with self.assertRaisesMessage( management.CommandError, YAML_IMPORT_ERROR_MESSAGE ): management.call_command("dumpdata", format="yaml") @unittest.skipUnless(HAS_YAML, "No yaml library detected") class YamlSerializerTestCase(SerializersTestBase, TestCase): serializer_name = "yaml" pkless_str = """- model: serializers.category pk: null fields: name: Reference - model: serializers.category fields: name: Non-fiction""" mapping_ordering_str = ( """- model: serializers.article pk: %(article_pk)s fields: author: %(author_pk)s headline: Poker has no place on ESPN pub_date: 2006-06-16 11:00:00 categories:""" + ( " [%(first_category_pk)s, %(second_category_pk)s]" if HAS_YAML and yaml.__version__ < "5.1" else "\n - %(first_category_pk)s\n - %(second_category_pk)s" ) + """ meta_data: [] topics: [] """ ) @staticmethod def _validate_output(serial_str): try: yaml.safe_load(StringIO(serial_str)) except Exception: return False else: return True @staticmethod def _get_pk_values(serial_str): ret_list = [] stream = StringIO(serial_str) for obj_dict in yaml.safe_load(stream): ret_list.append(obj_dict["pk"]) return ret_list @staticmethod def _get_field_values(serial_str, field_name): ret_list = [] stream = StringIO(serial_str) for obj_dict in yaml.safe_load(stream): if "fields" in obj_dict and field_name in obj_dict["fields"]: field_value = obj_dict["fields"][field_name] # yaml.safe_load will return non-string objects for some # of the fields we are interested in, this ensures that # everything comes back as a string if isinstance(field_value, str): ret_list.append(field_value) else: ret_list.append(str(field_value)) return ret_list def test_yaml_deserializer_exception(self): with self.assertRaises(DeserializationError): for obj in serializers.deserialize("yaml", "{"): pass @unittest.skipUnless(HAS_YAML, "No yaml library detected") class YamlSerializerTransactionTestCase( SerializersTransactionTestBase, TransactionTestCase ): serializer_name = "yaml" fwd_ref_str = """- model: serializers.article pk: 1 fields: headline: Forward references pose no problem pub_date: 2006-06-16 15:00:00 categories: [1] author: 1 - model: serializers.category pk: 1 fields: name: Reference - model: serializers.author pk: 1 fields: name: Agnes"""
django
python
def special(request): return {"path": request.special_path}
import json import sys from unittest.mock import patch from django.core.exceptions import SuspiciousFileOperation from django.test import SimpleTestCase from django.utils import text from django.utils.functional import lazystr from django.utils.text import format_lazy from django.utils.translation import gettext_lazy, override IS_WIDE_BUILD = len("\U0001f4a9") == 1 class TestUtilsText(SimpleTestCase): def test_get_text_list(self): self.assertEqual(text.get_text_list(["a", "b", "c", "d"]), "a, b, c or d") self.assertEqual(text.get_text_list(["a", "b", "c"], "and"), "a, b and c") self.assertEqual(text.get_text_list(["a", "b"], "and"), "a and b") self.assertEqual(text.get_text_list(["a"]), "a") self.assertEqual(text.get_text_list([]), "") with override("ar"): self.assertEqual(text.get_text_list(["a", "b", "c"]), "a، b أو c") def test_smart_split(self): testdata = [ ('This is "a person" test.', ["This", "is", '"a person"', "test."]), ('This is "a person\'s" test.', ["This", "is", '"a person\'s"', "test."]), ('This is "a person\\"s" test.', ["This", "is", '"a person\\"s"', "test."]), ("\"a 'one", ['"a', "'one"]), ("all friends' tests", ["all", "friends'", "tests"]), ( 'url search_page words="something else"', ["url", "search_page", 'words="something else"'], ), ( "url search_page words='something else'", ["url", "search_page", "words='something else'"], ), ( 'url search_page words "something else"', ["url", "search_page", "words", '"something else"'], ), ( 'url search_page words-"something else"', ["url", "search_page", 'words-"something else"'], ), ("url search_page words=hello", ["url", "search_page", "words=hello"]), ( 'url search_page words="something else', ["url", "search_page", 'words="something', "else"], ), ("cut:','|cut:' '", ["cut:','|cut:' '"]), (lazystr("a b c d"), ["a", "b", "c", "d"]), # Test for #20231 ] for test, expected in testdata: with self.subTest(value=test): self.assertEqual(list(text.smart_split(test)), expected) def test_truncate_chars(self): truncator = text.Truncator("The quick brown fox jumped over the lazy dog.") self.assertEqual( "The quick brown fox jumped over the lazy dog.", truncator.chars(100) ), self.assertEqual("The quick brown fox …", truncator.chars(21)) self.assertEqual("The quick brown fo.....", truncator.chars(23, ".....")) self.assertEqual(".....", truncator.chars(4, ".....")) nfc = text.Truncator("o\xfco\xfco\xfco\xfc") nfd = text.Truncator("ou\u0308ou\u0308ou\u0308ou\u0308") self.assertEqual("oüoüoüoü", nfc.chars(8)) self.assertEqual("oüoüoüoü", nfd.chars(8)) self.assertEqual("oü…", nfc.chars(3)) self.assertEqual("oü…", nfd.chars(3)) # Ensure the final length is calculated correctly when there are # combining characters with no precomposed form, and that combining # characters are not split up. truncator = text.Truncator("-B\u030aB\u030a----8") self.assertEqual("-B\u030a…", truncator.chars(3)) self.assertEqual("-B\u030aB\u030a-…", truncator.chars(5)) self.assertEqual("-B\u030aB\u030a----8", truncator.chars(8)) # Ensure the length of the end text is correctly calculated when it # contains combining characters with no precomposed form. truncator = text.Truncator("-----") self.assertEqual("---B\u030a", truncator.chars(4, "B\u030a")) self.assertEqual("-----", truncator.chars(5, "B\u030a")) # Make a best effort to shorten to the desired length, but requesting # a length shorter than the ellipsis shouldn't break self.assertEqual("...", text.Truncator("asdf").chars(1, truncate="...")) # lazy strings are handled correctly self.assertEqual( text.Truncator(lazystr("The quick brown fox")).chars(10), "The quick…" ) def test_truncate_chars_html(self): truncator = text.Truncator( '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em>' "</strong></p>" ) self.assertEqual( '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em>' "</strong></p>", truncator.chars(80, html=True), ) self.assertEqual( '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em>' "</strong></p>", truncator.chars(46, html=True), ) self.assertEqual( '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog…</em>' "</strong></p>", truncator.chars(45, html=True), ) self.assertEqual( '<p id="par"><strong><em>The quick…</em></strong></p>', truncator.chars(10, html=True), ) self.assertEqual( '<p id="par"><strong><em>…</em></strong></p>', truncator.chars(1, html=True), ) self.assertEqual("", truncator.chars(0, html=True)) self.assertEqual("", truncator.chars(-1, html=True)) self.assertEqual( '<p id="par"><strong><em>The qu....</em></strong></p>', truncator.chars(10, "....", html=True), ) self.assertEqual( '<p id="par"><strong><em>The quick </em></strong></p>', truncator.chars(10, "", html=True), ) truncator = text.Truncator("foo</p>") self.assertEqual("foo</p>", truncator.chars(5, html=True)) @patch("django.utils.text.Truncator.MAX_LENGTH_HTML", 10_000) def test_truncate_chars_html_size_limit(self): max_len = text.Truncator.MAX_LENGTH_HTML bigger_len = text.Truncator.MAX_LENGTH_HTML + 1 valid_html = "<p>Joel is a slug</p>" # 14 chars perf_test_values = [ ("</a" + "\t" * (max_len - 6) + "//>", "</a>"), ("</p" + "\t" * bigger_len + "//>", "</p>"), ("&" * bigger_len, ""), ("_X<<<<<<<<<<<>", "_X&lt;&lt;&lt;&lt;&lt;&lt;&lt;…"), (valid_html * bigger_len, "<p>Joel is a…</p>"), # 10 chars ] for value, expected in perf_test_values: with self.subTest(value=value): truncator = text.Truncator(value) self.assertEqual(expected, truncator.chars(10, html=True)) def test_truncate_chars_html_with_newline_inside_tag(self): truncator = text.Truncator( '<p>The quick <a href="xyz.html"\n id="mylink">brown fox</a> jumped over ' "the lazy dog.</p>" ) self.assertEqual( '<p>The quick <a href="xyz.html"\n id="mylink">brow…</a></p>', truncator.chars(15, html=True), ) self.assertEqual( "<p>Th…</p>", truncator.chars(3, html=True), ) def test_truncate_chars_html_with_void_elements(self): truncator = text.Truncator( "<br/>The <hr />quick brown fox jumped over the lazy dog." ) self.assertEqual("<br/>The <hr />quick brown…", truncator.chars(16, html=True)) truncator = text.Truncator( "<br>The <hr/>quick <em>brown fox</em> jumped over the lazy dog." ) self.assertEqual( "<br>The <hr/>quick <em>brown…</em>", truncator.chars(16, html=True) ) self.assertEqual("<br>The <hr/>q…", truncator.chars(6, html=True)) self.assertEqual("<br>The <hr/>…", truncator.chars(5, html=True)) self.assertEqual("<br>The…", truncator.chars(4, html=True)) self.assertEqual("<br>Th…", truncator.chars(3, html=True)) def test_truncate_chars_html_with_html_entities(self): truncator = text.Truncator( "<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo est&aacute;?</i>" ) self.assertEqual( "<i>Buenos días! ¿Cómo está?</i>", truncator.chars(40, html=True), ) self.assertEqual( "<i>Buenos días…</i>", truncator.chars(12, html=True), ) self.assertEqual( "<i>Buenos días! ¿Cómo está…</i>", truncator.chars(24, html=True), ) truncator = text.Truncator("<p>I &lt;3 python, what about you?</p>") self.assertEqual("<p>I &lt;3 python, wh…</p>", truncator.chars(16, html=True)) def test_truncate_words(self): truncator = text.Truncator("The quick brown fox jumped over the lazy dog.") self.assertEqual( "The quick brown fox jumped over the lazy dog.", truncator.words(10) ) self.assertEqual("The quick brown fox…", truncator.words(4)) self.assertEqual("The quick brown fox[snip]", truncator.words(4, "[snip]")) # lazy strings are handled correctly truncator = text.Truncator( lazystr("The quick brown fox jumped over the lazy dog.") ) self.assertEqual("The quick brown fox…", truncator.words(4)) self.assertEqual("", truncator.words(0)) self.assertEqual("", truncator.words(-1)) def test_truncate_html_words(self): truncator = text.Truncator( '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em>' "</strong></p>" ) self.assertEqual( '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em>' "</strong></p>", truncator.words(10, html=True), ) self.assertEqual( '<p id="par"><strong><em>The quick brown fox…</em></strong></p>', truncator.words(4, html=True), ) self.assertEqual( "", truncator.words(0, html=True), ) self.assertEqual( '<p id="par"><strong><em>The quick brown fox....</em></strong></p>', truncator.words(4, "....", html=True), ) self.assertEqual( '<p id="par"><strong><em>The quick brown fox</em></strong></p>', truncator.words(4, "", html=True), ) truncator = text.Truncator( "<p>The quick \t brown fox jumped over the lazy dog.</p>" ) self.assertEqual( "<p>The quick brown fox…</p>", truncator.words(4, html=True), ) # Test with new line inside tag truncator = text.Truncator( '<p>The quick <a href="xyz.html"\n id="mylink">brown fox</a> jumped over ' "the lazy dog.</p>" ) self.assertEqual( '<p>The quick <a href="xyz.html"\n id="mylink">brown…</a></p>', truncator.words(3, html=True), ) self.assertEqual( "<p>The…</p>", truncator.words(1, html=True), ) # Test self-closing tags truncator = text.Truncator( "<br/>The <hr />quick brown fox jumped over the lazy dog." ) self.assertEqual("<br/>The <hr />quick brown…", truncator.words(3, html=True)) truncator = text.Truncator( "<br>The <hr/>quick <em>brown fox</em> jumped over the lazy dog." ) self.assertEqual( "<br>The <hr/>quick <em>brown…</em>", truncator.words(3, html=True) ) # Test html entities truncator = text.Truncator( "<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo est&aacute;?</i>" ) self.assertEqual( "<i>Buenos días! ¿Cómo…</i>", truncator.words(3, html=True), ) truncator = text.Truncator("<p>I &lt;3 python, what about you?</p>") self.assertEqual("<p>I &lt;3 python,…</p>", truncator.words(3, html=True)) truncator = text.Truncator("foo</p>") self.assertEqual("foo</p>", truncator.words(3, html=True)) # Only open brackets. truncator = text.Truncator("<" * 60_000) self.assertEqual(truncator.words(1, html=True), "&lt;…") # Tags with special chars in attrs. truncator = text.Truncator( """<i style="margin: 5%; font: *;">Hello, my dear lady!</i>""" ) self.assertEqual( """<i style="margin: 5%; font: *;">Hello, my dear…</i>""", truncator.words(3, html=True), ) # Tags with special non-latin chars in attrs. truncator = text.Truncator("""<p data-x="א">Hello, my dear lady!</p>""") self.assertEqual( """<p data-x="א">Hello, my dear…</p>""", truncator.words(3, html=True), ) # Misplaced brackets. truncator = text.Truncator("hello >< world") self.assertEqual(truncator.words(1, html=True), "hello…") self.assertEqual(truncator.words(2, html=True), "hello &gt;…") self.assertEqual(truncator.words(3, html=True), "hello &gt;&lt;…") self.assertEqual(truncator.words(4, html=True), "hello &gt;&lt; world") @patch("django.utils.text.Truncator.MAX_LENGTH_HTML", 10_000) def test_truncate_words_html_size_limit(self): max_len = text.Truncator.MAX_LENGTH_HTML bigger_len = text.Truncator.MAX_LENGTH_HTML + 1 valid_html = "<p>Joel is a slug</p>" # 4 words perf_test_values = [ ("</a" + "\t" * (max_len - 6) + "//>", "</a>"), ("</p" + "\t" * bigger_len + "//>", "</p>"), ("&" * max_len, ""), ("&" * bigger_len, ""), ("_X<<<<<<<<<<<>", "_X&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&gt;"), (valid_html * bigger_len, valid_html * 12 + "<p>Joel is…</p>"), # 50 words ] for value, expected in perf_test_values: with self.subTest(value=value): truncator = text.Truncator(value) self.assertEqual(expected, truncator.words(50, html=True)) def test_wrap(self): digits = "1234 67 9" self.assertEqual(text.wrap(digits, 100), "1234 67 9") self.assertEqual(text.wrap(digits, 9), "1234 67 9") self.assertEqual(text.wrap(digits, 8), "1234 67\n9") self.assertEqual(text.wrap("short\na long line", 7), "short\na long\nline") self.assertEqual( text.wrap("do-not-break-long-words please? ok", 8), "do-not-break-long-words\nplease?\nok", ) long_word = "l%sng" % ("o" * 20) self.assertEqual(text.wrap(long_word, 20), long_word) self.assertEqual( text.wrap("a %s word" % long_word, 10), "a\n%s\nword" % long_word ) self.assertEqual(text.wrap(lazystr(digits), 100), "1234 67 9") def test_normalize_newlines(self): self.assertEqual( text.normalize_newlines("abc\ndef\rghi\r\n"), "abc\ndef\nghi\n" ) self.assertEqual(text.normalize_newlines("\n\r\r\n\r"), "\n\n\n\n") self.assertEqual(text.normalize_newlines("abcdefghi"), "abcdefghi") self.assertEqual(text.normalize_newlines(""), "") self.assertEqual( text.normalize_newlines(lazystr("abc\ndef\rghi\r\n")), "abc\ndef\nghi\n" ) def test_phone2numeric(self): numeric = text.phone2numeric("0800 flowers") self.assertEqual(numeric, "0800 3569377") lazy_numeric = lazystr(text.phone2numeric("0800 flowers")) self.assertEqual(lazy_numeric, "0800 3569377") def test_slugify(self): items = ( # given - expected - Unicode? ("Hello, World!", "hello-world", False), ("spam & eggs", "spam-eggs", False), (" multiple---dash and space ", "multiple-dash-and-space", False), ("\t whitespace-in-value \n", "whitespace-in-value", False), ("underscore_in-value", "underscore_in-value", False), ("__strip__underscore-value___", "strip__underscore-value", False), ("--strip-dash-value---", "strip-dash-value", False), ("__strip-mixed-value---", "strip-mixed-value", False), ("_ -strip-mixed-value _-", "strip-mixed-value", False), ("spam & ıçüş", "spam-ıçüş", True), ("foo ıç bar", "foo-ıç-bar", True), (" foo ıç bar", "foo-ıç-bar", True), ("你好", "你好", True), ("İstanbul", "istanbul", True), ) for value, output, is_unicode in items: with self.subTest(value=value): self.assertEqual(text.slugify(value, allow_unicode=is_unicode), output) # Interning the result may be useful, e.g. when fed to Path. with self.subTest("intern"): self.assertEqual(sys.intern(text.slugify("a")), "a") def test_unescape_string_literal(self): items = [ ('"abc"', "abc"), ("'abc'", "abc"), ('"a "bc""', 'a "bc"'), ("''ab' c'", "'ab' c"), ] for value, output in items: with self.subTest(value=value): self.assertEqual(text.unescape_string_literal(value), output) self.assertEqual(text.unescape_string_literal(lazystr(value)), output) def test_unescape_string_literal_invalid_value(self): items = ["", "abc", "'abc\""] for item in items: msg = f"Not a string literal: {item!r}" with self.assertRaisesMessage(ValueError, msg): text.unescape_string_literal(item) def test_get_valid_filename(self): filename = "^&'@{}[],$=!-#()%+~_123.txt" self.assertEqual(text.get_valid_filename(filename), "-_123.txt") self.assertEqual(text.get_valid_filename(lazystr(filename)), "-_123.txt") msg = "Could not derive file name from '???'" with self.assertRaisesMessage(SuspiciousFileOperation, msg): text.get_valid_filename("???") # After sanitizing this would yield '..'. msg = "Could not derive file name from '$.$.$'" with self.assertRaisesMessage(SuspiciousFileOperation, msg): text.get_valid_filename("$.$.$") def test_compress_sequence(self): data = [{"key": i} for i in range(10)] seq = list(json.JSONEncoder().iterencode(data)) seq = [s.encode() for s in seq] actual_length = len(b"".join(seq)) out = text.compress_sequence(seq) compressed_length = len(b"".join(out)) self.assertLess(compressed_length, actual_length) def test_format_lazy(self): self.assertEqual("django/test", format_lazy("{}/{}", "django", lazystr("test"))) self.assertEqual("django/test", format_lazy("{0}/{1}", *("django", "test"))) self.assertEqual( "django/test", format_lazy("{a}/{b}", **{"a": "django", "b": "test"}) ) self.assertEqual( "django/test", format_lazy("{a[0]}/{a[1]}", a=("django", "test")) ) t = {} s = format_lazy("{0[a]}-{p[a]}", t, p=t) t["a"] = lazystr("django") self.assertEqual("django-django", s) t["a"] = "update" self.assertEqual("update-update", s) # The format string can be lazy. (string comes from contrib.admin) s = format_lazy( gettext_lazy("Added {name} “{object}”."), name="article", object="My first try", ) with override("fr"): self.assertEqual("Ajout de article «\xa0My first try\xa0».", s)
django
python
#! /usr/bin/env python3 import argparse import os import subprocess import sys def run(cmd, *, cwd=None, env=None, dry_run=True): """Run a command with optional dry-run behavior.""" environ = os.environ.copy() if env: environ.update(env) if dry_run: print("[DRY RUN]", " ".join(cmd)) else: print("[EXECUTE]", " ".join(cmd)) try: result = subprocess.check_output( cmd, cwd=cwd, env=environ, stderr=subprocess.STDOUT ) except subprocess.CalledProcessError as e: result = e.output print(" [ERROR]", result) raise else: print(" [RESULT]", result) return result.decode().strip() def validate_env(checkout_dir): if not checkout_dir: sys.exit("Error: checkout directory not provided (--checkout-dir).") if not os.path.exists(checkout_dir): sys.exit(f"Error: checkout directory '{checkout_dir}' does not exist.") if not os.path.isdir(checkout_dir): sys.exit(f"Error: '{checkout_dir}' is not a directory.") def get_remote_branches(checkout_dir, include_fn): """Return list of remote branches filtered by include_fn.""" result = run( ["git", "branch", "--list", "-r"], cwd=checkout_dir, dry_run=False, ) branches = [b.strip() for b in result.split("\n") if b.strip()] return [b for b in branches if include_fn(b)] def get_branch_info(checkout_dir, branch): """Return (commit_hash, last_update_date) for a given branch.""" commit_hash = run(["git", "rev-parse", branch], cwd=checkout_dir, dry_run=False) last_update = run( ["git", "show", branch, "--format=format:%ai", "-s"], cwd=checkout_dir, dry_run=False, ) return commit_hash, last_update def create_tag(checkout_dir, branch, commit_hash, last_update, *, dry_run=True): """Create a tag locally for a given branch at its last update.""" tag_name = branch.replace("origin/", "", 1) msg = f'"Tagged {tag_name} for EOL stable branch removal."' run( ["git", "tag", "--sign", "--message", msg, tag_name, commit_hash], cwd=checkout_dir, env={"GIT_COMMITTER_DATE": last_update}, dry_run=dry_run, ) return tag_name def delete_remote_and_local_branch(checkout_dir, branch, *, dry_run=True): """Delete a remote branch from origin and the maching local branch.""" try: run( ["git", "branch", "-D", branch], cwd=checkout_dir, dry_run=dry_run, ) except subprocess.CalledProcessError: print(f"[ERROR] Local branch {branch} can not be deleted.") run( ["git", "push", "origin", "--delete", branch.replace("origin/", "", 1)], cwd=checkout_dir, dry_run=dry_run, ) def main(): parser = argparse.ArgumentParser( description="Archive Django branches into tags and optionally delete them." ) parser.add_argument( "--checkout-dir", required=True, help="Path to Django git checkout" ) parser.add_argument( "--dry-run", action="store_true", help="Print commands instead of executing them", ) parser.add_argument( "--branches", nargs="*", help="Specific remote branches to include (optional)" ) args = parser.parse_args() validate_env(args.checkout_dir) dry_run = args.dry_run checkout_dir = args.checkout_dir if args.branches: wanted = set(f"origin/{b}" for b in args.branches) else: wanted = set() branches = get_remote_branches(checkout_dir, include_fn=lambda b: b in wanted) if not branches: print("No branches matched inclusion criteria.") return print("\nMatched branches:") print("\n".join(branches)) print() branch_updates = {b: get_branch_info(checkout_dir, b) for b in branches} print("\nLast updates:") for b, (h, d) in branch_updates.items(): print(f"{b}\t{h}\t{d}") if ( input("\nDelete remote branches and create tags? [y/N]: ").strip().lower() == "y" ): for b, (commit_hash, last_update_date) in branch_updates.items(): print(f"Creating tag for {b} at {commit_hash=} with {last_update_date=}") create_tag(checkout_dir, b, commit_hash, last_update_date, dry_run=dry_run) print(f"Deleting remote branch {b}") delete_remote_and_local_branch(checkout_dir, b, dry_run=dry_run) run( ["git", "push", "--tags"], cwd=checkout_dir, dry_run=dry_run, ) print("Done.") if __name__ == "__main__": main()
import os import stat import sys import tempfile import unittest import zipfile from django.core.exceptions import SuspiciousOperation from django.test import SimpleTestCase from django.utils import archive try: import bz2 # NOQA HAS_BZ2 = True except ImportError: HAS_BZ2 = False try: import lzma # NOQA HAS_LZMA = True except ImportError: HAS_LZMA = False class TestArchive(unittest.TestCase): def setUp(self): self.testdir = os.path.join(os.path.dirname(__file__), "archives") old_cwd = os.getcwd() os.chdir(self.testdir) self.addCleanup(os.chdir, old_cwd) def test_extract_function(self): with os.scandir(self.testdir) as entries: for entry in entries: with self.subTest(entry.name), tempfile.TemporaryDirectory() as tmpdir: if (entry.name.endswith(".bz2") and not HAS_BZ2) or ( entry.name.endswith((".lzma", ".xz")) and not HAS_LZMA ): continue archive.extract(entry.path, tmpdir) self.assertTrue(os.path.isfile(os.path.join(tmpdir, "1"))) self.assertTrue(os.path.isfile(os.path.join(tmpdir, "2"))) self.assertTrue(os.path.isfile(os.path.join(tmpdir, "foo", "1"))) self.assertTrue(os.path.isfile(os.path.join(tmpdir, "foo", "2"))) self.assertTrue( os.path.isfile(os.path.join(tmpdir, "foo", "bar", "1")) ) self.assertTrue( os.path.isfile(os.path.join(tmpdir, "foo", "bar", "2")) ) @unittest.skipIf( sys.platform == "win32", "Python on Windows has a limited os.chmod()." ) def test_extract_file_permissions(self): """archive.extract() preserves file permissions.""" mask = stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO umask = os.umask(0) os.umask(umask) # Restore the original umask. with os.scandir(self.testdir) as entries: for entry in entries: if ( entry.name.startswith("leadpath_") or (entry.name.endswith(".bz2") and not HAS_BZ2) or (entry.name.endswith((".lzma", ".xz")) and not HAS_LZMA) ): continue with self.subTest(entry.name), tempfile.TemporaryDirectory() as tmpdir: archive.extract(entry.path, tmpdir) # An executable file in the archive has executable # permissions. filepath = os.path.join(tmpdir, "executable") self.assertEqual(os.stat(filepath).st_mode & mask, 0o775) # A file is readable even if permission data is missing. filepath = os.path.join(tmpdir, "no_permissions") self.assertEqual(os.stat(filepath).st_mode & mask, 0o666 & ~umask) class TestArchiveInvalid(SimpleTestCase): def test_extract_function_traversal(self): archives_dir = os.path.join(os.path.dirname(__file__), "traversal_archives") tests = [ ("traversal.tar", ".."), ("traversal_absolute.tar", "/tmp/evil.py"), ] if sys.platform == "win32": tests += [ ("traversal_disk_win.tar", "d:evil.py"), ("traversal_disk_win.zip", "d:evil.py"), ] msg = "Archive contains invalid path: '%s'" for entry, invalid_path in tests: with self.subTest(entry), tempfile.TemporaryDirectory() as tmpdir: with self.assertRaisesMessage(SuspiciousOperation, msg % invalid_path): archive.extract(os.path.join(archives_dir, entry), tmpdir) def test_extract_function_traversal_startswith(self): with tempfile.TemporaryDirectory() as tmpdir: base = os.path.abspath(tmpdir) tarfile_handle = tempfile.NamedTemporaryFile(suffix=".zip", delete=False) tar_path = tarfile_handle.name tarfile_handle.close() self.addCleanup(os.remove, tar_path) malicious_member = os.path.join(base + "abc", "evil.txt") with zipfile.ZipFile(tar_path, "w") as zf: zf.writestr(malicious_member, "evil\n") zf.writestr("test.txt", "data\n") with self.assertRaisesMessage( SuspiciousOperation, "Archive contains invalid path" ): archive.extract(tar_path, base)
django
python
from django.contrib.sitemaps import views from django.urls import path from .http import SimpleSitemap class HTTPSSitemap(SimpleSitemap): protocol = "https" secure_sitemaps = { "simple": HTTPSSitemap, } urlpatterns = [ path("secure/index.xml", views.index, {"sitemaps": secure_sitemaps}), path( "secure/sitemap-<section>.xml", views.sitemap, {"sitemaps": secure_sitemaps}, name="django.contrib.sitemaps.views.sitemap", ), ]
import platform import unittest from datetime import UTC, datetime from unittest import mock from django.test import SimpleTestCase from django.utils.datastructures import MultiValueDict from django.utils.http import ( MAX_HEADER_LENGTH, MAX_URL_LENGTH, base36_to_int, content_disposition_header, escape_leading_slashes, http_date, int_to_base36, is_same_domain, parse_etags, parse_header_parameters, parse_http_date, quote_etag, url_has_allowed_host_and_scheme, urlencode, urlsafe_base64_decode, urlsafe_base64_encode, ) class URLEncodeTests(SimpleTestCase): cannot_encode_none_msg = ( "Cannot encode None for key 'a' in a query string. Did you mean to " "pass an empty string or omit the value?" ) def test_tuples(self): self.assertEqual(urlencode((("a", 1), ("b", 2), ("c", 3))), "a=1&b=2&c=3") def test_dict(self): result = urlencode({"a": 1, "b": 2, "c": 3}) self.assertEqual(result, "a=1&b=2&c=3") def test_dict_containing_sequence_not_doseq(self): self.assertEqual(urlencode({"a": [1, 2]}, doseq=False), "a=%5B1%2C+2%5D") def test_dict_containing_tuple_not_doseq(self): self.assertEqual(urlencode({"a": (1, 2)}, doseq=False), "a=%281%2C+2%29") def test_custom_iterable_not_doseq(self): class IterableWithStr: def __str__(self): return "custom" def __iter__(self): yield from range(0, 3) self.assertEqual(urlencode({"a": IterableWithStr()}, doseq=False), "a=custom") def test_dict_containing_sequence_doseq(self): self.assertEqual(urlencode({"a": [1, 2]}, doseq=True), "a=1&a=2") def test_dict_containing_empty_sequence_doseq(self): self.assertEqual(urlencode({"a": []}, doseq=True), "") def test_multivaluedict(self): result = urlencode( MultiValueDict( { "name": ["Adrian", "Simon"], "position": ["Developer"], } ), doseq=True, ) self.assertEqual(result, "name=Adrian&name=Simon&position=Developer") def test_dict_with_bytes_values(self): self.assertEqual(urlencode({"a": b"abc"}, doseq=True), "a=abc") def test_dict_with_sequence_of_bytes(self): self.assertEqual( urlencode({"a": [b"spam", b"eggs", b"bacon"]}, doseq=True), "a=spam&a=eggs&a=bacon", ) def test_dict_with_bytearray(self): self.assertEqual(urlencode({"a": bytearray(range(2))}, doseq=True), "a=0&a=1") def test_generator(self): self.assertEqual(urlencode({"a": range(2)}, doseq=True), "a=0&a=1") self.assertEqual(urlencode({"a": range(2)}, doseq=False), "a=range%280%2C+2%29") def test_none(self): with self.assertRaisesMessage(TypeError, self.cannot_encode_none_msg): urlencode({"a": None}) def test_none_in_sequence(self): with self.assertRaisesMessage(TypeError, self.cannot_encode_none_msg): urlencode({"a": [None]}, doseq=True) def test_none_in_generator(self): def gen(): yield None with self.assertRaisesMessage(TypeError, self.cannot_encode_none_msg): urlencode({"a": gen()}, doseq=True) class Base36IntTests(SimpleTestCase): def test_roundtrip(self): for n in [0, 1, 1000, 1000000]: self.assertEqual(n, base36_to_int(int_to_base36(n))) def test_negative_input(self): with self.assertRaisesMessage(ValueError, "Negative base36 conversion input."): int_to_base36(-1) def test_to_base36_errors(self): for n in ["1", "foo", {1: 2}, (1, 2, 3), 3.141]: with self.assertRaises(TypeError): int_to_base36(n) def test_invalid_literal(self): for n in ["#", " "]: with self.assertRaisesMessage( ValueError, "invalid literal for int() with base 36: '%s'" % n ): base36_to_int(n) def test_input_too_large(self): with self.assertRaisesMessage(ValueError, "Base36 input too large"): base36_to_int("1" * 14) def test_to_int_errors(self): for n in [123, {1: 2}, (1, 2, 3), 3.141]: with self.assertRaises(TypeError): base36_to_int(n) def test_values(self): for n, b36 in [(0, "0"), (1, "1"), (42, "16"), (818469960, "django")]: self.assertEqual(int_to_base36(n), b36) self.assertEqual(base36_to_int(b36), n) class URLHasAllowedHostAndSchemeTests(unittest.TestCase): def test_bad_urls(self): bad_urls = ( "http://example.com", "http:///example.com", "https://example.com", "ftp://example.com", r"\\example.com", r"\\\example.com", r"/\\/example.com", r"\\\example.com", r"\\example.com", r"\\//example.com", r"/\/example.com", r"\/example.com", r"/\example.com", "http:///example.com", r"http:/\//example.com", r"http:\/example.com", r"http:/\example.com", 'javascript:alert("XSS")', "\njavascript:alert(x)", "java\nscript:alert(x)", "\x08//example.com", r"http://otherserver\@example.com", r"http:\\testserver\@example.com", r"http://testserver\me:[email protected]", r"http://testserver\@example.com", r"http:\\testserver\confirm\[email protected]", "http:999999999", "ftp:9999999999", "\n", "http://[2001:cdba:0000:0000:0000:0000:3257:9652/", "http://2001:cdba:0000:0000:0000:0000:3257:9652]/", ) for bad_url in bad_urls: with self.subTest(url=bad_url): self.assertIs( url_has_allowed_host_and_scheme( bad_url, allowed_hosts={"testserver", "testserver2"} ), False, ) def test_good_urls(self): good_urls = ( "/view/?param=http://example.com", "/view/?param=https://example.com", "/view?param=ftp://example.com", "view/?param=//example.com", "https://testserver/", "HTTPS://testserver/", "//testserver/", "http://testserver/[email protected]", "/url%20with%20spaces/", "path/http:2222222222", ) for good_url in good_urls: with self.subTest(url=good_url): self.assertIs( url_has_allowed_host_and_scheme( good_url, allowed_hosts={"otherserver", "testserver"} ), True, ) def test_basic_auth(self): # Valid basic auth credentials are allowed. self.assertIs( url_has_allowed_host_and_scheme( r"http://user:pass@testserver/", allowed_hosts={"user:pass@testserver"} ), True, ) def test_no_allowed_hosts(self): # A path without host is allowed. self.assertIs( url_has_allowed_host_and_scheme( "/confirm/[email protected]", allowed_hosts=None ), True, ) # Basic auth without host is not allowed. self.assertIs( url_has_allowed_host_and_scheme( r"http://testserver\@example.com", allowed_hosts=None ), False, ) def test_allowed_hosts_str(self): self.assertIs( url_has_allowed_host_and_scheme( "http://good.com/good", allowed_hosts="good.com" ), True, ) self.assertIs( url_has_allowed_host_and_scheme( "http://good.co/evil", allowed_hosts="good.com" ), False, ) def test_secure_param_https_urls(self): secure_urls = ( "https://example.com/p", "HTTPS://example.com/p", "/view/?param=http://example.com", ) for url in secure_urls: with self.subTest(url=url): self.assertIs( url_has_allowed_host_and_scheme( url, allowed_hosts={"example.com"}, require_https=True ), True, ) def test_secure_param_non_https_urls(self): insecure_urls = ( "http://example.com/p", "ftp://example.com/p", "//example.com/p", ) for url in insecure_urls: with self.subTest(url=url): self.assertIs( url_has_allowed_host_and_scheme( url, allowed_hosts={"example.com"}, require_https=True ), False, ) def test_max_url_length(self): allowed_host = "example.com" max_extra_characters = "é" * (MAX_URL_LENGTH - len(allowed_host) - 1) max_length_boundary_url = f"{allowed_host}/{max_extra_characters}" cases = [ (max_length_boundary_url, True), (max_length_boundary_url + "ú", False), ] for url, expected in cases: with self.subTest(url=url): self.assertIs( url_has_allowed_host_and_scheme(url, allowed_hosts={allowed_host}), expected, ) class URLSafeBase64Tests(unittest.TestCase): def test_roundtrip(self): bytestring = b"foo" encoded = urlsafe_base64_encode(bytestring) decoded = urlsafe_base64_decode(encoded) self.assertEqual(bytestring, decoded) class IsSameDomainTests(unittest.TestCase): def test_good(self): for pair in ( ("example.com", "example.com"), ("example.com", ".example.com"), ("foo.example.com", ".example.com"), ("example.com:8888", "example.com:8888"), ("example.com:8888", ".example.com:8888"), ("foo.example.com:8888", ".example.com:8888"), ): self.assertIs(is_same_domain(*pair), True) def test_bad(self): for pair in ( ("example2.com", "example.com"), ("foo.example.com", "example.com"), ("example.com:9999", "example.com:8888"), ("foo.example.com:8888", ""), ): self.assertIs(is_same_domain(*pair), False) class ETagProcessingTests(unittest.TestCase): def test_parsing(self): self.assertEqual( parse_etags(r'"" , "etag", "e\\tag", W/"weak"'), ['""', '"etag"', r'"e\\tag"', 'W/"weak"'], ) self.assertEqual(parse_etags("*"), ["*"]) # Ignore RFC 2616 ETags that are invalid according to RFC 9110. self.assertEqual(parse_etags(r'"etag", "e\"t\"ag"'), ['"etag"']) def test_quoting(self): self.assertEqual(quote_etag("etag"), '"etag"') # unquoted self.assertEqual(quote_etag('"etag"'), '"etag"') # quoted self.assertEqual(quote_etag('W/"etag"'), 'W/"etag"') # quoted, weak class HttpDateProcessingTests(unittest.TestCase): def test_http_date(self): t = 1167616461.0 self.assertEqual(http_date(t), "Mon, 01 Jan 2007 01:54:21 GMT") def test_parsing_rfc1123(self): parsed = parse_http_date("Sun, 06 Nov 1994 08:49:37 GMT") self.assertEqual( datetime.fromtimestamp(parsed, UTC), datetime(1994, 11, 6, 8, 49, 37, tzinfo=UTC), ) @unittest.skipIf(platform.architecture()[0] == "32bit", "The Year 2038 problem.") @mock.patch("django.utils.http.datetime") def test_parsing_rfc850(self, mocked_datetime): mocked_datetime.side_effect = datetime now_1 = datetime(2019, 11, 6, 8, 49, 37, tzinfo=UTC) now_2 = datetime(2020, 11, 6, 8, 49, 37, tzinfo=UTC) now_3 = datetime(2048, 11, 6, 8, 49, 37, tzinfo=UTC) tests = ( ( now_1, "Tuesday, 31-Dec-69 08:49:37 GMT", datetime(2069, 12, 31, 8, 49, 37, tzinfo=UTC), ), ( now_1, "Tuesday, 10-Nov-70 08:49:37 GMT", datetime(1970, 11, 10, 8, 49, 37, tzinfo=UTC), ), ( now_1, "Sunday, 06-Nov-94 08:49:37 GMT", datetime(1994, 11, 6, 8, 49, 37, tzinfo=UTC), ), ( now_2, "Wednesday, 31-Dec-70 08:49:37 GMT", datetime(2070, 12, 31, 8, 49, 37, tzinfo=UTC), ), ( now_2, "Friday, 31-Dec-71 08:49:37 GMT", datetime(1971, 12, 31, 8, 49, 37, tzinfo=UTC), ), ( now_3, "Sunday, 31-Dec-00 08:49:37 GMT", datetime(2000, 12, 31, 8, 49, 37, tzinfo=UTC), ), ( now_3, "Friday, 31-Dec-99 08:49:37 GMT", datetime(1999, 12, 31, 8, 49, 37, tzinfo=UTC), ), ) for now, rfc850str, expected_date in tests: with self.subTest(rfc850str=rfc850str): mocked_datetime.now.return_value = now parsed = parse_http_date(rfc850str) mocked_datetime.now.assert_called_once_with(tz=UTC) self.assertEqual( datetime.fromtimestamp(parsed, UTC), expected_date, ) mocked_datetime.reset_mock() def test_parsing_asctime(self): parsed = parse_http_date("Sun Nov 6 08:49:37 1994") self.assertEqual( datetime.fromtimestamp(parsed, UTC), datetime(1994, 11, 6, 8, 49, 37, tzinfo=UTC), ) def test_parsing_asctime_nonascii_digits(self): """Non-ASCII unicode decimals raise an error.""" with self.assertRaises(ValueError): parse_http_date("Sun Nov 6 08:49:37 1994") with self.assertRaises(ValueError): parse_http_date("Sun Nov 12 08:49:37 1994") def test_parsing_year_less_than_70(self): parsed = parse_http_date("Sun Nov 6 08:49:37 0037") self.assertEqual( datetime.fromtimestamp(parsed, UTC), datetime(2037, 11, 6, 8, 49, 37, tzinfo=UTC), ) class EscapeLeadingSlashesTests(unittest.TestCase): def test(self): tests = ( ("//example.com", "/%2Fexample.com"), ("//", "/%2F"), ) for url, expected in tests: with self.subTest(url=url): self.assertEqual(escape_leading_slashes(url), expected) class ParseHeaderParameterTests(unittest.TestCase): def test_basic(self): tests = [ ("", ("", {})), (None, ("", {})), ("text/plain", ("text/plain", {})), ("text/vnd.just.made.this.up ; ", ("text/vnd.just.made.this.up", {})), ("text/plain;charset=us-ascii", ("text/plain", {"charset": "us-ascii"})), ( 'text/plain ; charset="us-ascii"', ("text/plain", {"charset": "us-ascii"}), ), ( 'text/plain ; charset="us-ascii"; another=opt', ("text/plain", {"charset": "us-ascii", "another": "opt"}), ), ( 'attachment; filename="silly.txt"', ("attachment", {"filename": "silly.txt"}), ), ( 'attachment; filename="strange;name"', ("attachment", {"filename": "strange;name"}), ), ( 'attachment; filename="strange;name";size=123;', ("attachment", {"filename": "strange;name", "size": "123"}), ), ( 'attachment; filename="strange;name";;;;size=123;;;', ("attachment", {"filename": "strange;name", "size": "123"}), ), ( 'form-data; name="files"; filename="fo\\"o;bar"', ("form-data", {"name": "files", "filename": 'fo"o;bar'}), ), ( 'form-data; name="files"; filename="\\"fo\\"o;b\\\\ar\\""', ("form-data", {"name": "files", "filename": '"fo"o;b\\ar"'}), ), ] for header, expected in tests: with self.subTest(header=header): self.assertEqual(parse_header_parameters(header), expected) def test_rfc2231_parsing(self): test_data = ( ( "Content-Type: application/x-stuff; " "title*=us-ascii'en-us'This%20is%20%2A%2A%2Afun%2A%2A%2A", "This is ***fun***", ), ( "Content-Type: application/x-stuff; title*=UTF-8''foo-%c3%a4.html", "foo-ä.html", ), ( "Content-Type: application/x-stuff; title*=iso-8859-1''foo-%E4.html", "foo-ä.html", ), ) for raw_line, expected_title in test_data: parsed = parse_header_parameters(raw_line) self.assertEqual(parsed[1]["title"], expected_title) def test_rfc2231_wrong_title(self): """ Test wrongly formatted RFC 2231 headers (missing double single quotes). Parsing should not crash (#24209). """ test_data = ( ( "Content-Type: application/x-stuff; " "title*='This%20is%20%2A%2A%2Afun%2A%2A%2A", "'This%20is%20%2A%2A%2Afun%2A%2A%2A", ), ("Content-Type: application/x-stuff; title*='foo.html", "'foo.html"), ("Content-Type: application/x-stuff; title*=bar.html", "bar.html"), ) for raw_line, expected_title in test_data: parsed = parse_header_parameters(raw_line) self.assertEqual(parsed[1]["title"], expected_title) def test_header_max_length(self): base_header = "Content-Type: application/x-stuff; title*=" base_header_len = len(base_header) test_data = [ (MAX_HEADER_LENGTH, {}), (MAX_HEADER_LENGTH, {"max_length": None}), (MAX_HEADER_LENGTH + 1, {"max_length": None}), (100, {"max_length": 100}), ] for line_length, kwargs in test_data: with self.subTest(line_length=line_length, kwargs=kwargs): title = "x" * (line_length - base_header_len) line = base_header + title assert len(line) == line_length parsed = parse_header_parameters(line, **kwargs) expected = ("content-type: application/x-stuff", {"title": title}) self.assertEqual(parsed, expected) def test_header_too_long(self): test_data = [ ("x" * (MAX_HEADER_LENGTH + 1), {}), ("x" * 101, {"max_length": 100}), ] for line, kwargs in test_data: with self.subTest(line_length=len(line), kwargs=kwargs): with self.assertRaises(ValueError): parse_header_parameters(line, **kwargs) class ContentDispositionHeaderTests(unittest.TestCase): def test_basic(self): tests = ( ((False, None), None), ((False, "example"), 'inline; filename="example"'), ((True, None), "attachment"), ((True, "example"), 'attachment; filename="example"'), ( (True, '"example" file\\name'), 'attachment; filename="\\"example\\" file\\\\name"', ), ((True, "espécimen"), "attachment; filename*=utf-8''esp%C3%A9cimen"), ( (True, '"espécimen" filename'), "attachment; filename*=utf-8''%22esp%C3%A9cimen%22%20filename", ), ((True, "some\nfile"), "attachment; filename*=utf-8''some%0Afile"), ) for (is_attachment, filename), expected in tests: with self.subTest(is_attachment=is_attachment, filename=filename): self.assertEqual( content_disposition_header(is_attachment, filename), expected )
django
python
""" A class for storing a tree graph. Primarily used for filter constructs in the ORM. """ import copy from django.utils.hashable import make_hashable class Node: """ A single internal node in the tree graph. A Node should be viewed as a connection (the root) with the children being either leaf nodes or other Node instances. """ # Standard connector type. Clients usually won't use this at all and # subclasses will usually override the value. default = "DEFAULT" def __init__(self, children=None, connector=None, negated=False): """Construct a new Node. If no connector is given, use the default.""" self.children = children[:] if children else [] self.connector = connector or self.default self.negated = negated @classmethod def create(cls, children=None, connector=None, negated=False): """ Create a new instance using Node() instead of __init__() as some subclasses, e.g. django.db.models.query_utils.Q, may implement a custom __init__() with a signature that conflicts with the one defined in Node.__init__(). """ obj = Node(children, connector or cls.default, negated) obj.__class__ = cls return obj def __str__(self): template = "(NOT (%s: %s))" if self.negated else "(%s: %s)" return template % (self.connector, ", ".join(str(c) for c in self.children)) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) def __copy__(self): obj = self.create(connector=self.connector, negated=self.negated) obj.children = self.children # Don't [:] as .__init__() via .create() does. return obj copy = __copy__ def __deepcopy__(self, memodict): obj = self.create(connector=self.connector, negated=self.negated) obj.children = copy.deepcopy(self.children, memodict) return obj def __len__(self): """Return the number of children this node has.""" return len(self.children) def __bool__(self): """Return whether or not this node has children.""" return bool(self.children) def __contains__(self, other): """Return True if 'other' is a direct child of this instance.""" return other in self.children def __eq__(self, other): return ( self.__class__ == other.__class__ and self.connector == other.connector and self.negated == other.negated and self.children == other.children ) def __hash__(self): return hash( ( self.__class__, self.connector, self.negated, *make_hashable(self.children), ) ) def add(self, data, conn_type): """ Combine this tree and the data represented by data using the connector conn_type. The combine is done by squashing the node other away if possible. This tree (self) will never be pushed to a child node of the combined tree, nor will the connector or negated properties change. Return a node which can be used in place of data regardless if the node other got squashed or not. """ if self.connector != conn_type: obj = self.copy() self.connector = conn_type self.children = [obj, data] return data elif ( isinstance(data, Node) and not data.negated and (data.connector == conn_type or len(data) == 1) ): # We can squash the other node's children directly into this node. # We are just doing (AB)(CD) == (ABCD) here, with the addition that # if the length of the other node is 1 the connector doesn't # matter. However, for the len(self) == 1 case we don't want to do # the squashing, as it would alter self.connector. self.children.extend(data.children) return self else: # We could use perhaps additional logic here to see if some # children could be used for pushdown here. self.children.append(data) return data def negate(self): """Negate the sense of the root connector.""" self.negated = not self.negated
import copy import unittest from django.db.models.sql import AND, OR from django.utils.tree import Node class NodeTests(unittest.TestCase): def setUp(self): self.node1_children = [("a", 1), ("b", 2)] self.node1 = Node(self.node1_children) self.node2 = Node() def test_str(self): self.assertEqual(str(self.node1), "(DEFAULT: ('a', 1), ('b', 2))") self.assertEqual(str(self.node2), "(DEFAULT: )") def test_repr(self): self.assertEqual(repr(self.node1), "<Node: (DEFAULT: ('a', 1), ('b', 2))>") self.assertEqual(repr(self.node2), "<Node: (DEFAULT: )>") def test_hash(self): node3 = Node(self.node1_children, negated=True) node4 = Node(self.node1_children, connector="OTHER") node5 = Node(self.node1_children) node6 = Node([["a", 1], ["b", 2]]) node7 = Node([("a", [1, 2])]) node8 = Node([("a", (1, 2))]) self.assertNotEqual(hash(self.node1), hash(self.node2)) self.assertNotEqual(hash(self.node1), hash(node3)) self.assertNotEqual(hash(self.node1), hash(node4)) self.assertEqual(hash(self.node1), hash(node5)) self.assertEqual(hash(self.node1), hash(node6)) self.assertEqual(hash(self.node2), hash(Node())) self.assertEqual(hash(node7), hash(node8)) def test_len(self): self.assertEqual(len(self.node1), 2) self.assertEqual(len(self.node2), 0) def test_bool(self): self.assertTrue(self.node1) self.assertFalse(self.node2) def test_contains(self): self.assertIn(("a", 1), self.node1) self.assertNotIn(("a", 1), self.node2) def test_add(self): # start with the same children of node1 then add an item node3 = Node(self.node1_children) node3_added_child = ("c", 3) # add() returns the added data self.assertEqual(node3.add(node3_added_child, Node.default), node3_added_child) # we added exactly one item, len() should reflect that self.assertEqual(len(self.node1) + 1, len(node3)) self.assertEqual(str(node3), "(DEFAULT: ('a', 1), ('b', 2), ('c', 3))") def test_add_eq_child_mixed_connector(self): node = Node(["a", "b"], OR) self.assertEqual(node.add("a", AND), "a") self.assertEqual(node, Node([Node(["a", "b"], OR), "a"], AND)) def test_negate(self): # negated is False by default self.assertFalse(self.node1.negated) self.node1.negate() self.assertTrue(self.node1.negated) self.node1.negate() self.assertFalse(self.node1.negated) def test_create(self): SubNode = type("SubNode", (Node,), {}) a = SubNode([SubNode(["a", "b"], OR), "c"], AND) b = SubNode.create(a.children, a.connector, a.negated) self.assertEqual(a, b) # Children lists are the same object, but equal. self.assertIsNot(a.children, b.children) self.assertEqual(a.children, b.children) # Child Node objects are the same objects. for a_child, b_child in zip(a.children, b.children): if isinstance(a_child, Node): self.assertIs(a_child, b_child) self.assertEqual(a_child, b_child) def test_copy(self): a = Node([Node(["a", "b"], OR), "c"], AND) b = copy.copy(a) self.assertEqual(a, b) # Children lists are the same object. self.assertIs(a.children, b.children) # Child Node objects are the same objects. for a_child, b_child in zip(a.children, b.children): if isinstance(a_child, Node): self.assertIs(a_child, b_child) self.assertEqual(a_child, b_child) def test_deepcopy(self): a = Node([Node(["a", "b"], OR), "c"], AND) b = copy.deepcopy(a) self.assertEqual(a, b) # Children lists are not be the same object, but equal. self.assertIsNot(a.children, b.children) self.assertEqual(a.children, b.children) # Child Node objects are not be the same objects. for a_child, b_child in zip(a.children, b.children): if isinstance(a_child, Node): self.assertIsNot(a_child, b_child) self.assertEqual(a_child, b_child) def test_eq_children(self): node = Node(self.node1_children) self.assertEqual(node, self.node1) self.assertNotEqual(node, self.node2) def test_eq_connector(self): new_node = Node(connector="NEW") default_node = Node(connector="DEFAULT") self.assertEqual(default_node, self.node2) self.assertNotEqual(default_node, new_node) def test_eq_negated(self): node = Node(negated=False) negated = Node(negated=True) self.assertNotEqual(negated, node)
django
python
from datetime import date, datetime from django.test import SimpleTestCase from django.utils import timezone class TimezoneTestCase(SimpleTestCase): def setUp(self): self.now = datetime.now() self.now_tz = timezone.make_aware( self.now, timezone.get_default_timezone(), ) self.now_tz_i = timezone.localtime( self.now_tz, timezone.get_fixed_timezone(195), ) self.today = date.today()
import datetime import zoneinfo from unittest import mock from django.test import SimpleTestCase, override_settings from django.utils import timezone PARIS_ZI = zoneinfo.ZoneInfo("Europe/Paris") EAT = timezone.get_fixed_timezone(180) # Africa/Nairobi ICT = timezone.get_fixed_timezone(420) # Asia/Bangkok UTC = datetime.UTC class TimezoneTests(SimpleTestCase): def test_default_timezone_is_zoneinfo(self): self.assertIsInstance(timezone.get_default_timezone(), zoneinfo.ZoneInfo) def test_now(self): with override_settings(USE_TZ=True): self.assertTrue(timezone.is_aware(timezone.now())) with override_settings(USE_TZ=False): self.assertTrue(timezone.is_naive(timezone.now())) def test_localdate(self): naive = datetime.datetime(2015, 1, 1, 0, 0, 1) with self.assertRaisesMessage( ValueError, "localtime() cannot be applied to a naive datetime" ): timezone.localdate(naive) with self.assertRaisesMessage( ValueError, "localtime() cannot be applied to a naive datetime" ): timezone.localdate(naive, timezone=EAT) aware = datetime.datetime(2015, 1, 1, 0, 0, 1, tzinfo=ICT) self.assertEqual( timezone.localdate(aware, timezone=EAT), datetime.date(2014, 12, 31) ) with timezone.override(EAT): self.assertEqual(timezone.localdate(aware), datetime.date(2014, 12, 31)) with mock.patch("django.utils.timezone.now", return_value=aware): self.assertEqual( timezone.localdate(timezone=EAT), datetime.date(2014, 12, 31) ) with timezone.override(EAT): self.assertEqual(timezone.localdate(), datetime.date(2014, 12, 31)) def test_override(self): default = timezone.get_default_timezone() try: timezone.activate(ICT) with timezone.override(EAT): self.assertIs(EAT, timezone.get_current_timezone()) self.assertIs(ICT, timezone.get_current_timezone()) with timezone.override(None): self.assertIs(default, timezone.get_current_timezone()) self.assertIs(ICT, timezone.get_current_timezone()) timezone.deactivate() with timezone.override(EAT): self.assertIs(EAT, timezone.get_current_timezone()) self.assertIs(default, timezone.get_current_timezone()) with timezone.override(None): self.assertIs(default, timezone.get_current_timezone()) self.assertIs(default, timezone.get_current_timezone()) finally: timezone.deactivate() def test_override_decorator(self): default = timezone.get_default_timezone() @timezone.override(EAT) def func_tz_eat(): self.assertIs(EAT, timezone.get_current_timezone()) @timezone.override(None) def func_tz_none(): self.assertIs(default, timezone.get_current_timezone()) try: timezone.activate(ICT) func_tz_eat() self.assertIs(ICT, timezone.get_current_timezone()) func_tz_none() self.assertIs(ICT, timezone.get_current_timezone()) timezone.deactivate() func_tz_eat() self.assertIs(default, timezone.get_current_timezone()) func_tz_none() self.assertIs(default, timezone.get_current_timezone()) finally: timezone.deactivate() def test_override_string_tz(self): with timezone.override("Asia/Bangkok"): self.assertEqual(timezone.get_current_timezone_name(), "Asia/Bangkok") def test_override_fixed_offset(self): with timezone.override(datetime.timezone(datetime.timedelta(), "tzname")): self.assertEqual(timezone.get_current_timezone_name(), "tzname") def test_activate_invalid_timezone(self): with self.assertRaisesMessage(ValueError, "Invalid timezone: None"): timezone.activate(None) def test_is_aware(self): self.assertTrue( timezone.is_aware(datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)) ) self.assertFalse(timezone.is_aware(datetime.datetime(2011, 9, 1, 13, 20, 30))) def test_is_naive(self): self.assertFalse( timezone.is_naive(datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)) ) self.assertTrue(timezone.is_naive(datetime.datetime(2011, 9, 1, 13, 20, 30))) def test_make_aware(self): self.assertEqual( timezone.make_aware(datetime.datetime(2011, 9, 1, 13, 20, 30), EAT), datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), ) with self.assertRaises(ValueError): timezone.make_aware( datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), EAT ) def test_make_naive(self): self.assertEqual( timezone.make_naive( datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), EAT ), datetime.datetime(2011, 9, 1, 13, 20, 30), ) self.assertEqual( timezone.make_naive( datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT), EAT ), datetime.datetime(2011, 9, 1, 13, 20, 30), ) with self.assertRaisesMessage( ValueError, "make_naive() cannot be applied to a naive datetime" ): timezone.make_naive(datetime.datetime(2011, 9, 1, 13, 20, 30), EAT) def test_make_naive_no_tz(self): self.assertEqual( timezone.make_naive(datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)), datetime.datetime(2011, 9, 1, 5, 20, 30), ) def test_make_aware_no_tz(self): self.assertEqual( timezone.make_aware(datetime.datetime(2011, 9, 1, 13, 20, 30)), datetime.datetime( 2011, 9, 1, 13, 20, 30, tzinfo=timezone.get_fixed_timezone(-300) ), ) def test_make_aware2(self): CEST = datetime.timezone(datetime.timedelta(hours=2), "CEST") self.assertEqual( timezone.make_aware(datetime.datetime(2011, 9, 1, 12, 20, 30), PARIS_ZI), datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=CEST), ) with self.assertRaises(ValueError): timezone.make_aware( datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=PARIS_ZI), PARIS_ZI ) def test_make_naive_zoneinfo(self): self.assertEqual( timezone.make_naive( datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=PARIS_ZI), PARIS_ZI ), datetime.datetime(2011, 9, 1, 12, 20, 30), ) self.assertEqual( timezone.make_naive( datetime.datetime(2011, 9, 1, 12, 20, 30, fold=1, tzinfo=PARIS_ZI), PARIS_ZI, ), datetime.datetime(2011, 9, 1, 12, 20, 30, fold=1), ) def test_make_aware_zoneinfo_ambiguous(self): # 2:30 happens twice, once before DST ends and once after ambiguous = datetime.datetime(2015, 10, 25, 2, 30) std = timezone.make_aware(ambiguous.replace(fold=1), timezone=PARIS_ZI) dst = timezone.make_aware(ambiguous, timezone=PARIS_ZI) self.assertEqual( std.astimezone(UTC) - dst.astimezone(UTC), datetime.timedelta(hours=1) ) self.assertEqual(std.utcoffset(), datetime.timedelta(hours=1)) self.assertEqual(dst.utcoffset(), datetime.timedelta(hours=2)) def test_make_aware_zoneinfo_non_existent(self): # 2:30 never happened due to DST non_existent = datetime.datetime(2015, 3, 29, 2, 30) std = timezone.make_aware(non_existent, PARIS_ZI) dst = timezone.make_aware(non_existent.replace(fold=1), PARIS_ZI) self.assertEqual( std.astimezone(UTC) - dst.astimezone(UTC), datetime.timedelta(hours=1) ) self.assertEqual(std.utcoffset(), datetime.timedelta(hours=1)) self.assertEqual(dst.utcoffset(), datetime.timedelta(hours=2)) def test_get_timezone_name(self): """ The _get_timezone_name() helper must return the offset for fixed offset timezones, for usage with Trunc DB functions. The datetime.timezone examples show the current behavior. """ tests = [ # datetime.timezone, fixed offset with and without `name`. (datetime.timezone(datetime.timedelta(hours=10)), "UTC+10:00"), ( datetime.timezone(datetime.timedelta(hours=10), name="Etc/GMT-10"), "Etc/GMT-10", ), # zoneinfo, named and fixed offset. (zoneinfo.ZoneInfo("Europe/Madrid"), "Europe/Madrid"), (zoneinfo.ZoneInfo("Etc/GMT-10"), "+10"), ] for tz, expected in tests: with self.subTest(tz=tz, expected=expected): self.assertEqual(timezone._get_timezone_name(tz), expected) def test_get_default_timezone(self): self.assertEqual(timezone.get_default_timezone_name(), "America/Chicago") def test_fixedoffset_timedelta(self): delta = datetime.timedelta(hours=1) self.assertEqual(timezone.get_fixed_timezone(delta).utcoffset(None), delta) def test_fixedoffset_negative_timedelta(self): delta = datetime.timedelta(hours=-2) self.assertEqual(timezone.get_fixed_timezone(delta).utcoffset(None), delta)
django
python
""" Utility functions for generating "lorem ipsum" Latin text. """ import random COMMON_P = ( "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod " "tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim " "veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea " "commodo consequat. Duis aute irure dolor in reprehenderit in voluptate " "velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint " "occaecat cupidatat non proident, sunt in culpa qui officia deserunt " "mollit anim id est laborum." ) WORDS = ( "exercitationem", "perferendis", "perspiciatis", "laborum", "eveniet", "sunt", "iure", "nam", "nobis", "eum", "cum", "officiis", "excepturi", "odio", "consectetur", "quasi", "aut", "quisquam", "vel", "eligendi", "itaque", "non", "odit", "tempore", "quaerat", "dignissimos", "facilis", "neque", "nihil", "expedita", "vitae", "vero", "ipsum", "nisi", "animi", "cumque", "pariatur", "velit", "modi", "natus", "iusto", "eaque", "sequi", "illo", "sed", "ex", "et", "voluptatibus", "tempora", "veritatis", "ratione", "assumenda", "incidunt", "nostrum", "placeat", "aliquid", "fuga", "provident", "praesentium", "rem", "necessitatibus", "suscipit", "adipisci", "quidem", "possimus", "voluptas", "debitis", "sint", "accusantium", "unde", "sapiente", "voluptate", "qui", "aspernatur", "laudantium", "soluta", "amet", "quo", "aliquam", "saepe", "culpa", "libero", "ipsa", "dicta", "reiciendis", "nesciunt", "doloribus", "autem", "impedit", "minima", "maiores", "repudiandae", "ipsam", "obcaecati", "ullam", "enim", "totam", "delectus", "ducimus", "quis", "voluptates", "dolores", "molestiae", "harum", "dolorem", "quia", "voluptatem", "molestias", "magni", "distinctio", "omnis", "illum", "dolorum", "voluptatum", "ea", "quas", "quam", "corporis", "quae", "blanditiis", "atque", "deserunt", "laboriosam", "earum", "consequuntur", "hic", "cupiditate", "quibusdam", "accusamus", "ut", "rerum", "error", "minus", "eius", "ab", "ad", "nemo", "fugit", "officia", "at", "in", "id", "quos", "reprehenderit", "numquam", "iste", "fugiat", "sit", "inventore", "beatae", "repellendus", "magnam", "recusandae", "quod", "explicabo", "doloremque", "aperiam", "consequatur", "asperiores", "commodi", "optio", "dolor", "labore", "temporibus", "repellat", "veniam", "architecto", "est", "esse", "mollitia", "nulla", "a", "similique", "eos", "alias", "dolore", "tenetur", "deleniti", "porro", "facere", "maxime", "corrupti", ) COMMON_WORDS = ( "lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipisicing", "elit", "sed", "do", "eiusmod", "tempor", "incididunt", "ut", "labore", "et", "dolore", "magna", "aliqua", ) def sentence(): """ Return a randomly generated sentence of lorem ipsum text. The first word is capitalized, and the sentence ends in either a period or question mark. Commas are added at random. """ # Determine the number of comma-separated sections and number of words in # each section for this sentence. sections = [ " ".join(random.sample(WORDS, random.randint(3, 12))) for i in range(random.randint(1, 5)) ] s = ", ".join(sections) # Convert to sentence case and add end punctuation. return "%s%s%s" % (s[0].upper(), s[1:], random.choice("?.")) def paragraph(): """ Return a randomly generated paragraph of lorem ipsum text. The paragraph consists of between 1 and 4 sentences, inclusive. """ return " ".join(sentence() for i in range(random.randint(1, 4))) def paragraphs(count, common=True): """ Return a list of paragraphs as returned by paragraph(). If `common` is True, then the first paragraph will be the standard 'lorem ipsum' paragraph. Otherwise, the first paragraph will be random Latin text. Either way, subsequent paragraphs will be random Latin text. """ paras = [] for i in range(count): if common and i == 0: paras.append(COMMON_P) else: paras.append(paragraph()) return paras def words(count, common=True): """ Return a string of `count` lorem ipsum words separated by a single space. If `common` is True, then the first 19 words will be the standard 'lorem ipsum' words. Otherwise, all words will be selected randomly. """ word_list = list(COMMON_WORDS) if common else [] c = len(word_list) if count > c: count -= c while count > 0: c = min(count, len(WORDS)) count -= c word_list += random.sample(WORDS, c) else: word_list = word_list[:count] return " ".join(word_list)
import unittest from unittest import mock from django.utils.lorem_ipsum import paragraph, paragraphs, sentence, words class LoremIpsumTests(unittest.TestCase): def test_negative_words(self): """words(n) returns n + 19 words, even if n is negative.""" self.assertEqual( words(-5), "lorem ipsum dolor sit amet consectetur adipisicing elit sed do " "eiusmod tempor incididunt ut", ) def test_same_or_less_common_words(self): """words(n) for n < 19.""" self.assertEqual(words(7), "lorem ipsum dolor sit amet consectetur adipisicing") def test_common_words_in_string(self): """ words(n) starts with the 19 standard lorem ipsum words for n > 19. """ self.assertTrue( words(25).startswith( "lorem ipsum dolor sit amet consectetur adipisicing elit sed " "do eiusmod tempor incididunt ut labore et dolore magna aliqua" ) ) def test_more_words_than_common(self): """words(n) returns n words for n > 19.""" self.assertEqual(len(words(25).split()), 25) def test_common_large_number_of_words(self): """words(n) has n words when n is greater than len(WORDS).""" self.assertEqual(len(words(500).split()), 500) @mock.patch("django.utils.lorem_ipsum.random.sample") def test_not_common_words(self, mock_sample): """words(n, common=False) returns random words.""" mock_sample.return_value = ["exercitationem", "perferendis"] self.assertEqual(words(2, common=False), "exercitationem perferendis") def test_sentence_starts_with_capital(self): """A sentence starts with a capital letter.""" self.assertTrue(sentence()[0].isupper()) @mock.patch("django.utils.lorem_ipsum.random.sample") @mock.patch("django.utils.lorem_ipsum.random.choice") @mock.patch("django.utils.lorem_ipsum.random.randint") def test_sentence(self, mock_randint, mock_choice, mock_sample): """ Sentences are built using some number of phrases and a set of words. """ mock_randint.return_value = 2 # Use two phrases. mock_sample.return_value = ["exercitationem", "perferendis"] mock_choice.return_value = "?" value = sentence() self.assertEqual(mock_randint.call_count, 3) self.assertEqual(mock_sample.call_count, 2) self.assertEqual(mock_choice.call_count, 1) self.assertEqual( value, "Exercitationem perferendis, exercitationem perferendis?" ) @mock.patch("django.utils.lorem_ipsum.random.choice") def test_sentence_ending(self, mock_choice): """Sentences end with a question mark or a period.""" mock_choice.return_value = "?" self.assertIn(sentence()[-1], "?") mock_choice.return_value = "." self.assertIn(sentence()[-1], ".") @mock.patch("django.utils.lorem_ipsum.random.sample") @mock.patch("django.utils.lorem_ipsum.random.choice") @mock.patch("django.utils.lorem_ipsum.random.randint") def test_paragraph(self, mock_paragraph_randint, mock_choice, mock_sample): """paragraph() generates a single paragraph.""" # Make creating 2 sentences use 2 phrases. mock_paragraph_randint.return_value = 2 mock_sample.return_value = ["exercitationem", "perferendis"] mock_choice.return_value = "." value = paragraph() self.assertEqual(mock_paragraph_randint.call_count, 7) self.assertEqual( value, ( "Exercitationem perferendis, exercitationem perferendis. " "Exercitationem perferendis, exercitationem perferendis." ), ) @mock.patch("django.utils.lorem_ipsum.random.sample") @mock.patch("django.utils.lorem_ipsum.random.choice") @mock.patch("django.utils.lorem_ipsum.random.randint") def test_paragraphs_not_common(self, mock_randint, mock_choice, mock_sample): """ paragraphs(1, common=False) generating one paragraph that's not the COMMON_P paragraph. """ # Make creating 2 sentences use 2 phrases. mock_randint.return_value = 2 mock_sample.return_value = ["exercitationem", "perferendis"] mock_choice.return_value = "." self.assertEqual( paragraphs(1, common=False), [ "Exercitationem perferendis, exercitationem perferendis. " "Exercitationem perferendis, exercitationem perferendis." ], ) self.assertEqual(mock_randint.call_count, 7) def test_paragraphs(self): """paragraphs(1) uses the COMMON_P paragraph.""" self.assertEqual( paragraphs(1), [ "Lorem ipsum dolor sit amet, consectetur adipisicing elit, " "sed do eiusmod tempor incididunt ut labore et dolore magna " "aliqua. Ut enim ad minim veniam, quis nostrud exercitation " "ullamco laboris nisi ut aliquip ex ea commodo consequat. " "Duis aute irure dolor in reprehenderit in voluptate velit " "esse cillum dolore eu fugiat nulla pariatur. Excepteur sint " "occaecat cupidatat non proident, sunt in culpa qui officia " "deserunt mollit anim id est laborum." ], )
django
python
import codecs import datetime import locale from decimal import Decimal from types import NoneType from urllib.parse import quote from django.utils.functional import Promise class DjangoUnicodeDecodeError(UnicodeDecodeError): def __str__(self): return "%s. You passed in %r (%s)" % ( super().__str__(), self.object, type(self.object), ) def smart_str(s, encoding="utf-8", strings_only=False, errors="strict"): """ Return a string representing 's'. Treat bytestrings using the 'encoding' codec. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, Promise): # The input is the result of a gettext_lazy() call. return s return force_str(s, encoding, strings_only, errors) _PROTECTED_TYPES = ( NoneType, int, float, Decimal, datetime.datetime, datetime.date, datetime.time, ) def is_protected_type(obj): """Determine if the object instance is of a protected type. Objects of protected types are preserved as-is when passed to force_str(strings_only=True). """ return isinstance(obj, _PROTECTED_TYPES) def force_str(s, encoding="utf-8", strings_only=False, errors="strict"): """ Similar to smart_str(), except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the common case first for performance reasons. if issubclass(type(s), str): return s if strings_only and is_protected_type(s): return s try: if isinstance(s, bytes): s = str(s, encoding, errors) else: s = str(s) except UnicodeDecodeError as e: raise DjangoUnicodeDecodeError(*e.args) from None return s def smart_bytes(s, encoding="utf-8", strings_only=False, errors="strict"): """ Return a bytestring version of 's', encoded as specified in 'encoding'. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, Promise): # The input is the result of a gettext_lazy() call. return s return force_bytes(s, encoding, strings_only, errors) def force_bytes(s, encoding="utf-8", strings_only=False, errors="strict"): """ Similar to smart_bytes, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the common case first for performance reasons. if isinstance(s, bytes): if encoding == "utf-8": return s else: return s.decode("utf-8", errors).encode(encoding, errors) if strings_only and is_protected_type(s): return s if isinstance(s, memoryview): return bytes(s) return str(s).encode(encoding, errors) def iri_to_uri(iri): """ Convert an Internationalized Resource Identifier (IRI) portion to a URI portion that is suitable for inclusion in a URL. This is the algorithm from RFC 3987 Section 3.1, slightly simplified since the input is assumed to be a string rather than an arbitrary byte stream. Take an IRI (string or UTF-8 bytes, e.g. '/I ♥ Django/' or b'/I \xe2\x99\xa5 Django/') and return a string containing the encoded result with ASCII chars only (e.g. '/I%20%E2%99%A5%20Django/'). """ # The list of safe characters here is constructed from the "reserved" and # "unreserved" characters specified in RFC 3986 Sections 2.2 and 2.3: # reserved = gen-delims / sub-delims # gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@" # sub-delims = "!" / "$" / "&" / "'" / "(" / ")" # / "*" / "+" / "," / ";" / "=" # unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" # Of the unreserved characters, urllib.parse.quote() already considers all # but the ~ safe. # The % character is also added to the list of safe characters here, as the # end of RFC 3987 Section 3.1 specifically mentions that % must not be # converted. if iri is None: return iri elif isinstance(iri, Promise): iri = str(iri) return quote(iri, safe="/#%[]=:;$&()+,!?*@'~") # List of byte values that uri_to_iri() decodes from percent encoding. # First, the unreserved characters from RFC 3986: _ascii_ranges = [[45, 46, 95, 126], range(65, 91), range(97, 123)] _hextobyte = { (fmt % char).encode(): bytes((char,)) for ascii_range in _ascii_ranges for char in ascii_range for fmt in ["%02x", "%02X"] } # And then everything above 128, because bytes ≥ 128 are part of multibyte # Unicode characters. _hexdig = "0123456789ABCDEFabcdef" _hextobyte.update( {(a + b).encode(): bytes.fromhex(a + b) for a in _hexdig[8:] for b in _hexdig} ) def uri_to_iri(uri): """ Convert a Uniform Resource Identifier(URI) into an Internationalized Resource Identifier(IRI). This is the algorithm from RFC 3987 Section 3.2, excluding step 4. Take an URI in ASCII bytes (e.g. '/I%20%E2%99%A5%20Django/') and return a string containing the encoded result (e.g. '/I%20♥%20Django/'). """ if uri is None: return uri uri = force_bytes(uri) # Fast selective unquote: First, split on '%' and then starting with the # second block, decode the first 2 bytes if they represent a hex code to # decode. The rest of the block is the part after '%AB', not containing # any '%'. Add that to the output without further processing. bits = uri.split(b"%") if len(bits) == 1: iri = uri else: parts = [bits[0]] append = parts.append hextobyte = _hextobyte for item in bits[1:]: hex = item[:2] if hex in hextobyte: append(hextobyte[item[:2]]) append(item[2:]) else: append(b"%") append(item) iri = b"".join(parts) return repercent_broken_unicode(iri).decode() def escape_uri_path(path): """ Escape the unsafe characters from the path portion of a Uniform Resource Identifier (URI). """ # These are the "reserved" and "unreserved" characters specified in RFC # 3986 Sections 2.2 and 2.3: # reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," # unreserved = alphanum | mark # mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")" # The list of safe characters here is constructed subtracting ";", "=", # and "?" according to RFC 3986 Section 3.3. # The reason for not subtracting and escaping "/" is that we are escaping # the entire path, not a path segment. return quote(path, safe="/:@&+$,-_.!~*'()") def punycode(domain): """Return the Punycode of the given domain if it's non-ASCII.""" return domain.encode("idna").decode("ascii") def repercent_broken_unicode(path): """ As per RFC 3987 Section 3.2, step three of converting a URI into an IRI, repercent-encode any octet produced that is not part of a strictly legal UTF-8 octet sequence. """ changed_parts = [] while True: try: path.decode() except UnicodeDecodeError as e: # CVE-2019-14235: A recursion shouldn't be used since the exception # handling uses massive amounts of memory repercent = quote(path[e.start : e.end], safe=b"/#%[]=:;$&()+,!?*@'~") changed_parts.append(path[: e.start] + repercent.encode()) path = path[e.end :] else: return b"".join(changed_parts) + path def filepath_to_uri(path): """Convert a file system path to a URI portion that is suitable for inclusion in a URL. Encode certain chars that would normally be recognized as special chars for URIs. Do not encode the ' character, as it is a valid character within URIs. See the encodeURIComponent() JavaScript function for details. """ if path is None: return path # I know about `os.sep` and `os.altsep` but I want to leave # some flexibility for hardcoding separators. return quote(str(path).replace("\\", "/"), safe="/~!*()'") def get_system_encoding(): """ The encoding for the character type functions. Fallback to 'ascii' if the #encoding is unsupported by Python or could not be determined. See tickets #10335 and #5846. """ try: encoding = locale.getlocale()[1] or "ascii" codecs.lookup(encoding) except Exception: encoding = "ascii" return encoding DEFAULT_LOCALE_ENCODING = get_system_encoding()
import datetime import inspect import sys import unittest from pathlib import Path from unittest import mock from urllib.parse import quote, quote_plus from django.test import SimpleTestCase from django.utils.encoding import ( DjangoUnicodeDecodeError, escape_uri_path, filepath_to_uri, force_bytes, force_str, get_system_encoding, iri_to_uri, repercent_broken_unicode, smart_bytes, smart_str, uri_to_iri, ) from django.utils.functional import SimpleLazyObject from django.utils.translation import gettext_lazy from django.utils.version import PYPY class TestEncodingUtils(SimpleTestCase): def test_force_str_exception(self): """ Broken __str__ actually raises an error. """ class MyString: def __str__(self): return b"\xc3\xb6\xc3\xa4\xc3\xbc" # str(s) raises a TypeError if the result is not a text type. with self.assertRaises(TypeError): force_str(MyString()) def test_force_str_lazy(self): s = SimpleLazyObject(lambda: "x") self.assertIs(type(force_str(s)), str) def test_force_str_DjangoUnicodeDecodeError(self): reason = "unexpected end of data" if PYPY else "invalid start byte" msg = ( f"'utf-8' codec can't decode byte 0xff in position 0: {reason}. " "You passed in b'\\xff' (<class 'bytes'>)" ) with self.assertRaisesMessage(DjangoUnicodeDecodeError, msg): force_str(b"\xff") def test_force_bytes_exception(self): """ force_bytes knows how to convert to bytes an exception containing non-ASCII characters in its args. """ error_msg = "This is an exception, voilà" exc = ValueError(error_msg) self.assertEqual(force_bytes(exc), error_msg.encode()) self.assertEqual( force_bytes(exc, encoding="ascii", errors="ignore"), b"This is an exception, voil", ) def test_force_bytes_strings_only(self): today = datetime.date.today() self.assertEqual(force_bytes(today, strings_only=True), today) def test_force_bytes_encoding(self): error_msg = "This is an exception, voilà".encode() result = force_bytes(error_msg, encoding="ascii", errors="ignore") self.assertEqual(result, b"This is an exception, voil") def test_force_bytes_memory_view(self): data = b"abc" result = force_bytes(memoryview(data)) # Type check is needed because memoryview(bytes) == bytes. self.assertIs(type(result), bytes) self.assertEqual(result, data) def test_smart_bytes(self): class Test: def __str__(self): return "ŠĐĆŽćžšđ" lazy_func = gettext_lazy("x") self.assertIs(smart_bytes(lazy_func), lazy_func) self.assertEqual( smart_bytes(Test()), b"\xc5\xa0\xc4\x90\xc4\x86\xc5\xbd\xc4\x87\xc5\xbe\xc5\xa1\xc4\x91", ) self.assertEqual(smart_bytes(1), b"1") self.assertEqual(smart_bytes("foo"), b"foo") def test_smart_str(self): class Test: def __str__(self): return "ŠĐĆŽćžšđ" lazy_func = gettext_lazy("x") self.assertIs(smart_str(lazy_func), lazy_func) self.assertEqual( smart_str(Test()), "\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" ) self.assertEqual(smart_str(1), "1") self.assertEqual(smart_str("foo"), "foo") def test_get_default_encoding(self): with mock.patch("locale.getlocale", side_effect=Exception): self.assertEqual(get_system_encoding(), "ascii") def test_repercent_broken_unicode_recursion_error(self): # Prepare a string long enough to force a recursion error if the tested # function uses recursion. data = b"\xfc" * sys.getrecursionlimit() try: self.assertEqual( repercent_broken_unicode(data), b"%FC" * sys.getrecursionlimit() ) except RecursionError: self.fail("Unexpected RecursionError raised.") def test_repercent_broken_unicode_small_fragments(self): data = b"test\xfctest\xfctest\xfc" decoded_paths = [] def mock_quote(*args, **kwargs): # The second frame is the call to repercent_broken_unicode(). decoded_paths.append(inspect.currentframe().f_back.f_locals["path"]) return quote(*args, **kwargs) with mock.patch("django.utils.encoding.quote", mock_quote): self.assertEqual(repercent_broken_unicode(data), b"test%FCtest%FCtest%FC") # decode() is called on smaller fragment of the path each time. self.assertEqual( decoded_paths, [b"test\xfctest\xfctest\xfc", b"test\xfctest\xfc", b"test\xfc"], ) class TestRFC3987IEncodingUtils(unittest.TestCase): def test_filepath_to_uri(self): self.assertIsNone(filepath_to_uri(None)) self.assertEqual( filepath_to_uri("upload\\чубака.mp4"), "upload/%D1%87%D1%83%D0%B1%D0%B0%D0%BA%D0%B0.mp4", ) self.assertEqual(filepath_to_uri(Path("upload/test.png")), "upload/test.png") self.assertEqual(filepath_to_uri(Path("upload\\test.png")), "upload/test.png") def test_iri_to_uri(self): cases = [ # Valid UTF-8 sequences are encoded. ("red%09rosé#red", "red%09ros%C3%A9#red"), ("/blog/for/Jürgen Münster/", "/blog/for/J%C3%BCrgen%20M%C3%BCnster/"), ( "locations/%s" % quote_plus("Paris & Orléans"), "locations/Paris+%26+Orl%C3%A9ans", ), # Reserved chars remain unescaped. ("%&", "%&"), ("red&♥ros%#red", "red&%E2%99%A5ros%#red"), (gettext_lazy("red&♥ros%#red"), "red&%E2%99%A5ros%#red"), ] for iri, uri in cases: with self.subTest(iri): self.assertEqual(iri_to_uri(iri), uri) # Test idempotency. self.assertEqual(iri_to_uri(iri_to_uri(iri)), uri) def test_uri_to_iri(self): cases = [ (None, None), # Valid UTF-8 sequences are decoded. ("/%e2%89%Ab%E2%99%a5%E2%89%aB/", "/≫♥≫/"), ("/%E2%99%A5%E2%99%A5/?utf8=%E2%9C%93", "/♥♥/?utf8=✓"), ("/%41%5a%6B/", "/AZk/"), # Reserved and non-URL valid ASCII chars are not decoded. ("/%25%20%02%41%7b/", "/%25%20%02A%7b/"), # Broken UTF-8 sequences remain escaped. ("/%AAd%AAj%AAa%AAn%AAg%AAo%AA/", "/%AAd%AAj%AAa%AAn%AAg%AAo%AA/"), ("/%E2%99%A5%E2%E2%99%A5/", "/♥%E2♥/"), ("/%E2%99%A5%E2%99%E2%99%A5/", "/♥%E2%99♥/"), ("/%E2%E2%99%A5%E2%99%A5%99/", "/%E2♥♥%99/"), ( "/%E2%99%A5%E2%99%A5/?utf8=%9C%93%E2%9C%93%9C%93", "/♥♥/?utf8=%9C%93✓%9C%93", ), ] for uri, iri in cases: with self.subTest(uri): self.assertEqual(uri_to_iri(uri), iri) # Test idempotency. self.assertEqual(uri_to_iri(uri_to_iri(uri)), iri) def test_complementarity(self): cases = [ ( "/blog/for/J%C3%BCrgen%20M%C3%BCnster/", "/blog/for/J\xfcrgen%20M\xfcnster/", ), ("%&", "%&"), ("red&%E2%99%A5ros%#red", "red&♥ros%#red"), ("/%E2%99%A5%E2%99%A5/", "/♥♥/"), ("/%E2%99%A5%E2%99%A5/?utf8=%E2%9C%93", "/♥♥/?utf8=✓"), ("/%25%20%02%7b/", "/%25%20%02%7b/"), ("/%AAd%AAj%AAa%AAn%AAg%AAo%AA/", "/%AAd%AAj%AAa%AAn%AAg%AAo%AA/"), ("/%E2%99%A5%E2%E2%99%A5/", "/♥%E2♥/"), ("/%E2%99%A5%E2%99%E2%99%A5/", "/♥%E2%99♥/"), ("/%E2%E2%99%A5%E2%99%A5%99/", "/%E2♥♥%99/"), ( "/%E2%99%A5%E2%99%A5/?utf8=%9C%93%E2%9C%93%9C%93", "/♥♥/?utf8=%9C%93✓%9C%93", ), ] for uri, iri in cases: with self.subTest(uri): self.assertEqual(iri_to_uri(uri_to_iri(uri)), uri) self.assertEqual(uri_to_iri(iri_to_uri(iri)), iri) def test_escape_uri_path(self): cases = [ ( "/;some/=awful/?path/:with/@lots/&of/+awful/chars", "/%3Bsome/%3Dawful/%3Fpath/:with/@lots/&of/+awful/chars", ), ("/foo#bar", "/foo%23bar"), ("/foo?bar", "/foo%3Fbar"), ] for uri, expected in cases: with self.subTest(uri): self.assertEqual(escape_uri_path(uri), expected)
django
python
""" Functions for reversing a regular expression (used in reverse URL resolving). Used internally by Django and not intended for external use. This is not, and is not intended to be, a complete reg-exp decompiler. It should be good enough for a large class of URLS, however. """ import re from django.utils.functional import SimpleLazyObject # Mapping of an escape character to a representative of that class. So, e.g., # "\w" is replaced by "x" in a reverse URL. A value of None means to ignore # this sequence. Any missing key is mapped to itself. ESCAPE_MAPPINGS = { "A": None, "b": None, "B": None, "d": "0", "D": "x", "s": " ", "S": "x", "w": "x", "W": "!", "Z": None, } class Choice(list): """Represent multiple possibilities at this point in a pattern string.""" class Group(list): """Represent a capturing group in the pattern string.""" class NonCapture(list): """Represent a non-capturing group in the pattern string.""" def normalize(pattern): r""" Given a reg-exp pattern, normalize it to an iterable of forms that suffice for reverse matching. This does the following: (1) For any repeating sections, keeps the minimum number of occurrences permitted (this means zero for optional groups). (2) If an optional group includes parameters, include one occurrence of that group (along with the zero occurrence case from step (1)). (3) Select the first (essentially an arbitrary) element from any character class. Select an arbitrary character for any unordered class (e.g. '.' or '\w') in the pattern. (4) Ignore look-ahead and look-behind assertions. (5) Raise an error on any disjunctive ('|') constructs. Django's URLs for forward resolving are either all positional arguments or all keyword arguments. That is assumed here, as well. Although reverse resolving can be done using positional args when keyword args are specified, the two cannot be mixed in the same reverse() call. """ # Do a linear scan to work out the special features of this pattern. The # idea is that we scan once here and collect all the information we need to # make future decisions. result = [] non_capturing_groups = [] consume_next = True pattern_iter = next_char(iter(pattern)) num_args = 0 # A "while" loop is used here because later on we need to be able to peek # at the next character and possibly go around without consuming another # one at the top of the loop. try: ch, escaped = next(pattern_iter) except StopIteration: return [("", [])] try: while True: if escaped: result.append(ch) elif ch == ".": # Replace "any character" with an arbitrary representative. result.append(".") elif ch == "|": # FIXME: One day we'll should do this, but not in 1.0. raise NotImplementedError("Awaiting Implementation") elif ch == "^": pass elif ch == "$": break elif ch == ")": # This can only be the end of a non-capturing group, since all # other unescaped parentheses are handled by the grouping # section later (and the full group is handled there). # # We regroup everything inside the capturing group so that it # can be quantified, if necessary. start = non_capturing_groups.pop() inner = NonCapture(result[start:]) result = result[:start] + [inner] elif ch == "[": # Replace ranges with the first character in the range. ch, escaped = next(pattern_iter) result.append(ch) ch, escaped = next(pattern_iter) while escaped or ch != "]": ch, escaped = next(pattern_iter) elif ch == "(": # Some kind of group. ch, escaped = next(pattern_iter) if ch != "?" or escaped: # A positional group name = "_%d" % num_args num_args += 1 result.append(Group((("%%(%s)s" % name), name))) walk_to_end(ch, pattern_iter) else: ch, escaped = next(pattern_iter) if ch in "!=<": # All of these are ignorable. Walk to the end of the # group. walk_to_end(ch, pattern_iter) elif ch == ":": # Non-capturing group non_capturing_groups.append(len(result)) elif ch != "P": # Anything else, other than a named group, is something # we cannot reverse. raise ValueError("Non-reversible reg-exp portion: '(?%s'" % ch) else: ch, escaped = next(pattern_iter) if ch not in ("<", "="): raise ValueError( "Non-reversible reg-exp portion: '(?P%s'" % ch ) # We are in a named capturing group. Extra the name and # then skip to the end. if ch == "<": terminal_char = ">" # We are in a named backreference. else: terminal_char = ")" name = [] ch, escaped = next(pattern_iter) while ch != terminal_char: name.append(ch) ch, escaped = next(pattern_iter) param = "".join(name) # Named backreferences have already consumed the # parenthesis. if terminal_char != ")": result.append(Group((("%%(%s)s" % param), param))) walk_to_end(ch, pattern_iter) else: result.append(Group((("%%(%s)s" % param), None))) elif ch in "*?+{": # Quantifiers affect the previous item in the result list. count, ch = get_quantifier(ch, pattern_iter) if ch: # We had to look ahead, but it wasn't need to compute the # quantifier, so use this character next time around the # main loop. consume_next = False if count == 0: if contains(result[-1], Group): # If we are quantifying a capturing group (or # something containing such a group) and the minimum is # zero, we must also handle the case of one occurrence # being present. All the quantifiers (except {0,0}, # which we conveniently ignore) that have a 0 minimum # also allow a single occurrence. result[-1] = Choice([None, result[-1]]) else: result.pop() elif count > 1: result.extend([result[-1]] * (count - 1)) else: # Anything else is a literal. result.append(ch) if consume_next: ch, escaped = next(pattern_iter) consume_next = True except StopIteration: pass except NotImplementedError: # A case of using the disjunctive form. No results for you! return [("", [])] return list(zip(*flatten_result(result))) def next_char(input_iter): r""" An iterator that yields the next character from "pattern_iter", respecting escape sequences. An escaped character is replaced by a representative of its class (e.g. \w -> "x"). If the escaped character is one that is skipped, it is not returned (the next character is returned instead). Yield the next character, along with a boolean indicating whether it is a raw (unescaped) character or not. """ for ch in input_iter: if ch != "\\": yield ch, False continue ch = next(input_iter) representative = ESCAPE_MAPPINGS.get(ch, ch) if representative is None: continue yield representative, True def walk_to_end(ch, input_iter): """ The iterator is currently inside a capturing group. Walk to the close of this group, skipping over any nested groups and handling escaped parentheses correctly. """ if ch == "(": nesting = 1 else: nesting = 0 for ch, escaped in input_iter: if escaped: continue elif ch == "(": nesting += 1 elif ch == ")": if not nesting: return nesting -= 1 def get_quantifier(ch, input_iter): """ Parse a quantifier from the input, where "ch" is the first character in the quantifier. Return the minimum number of occurrences permitted by the quantifier and either None or the next character from the input_iter if the next character is not part of the quantifier. """ if ch in "*?+": try: ch2, escaped = next(input_iter) except StopIteration: ch2 = None if ch2 == "?": ch2 = None if ch == "+": return 1, ch2 return 0, ch2 quant = [] while ch != "}": ch, escaped = next(input_iter) quant.append(ch) quant = quant[:-1] values = "".join(quant).split(",") # Consume the trailing '?', if necessary. try: ch, escaped = next(input_iter) except StopIteration: ch = None if ch == "?": ch = None return int(values[0]), ch def contains(source, inst): """ Return True if the "source" contains an instance of "inst". False, otherwise. """ if isinstance(source, inst): return True if isinstance(source, NonCapture): for elt in source: if contains(elt, inst): return True return False def flatten_result(source): """ Turn the given source sequence into a list of reg-exp possibilities and their arguments. Return a list of strings and a list of argument lists. Each of the two lists will be of the same length. """ if source is None: return [""], [[]] if isinstance(source, Group): if source[1] is None: params = [] else: params = [source[1]] return [source[0]], [params] result = [""] result_args = [[]] pos = last = 0 for pos, elt in enumerate(source): if isinstance(elt, str): continue piece = "".join(source[last:pos]) if isinstance(elt, Group): piece += elt[0] param = elt[1] else: param = None last = pos + 1 for i in range(len(result)): result[i] += piece if param: result_args[i].append(param) if isinstance(elt, (Choice, NonCapture)): if isinstance(elt, NonCapture): elt = [elt] inner_result, inner_args = [], [] for item in elt: res, args = flatten_result(item) inner_result.extend(res) inner_args.extend(args) new_result = [] new_args = [] for item, args in zip(result, result_args): for i_item, i_args in zip(inner_result, inner_args): new_result.append(item + i_item) new_args.append(args[:] + i_args) result = new_result result_args = new_args if pos >= last: piece = "".join(source[last:]) for i in range(len(result)): result[i] += piece return result, result_args def _lazy_re_compile(regex, flags=0): """Lazily compile a regex with flags.""" def _compile(): # Compile the regex if it was not passed pre-compiled. if isinstance(regex, (str, bytes)): return re.compile(regex, flags) else: assert not flags, "flags must be empty if regex is passed pre-compiled" return regex return SimpleLazyObject(_compile)
import re import unittest from django.test import SimpleTestCase from django.utils import regex_helper class NormalizeTests(unittest.TestCase): def test_empty(self): pattern = r"" expected = [("", [])] result = regex_helper.normalize(pattern) self.assertEqual(result, expected) def test_escape(self): pattern = r"\\\^\$\.\|\?\*\+\(\)\[" expected = [("\\^$.|?*+()[", [])] result = regex_helper.normalize(pattern) self.assertEqual(result, expected) def test_group_positional(self): pattern = r"(.*)-(.+)" expected = [("%(_0)s-%(_1)s", ["_0", "_1"])] result = regex_helper.normalize(pattern) self.assertEqual(result, expected) def test_group_noncapturing(self): pattern = r"(?:non-capturing)" expected = [("non-capturing", [])] result = regex_helper.normalize(pattern) self.assertEqual(result, expected) def test_group_named(self): pattern = r"(?P<first_group_name>.*)-(?P<second_group_name>.*)" expected = [ ( "%(first_group_name)s-%(second_group_name)s", ["first_group_name", "second_group_name"], ) ] result = regex_helper.normalize(pattern) self.assertEqual(result, expected) def test_group_backreference(self): pattern = r"(?P<first_group_name>.*)-(?P=first_group_name)" expected = [("%(first_group_name)s-%(first_group_name)s", ["first_group_name"])] result = regex_helper.normalize(pattern) self.assertEqual(result, expected) class LazyReCompileTests(SimpleTestCase): def test_flags_with_pre_compiled_regex(self): test_pattern = re.compile("test") lazy_test_pattern = regex_helper._lazy_re_compile(test_pattern, re.I) msg = "flags must be empty if regex is passed pre-compiled" with self.assertRaisesMessage(AssertionError, msg): lazy_test_pattern.match("TEST")
django
python
import datetime def _get_duration_components(duration): days = duration.days seconds = duration.seconds microseconds = duration.microseconds minutes = seconds // 60 seconds %= 60 hours = minutes // 60 minutes %= 60 return days, hours, minutes, seconds, microseconds def duration_string(duration): """Version of str(timedelta) which is not English specific.""" days, hours, minutes, seconds, microseconds = _get_duration_components(duration) string = "{:02d}:{:02d}:{:02d}".format(hours, minutes, seconds) if days: string = "{} ".format(days) + string if microseconds: string += ".{:06d}".format(microseconds) return string def duration_iso_string(duration): if duration < datetime.timedelta(0): sign = "-" duration *= -1 else: sign = "" days, hours, minutes, seconds, microseconds = _get_duration_components(duration) ms = ".{:06d}".format(microseconds) if microseconds else "" return "{}P{}DT{:02d}H{:02d}M{:02d}{}S".format( sign, days, hours, minutes, seconds, ms ) def duration_microseconds(delta): return (24 * 60 * 60 * delta.days + delta.seconds) * 1000000 + delta.microseconds
import datetime import unittest from django.utils.dateparse import parse_duration from django.utils.duration import ( duration_iso_string, duration_microseconds, duration_string, ) class TestDurationString(unittest.TestCase): def test_simple(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5) self.assertEqual(duration_string(duration), "01:03:05") def test_days(self): duration = datetime.timedelta(days=1, hours=1, minutes=3, seconds=5) self.assertEqual(duration_string(duration), "1 01:03:05") def test_microseconds(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5, microseconds=12345) self.assertEqual(duration_string(duration), "01:03:05.012345") def test_negative(self): duration = datetime.timedelta(days=-1, hours=1, minutes=3, seconds=5) self.assertEqual(duration_string(duration), "-1 01:03:05") class TestParseDurationRoundtrip(unittest.TestCase): def test_simple(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5) self.assertEqual(parse_duration(duration_string(duration)), duration) def test_days(self): duration = datetime.timedelta(days=1, hours=1, minutes=3, seconds=5) self.assertEqual(parse_duration(duration_string(duration)), duration) def test_microseconds(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5, microseconds=12345) self.assertEqual(parse_duration(duration_string(duration)), duration) def test_negative(self): duration = datetime.timedelta(days=-1, hours=1, minutes=3, seconds=5) self.assertEqual(parse_duration(duration_string(duration)), duration) class TestISODurationString(unittest.TestCase): def test_simple(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5) self.assertEqual(duration_iso_string(duration), "P0DT01H03M05S") def test_days(self): duration = datetime.timedelta(days=1, hours=1, minutes=3, seconds=5) self.assertEqual(duration_iso_string(duration), "P1DT01H03M05S") def test_microseconds(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5, microseconds=12345) self.assertEqual(duration_iso_string(duration), "P0DT01H03M05.012345S") def test_negative(self): duration = -1 * datetime.timedelta(days=1, hours=1, minutes=3, seconds=5) self.assertEqual(duration_iso_string(duration), "-P1DT01H03M05S") class TestParseISODurationRoundtrip(unittest.TestCase): def test_simple(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5) self.assertEqual(parse_duration(duration_iso_string(duration)), duration) def test_days(self): duration = datetime.timedelta(days=1, hours=1, minutes=3, seconds=5) self.assertEqual(parse_duration(duration_iso_string(duration)), duration) def test_microseconds(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5, microseconds=12345) self.assertEqual(parse_duration(duration_iso_string(duration)), duration) def test_negative(self): duration = datetime.timedelta(days=-1, hours=1, minutes=3, seconds=5) self.assertEqual( parse_duration(duration_iso_string(duration)).total_seconds(), duration.total_seconds(), ) class TestDurationMicroseconds(unittest.TestCase): def test(self): deltas = [ datetime.timedelta.max, datetime.timedelta.min, datetime.timedelta.resolution, -datetime.timedelta.resolution, datetime.timedelta(microseconds=8999999999999999), ] for delta in deltas: with self.subTest(delta=delta): self.assertEqual( datetime.timedelta(microseconds=duration_microseconds(delta)), delta )
django
python
import itertools import logging import os import signal import subprocess import sys import threading import time import traceback import weakref from collections import defaultdict from functools import lru_cache, wraps from pathlib import Path from types import ModuleType from zipimport import zipimporter import django from django.apps import apps from django.core.signals import request_finished from django.dispatch import Signal from django.utils.functional import cached_property from django.utils.version import get_version_tuple autoreload_started = Signal() file_changed = Signal() DJANGO_AUTORELOAD_ENV = "RUN_MAIN" logger = logging.getLogger("django.utils.autoreload") # If an error is raised while importing a file, it's not placed in sys.modules. # This means that any future modifications aren't caught. Keep a list of these # file paths to allow watching them in the future. _error_files = [] _exception = None try: import termios except ImportError: termios = None try: import pywatchman except ImportError: pywatchman = None def is_django_module(module): """Return True if the given module is nested under Django.""" return module.__name__.startswith("django.") def is_django_path(path): """Return True if the given file path is nested under Django.""" return Path(django.__file__).parent in Path(path).parents def check_errors(fn): @wraps(fn) def wrapper(*args, **kwargs): global _exception try: fn(*args, **kwargs) except Exception: _exception = sys.exc_info() et, ev, tb = _exception if getattr(ev, "filename", None) is None: # get the filename from the last item in the stack filename = traceback.extract_tb(tb)[-1][0] else: filename = ev.filename if filename not in _error_files: _error_files.append(filename) raise return wrapper def raise_last_exception(): if _exception is not None: raise _exception[1] def ensure_echo_on(): """ Ensure that echo mode is enabled. Some tools such as PDB disable it which causes usability issues after reload. """ if not termios or not sys.stdin.isatty(): return attr_list = termios.tcgetattr(sys.stdin) if not attr_list[3] & termios.ECHO: attr_list[3] |= termios.ECHO if hasattr(signal, "SIGTTOU"): old_handler = signal.signal(signal.SIGTTOU, signal.SIG_IGN) else: old_handler = None termios.tcsetattr(sys.stdin, termios.TCSANOW, attr_list) if old_handler is not None: signal.signal(signal.SIGTTOU, old_handler) def iter_all_python_module_files(): # This is a hot path during reloading. Create a stable sorted list of # modules based on the module name and pass it to iter_modules_and_files(). # This ensures cached results are returned in the usual case that modules # aren't loaded on the fly. keys = sorted(sys.modules) modules = tuple( m for m in map(sys.modules.__getitem__, keys) if not isinstance(m, weakref.ProxyTypes) ) return iter_modules_and_files(modules, frozenset(_error_files)) @lru_cache(maxsize=1) def iter_modules_and_files(modules, extra_files): """Iterate through all modules needed to be watched.""" sys_file_paths = [] for module in modules: # During debugging (with PyDev) the 'typing.io' and 'typing.re' objects # are added to sys.modules, however they are types not modules and so # cause issues here. if not isinstance(module, ModuleType): continue if module.__name__ in ("__main__", "__mp_main__"): # __main__ (usually manage.py) doesn't always have a __spec__ set. # Handle this by falling back to using __file__, resolved below. # See https://docs.python.org/reference/import.html#main-spec # __file__ may not exists, e.g. when running ipdb debugger. if hasattr(module, "__file__"): sys_file_paths.append(module.__file__) continue if getattr(module, "__spec__", None) is None: continue spec = module.__spec__ # Modules could be loaded from places without a concrete location. If # this is the case, skip them. if spec.has_location: origin = ( spec.loader.archive if isinstance(spec.loader, zipimporter) else spec.origin ) sys_file_paths.append(origin) results = set() for filename in itertools.chain(sys_file_paths, extra_files): if not filename: continue path = Path(filename) try: if not path.exists(): # The module could have been removed, don't fail loudly if this # is the case. continue except ValueError as e: # Network filesystems may return null bytes in file paths. logger.debug('"%s" raised when resolving path: "%s"', e, path) continue resolved_path = path.resolve().absolute() results.add(resolved_path) return frozenset(results) @lru_cache(maxsize=1) def common_roots(paths): """ Return a tuple of common roots that are shared between the given paths. File system watchers operate on directories and aren't cheap to create. Try to find the minimum set of directories to watch that encompass all of the files that need to be watched. """ # Inspired from Werkzeug: # https://github.com/pallets/werkzeug/blob/7477be2853df70a022d9613e765581b9411c3c39/werkzeug/_reloader.py # Create a sorted list of the path components, longest first. path_parts = sorted([x.parts for x in paths], key=len, reverse=True) tree = {} for chunks in path_parts: node = tree # Add each part of the path to the tree. for chunk in chunks: node = node.setdefault(chunk, {}) # Clear the last leaf in the tree. node.clear() # Turn the tree into a list of Path instances. def _walk(node, path): for prefix, child in node.items(): yield from _walk(child, [*path, prefix]) if not node: yield Path(*path) return tuple(_walk(tree, ())) def sys_path_directories(): """ Yield absolute directories from sys.path, ignoring entries that don't exist. """ for path in sys.path: path = Path(path) if not path.exists(): continue resolved_path = path.resolve().absolute() # If the path is a file (like a zip file), watch the parent directory. if resolved_path.is_file(): yield resolved_path.parent else: yield resolved_path def get_child_arguments(): """ Return the executable. This contains a workaround for Windows if the executable is reported to not have the .exe extension which can cause bugs on reloading. """ import __main__ py_script = Path(sys.argv[0]) exe_entrypoint = py_script.with_suffix(".exe") args = [sys.executable] + ["-W%s" % o for o in sys.warnoptions] if sys.implementation.name in ("cpython", "pypy"): args.extend( f"-X{key}" if value is True else f"-X{key}={value}" for key, value in sys._xoptions.items() ) # __spec__ is set when the server was started with the `-m` option, # see https://docs.python.org/3/reference/import.html#main-spec # __spec__ may not exist, e.g. when running in a Conda env. if getattr(__main__, "__spec__", None) is not None and not exe_entrypoint.exists(): spec = __main__.__spec__ if (spec.name == "__main__" or spec.name.endswith(".__main__")) and spec.parent: name = spec.parent else: name = spec.name args += ["-m", name] args += sys.argv[1:] elif not py_script.exists(): # sys.argv[0] may not exist for several reasons on Windows. # It may exist with a .exe extension or have a -script.py suffix. if exe_entrypoint.exists(): # Should be executed directly, ignoring sys.executable. return [exe_entrypoint, *sys.argv[1:]] script_entrypoint = py_script.with_name("%s-script.py" % py_script.name) if script_entrypoint.exists(): # Should be executed as usual. return [*args, script_entrypoint, *sys.argv[1:]] raise RuntimeError("Script %s does not exist." % py_script) else: args += sys.argv return args def trigger_reload(filename): logger.info("%s changed, reloading.", filename) sys.exit(3) def restart_with_reloader(): new_environ = {**os.environ, DJANGO_AUTORELOAD_ENV: "true"} orig = getattr(sys, "orig_argv", ()) if any( (arg == "-u") or ( arg.startswith("-") and not arg.startswith(("--", "-X", "-W")) and len(arg) > 2 and arg[1:].isalpha() and "u" in arg ) for arg in orig[1:] ): new_environ.setdefault("PYTHONUNBUFFERED", "1") args = get_child_arguments() while True: p = subprocess.run(args, env=new_environ, close_fds=False) if p.returncode != 3: return p.returncode class BaseReloader: def __init__(self): self.extra_files = set() self.directory_globs = defaultdict(set) self._stop_condition = threading.Event() def watch_dir(self, path, glob): path = Path(path) try: path = path.absolute() except FileNotFoundError: logger.debug( "Unable to watch directory %s as it cannot be resolved.", path, exc_info=True, ) return logger.debug("Watching dir %s with glob %s.", path, glob) self.directory_globs[path].add(glob) def watched_files(self, include_globs=True): """ Yield all files that need to be watched, including module files and files within globs. """ yield from iter_all_python_module_files() yield from self.extra_files if include_globs: for directory, patterns in self.directory_globs.items(): for pattern in patterns: yield from directory.glob(pattern) def wait_for_apps_ready(self, app_reg, django_main_thread): """ Wait until Django reports that the apps have been loaded. If the given thread has terminated before the apps are ready, then a SyntaxError or other non-recoverable error has been raised. In that case, stop waiting for the apps_ready event and continue processing. Return True if the thread is alive and the ready event has been triggered, or False if the thread is terminated while waiting for the event. """ while django_main_thread.is_alive(): if app_reg.ready_event.wait(timeout=0.1): return True else: logger.debug("Main Django thread has terminated before apps are ready.") return False def run(self, django_main_thread): logger.debug("Waiting for apps ready_event.") self.wait_for_apps_ready(apps, django_main_thread) from django.urls import get_resolver # Prevent a race condition where URL modules aren't loaded when the # reloader starts by accessing the urlconf_module property. try: get_resolver().urlconf_module except Exception: # Loading the urlconf can result in errors during development. # If this occurs then swallow the error and continue. pass logger.debug("Apps ready_event triggered. Sending autoreload_started signal.") autoreload_started.send(sender=self) self.run_loop() def run_loop(self): ticker = self.tick() while not self.should_stop: try: next(ticker) except StopIteration: break self.stop() def tick(self): """ This generator is called in a loop from run_loop. It's important that the method takes care of pausing or otherwise waiting for a period of time. This split between run_loop() and tick() is to improve the testability of the reloader implementations by decoupling the work they do from the loop. """ raise NotImplementedError("subclasses must implement tick().") @classmethod def check_availability(cls): raise NotImplementedError("subclasses must implement check_availability().") def notify_file_changed(self, path): results = file_changed.send(sender=self, file_path=path) logger.debug("%s notified as changed. Signal results: %s.", path, results) if not any(res[1] for res in results): trigger_reload(path) # These are primarily used for testing. @property def should_stop(self): return self._stop_condition.is_set() def stop(self): self._stop_condition.set() class StatReloader(BaseReloader): SLEEP_TIME = 1 # Check for changes once per second. def tick(self): mtimes = {} while True: for filepath, mtime in self.snapshot_files(): old_time = mtimes.get(filepath) mtimes[filepath] = mtime if old_time is None: logger.debug("File %s first seen with mtime %s", filepath, mtime) continue elif mtime > old_time: logger.debug( "File %s previous mtime: %s, current mtime: %s", filepath, old_time, mtime, ) self.notify_file_changed(filepath) time.sleep(self.SLEEP_TIME) yield def snapshot_files(self): # watched_files may produce duplicate paths if globs overlap. seen_files = set() for file in self.watched_files(): if file in seen_files: continue try: mtime = file.stat().st_mtime except OSError: # This is thrown when the file does not exist. continue seen_files.add(file) yield file, mtime @classmethod def check_availability(cls): return True class WatchmanUnavailable(RuntimeError): pass class WatchmanReloader(BaseReloader): def __init__(self): self.roots = defaultdict(set) self.processed_request = threading.Event() self.client_timeout = int(os.environ.get("DJANGO_WATCHMAN_TIMEOUT", 5)) super().__init__() @cached_property def client(self): return pywatchman.client(timeout=self.client_timeout) def _watch_root(self, root): # In practice this shouldn't occur, however, it's possible that a # directory that doesn't exist yet is being watched. If it's outside of # sys.path then this will end up a new root. How to handle this isn't # clear: Not adding the root will likely break when subscribing to the # changes, however, as this is currently an internal API, no files # will be being watched outside of sys.path. Fixing this by checking # inside watch_glob() and watch_dir() is expensive, instead this could # could fall back to the StatReloader if this case is detected? For # now, watching its parent, if possible, is sufficient. if not root.exists(): if not root.parent.exists(): logger.warning( "Unable to watch root dir %s as neither it or its parent exist.", root, ) return root = root.parent result = self.client.query("watch-project", str(root.absolute())) if "warning" in result: logger.warning("Watchman warning: %s", result["warning"]) logger.debug("Watchman watch-project result: %s", result) return result["watch"], result.get("relative_path") @lru_cache def _get_clock(self, root): return self.client.query("clock", root)["clock"] def _subscribe(self, directory, name, expression): root, rel_path = self._watch_root(directory) # Only receive notifications of files changing, filtering out other # types like special files: # https://facebook.github.io/watchman/docs/type only_files_expression = [ "allof", ["anyof", ["type", "f"], ["type", "l"]], expression, ] query = { "expression": only_files_expression, "fields": ["name"], "since": self._get_clock(root), "dedup_results": True, } if rel_path: query["relative_root"] = rel_path logger.debug( "Issuing watchman subscription %s, for root %s. Query: %s", name, root, query, ) self.client.query("subscribe", root, name, query) def _subscribe_dir(self, directory, filenames): if not directory.exists(): if not directory.parent.exists(): logger.warning( "Unable to watch directory %s as neither it or its parent exist.", directory, ) return prefix = "files-parent-%s" % directory.name filenames = ["%s/%s" % (directory.name, filename) for filename in filenames] directory = directory.parent expression = ["name", filenames, "wholename"] else: prefix = "files" expression = ["name", filenames] self._subscribe(directory, "%s:%s" % (prefix, directory), expression) def _watch_glob(self, directory, patterns): """ Watch a directory with a specific glob. If the directory doesn't yet exist, attempt to watch the parent directory and amend the patterns to include this. It's important this method isn't called more than one per directory when updating all subscriptions. Subsequent calls will overwrite the named subscription, so it must include all possible glob expressions. """ prefix = "glob" if not directory.exists(): if not directory.parent.exists(): logger.warning( "Unable to watch directory %s as neither it or its parent exist.", directory, ) return prefix = "glob-parent-%s" % directory.name patterns = ["%s/%s" % (directory.name, pattern) for pattern in patterns] directory = directory.parent expression = ["anyof"] for pattern in patterns: expression.append(["match", pattern, "wholename"]) self._subscribe(directory, "%s:%s" % (prefix, directory), expression) def watched_roots(self, watched_files): extra_directories = self.directory_globs.keys() watched_file_dirs = [f.parent for f in watched_files] sys_paths = list(sys_path_directories()) return frozenset((*extra_directories, *watched_file_dirs, *sys_paths)) def _update_watches(self): watched_files = list(self.watched_files(include_globs=False)) found_roots = common_roots(self.watched_roots(watched_files)) logger.debug("Watching %s files", len(watched_files)) logger.debug("Found common roots: %s", found_roots) # Setup initial roots for performance, shortest roots first. for root in sorted(found_roots): self._watch_root(root) for directory, patterns in self.directory_globs.items(): self._watch_glob(directory, patterns) # Group sorted watched_files by their parent directory. sorted_files = sorted(watched_files, key=lambda p: p.parent) for directory, group in itertools.groupby(sorted_files, key=lambda p: p.parent): # These paths need to be relative to the parent directory. self._subscribe_dir( directory, [str(p.relative_to(directory)) for p in group] ) def update_watches(self): try: self._update_watches() except Exception as ex: # If the service is still available, raise the original exception. if self.check_server_status(ex): raise def _check_subscription(self, sub): subscription = self.client.getSubscription(sub) if not subscription: return logger.debug("Watchman subscription %s has results.", sub) for result in subscription: # When using watch-project, it's not simple to get the relative # directory without storing some specific state. Store the full # path to the directory in the subscription name, prefixed by its # type (glob, files). root_directory = Path(result["subscription"].split(":", 1)[1]) logger.debug("Found root directory %s", root_directory) for file in result.get("files", []): self.notify_file_changed(root_directory / file) def request_processed(self, **kwargs): logger.debug("Request processed. Setting update_watches event.") self.processed_request.set() def tick(self): request_finished.connect(self.request_processed) self.update_watches() while True: if self.processed_request.is_set(): self.update_watches() self.processed_request.clear() try: self.client.receive() except pywatchman.SocketTimeout: pass except pywatchman.WatchmanError as ex: logger.debug("Watchman error: %s, checking server status.", ex) self.check_server_status(ex) else: for sub in list(self.client.subs.keys()): self._check_subscription(sub) yield # Protect against busy loops. time.sleep(0.1) def stop(self): self.client.close() super().stop() def check_server_status(self, inner_ex=None): """Return True if the server is available.""" try: self.client.query("version") except Exception: raise WatchmanUnavailable(str(inner_ex)) from inner_ex return True @classmethod def check_availability(cls): if not pywatchman: raise WatchmanUnavailable("pywatchman not installed.") client = pywatchman.client(timeout=0.1) try: result = client.capabilityCheck() except Exception: # The service is down? raise WatchmanUnavailable("Cannot connect to the watchman service.") version = get_version_tuple(result["version"]) # Watchman 4.9 includes multiple improvements to watching project # directories as well as case insensitive filesystems. logger.debug("Watchman version %s", version) if version < (4, 9): raise WatchmanUnavailable("Watchman 4.9 or later is required.") def get_reloader(): """Return the most suitable reloader for this environment.""" try: WatchmanReloader.check_availability() except WatchmanUnavailable: return StatReloader() return WatchmanReloader() def start_django(reloader, main_func, *args, **kwargs): ensure_echo_on() main_func = check_errors(main_func) django_main_thread = threading.Thread( target=main_func, args=args, kwargs=kwargs, name="django-main-thread" ) django_main_thread.daemon = True django_main_thread.start() while not reloader.should_stop: reloader.run(django_main_thread) def run_with_reloader(main_func, *args, **kwargs): signal.signal(signal.SIGTERM, lambda *args: sys.exit(0)) try: if os.environ.get(DJANGO_AUTORELOAD_ENV) == "true": reloader = get_reloader() logger.info( "Watching for file changes with %s", reloader.__class__.__name__ ) start_django(reloader, main_func, *args, **kwargs) else: exit_code = restart_with_reloader() sys.exit(exit_code) except KeyboardInterrupt: pass
import contextlib import os import py_compile import shutil import sys import tempfile import threading import time import types import weakref import zipfile import zoneinfo from importlib import import_module from pathlib import Path from subprocess import CompletedProcess from unittest import mock, skip, skipIf import django.__main__ from django.apps.registry import Apps from django.test import SimpleTestCase from django.test.utils import extend_sys_path from django.utils import autoreload from django.utils.autoreload import WatchmanUnavailable from .test_module import __main__ as test_main from .test_module import main_module as test_main_module from .utils import on_macos_with_hfs class TestIterModulesAndFiles(SimpleTestCase): def import_and_cleanup(self, name): import_module(name) self.addCleanup(lambda: sys.path_importer_cache.clear()) self.addCleanup(lambda: sys.modules.pop(name, None)) def clear_autoreload_caches(self): autoreload.iter_modules_and_files.cache_clear() def assertFileFound(self, filename): # Some temp directories are symlinks. Python resolves these fully while # importing. resolved_filename = filename.resolve(strict=True) self.clear_autoreload_caches() # Test uncached access self.assertIn( resolved_filename, list(autoreload.iter_all_python_module_files()) ) # Test cached access self.assertIn( resolved_filename, list(autoreload.iter_all_python_module_files()) ) self.assertEqual(autoreload.iter_modules_and_files.cache_info().hits, 1) def assertFileNotFound(self, filename): resolved_filename = filename.resolve(strict=True) self.clear_autoreload_caches() # Test uncached access self.assertNotIn( resolved_filename, list(autoreload.iter_all_python_module_files()) ) # Test cached access self.assertNotIn( resolved_filename, list(autoreload.iter_all_python_module_files()) ) self.assertEqual(autoreload.iter_modules_and_files.cache_info().hits, 1) def temporary_file(self, filename): dirname = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, dirname) return Path(dirname) / filename def test_paths_are_pathlib_instances(self): for filename in autoreload.iter_all_python_module_files(): self.assertIsInstance(filename, Path) def test_file_added(self): """ When a file is added, it's returned by iter_all_python_module_files(). """ filename = self.temporary_file("test_deleted_removed_module.py") filename.touch() with extend_sys_path(str(filename.parent)): self.import_and_cleanup("test_deleted_removed_module") self.assertFileFound(filename.absolute()) def test_check_errors(self): """ When a file containing an error is imported in a function wrapped by check_errors(), gen_filenames() returns it. """ filename = self.temporary_file("test_syntax_error.py") filename.write_text("Ceci n'est pas du Python.") with extend_sys_path(str(filename.parent)): try: with self.assertRaises(SyntaxError): autoreload.check_errors(import_module)("test_syntax_error") finally: autoreload._exception = None self.assertFileFound(filename) def test_check_errors_catches_all_exceptions(self): """ Since Python may raise arbitrary exceptions when importing code, check_errors() must catch Exception, not just some subclasses. """ filename = self.temporary_file("test_exception.py") filename.write_text("raise Exception") with extend_sys_path(str(filename.parent)): try: with self.assertRaises(Exception): autoreload.check_errors(import_module)("test_exception") finally: autoreload._exception = None self.assertFileFound(filename) def test_zip_reload(self): """ Modules imported from zipped files have their archive location included in the result. """ zip_file = self.temporary_file("zip_import.zip") with zipfile.ZipFile(str(zip_file), "w", zipfile.ZIP_DEFLATED) as zipf: zipf.writestr("test_zipped_file.py", "") with extend_sys_path(str(zip_file)): self.import_and_cleanup("test_zipped_file") self.assertFileFound(zip_file) def test_bytecode_conversion_to_source(self): """.pyc and .pyo files are included in the files list.""" filename = self.temporary_file("test_compiled.py") filename.touch() compiled_file = Path( py_compile.compile(str(filename), str(filename.with_suffix(".pyc"))) ) filename.unlink() with extend_sys_path(str(compiled_file.parent)): self.import_and_cleanup("test_compiled") self.assertFileFound(compiled_file) def test_weakref_in_sys_module(self): """iter_all_python_module_file() ignores weakref modules.""" time_proxy = weakref.proxy(time) sys.modules["time_proxy"] = time_proxy self.addCleanup(lambda: sys.modules.pop("time_proxy", None)) list(autoreload.iter_all_python_module_files()) # No crash. def test_module_without_spec(self): module = types.ModuleType("test_module") del module.__spec__ self.assertEqual( autoreload.iter_modules_and_files((module,), frozenset()), frozenset() ) def test_main_module_is_resolved(self): main_module = sys.modules["__main__"] self.assertFileFound(Path(main_module.__file__)) def test_main_module_without_file_is_not_resolved(self): fake_main = types.ModuleType("__main__") self.assertEqual( autoreload.iter_modules_and_files((fake_main,), frozenset()), frozenset() ) def test_path_with_embedded_null_bytes(self): for path in ( "embedded_null_byte\x00.py", "di\x00rectory/embedded_null_byte.py", ): with self.subTest(path=path): self.assertEqual( autoreload.iter_modules_and_files((), frozenset([path])), frozenset(), ) class TestChildArguments(SimpleTestCase): @mock.patch.dict(sys.modules, {"__main__": django.__main__}) @mock.patch("sys.argv", [django.__main__.__file__, "runserver"]) @mock.patch("sys.warnoptions", []) @mock.patch("sys._xoptions", {}) def test_run_as_module(self): self.assertEqual( autoreload.get_child_arguments(), [sys.executable, "-m", "django", "runserver"], ) @mock.patch.dict(sys.modules, {"__main__": test_main}) @mock.patch("sys.argv", [test_main.__file__, "runserver"]) @mock.patch("sys.warnoptions", []) @mock.patch("sys._xoptions", {}) def test_run_as_non_django_module(self): self.assertEqual( autoreload.get_child_arguments(), [sys.executable, "-m", "utils_tests.test_module", "runserver"], ) @mock.patch.dict(sys.modules, {"__main__": test_main_module}) @mock.patch("sys.argv", [test_main.__file__, "runserver"]) @mock.patch("sys.warnoptions", []) @mock.patch("sys._xoptions", {}) def test_run_as_non_django_module_non_package(self): self.assertEqual( autoreload.get_child_arguments(), [sys.executable, "-m", "utils_tests.test_module.main_module", "runserver"], ) @mock.patch("__main__.__spec__", None) @mock.patch("sys.argv", [__file__, "runserver"]) @mock.patch("sys.warnoptions", ["error"]) @mock.patch("sys._xoptions", {}) def test_warnoptions(self): self.assertEqual( autoreload.get_child_arguments(), [sys.executable, "-Werror", __file__, "runserver"], ) @mock.patch("sys.argv", [__file__, "runserver"]) @mock.patch("sys.warnoptions", []) @mock.patch("sys._xoptions", {"utf8": True, "a": "b"}) def test_xoptions(self): self.assertEqual( autoreload.get_child_arguments(), [sys.executable, "-Xutf8", "-Xa=b", __file__, "runserver"], ) @mock.patch("__main__.__spec__", None) @mock.patch("sys.warnoptions", []) def test_exe_fallback(self): with tempfile.TemporaryDirectory() as tmpdir: exe_path = Path(tmpdir) / "django-admin.exe" exe_path.touch() with mock.patch("sys.argv", [exe_path.with_suffix(""), "runserver"]): self.assertEqual( autoreload.get_child_arguments(), [exe_path, "runserver"] ) @mock.patch("sys.warnoptions", []) @mock.patch.dict(sys.modules, {"__main__": django.__main__}) def test_use_exe_when_main_spec(self): with tempfile.TemporaryDirectory() as tmpdir: exe_path = Path(tmpdir) / "django-admin.exe" exe_path.touch() with mock.patch("sys.argv", [exe_path.with_suffix(""), "runserver"]): self.assertEqual( autoreload.get_child_arguments(), [exe_path, "runserver"] ) @mock.patch("__main__.__spec__", None) @mock.patch("sys.warnoptions", []) @mock.patch("sys._xoptions", {}) def test_entrypoint_fallback(self): with tempfile.TemporaryDirectory() as tmpdir: script_path = Path(tmpdir) / "django-admin-script.py" script_path.touch() with mock.patch( "sys.argv", [script_path.with_name("django-admin"), "runserver"] ): self.assertEqual( autoreload.get_child_arguments(), [sys.executable, script_path, "runserver"], ) @mock.patch("__main__.__spec__", None) @mock.patch("sys.argv", ["does-not-exist", "runserver"]) @mock.patch("sys.warnoptions", []) def test_raises_runtimeerror(self): msg = "Script does-not-exist does not exist." with self.assertRaisesMessage(RuntimeError, msg): autoreload.get_child_arguments() @mock.patch("sys.argv", [__file__, "runserver"]) @mock.patch("sys.warnoptions", []) @mock.patch("sys._xoptions", {}) def test_module_no_spec(self): module = types.ModuleType("test_module") del module.__spec__ with mock.patch.dict(sys.modules, {"__main__": module}): self.assertEqual( autoreload.get_child_arguments(), [sys.executable, __file__, "runserver"], ) class TestUtilities(SimpleTestCase): def test_is_django_module(self): for module, expected in ((zoneinfo, False), (sys, False), (autoreload, True)): with self.subTest(module=module): self.assertIs(autoreload.is_django_module(module), expected) def test_is_django_path(self): for module, expected in ( (zoneinfo.__file__, False), (contextlib.__file__, False), (autoreload.__file__, True), ): with self.subTest(module=module): self.assertIs(autoreload.is_django_path(module), expected) class TestCommonRoots(SimpleTestCase): def test_common_roots(self): paths = ( Path("/first/second"), Path("/first/second/third"), Path("/first/"), Path("/root/first/"), ) results = autoreload.common_roots(paths) self.assertCountEqual(results, [Path("/first/"), Path("/root/first/")]) class TestSysPathDirectories(SimpleTestCase): def setUp(self): _directory = tempfile.TemporaryDirectory() self.addCleanup(_directory.cleanup) self.directory = Path(_directory.name).resolve(strict=True).absolute() self.file = self.directory / "test" self.file.touch() def test_sys_paths_with_directories(self): with extend_sys_path(str(self.file)): paths = list(autoreload.sys_path_directories()) self.assertIn(self.file.parent, paths) def test_sys_paths_non_existing(self): nonexistent_file = Path(self.directory.name) / "does_not_exist" with extend_sys_path(str(nonexistent_file)): paths = list(autoreload.sys_path_directories()) self.assertNotIn(nonexistent_file, paths) self.assertNotIn(nonexistent_file.parent, paths) def test_sys_paths_absolute(self): paths = list(autoreload.sys_path_directories()) self.assertTrue(all(p.is_absolute() for p in paths)) def test_sys_paths_directories(self): with extend_sys_path(str(self.directory)): paths = list(autoreload.sys_path_directories()) self.assertIn(self.directory, paths) class GetReloaderTests(SimpleTestCase): @mock.patch("django.utils.autoreload.WatchmanReloader") def test_watchman_unavailable(self, mocked_watchman): mocked_watchman.check_availability.side_effect = WatchmanUnavailable self.assertIsInstance(autoreload.get_reloader(), autoreload.StatReloader) @mock.patch.object(autoreload.WatchmanReloader, "check_availability") def test_watchman_available(self, mocked_available): # If WatchmanUnavailable isn't raised, Watchman will be chosen. mocked_available.return_value = None result = autoreload.get_reloader() self.assertIsInstance(result, autoreload.WatchmanReloader) class RunWithReloaderTests(SimpleTestCase): @mock.patch.dict(os.environ, {autoreload.DJANGO_AUTORELOAD_ENV: "true"}) @mock.patch("django.utils.autoreload.get_reloader") def test_swallows_keyboard_interrupt(self, mocked_get_reloader): mocked_get_reloader.side_effect = KeyboardInterrupt() autoreload.run_with_reloader(lambda: None) # No exception @mock.patch.dict(os.environ, {autoreload.DJANGO_AUTORELOAD_ENV: "false"}) @mock.patch("django.utils.autoreload.restart_with_reloader") def test_calls_sys_exit(self, mocked_restart_reloader): mocked_restart_reloader.return_value = 1 with self.assertRaises(SystemExit) as exc: autoreload.run_with_reloader(lambda: None) self.assertEqual(exc.exception.code, 1) @mock.patch.dict(os.environ, {autoreload.DJANGO_AUTORELOAD_ENV: "true"}) @mock.patch("django.utils.autoreload.start_django") @mock.patch("django.utils.autoreload.get_reloader") def test_calls_start_django(self, mocked_reloader, mocked_start_django): mocked_reloader.return_value = mock.sentinel.RELOADER autoreload.run_with_reloader(mock.sentinel.METHOD) self.assertEqual(mocked_start_django.call_count, 1) self.assertSequenceEqual( mocked_start_django.call_args[0], [mock.sentinel.RELOADER, mock.sentinel.METHOD], ) class StartDjangoTests(SimpleTestCase): @mock.patch("django.utils.autoreload.ensure_echo_on") def test_echo_on_called(self, mocked_echo): fake_reloader = mock.MagicMock() autoreload.start_django(fake_reloader, lambda: None) self.assertEqual(mocked_echo.call_count, 1) @mock.patch("django.utils.autoreload.check_errors") def test_check_errors_called(self, mocked_check_errors): fake_method = mock.MagicMock(return_value=None) fake_reloader = mock.MagicMock() autoreload.start_django(fake_reloader, fake_method) self.assertCountEqual(mocked_check_errors.call_args[0], [fake_method]) @mock.patch("threading.Thread") @mock.patch("django.utils.autoreload.check_errors") def test_starts_thread_with_args(self, mocked_check_errors, mocked_thread): fake_reloader = mock.MagicMock() fake_main_func = mock.MagicMock() fake_thread = mock.MagicMock() mocked_check_errors.return_value = fake_main_func mocked_thread.return_value = fake_thread autoreload.start_django(fake_reloader, fake_main_func, 123, abc=123) self.assertEqual(mocked_thread.call_count, 1) self.assertEqual( mocked_thread.call_args[1], { "target": fake_main_func, "args": (123,), "kwargs": {"abc": 123}, "name": "django-main-thread", }, ) self.assertIs(fake_thread.daemon, True) self.assertTrue(fake_thread.start.called) class TestCheckErrors(SimpleTestCase): def test_mutates_error_files(self): fake_method = mock.MagicMock(side_effect=RuntimeError()) wrapped = autoreload.check_errors(fake_method) with mock.patch.object(autoreload, "_error_files") as mocked_error_files: try: with self.assertRaises(RuntimeError): wrapped() finally: autoreload._exception = None self.assertEqual(mocked_error_files.append.call_count, 1) class TestRaiseLastException(SimpleTestCase): @mock.patch("django.utils.autoreload._exception", None) def test_no_exception(self): # Should raise no exception if _exception is None autoreload.raise_last_exception() def test_raises_exception(self): class MyException(Exception): pass # Create an exception try: raise MyException("Test Message") except MyException: exc_info = sys.exc_info() with mock.patch("django.utils.autoreload._exception", exc_info): with self.assertRaisesMessage(MyException, "Test Message"): autoreload.raise_last_exception() def test_raises_custom_exception(self): class MyException(Exception): def __init__(self, msg, extra_context): super().__init__(msg) self.extra_context = extra_context # Create an exception. try: raise MyException("Test Message", "extra context") except MyException: exc_info = sys.exc_info() with mock.patch("django.utils.autoreload._exception", exc_info): with self.assertRaisesMessage(MyException, "Test Message"): autoreload.raise_last_exception() def test_raises_exception_with_context(self): try: raise Exception(2) except Exception as e: try: raise Exception(1) from e except Exception: exc_info = sys.exc_info() with mock.patch("django.utils.autoreload._exception", exc_info): with self.assertRaises(Exception) as cm: autoreload.raise_last_exception() self.assertEqual(cm.exception.args[0], 1) self.assertEqual(cm.exception.__cause__.args[0], 2) class RestartWithReloaderTests(SimpleTestCase): executable = "/usr/bin/python" def patch_autoreload(self, argv): patch_call = mock.patch( "django.utils.autoreload.subprocess.run", return_value=CompletedProcess(argv, 0), ) patches = [ mock.patch("django.utils.autoreload.sys.argv", argv), mock.patch("django.utils.autoreload.sys.executable", self.executable), mock.patch("django.utils.autoreload.sys.warnoptions", ["all"]), mock.patch("django.utils.autoreload.sys._xoptions", {}), ] for p in patches: p.start() self.addCleanup(p.stop) mock_call = patch_call.start() self.addCleanup(patch_call.stop) return mock_call def test_manage_py(self): with tempfile.TemporaryDirectory() as temp_dir: script = Path(temp_dir) / "manage.py" script.touch() argv = [str(script), "runserver"] mock_call = self.patch_autoreload(argv) with mock.patch("__main__.__spec__", None): autoreload.restart_with_reloader() self.assertEqual(mock_call.call_count, 1) self.assertEqual( mock_call.call_args[0][0], [self.executable, "-Wall"] + argv, ) def test_python_m_django(self): main = "/usr/lib/pythonX.Y/site-packages/django/__main__.py" argv = [main, "runserver"] mock_call = self.patch_autoreload(argv) with mock.patch("django.__main__.__file__", main): with mock.patch.dict(sys.modules, {"__main__": django.__main__}): autoreload.restart_with_reloader() self.assertEqual(mock_call.call_count, 1) self.assertEqual( mock_call.call_args[0][0], [self.executable, "-Wall", "-m", "django"] + argv[1:], ) def test_propagates_unbuffered_from_parent(self): for args in ("-u", "-Iuv"): with self.subTest(args=args): with mock.patch.dict(os.environ, {}, clear=True): with tempfile.TemporaryDirectory() as d: script = Path(d) / "manage.py" script.touch() mock_call = self.patch_autoreload([str(script), "runserver"]) with ( mock.patch("__main__.__spec__", None), mock.patch.object( autoreload.sys, "orig_argv", [self.executable, args, str(script), "runserver"], ), ): autoreload.restart_with_reloader() env = mock_call.call_args.kwargs["env"] self.assertEqual(env.get("PYTHONUNBUFFERED"), "1") def test_does_not_propagate_unbuffered_from_parent(self): for args in ( "-Xdev", "-Xfaulthandler", "--user", "-Wall", "-Wdefault", "-Wignore::UserWarning", ): with self.subTest(args=args): with mock.patch.dict(os.environ, {}, clear=True): with tempfile.TemporaryDirectory() as d: script = Path(d) / "manage.py" script.touch() mock_call = self.patch_autoreload([str(script), "runserver"]) with ( mock.patch("__main__.__spec__", None), mock.patch.object( autoreload.sys, "orig_argv", [self.executable, args, str(script), "runserver"], ), ): autoreload.restart_with_reloader() env = mock_call.call_args.kwargs["env"] self.assertIsNone(env.get("PYTHONUNBUFFERED")) class ReloaderTests(SimpleTestCase): RELOADER_CLS = None def setUp(self): _tempdir = tempfile.TemporaryDirectory() self.tempdir = Path(_tempdir.name).resolve(strict=True).absolute() self.existing_file = self.ensure_file(self.tempdir / "test.py") self.nonexistent_file = (self.tempdir / "does_not_exist.py").absolute() self.reloader = self.RELOADER_CLS() self.addCleanup(self.reloader.stop) self.addCleanup(_tempdir.cleanup) def ensure_file(self, path): path.parent.mkdir(exist_ok=True, parents=True) path.touch() # On Linux and Windows updating the mtime of a file using touch() will # set a timestamp value that is in the past, as the time value for the # last kernel tick is used rather than getting the correct absolute # time. # To make testing simpler set the mtime to be the observed time when # this function is called. self.set_mtime(path, time.time()) return path.absolute() def set_mtime(self, fp, value): os.utime(str(fp), (value, value)) def increment_mtime(self, fp, by=1): current_time = time.time() self.set_mtime(fp, current_time + by) @contextlib.contextmanager def tick_twice(self): ticker = self.reloader.tick() next(ticker) yield next(ticker) class IntegrationTests: @mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed") @mock.patch( "django.utils.autoreload.iter_all_python_module_files", return_value=frozenset() ) def test_glob(self, mocked_modules, notify_mock): non_py_file = self.ensure_file(self.tempdir / "non_py_file") self.reloader.watch_dir(self.tempdir, "*.py") with self.tick_twice(): self.increment_mtime(non_py_file) self.increment_mtime(self.existing_file) self.assertEqual(notify_mock.call_count, 1) self.assertCountEqual(notify_mock.call_args[0], [self.existing_file]) @mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed") @mock.patch( "django.utils.autoreload.iter_all_python_module_files", return_value=frozenset() ) def test_multiple_globs(self, mocked_modules, notify_mock): self.ensure_file(self.tempdir / "x.test") self.reloader.watch_dir(self.tempdir, "*.py") self.reloader.watch_dir(self.tempdir, "*.test") with self.tick_twice(): self.increment_mtime(self.existing_file) self.assertEqual(notify_mock.call_count, 1) self.assertCountEqual(notify_mock.call_args[0], [self.existing_file]) @mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed") @mock.patch( "django.utils.autoreload.iter_all_python_module_files", return_value=frozenset() ) def test_overlapping_globs(self, mocked_modules, notify_mock): self.reloader.watch_dir(self.tempdir, "*.py") self.reloader.watch_dir(self.tempdir, "*.p*") with self.tick_twice(): self.increment_mtime(self.existing_file) self.assertEqual(notify_mock.call_count, 1) self.assertCountEqual(notify_mock.call_args[0], [self.existing_file]) @mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed") @mock.patch( "django.utils.autoreload.iter_all_python_module_files", return_value=frozenset() ) def test_glob_recursive(self, mocked_modules, notify_mock): non_py_file = self.ensure_file(self.tempdir / "dir" / "non_py_file") py_file = self.ensure_file(self.tempdir / "dir" / "file.py") self.reloader.watch_dir(self.tempdir, "**/*.py") with self.tick_twice(): self.increment_mtime(non_py_file) self.increment_mtime(py_file) self.assertEqual(notify_mock.call_count, 1) self.assertCountEqual(notify_mock.call_args[0], [py_file]) @mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed") @mock.patch( "django.utils.autoreload.iter_all_python_module_files", return_value=frozenset() ) def test_multiple_recursive_globs(self, mocked_modules, notify_mock): non_py_file = self.ensure_file(self.tempdir / "dir" / "test.txt") py_file = self.ensure_file(self.tempdir / "dir" / "file.py") self.reloader.watch_dir(self.tempdir, "**/*.txt") self.reloader.watch_dir(self.tempdir, "**/*.py") with self.tick_twice(): self.increment_mtime(non_py_file) self.increment_mtime(py_file) self.assertEqual(notify_mock.call_count, 2) self.assertCountEqual( notify_mock.call_args_list, [mock.call(py_file), mock.call(non_py_file)] ) @mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed") @mock.patch( "django.utils.autoreload.iter_all_python_module_files", return_value=frozenset() ) def test_nested_glob_recursive(self, mocked_modules, notify_mock): inner_py_file = self.ensure_file(self.tempdir / "dir" / "file.py") self.reloader.watch_dir(self.tempdir, "**/*.py") self.reloader.watch_dir(inner_py_file.parent, "**/*.py") with self.tick_twice(): self.increment_mtime(inner_py_file) self.assertEqual(notify_mock.call_count, 1) self.assertCountEqual(notify_mock.call_args[0], [inner_py_file]) @mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed") @mock.patch( "django.utils.autoreload.iter_all_python_module_files", return_value=frozenset() ) def test_overlapping_glob_recursive(self, mocked_modules, notify_mock): py_file = self.ensure_file(self.tempdir / "dir" / "file.py") self.reloader.watch_dir(self.tempdir, "**/*.p*") self.reloader.watch_dir(self.tempdir, "**/*.py*") with self.tick_twice(): self.increment_mtime(py_file) self.assertEqual(notify_mock.call_count, 1) self.assertCountEqual(notify_mock.call_args[0], [py_file]) class BaseReloaderTests(ReloaderTests): RELOADER_CLS = autoreload.BaseReloader def test_watch_dir_with_unresolvable_path(self): path = Path("unresolvable_directory") with mock.patch.object(Path, "absolute", side_effect=FileNotFoundError): self.reloader.watch_dir(path, "**/*.mo") self.assertEqual(list(self.reloader.directory_globs), []) def test_watch_with_glob(self): self.reloader.watch_dir(self.tempdir, "*.py") watched_files = list(self.reloader.watched_files()) self.assertIn(self.existing_file, watched_files) def test_watch_files_with_recursive_glob(self): inner_file = self.ensure_file(self.tempdir / "test" / "test.py") self.reloader.watch_dir(self.tempdir, "**/*.py") watched_files = list(self.reloader.watched_files()) self.assertIn(self.existing_file, watched_files) self.assertIn(inner_file, watched_files) def test_run_loop_catches_stopiteration(self): def mocked_tick(): yield with mock.patch.object(self.reloader, "tick", side_effect=mocked_tick) as tick: self.reloader.run_loop() self.assertEqual(tick.call_count, 1) def test_run_loop_stop_and_return(self): def mocked_tick(*args): yield self.reloader.stop() return # Raises StopIteration with mock.patch.object(self.reloader, "tick", side_effect=mocked_tick) as tick: self.reloader.run_loop() self.assertEqual(tick.call_count, 1) def test_wait_for_apps_ready_checks_for_exception(self): app_reg = Apps() app_reg.ready_event.set() # thread.is_alive() is False if it's not started. dead_thread = threading.Thread() self.assertFalse(self.reloader.wait_for_apps_ready(app_reg, dead_thread)) def test_wait_for_apps_ready_without_exception(self): app_reg = Apps() app_reg.ready_event.set() thread = mock.MagicMock() thread.is_alive.return_value = True self.assertTrue(self.reloader.wait_for_apps_ready(app_reg, thread)) def skip_unless_watchman_available(): try: autoreload.WatchmanReloader.check_availability() except WatchmanUnavailable as e: return skip("Watchman unavailable: %s" % e) return lambda func: func @skip_unless_watchman_available() class WatchmanReloaderTests(ReloaderTests, IntegrationTests): RELOADER_CLS = autoreload.WatchmanReloader def setUp(self): super().setUp() # Shorten the timeout to speed up tests. self.reloader.client_timeout = int(os.environ.get("DJANGO_WATCHMAN_TIMEOUT", 2)) def test_watch_glob_ignores_non_existing_directories_two_levels(self): with mock.patch.object(self.reloader, "_subscribe") as mocked_subscribe: self.reloader._watch_glob(self.tempdir / "does_not_exist" / "more", ["*"]) self.assertFalse(mocked_subscribe.called) def test_watch_glob_uses_existing_parent_directories(self): with mock.patch.object(self.reloader, "_subscribe") as mocked_subscribe: self.reloader._watch_glob(self.tempdir / "does_not_exist", ["*"]) self.assertSequenceEqual( mocked_subscribe.call_args[0], [ self.tempdir, "glob-parent-does_not_exist:%s" % self.tempdir, ["anyof", ["match", "does_not_exist/*", "wholename"]], ], ) def test_watch_glob_multiple_patterns(self): with mock.patch.object(self.reloader, "_subscribe") as mocked_subscribe: self.reloader._watch_glob(self.tempdir, ["*", "*.py"]) self.assertSequenceEqual( mocked_subscribe.call_args[0], [ self.tempdir, "glob:%s" % self.tempdir, ["anyof", ["match", "*", "wholename"], ["match", "*.py", "wholename"]], ], ) def test_watched_roots_contains_files(self): paths = self.reloader.watched_roots([self.existing_file]) self.assertIn(self.existing_file.parent, paths) def test_watched_roots_contains_directory_globs(self): self.reloader.watch_dir(self.tempdir, "*.py") paths = self.reloader.watched_roots([]) self.assertIn(self.tempdir, paths) def test_watched_roots_contains_sys_path(self): with extend_sys_path(str(self.tempdir)): paths = self.reloader.watched_roots([]) self.assertIn(self.tempdir, paths) def test_check_server_status(self): self.assertTrue(self.reloader.check_server_status()) def test_check_server_status_raises_error(self): with mock.patch.object(self.reloader.client, "query") as mocked_query: mocked_query.side_effect = Exception() with self.assertRaises(autoreload.WatchmanUnavailable): self.reloader.check_server_status() @mock.patch("pywatchman.client") def test_check_availability(self, mocked_client): mocked_client().capabilityCheck.side_effect = Exception() with self.assertRaisesMessage( WatchmanUnavailable, "Cannot connect to the watchman service" ): self.RELOADER_CLS.check_availability() @mock.patch("pywatchman.client") def test_check_availability_lower_version(self, mocked_client): mocked_client().capabilityCheck.return_value = {"version": "4.8.10"} with self.assertRaisesMessage( WatchmanUnavailable, "Watchman 4.9 or later is required." ): self.RELOADER_CLS.check_availability() def test_pywatchman_not_available(self): with mock.patch.object(autoreload, "pywatchman") as mocked: mocked.__bool__.return_value = False with self.assertRaisesMessage( WatchmanUnavailable, "pywatchman not installed." ): self.RELOADER_CLS.check_availability() def test_update_watches_raises_exceptions(self): class TestException(Exception): pass with mock.patch.object(self.reloader, "_update_watches") as mocked_watches: with mock.patch.object( self.reloader, "check_server_status" ) as mocked_server_status: mocked_watches.side_effect = TestException() mocked_server_status.return_value = True with self.assertRaises(TestException): self.reloader.update_watches() self.assertIsInstance( mocked_server_status.call_args[0][0], TestException ) @mock.patch.dict(os.environ, {"DJANGO_WATCHMAN_TIMEOUT": "10"}) def test_setting_timeout_from_environment_variable(self): self.assertEqual(self.RELOADER_CLS().client_timeout, 10) @skipIf(on_macos_with_hfs(), "These tests do not work with HFS+ as a filesystem") class StatReloaderTests(ReloaderTests, IntegrationTests): RELOADER_CLS = autoreload.StatReloader def setUp(self): super().setUp() # Shorten the sleep time to speed up tests. self.reloader.SLEEP_TIME = 0.01 @mock.patch("django.utils.autoreload.StatReloader.notify_file_changed") def test_tick_does_not_trigger_twice(self, mock_notify_file_changed): with mock.patch.object( self.reloader, "watched_files", return_value=[self.existing_file] ): ticker = self.reloader.tick() next(ticker) self.increment_mtime(self.existing_file) next(ticker) next(ticker) self.assertEqual(mock_notify_file_changed.call_count, 1) def test_snapshot_files_ignores_missing_files(self): with mock.patch.object( self.reloader, "watched_files", return_value=[self.nonexistent_file] ): self.assertEqual(dict(self.reloader.snapshot_files()), {}) def test_snapshot_files_updates(self): with mock.patch.object( self.reloader, "watched_files", return_value=[self.existing_file] ): snapshot1 = dict(self.reloader.snapshot_files()) self.assertIn(self.existing_file, snapshot1) self.increment_mtime(self.existing_file) snapshot2 = dict(self.reloader.snapshot_files()) self.assertNotEqual( snapshot1[self.existing_file], snapshot2[self.existing_file] ) def test_snapshot_files_with_duplicates(self): with mock.patch.object( self.reloader, "watched_files", return_value=[self.existing_file, self.existing_file], ): snapshot = list(self.reloader.snapshot_files()) self.assertEqual(len(snapshot), 1) self.assertEqual(snapshot[0][0], self.existing_file)
django
python
""" Django's standard crypto functions and utilities. """ import hashlib import hmac import secrets from django.conf import settings from django.utils.encoding import force_bytes class InvalidAlgorithm(ValueError): """Algorithm is not supported by hashlib.""" pass def salted_hmac(key_salt, value, secret=None, *, algorithm="sha1"): """ Return the HMAC of 'value', using a key generated from key_salt and a secret (which defaults to settings.SECRET_KEY). Default algorithm is SHA1, but any algorithm name supported by hashlib can be passed. A different key_salt should be passed in for every application of HMAC. """ if secret is None: secret = settings.SECRET_KEY key_salt = force_bytes(key_salt) secret = force_bytes(secret) try: hasher = getattr(hashlib, algorithm) except AttributeError as e: raise InvalidAlgorithm( "%r is not an algorithm accepted by the hashlib module." % algorithm ) from e # We need to generate a derived key from our base key. We can do this by # passing the key_salt and our base key through a pseudo-random function. key = hasher(key_salt + secret).digest() # If len(key_salt + secret) > block size of the hash algorithm, the above # line is redundant and could be replaced by key = key_salt + secret, since # the hmac module does the same thing for keys longer than the block size. # However, we need to ensure that we *always* do this. return hmac.new(key, msg=force_bytes(value), digestmod=hasher) RANDOM_STRING_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" def get_random_string(length, allowed_chars=RANDOM_STRING_CHARS): """ Return a securely generated random string. The bit length of the returned value can be calculated with the formula: log_2(len(allowed_chars)^length) For example, with default `allowed_chars` (26+26+10), this gives: * length: 12, bit length =~ 71 bits * length: 22, bit length =~ 131 bits """ return "".join(secrets.choice(allowed_chars) for i in range(length)) def constant_time_compare(val1, val2): """Return True if the two strings are equal, False otherwise.""" return secrets.compare_digest(force_bytes(val1), force_bytes(val2)) def pbkdf2(password, salt, iterations, dklen=0, digest=None): """Return the hash of password using pbkdf2.""" if digest is None: digest = hashlib.sha256 dklen = dklen or None password = force_bytes(password) salt = force_bytes(salt) return hashlib.pbkdf2_hmac(digest().name, password, salt, iterations, dklen)
import hashlib import unittest from django.test import SimpleTestCase from django.utils.crypto import ( InvalidAlgorithm, constant_time_compare, pbkdf2, salted_hmac, ) class TestUtilsCryptoMisc(SimpleTestCase): def test_constant_time_compare(self): # It's hard to test for constant time, just test the result. self.assertTrue(constant_time_compare(b"spam", b"spam")) self.assertFalse(constant_time_compare(b"spam", b"eggs")) self.assertTrue(constant_time_compare("spam", "spam")) self.assertFalse(constant_time_compare("spam", "eggs")) self.assertTrue(constant_time_compare(b"spam", "spam")) self.assertFalse(constant_time_compare("spam", b"eggs")) self.assertTrue(constant_time_compare("ありがとう", "ありがとう")) self.assertFalse(constant_time_compare("ありがとう", "おはよう")) def test_salted_hmac(self): tests = [ ((b"salt", b"value"), {}, "b51a2e619c43b1ca4f91d15c57455521d71d61eb"), (("salt", "value"), {}, "b51a2e619c43b1ca4f91d15c57455521d71d61eb"), ( ("salt", "value"), {"secret": "abcdefg"}, "8bbee04ccddfa24772d1423a0ba43bd0c0e24b76", ), ( ("salt", "value"), {"secret": "x" * hashlib.sha1().block_size}, "bd3749347b412b1b0a9ea65220e55767ac8e96b0", ), ( ("salt", "value"), {"algorithm": "sha256"}, "ee0bf789e4e009371a5372c90f73fcf17695a8439c9108b0480f14e347b3f9ec", ), ( ("salt", "value"), { "algorithm": "blake2b", "secret": "x" * hashlib.blake2b().block_size, }, "fc6b9800a584d40732a07fa33fb69c35211269441823bca431a143853c32f" "e836cf19ab881689528ede647dac412170cd5d3407b44c6d0f44630690c54" "ad3d58", ), ] for args, kwargs, digest in tests: with self.subTest(args=args, kwargs=kwargs): self.assertEqual(salted_hmac(*args, **kwargs).hexdigest(), digest) def test_invalid_algorithm(self): msg = "'whatever' is not an algorithm accepted by the hashlib module." with self.assertRaisesMessage(InvalidAlgorithm, msg): salted_hmac("salt", "value", algorithm="whatever") class TestUtilsCryptoPBKDF2(unittest.TestCase): # https://tools.ietf.org/html/draft-josefsson-pbkdf2-test-vectors-06 rfc_vectors = [ { "args": { "password": "password", "salt": "salt", "iterations": 1, "dklen": 20, "digest": hashlib.sha1, }, "result": "0c60c80f961f0e71f3a9b524af6012062fe037a6", }, { "args": { "password": "password", "salt": "salt", "iterations": 2, "dklen": 20, "digest": hashlib.sha1, }, "result": "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957", }, { "args": { "password": "password", "salt": "salt", "iterations": 4096, "dklen": 20, "digest": hashlib.sha1, }, "result": "4b007901b765489abead49d926f721d065a429c1", }, # # this takes way too long :( # { # "args": { # "password": "password", # "salt": "salt", # "iterations": 16777216, # "dklen": 20, # "digest": hashlib.sha1, # }, # "result": "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984", # }, { "args": { "password": "passwordPASSWORDpassword", "salt": "saltSALTsaltSALTsaltSALTsaltSALTsalt", "iterations": 4096, "dklen": 25, "digest": hashlib.sha1, }, "result": "3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038", }, { "args": { "password": "pass\0word", "salt": "sa\0lt", "iterations": 4096, "dklen": 16, "digest": hashlib.sha1, }, "result": "56fa6aa75548099dcc37d7f03425e0c3", }, ] regression_vectors = [ { "args": { "password": "password", "salt": "salt", "iterations": 1, "dklen": 20, "digest": hashlib.sha256, }, "result": "120fb6cffcf8b32c43e7225256c4f837a86548c9", }, { "args": { "password": "password", "salt": "salt", "iterations": 1, "dklen": 20, "digest": hashlib.sha512, }, "result": "867f70cf1ade02cff3752599a3a53dc4af34c7a6", }, { "args": { "password": "password", "salt": "salt", "iterations": 1000, "dklen": 0, "digest": hashlib.sha512, }, "result": ( "afe6c5530785b6cc6b1c6453384731bd5ee432ee" "549fd42fb6695779ad8a1c5bf59de69c48f774ef" "c4007d5298f9033c0241d5ab69305e7b64eceeb8d" "834cfec" ), }, # Check leading zeros are not stripped (#17481) { "args": { "password": b"\xba", "salt": "salt", "iterations": 1, "dklen": 20, "digest": hashlib.sha1, }, "result": "0053d3b91a7f1e54effebd6d68771e8a6e0b2c5b", }, ] def test_public_vectors(self): for vector in self.rfc_vectors: result = pbkdf2(**vector["args"]) self.assertEqual(result.hex(), vector["result"]) def test_regression_vectors(self): for vector in self.regression_vectors: result = pbkdf2(**vector["args"]) self.assertEqual(result.hex(), vector["result"]) def test_default_hmac_alg(self): kwargs = { "password": b"password", "salt": b"salt", "iterations": 1, "dklen": 20, } self.assertEqual( pbkdf2(**kwargs), hashlib.pbkdf2_hmac(hash_name=hashlib.sha256().name, **kwargs), )
django
python
""" termcolors.py """ color_names = ("black", "red", "green", "yellow", "blue", "magenta", "cyan", "white") foreground = {color_names[x]: "3%s" % x for x in range(8)} background = {color_names[x]: "4%s" % x for x in range(8)} RESET = "0" opt_dict = { "bold": "1", "underscore": "4", "blink": "5", "reverse": "7", "conceal": "8", } def colorize(text="", opts=(), **kwargs): """ Return your text, enclosed in ANSI graphics codes. Depends on the keyword arguments 'fg' and 'bg', and the contents of the opts tuple/list. Return the RESET code if no parameters are given. Valid colors: 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white' Valid options: 'bold' 'underscore' 'blink' 'reverse' 'conceal' 'noreset' - string will not be auto-terminated with the RESET code Examples: colorize('hello', fg='red', bg='blue', opts=('blink',)) colorize() colorize('goodbye', opts=('underscore',)) print(colorize('first line', fg='red', opts=('noreset',))) print('this should be red too') print(colorize('and so should this')) print('this should not be red') """ code_list = [] if text == "" and len(opts) == 1 and opts[0] == "reset": return "\x1b[%sm" % RESET for k, v in kwargs.items(): if k == "fg": code_list.append(foreground[v]) elif k == "bg": code_list.append(background[v]) for o in opts: if o in opt_dict: code_list.append(opt_dict[o]) if "noreset" not in opts: text = "%s\x1b[%sm" % (text or "", RESET) return "%s%s" % (("\x1b[%sm" % ";".join(code_list)), text or "") def make_style(opts=(), **kwargs): """ Return a function with default parameters for colorize() Example: bold_red = make_style(opts=('bold',), fg='red') print(bold_red('hello')) KEYWORD = make_style(fg='yellow') COMMENT = make_style(fg='blue', opts=('bold',)) """ return lambda text: colorize(text, opts, **kwargs) NOCOLOR_PALETTE = "nocolor" DARK_PALETTE = "dark" LIGHT_PALETTE = "light" PALETTES = { NOCOLOR_PALETTE: { "ERROR": {}, "SUCCESS": {}, "WARNING": {}, "NOTICE": {}, "SQL_FIELD": {}, "SQL_COLTYPE": {}, "SQL_KEYWORD": {}, "SQL_TABLE": {}, "HTTP_INFO": {}, "HTTP_SUCCESS": {}, "HTTP_REDIRECT": {}, "HTTP_NOT_MODIFIED": {}, "HTTP_BAD_REQUEST": {}, "HTTP_NOT_FOUND": {}, "HTTP_SERVER_ERROR": {}, "MIGRATE_HEADING": {}, "MIGRATE_LABEL": {}, }, DARK_PALETTE: { "ERROR": {"fg": "red", "opts": ("bold",)}, "SUCCESS": {"fg": "green", "opts": ("bold",)}, "WARNING": {"fg": "yellow", "opts": ("bold",)}, "NOTICE": {"fg": "red"}, "SQL_FIELD": {"fg": "green", "opts": ("bold",)}, "SQL_COLTYPE": {"fg": "green"}, "SQL_KEYWORD": {"fg": "yellow"}, "SQL_TABLE": {"opts": ("bold",)}, "HTTP_INFO": {"opts": ("bold",)}, "HTTP_SUCCESS": {}, "HTTP_REDIRECT": {"fg": "green"}, "HTTP_NOT_MODIFIED": {"fg": "cyan"}, "HTTP_BAD_REQUEST": {"fg": "red", "opts": ("bold",)}, "HTTP_NOT_FOUND": {"fg": "yellow"}, "HTTP_SERVER_ERROR": {"fg": "magenta", "opts": ("bold",)}, "MIGRATE_HEADING": {"fg": "cyan", "opts": ("bold",)}, "MIGRATE_LABEL": {"opts": ("bold",)}, }, LIGHT_PALETTE: { "ERROR": {"fg": "red", "opts": ("bold",)}, "SUCCESS": {"fg": "green", "opts": ("bold",)}, "WARNING": {"fg": "yellow", "opts": ("bold",)}, "NOTICE": {"fg": "red"}, "SQL_FIELD": {"fg": "green", "opts": ("bold",)}, "SQL_COLTYPE": {"fg": "green"}, "SQL_KEYWORD": {"fg": "blue"}, "SQL_TABLE": {"opts": ("bold",)}, "HTTP_INFO": {"opts": ("bold",)}, "HTTP_SUCCESS": {}, "HTTP_REDIRECT": {"fg": "green", "opts": ("bold",)}, "HTTP_NOT_MODIFIED": {"fg": "green"}, "HTTP_BAD_REQUEST": {"fg": "red", "opts": ("bold",)}, "HTTP_NOT_FOUND": {"fg": "red"}, "HTTP_SERVER_ERROR": {"fg": "magenta", "opts": ("bold",)}, "MIGRATE_HEADING": {"fg": "cyan", "opts": ("bold",)}, "MIGRATE_LABEL": {"opts": ("bold",)}, }, } DEFAULT_PALETTE = DARK_PALETTE def parse_color_setting(config_string): """Parse a DJANGO_COLORS environment variable to produce the system palette The general form of a palette definition is: "palette;role=fg;role=fg/bg;role=fg,option,option;role=fg/bg,option,option" where: palette is a named palette; one of 'light', 'dark', or 'nocolor'. role is a named style used by Django fg is a foreground color. bg is a background color. option is a display options. Specifying a named palette is the same as manually specifying the individual definitions for each role. Any individual definitions following the palette definition will augment the base palette definition. Valid roles: 'error', 'success', 'warning', 'notice', 'sql_field', 'sql_coltype', 'sql_keyword', 'sql_table', 'http_info', 'http_success', 'http_redirect', 'http_not_modified', 'http_bad_request', 'http_not_found', 'http_server_error', 'migrate_heading', 'migrate_label' Valid colors: 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white' Valid options: 'bold', 'underscore', 'blink', 'reverse', 'conceal', 'noreset' """ if not config_string: return PALETTES[DEFAULT_PALETTE] # Split the color configuration into parts parts = config_string.lower().split(";") palette = PALETTES[NOCOLOR_PALETTE].copy() for part in parts: if part in PALETTES: # A default palette has been specified palette.update(PALETTES[part]) elif "=" in part: # Process a palette defining string definition = {} # Break the definition into the role, # plus the list of specific instructions. # The role must be in upper case role, instructions = part.split("=") role = role.upper() styles = instructions.split(",") styles.reverse() # The first instruction can contain a slash # to break apart fg/bg. colors = styles.pop().split("/") colors.reverse() fg = colors.pop() if fg in color_names: definition["fg"] = fg if colors and colors[-1] in color_names: definition["bg"] = colors[-1] # All remaining instructions are options opts = tuple(s for s in styles if s in opt_dict) if opts: definition["opts"] = opts # The nocolor palette has all available roles. # Use that palette as the basis for determining # if the role is valid. if role in PALETTES[NOCOLOR_PALETTE] and definition: palette[role] = definition # If there are no colors specified, return the empty palette. if palette == PALETTES[NOCOLOR_PALETTE]: return None return palette
import unittest from django.utils.termcolors import ( DARK_PALETTE, DEFAULT_PALETTE, LIGHT_PALETTE, NOCOLOR_PALETTE, PALETTES, colorize, parse_color_setting, ) class TermColorTests(unittest.TestCase): def test_empty_string(self): self.assertEqual(parse_color_setting(""), PALETTES[DEFAULT_PALETTE]) def test_simple_palette(self): self.assertEqual(parse_color_setting("light"), PALETTES[LIGHT_PALETTE]) self.assertEqual(parse_color_setting("dark"), PALETTES[DARK_PALETTE]) self.assertIsNone(parse_color_setting("nocolor")) def test_fg(self): self.assertEqual( parse_color_setting("error=green"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) def test_fg_bg(self): self.assertEqual( parse_color_setting("error=green/blue"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue"}), ) def test_fg_opts(self): self.assertEqual( parse_color_setting("error=green,blink"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink",)}), ) self.assertEqual( parse_color_setting("error=green,bold,blink"), dict( PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink", "bold")}, ), ) def test_fg_bg_opts(self): self.assertEqual( parse_color_setting("error=green/blue,blink"), dict( PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue", "opts": ("blink",)}, ), ) self.assertEqual( parse_color_setting("error=green/blue,bold,blink"), dict( PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue", "opts": ("blink", "bold")}, ), ) def test_override_palette(self): self.assertEqual( parse_color_setting("light;error=green"), dict(PALETTES[LIGHT_PALETTE], ERROR={"fg": "green"}), ) def test_override_nocolor(self): self.assertEqual( parse_color_setting("nocolor;error=green"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) def test_reverse_override(self): self.assertEqual( parse_color_setting("error=green;light"), PALETTES[LIGHT_PALETTE] ) def test_multiple_roles(self): self.assertEqual( parse_color_setting("error=green;sql_field=blue"), dict( PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}, SQL_FIELD={"fg": "blue"}, ), ) def test_override_with_multiple_roles(self): self.assertEqual( parse_color_setting("light;error=green;sql_field=blue"), dict( PALETTES[LIGHT_PALETTE], ERROR={"fg": "green"}, SQL_FIELD={"fg": "blue"} ), ) def test_empty_definition(self): self.assertIsNone(parse_color_setting(";")) self.assertEqual(parse_color_setting("light;"), PALETTES[LIGHT_PALETTE]) self.assertIsNone(parse_color_setting(";;;")) def test_empty_options(self): self.assertEqual( parse_color_setting("error=green,"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=green,,,"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=green,,blink,,"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink",)}), ) def test_bad_palette(self): self.assertIsNone(parse_color_setting("unknown")) def test_bad_role(self): self.assertIsNone(parse_color_setting("unknown=")) self.assertIsNone(parse_color_setting("unknown=green")) self.assertEqual( parse_color_setting("unknown=green;sql_field=blue"), dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={"fg": "blue"}), ) def test_bad_color(self): self.assertIsNone(parse_color_setting("error=")) self.assertEqual( parse_color_setting("error=;sql_field=blue"), dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={"fg": "blue"}), ) self.assertIsNone(parse_color_setting("error=unknown")) self.assertEqual( parse_color_setting("error=unknown;sql_field=blue"), dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={"fg": "blue"}), ) self.assertEqual( parse_color_setting("error=green/unknown"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=green/blue/something"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue"}), ) self.assertEqual( parse_color_setting("error=green/blue/something,blink"), dict( PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue", "opts": ("blink",)}, ), ) def test_bad_option(self): self.assertEqual( parse_color_setting("error=green,unknown"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=green,unknown,blink"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink",)}), ) def test_role_case(self): self.assertEqual( parse_color_setting("ERROR=green"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("eRrOr=green"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) def test_color_case(self): self.assertEqual( parse_color_setting("error=GREEN"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=GREEN/BLUE"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue"}), ) self.assertEqual( parse_color_setting("error=gReEn"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=gReEn/bLuE"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue"}), ) def test_opts_case(self): self.assertEqual( parse_color_setting("error=green,BLINK"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink",)}), ) self.assertEqual( parse_color_setting("error=green,bLiNk"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink",)}), ) def test_colorize_empty_text(self): self.assertEqual(colorize(text=None), "\x1b[m\x1b[0m") self.assertEqual(colorize(text=""), "\x1b[m\x1b[0m") self.assertEqual(colorize(text=None, opts=("noreset",)), "\x1b[m") self.assertEqual(colorize(text="", opts=("noreset",)), "\x1b[m") def test_colorize_reset(self): self.assertEqual(colorize(text="", opts=("reset",)), "\x1b[0m") def test_colorize_fg_bg(self): self.assertEqual(colorize(text="Test", fg="red"), "\x1b[31mTest\x1b[0m") self.assertEqual(colorize(text="Test", bg="red"), "\x1b[41mTest\x1b[0m") # Ignored kwarg. self.assertEqual(colorize(text="Test", other="red"), "\x1b[mTest\x1b[0m") def test_colorize_opts(self): self.assertEqual( colorize(text="Test", opts=("bold", "underscore")), "\x1b[1;4mTest\x1b[0m", ) self.assertEqual( colorize(text="Test", opts=("blink",)), "\x1b[5mTest\x1b[0m", ) # Ignored opts. self.assertEqual( colorize(text="Test", opts=("not_an_option",)), "\x1b[mTest\x1b[0m", )
django
python
from functools import wraps from asgiref.sync import iscoroutinefunction def _make_csp_decorator(config_attr_name, config_attr_value): """General CSP override decorator factory.""" if not isinstance(config_attr_value, dict): raise TypeError("CSP config should be a mapping.") def decorator(view_func): @wraps(view_func) async def _wrapped_async_view(request, *args, **kwargs): response = await view_func(request, *args, **kwargs) setattr(response, config_attr_name, config_attr_value) return response @wraps(view_func) def _wrapped_sync_view(request, *args, **kwargs): response = view_func(request, *args, **kwargs) setattr(response, config_attr_name, config_attr_value) return response if iscoroutinefunction(view_func): return _wrapped_async_view return _wrapped_sync_view return decorator def csp_override(config): """Override the Content-Security-Policy header for a view.""" return _make_csp_decorator("_csp_config", config) def csp_report_only_override(config): """Override the Content-Security-Policy-Report-Only header for a view.""" return _make_csp_decorator("_csp_ro_config", config)
from secrets import token_urlsafe from unittest.mock import patch from django.test import SimpleTestCase from django.utils.csp import CSP, LazyNonce, build_policy from django.utils.functional import empty basic_config = { "default-src": [CSP.SELF], } alt_config = { "default-src": [CSP.SELF, CSP.UNSAFE_INLINE], } basic_policy = "default-src 'self'" class CSPConstantsTests(SimpleTestCase): def test_constants(self): self.assertEqual(CSP.NONE, "'none'") self.assertEqual(CSP.REPORT_SAMPLE, "'report-sample'") self.assertEqual(CSP.SELF, "'self'") self.assertEqual(CSP.STRICT_DYNAMIC, "'strict-dynamic'") self.assertEqual(CSP.UNSAFE_EVAL, "'unsafe-eval'") self.assertEqual(CSP.UNSAFE_HASHES, "'unsafe-hashes'") self.assertEqual(CSP.UNSAFE_INLINE, "'unsafe-inline'") self.assertEqual(CSP.WASM_UNSAFE_EVAL, "'wasm-unsafe-eval'") self.assertEqual(CSP.NONCE, "<CSP_NONCE_SENTINEL>") class CSPBuildPolicyTest(SimpleTestCase): def assertPolicyEqual(self, a, b): parts_a = sorted(a.split("; ")) if a is not None else None parts_b = sorted(b.split("; ")) if b is not None else None self.assertEqual(parts_a, parts_b, f"Policies not equal: {a!r} != {b!r}") def test_config_empty(self): self.assertPolicyEqual(build_policy({}), "") def test_config_basic(self): self.assertPolicyEqual(build_policy(basic_config), basic_policy) def test_config_multiple_directives(self): policy = { "default-src": [CSP.SELF], "script-src": [CSP.NONE], } self.assertPolicyEqual( build_policy(policy), "default-src 'self'; script-src 'none'" ) def test_config_value_as_string(self): """ Test that a single value can be passed as a string. """ policy = {"default-src": CSP.SELF} self.assertPolicyEqual(build_policy(policy), "default-src 'self'") def test_config_value_as_tuple(self): """ Test that a tuple can be passed as a value. """ policy = {"default-src": (CSP.SELF, "foo.com")} self.assertPolicyEqual(build_policy(policy), "default-src 'self' foo.com") def test_config_value_as_set(self): """ Test that a set can be passed as a value. Sets are often used in Django settings to ensure uniqueness, however, sets are unordered. The middleware ensures consistency via sorting if a set is passed. """ policy = {"default-src": {CSP.SELF, "foo.com", "bar.com"}} self.assertPolicyEqual( build_policy(policy), "default-src 'self' bar.com foo.com" ) def test_config_value_none(self): """ Test that `None` removes the directive from the policy. Useful in cases where the CSP config is scripted in some way or explicitly not wanting to set a directive. """ policy = {"default-src": [CSP.SELF], "script-src": None} self.assertPolicyEqual(build_policy(policy), basic_policy) def test_config_value_boolean_true(self): policy = {"default-src": [CSP.SELF], "block-all-mixed-content": True} self.assertPolicyEqual( build_policy(policy), "default-src 'self'; block-all-mixed-content" ) def test_config_value_boolean_false(self): policy = {"default-src": [CSP.SELF], "block-all-mixed-content": False} self.assertPolicyEqual(build_policy(policy), basic_policy) def test_config_value_multiple_boolean(self): policy = { "default-src": [CSP.SELF], "block-all-mixed-content": True, "upgrade-insecure-requests": True, } self.assertPolicyEqual( build_policy(policy), "default-src 'self'; block-all-mixed-content; upgrade-insecure-requests", ) def test_config_with_nonce_arg(self): """ Test when the `CSP.NONCE` is not in the defined policy, the nonce argument has no effect. """ self.assertPolicyEqual(build_policy(basic_config, nonce="abc123"), basic_policy) def test_config_with_nonce(self): policy = {"default-src": [CSP.SELF, CSP.NONCE]} self.assertPolicyEqual( build_policy(policy, nonce="abc123"), "default-src 'self' 'nonce-abc123'", ) def test_config_with_multiple_nonces(self): policy = { "default-src": [CSP.SELF, CSP.NONCE], "script-src": [CSP.SELF, CSP.NONCE], } self.assertPolicyEqual( build_policy(policy, nonce="abc123"), "default-src 'self' 'nonce-abc123'; script-src 'self' 'nonce-abc123'", ) def test_config_with_empty_directive(self): policy = {"default-src": []} self.assertPolicyEqual(build_policy(policy), "") class LazyNonceTests(SimpleTestCase): def test_generates_on_usage(self): generated_tokens = [] nonce = LazyNonce() self.assertFalse(nonce) self.assertIs(nonce._wrapped, empty) def memento_token_urlsafe(size): generated_tokens.append(result := token_urlsafe(size)) return result with patch("django.utils.csp.secrets.token_urlsafe", memento_token_urlsafe): # Force usage, similar to template rendering, to generate the # nonce. val = str(nonce) self.assertTrue(nonce) self.assertEqual(nonce, val) self.assertIsInstance(nonce, str) self.assertEqual(len(val), 22) # Based on secrets.token_urlsafe of 16 bytes. self.assertEqual(generated_tokens, [nonce]) # Also test the wrapped value. self.assertEqual(nonce._wrapped, val) def test_returns_same_value(self): nonce = LazyNonce() first = str(nonce) second = str(nonce) self.assertEqual(first, second)
django
python
import functools import inspect import threading from contextlib import contextmanager from django.utils.version import PY314 if PY314: import annotationlib lock = threading.Lock() safe_signature_from_callable = functools.partial( inspect._signature_from_callable, annotation_format=annotationlib.Format.FORWARDREF, ) @functools.lru_cache(maxsize=512) def _get_func_parameters(func, remove_first): # As the annotations are not used in any case, inspect the signature with # FORWARDREF to leave any deferred annotations unevaluated. if PY314: signature = inspect.signature( func, annotation_format=annotationlib.Format.FORWARDREF ) else: signature = inspect.signature(func) parameters = tuple(signature.parameters.values()) if remove_first: parameters = parameters[1:] return parameters def _get_callable_parameters(meth_or_func): is_method = inspect.ismethod(meth_or_func) func = meth_or_func.__func__ if is_method else meth_or_func return _get_func_parameters(func, remove_first=is_method) ARG_KINDS = frozenset( { inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.KEYWORD_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD, } ) def get_func_args(func): params = _get_callable_parameters(func) return [param.name for param in params if param.kind in ARG_KINDS] def get_func_full_args(func): """ Return a list of (argument name, default value) tuples. If the argument does not have a default value, omit it in the tuple. Arguments such as *args and **kwargs are also included. """ params = _get_callable_parameters(func) args = [] for param in params: name = param.name # Ignore 'self' if name == "self": continue if param.kind == inspect.Parameter.VAR_POSITIONAL: name = "*" + name elif param.kind == inspect.Parameter.VAR_KEYWORD: name = "**" + name if param.default != inspect.Parameter.empty: args.append((name, param.default)) else: args.append((name,)) return args def func_accepts_kwargs(func): """Return True if function 'func' accepts keyword arguments **kwargs.""" return any(p for p in _get_callable_parameters(func) if p.kind == p.VAR_KEYWORD) def func_accepts_var_args(func): """ Return True if function 'func' accepts positional arguments *args. """ return any(p for p in _get_callable_parameters(func) if p.kind == p.VAR_POSITIONAL) def method_has_no_args(meth): """Return True if a method only accepts 'self'.""" count = len([p for p in _get_callable_parameters(meth) if p.kind in ARG_KINDS]) return count == 0 if inspect.ismethod(meth) else count == 1 def func_supports_parameter(func, name): return any(param.name == name for param in _get_callable_parameters(func)) def is_module_level_function(func): if not inspect.isfunction(func) or inspect.isbuiltin(func): return False if "<locals>" in func.__qualname__: return False return True @contextmanager def lazy_annotations(): """ inspect.getfullargspec eagerly evaluates type annotations. To add compatibility with Python 3.14+ deferred evaluation, patch the module-level helper to provide the annotation_format that we are using elsewhere. This private helper could be removed when there is an upstream solution for https://github.com/python/cpython/issues/141560. This context manager is not reentrant. """ if not PY314: yield return with lock: original_helper = inspect._signature_from_callable inspect._signature_from_callable = safe_signature_from_callable try: yield finally: inspect._signature_from_callable = original_helper
import subprocess import unittest from typing import TYPE_CHECKING from django.shortcuts import aget_object_or_404 from django.utils import inspect from django.utils.version import PY314 if TYPE_CHECKING: from django.utils.safestring import SafeString class Person: def no_arguments(self): return None def one_argument(self, something): return something def just_args(self, *args): return args def all_kinds(self, name, address="home", age=25, *args, **kwargs): return kwargs @classmethod def cls_all_kinds(cls, name, address="home", age=25, *args, **kwargs): return kwargs class TestInspectMethods(unittest.TestCase): def test_get_callable_parameters(self): self.assertIs( inspect._get_callable_parameters(Person.no_arguments), inspect._get_callable_parameters(Person.no_arguments), ) self.assertIs( inspect._get_callable_parameters(Person().no_arguments), inspect._get_callable_parameters(Person().no_arguments), ) def test_get_func_full_args_no_arguments(self): self.assertEqual(inspect.get_func_full_args(Person.no_arguments), []) self.assertEqual(inspect.get_func_full_args(Person().no_arguments), []) def test_get_func_full_args_one_argument(self): self.assertEqual( inspect.get_func_full_args(Person.one_argument), [("something",)] ) self.assertEqual( inspect.get_func_full_args(Person().one_argument), [("something",)], ) def test_get_func_full_args_all_arguments_method(self): arguments = [ ("name",), ("address", "home"), ("age", 25), ("*args",), ("**kwargs",), ] self.assertEqual(inspect.get_func_full_args(Person.all_kinds), arguments) self.assertEqual(inspect.get_func_full_args(Person().all_kinds), arguments) def test_get_func_full_args_all_arguments_classmethod(self): arguments = [ ("name",), ("address", "home"), ("age", 25), ("*args",), ("**kwargs",), ] self.assertEqual(inspect.get_func_full_args(Person.cls_all_kinds), arguments) self.assertEqual(inspect.get_func_full_args(Person().cls_all_kinds), arguments) def test_func_accepts_var_args_has_var_args(self): self.assertIs(inspect.func_accepts_var_args(Person.just_args), True) self.assertIs(inspect.func_accepts_var_args(Person().just_args), True) def test_func_accepts_var_args_no_var_args(self): self.assertIs(inspect.func_accepts_var_args(Person.one_argument), False) self.assertIs(inspect.func_accepts_var_args(Person().one_argument), False) def test_method_has_no_args(self): self.assertIs(inspect.method_has_no_args(Person.no_arguments), True) self.assertIs(inspect.method_has_no_args(Person().no_arguments), True) self.assertIs(inspect.method_has_no_args(Person.one_argument), False) self.assertIs(inspect.method_has_no_args(Person().one_argument), False) def test_func_supports_parameter(self): self.assertIs( inspect.func_supports_parameter(Person.all_kinds, "address"), True ) self.assertIs( inspect.func_supports_parameter(Person().all_kinds, "address"), True, ) self.assertIs(inspect.func_supports_parameter(Person.all_kinds, "zone"), False) self.assertIs( inspect.func_supports_parameter(Person().all_kinds, "zone"), False, ) def test_func_accepts_kwargs(self): self.assertIs(inspect.func_accepts_kwargs(Person.just_args), False) self.assertIs(inspect.func_accepts_kwargs(Person().just_args), False) self.assertIs(inspect.func_accepts_kwargs(Person.all_kinds), True) self.assertIs(inspect.func_accepts_kwargs(Person().just_args), False) @unittest.skipUnless(PY314, "Deferred annotations are Python 3.14+ only") def test_func_accepts_kwargs_deferred_annotations(self): def func_with_annotations(self, name: str, complex: SafeString) -> None: pass # Inspection fails with deferred annotations with python 3.14+. Earlier # Python versions trigger the NameError on module initialization. self.assertIs(inspect.func_accepts_kwargs(func_with_annotations), False) class IsModuleLevelFunctionTestCase(unittest.TestCase): @classmethod def _class_method(cls) -> None: return None @staticmethod def _static_method() -> None: return None def test_builtin(self): self.assertIs(inspect.is_module_level_function(any), False) self.assertIs(inspect.is_module_level_function(isinstance), False) def test_from_module(self): self.assertIs(inspect.is_module_level_function(subprocess.run), True) self.assertIs(inspect.is_module_level_function(subprocess.check_output), True) self.assertIs( inspect.is_module_level_function(inspect.is_module_level_function), True ) def test_private_function(self): def private_function(): pass self.assertIs(inspect.is_module_level_function(private_function), False) def test_coroutine(self): self.assertIs(inspect.is_module_level_function(aget_object_or_404), True) def test_method(self): self.assertIs(inspect.is_module_level_function(self.test_method), False) self.assertIs(inspect.is_module_level_function(self.setUp), False) def test_unbound_method(self): self.assertIs( inspect.is_module_level_function(self.__class__.test_unbound_method), True ) self.assertIs(inspect.is_module_level_function(self.__class__.setUp), True) def test_lambda(self): self.assertIs(inspect.is_module_level_function(lambda: True), False) def test_class_and_static_method(self): self.assertIs(inspect.is_module_level_function(self._static_method), True) self.assertIs(inspect.is_module_level_function(self._class_method), False)
django
python
""" Syndication feed generation library -- used for generating RSS, etc. Sample usage: >>> from django.utils import feedgenerator >>> feed = feedgenerator.Rss201rev2Feed( ... title="Poynter E-Media Tidbits", ... link="http://www.poynter.org/column.asp?id=31", ... description="A group blog by the sharpest minds in online journalism.", ... language="en", ... ) >>> feed.add_item( ... title="Hello", ... link="http://www.holovaty.com/test/", ... description="Testing." ... ) >>> with open('test.rss', 'w') as fp: ... feed.write(fp, 'utf-8') For definitions of the different versions of RSS, see: https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss """ import datetime import email import mimetypes from io import StringIO from urllib.parse import urlparse from django.forms.utils import flatatt from django.utils.encoding import iri_to_uri from django.utils.xmlutils import SimplerXMLGenerator def rfc2822_date(date): if not isinstance(date, datetime.datetime): date = datetime.datetime.combine(date, datetime.time()) return email.utils.format_datetime(date) def rfc3339_date(date): if not isinstance(date, datetime.datetime): date = datetime.datetime.combine(date, datetime.time()) return date.isoformat() + ("Z" if date.utcoffset() is None else "") def get_tag_uri(url, date): """ Create a TagURI. See https://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id """ bits = urlparse(url) d = "" if date is not None: d = ",%s" % date.strftime("%Y-%m-%d") return "tag:%s%s:%s/%s" % (bits.hostname, d, bits.path, bits.fragment) def _guess_stylesheet_mimetype(url): """ Return the given stylesheet's mimetype tuple, using a slightly custom version of Python's mimetypes.guess_type(). """ mimetypedb = mimetypes.MimeTypes() # The official mimetype for XSLT files is technically # `application/xslt+xml` but as of 2024 almost no browser supports that # (they all expect text/xsl). On top of that, windows seems to assume that # the type for xsl is text/xml. mimetypedb.readfp(StringIO("text/xsl\txsl\ntext/xsl\txslt")) return mimetypedb.guess_type(url) class Stylesheet: """An RSS stylesheet""" def __init__(self, url, mimetype="", media="screen"): self._url = url self._mimetype = mimetype self.media = media # Using a property to delay the evaluation of self._url as late as possible # in case of a lazy object (like reverse_lazy(...) for example). @property def url(self): return iri_to_uri(self._url) @property def mimetype(self): if self._mimetype == "": return _guess_stylesheet_mimetype(self.url)[0] return self._mimetype def __str__(self): attrs = { "href": iri_to_uri(self._url), "type": self.mimetype, "media": self.media, } return flatatt(attrs).strip() def __repr__(self): return repr((self.url, self.mimetype, self.media)) class SyndicationFeed: "Base class for all syndication feeds. Subclasses should provide write()" def __init__( self, title, link, description, language=None, author_email=None, author_name=None, author_link=None, subtitle=None, categories=None, feed_url=None, feed_copyright=None, feed_guid=None, ttl=None, stylesheets=None, **kwargs, ): def to_str(s): return str(s) if s is not None else s def to_stylesheet(s): return s if isinstance(s, Stylesheet) else Stylesheet(s) categories = categories and [str(c) for c in categories] if stylesheets is not None: if isinstance(stylesheets, (Stylesheet, str)): raise TypeError( f"stylesheets should be a list, not {stylesheets.__class__}" ) stylesheets = [to_stylesheet(s) for s in stylesheets] self.feed = { "title": to_str(title), "link": iri_to_uri(link), "description": to_str(description), "language": to_str(language), "author_email": to_str(author_email), "author_name": to_str(author_name), "author_link": iri_to_uri(author_link), "subtitle": to_str(subtitle), "categories": categories or (), "feed_url": iri_to_uri(feed_url), "feed_copyright": to_str(feed_copyright), "id": feed_guid or link, "ttl": to_str(ttl), "stylesheets": stylesheets, **kwargs, } self.items = [] def add_item( self, title, link, description, author_email=None, author_name=None, author_link=None, pubdate=None, comments=None, unique_id=None, unique_id_is_permalink=None, categories=(), item_copyright=None, ttl=None, updateddate=None, enclosures=None, **kwargs, ): """ Add an item to the feed. All args are expected to be strings except pubdate and updateddate, which are datetime.datetime objects, and enclosures, which is an iterable of instances of the Enclosure class. """ def to_str(s): return str(s) if s is not None else s categories = categories and [to_str(c) for c in categories] self.items.append( { "title": to_str(title), "link": iri_to_uri(link), "description": to_str(description), "author_email": to_str(author_email), "author_name": to_str(author_name), "author_link": iri_to_uri(author_link), "pubdate": pubdate, "updateddate": updateddate, "comments": to_str(comments), "unique_id": to_str(unique_id), "unique_id_is_permalink": unique_id_is_permalink, "enclosures": enclosures or (), "categories": categories or (), "item_copyright": to_str(item_copyright), "ttl": to_str(ttl), **kwargs, } ) def num_items(self): return len(self.items) def root_attributes(self): """ Return extra attributes to place on the root (i.e. feed/channel) element. Called from write(). """ return {} def add_root_elements(self, handler): """ Add elements in the root (i.e. feed/channel) element. Called from write(). """ pass def add_stylesheets(self, handler): """ Add stylesheet(s) to the feed. Called from write(). """ pass def item_attributes(self, item): """ Return extra attributes to place on each item (i.e. item/entry) element. """ return {} def add_item_elements(self, handler, item): """ Add elements on each item (i.e. item/entry) element. """ pass def write(self, outfile, encoding): """ Output the feed in the given encoding to outfile, which is a file-like object. Subclasses should override this. """ raise NotImplementedError( "subclasses of SyndicationFeed must provide a write() method" ) def writeString(self, encoding): """ Return the feed in the given encoding as a string. """ s = StringIO() self.write(s, encoding) return s.getvalue() def latest_post_date(self): """ Return the latest item's pubdate or updateddate. If no items have either of these attributes this return the current UTC date/time. """ latest_date = None date_keys = ("updateddate", "pubdate") for item in self.items: for date_key in date_keys: item_date = item.get(date_key) if item_date: if latest_date is None or item_date > latest_date: latest_date = item_date return latest_date or datetime.datetime.now(tz=datetime.UTC) class Enclosure: """An RSS enclosure""" def __init__(self, url, length, mime_type): "All args are expected to be strings" self.length, self.mime_type = length, mime_type self.url = iri_to_uri(url) class RssFeed(SyndicationFeed): content_type = "application/rss+xml; charset=utf-8" def write(self, outfile, encoding): handler = SimplerXMLGenerator(outfile, encoding, short_empty_elements=True) handler.startDocument() # Any stylesheet must come after the start of the document but before # any tag. https://www.w3.org/Style/styling-XML.en.html self.add_stylesheets(handler) handler.startElement("rss", self.rss_attributes()) handler.startElement("channel", self.root_attributes()) self.add_root_elements(handler) self.write_items(handler) self.endChannelElement(handler) handler.endElement("rss") def rss_attributes(self): return { "version": self._version, "xmlns:atom": "http://www.w3.org/2005/Atom", } def write_items(self, handler): for item in self.items: handler.startElement("item", self.item_attributes(item)) self.add_item_elements(handler, item) handler.endElement("item") def add_stylesheets(self, handler): for stylesheet in self.feed["stylesheets"] or []: handler.processingInstruction("xml-stylesheet", stylesheet) def add_root_elements(self, handler): handler.addQuickElement("title", self.feed["title"]) handler.addQuickElement("link", self.feed["link"]) handler.addQuickElement("description", self.feed["description"]) if self.feed["feed_url"] is not None: handler.addQuickElement( "atom:link", None, {"rel": "self", "href": self.feed["feed_url"]} ) if self.feed["language"] is not None: handler.addQuickElement("language", self.feed["language"]) for cat in self.feed["categories"]: handler.addQuickElement("category", cat) if self.feed["feed_copyright"] is not None: handler.addQuickElement("copyright", self.feed["feed_copyright"]) handler.addQuickElement("lastBuildDate", rfc2822_date(self.latest_post_date())) if self.feed["ttl"] is not None: handler.addQuickElement("ttl", self.feed["ttl"]) def endChannelElement(self, handler): handler.endElement("channel") class RssUserland091Feed(RssFeed): _version = "0.91" def add_item_elements(self, handler, item): handler.addQuickElement("title", item["title"]) handler.addQuickElement("link", item["link"]) if item["description"] is not None: handler.addQuickElement("description", item["description"]) class Rss201rev2Feed(RssFeed): # Spec: https://cyber.harvard.edu/rss/rss.html _version = "2.0" def add_item_elements(self, handler, item): handler.addQuickElement("title", item["title"]) handler.addQuickElement("link", item["link"]) if item["description"] is not None: handler.addQuickElement("description", item["description"]) # Author information. if item["author_name"] and item["author_email"]: handler.addQuickElement( "author", "%s (%s)" % (item["author_email"], item["author_name"]) ) elif item["author_email"]: handler.addQuickElement("author", item["author_email"]) elif item["author_name"]: handler.addQuickElement( "dc:creator", item["author_name"], {"xmlns:dc": "http://purl.org/dc/elements/1.1/"}, ) if item["pubdate"] is not None: handler.addQuickElement("pubDate", rfc2822_date(item["pubdate"])) if item["comments"] is not None: handler.addQuickElement("comments", item["comments"]) if item["unique_id"] is not None: guid_attrs = {} if isinstance(item.get("unique_id_is_permalink"), bool): guid_attrs["isPermaLink"] = str(item["unique_id_is_permalink"]).lower() handler.addQuickElement("guid", item["unique_id"], guid_attrs) if item["ttl"] is not None: handler.addQuickElement("ttl", item["ttl"]) # Enclosure. if item["enclosures"]: enclosures = list(item["enclosures"]) if len(enclosures) > 1: raise ValueError( "RSS feed items may only have one enclosure, see " "http://www.rssboard.org/rss-profile#element-channel-item-enclosure" ) enclosure = enclosures[0] handler.addQuickElement( "enclosure", "", { "url": enclosure.url, "length": enclosure.length, "type": enclosure.mime_type, }, ) # Categories. for cat in item["categories"]: handler.addQuickElement("category", cat) class Atom1Feed(SyndicationFeed): # Spec: https://tools.ietf.org/html/rfc4287 content_type = "application/atom+xml; charset=utf-8" ns = "http://www.w3.org/2005/Atom" def write(self, outfile, encoding): handler = SimplerXMLGenerator(outfile, encoding, short_empty_elements=True) handler.startDocument() handler.startElement("feed", self.root_attributes()) self.add_root_elements(handler) self.write_items(handler) handler.endElement("feed") def root_attributes(self): if self.feed["language"] is not None: return {"xmlns": self.ns, "xml:lang": self.feed["language"]} else: return {"xmlns": self.ns} def add_root_elements(self, handler): handler.addQuickElement("title", self.feed["title"]) handler.addQuickElement( "link", "", {"rel": "alternate", "href": self.feed["link"]} ) if self.feed["feed_url"] is not None: handler.addQuickElement( "link", "", {"rel": "self", "href": self.feed["feed_url"]} ) handler.addQuickElement("id", self.feed["id"]) handler.addQuickElement("updated", rfc3339_date(self.latest_post_date())) if self.feed["author_name"] is not None: handler.startElement("author", {}) handler.addQuickElement("name", self.feed["author_name"]) if self.feed["author_email"] is not None: handler.addQuickElement("email", self.feed["author_email"]) if self.feed["author_link"] is not None: handler.addQuickElement("uri", self.feed["author_link"]) handler.endElement("author") if self.feed["subtitle"] is not None: handler.addQuickElement("subtitle", self.feed["subtitle"]) for cat in self.feed["categories"]: handler.addQuickElement("category", "", {"term": cat}) if self.feed["feed_copyright"] is not None: handler.addQuickElement("rights", self.feed["feed_copyright"]) def write_items(self, handler): for item in self.items: handler.startElement("entry", self.item_attributes(item)) self.add_item_elements(handler, item) handler.endElement("entry") def add_item_elements(self, handler, item): handler.addQuickElement("title", item["title"]) handler.addQuickElement("link", "", {"href": item["link"], "rel": "alternate"}) if item["pubdate"] is not None: handler.addQuickElement("published", rfc3339_date(item["pubdate"])) if item["updateddate"] is not None: handler.addQuickElement("updated", rfc3339_date(item["updateddate"])) # Author information. if item["author_name"] is not None: handler.startElement("author", {}) handler.addQuickElement("name", item["author_name"]) if item["author_email"] is not None: handler.addQuickElement("email", item["author_email"]) if item["author_link"] is not None: handler.addQuickElement("uri", item["author_link"]) handler.endElement("author") # Unique ID. if item["unique_id"] is not None: unique_id = item["unique_id"] else: unique_id = get_tag_uri(item["link"], item["pubdate"]) handler.addQuickElement("id", unique_id) # Summary. if item["description"] is not None: handler.addQuickElement("summary", item["description"], {"type": "html"}) # Enclosures. for enclosure in item["enclosures"]: handler.addQuickElement( "link", "", { "rel": "enclosure", "href": enclosure.url, "length": enclosure.length, "type": enclosure.mime_type, }, ) # Categories. for cat in item["categories"]: handler.addQuickElement("category", "", {"term": cat}) # Rights. if item["item_copyright"] is not None: handler.addQuickElement("rights", item["item_copyright"]) # This isolates the decision of what the system default is, so calling code can # do "feedgenerator.DefaultFeed" instead of "feedgenerator.Rss201rev2Feed". DefaultFeed = Rss201rev2Feed
import datetime from unittest import mock from django.test import SimpleTestCase from django.utils import feedgenerator from django.utils.functional import SimpleLazyObject from django.utils.timezone import get_fixed_timezone class FeedgeneratorTests(SimpleTestCase): """ Tests for the low-level syndication feed framework. """ def test_get_tag_uri(self): """ get_tag_uri() correctly generates TagURIs. """ self.assertEqual( feedgenerator.get_tag_uri( "http://example.org/foo/bar#headline", datetime.date(2004, 10, 25) ), "tag:example.org,2004-10-25:/foo/bar/headline", ) def test_get_tag_uri_with_port(self): """ get_tag_uri() correctly generates TagURIs from URLs with port numbers. """ self.assertEqual( feedgenerator.get_tag_uri( "http://www.example.org:8000/2008/11/14/django#headline", datetime.datetime(2008, 11, 14, 13, 37, 0), ), "tag:www.example.org,2008-11-14:/2008/11/14/django/headline", ) def test_rfc2822_date(self): """ rfc2822_date() correctly formats datetime objects. """ self.assertEqual( feedgenerator.rfc2822_date(datetime.datetime(2008, 11, 14, 13, 37, 0)), "Fri, 14 Nov 2008 13:37:00 -0000", ) def test_rfc2822_date_with_timezone(self): """ rfc2822_date() correctly formats datetime objects with tzinfo. """ self.assertEqual( feedgenerator.rfc2822_date( datetime.datetime( 2008, 11, 14, 13, 37, 0, tzinfo=get_fixed_timezone(60) ) ), "Fri, 14 Nov 2008 13:37:00 +0100", ) def test_rfc2822_date_without_time(self): """ rfc2822_date() correctly formats date objects. """ self.assertEqual( feedgenerator.rfc2822_date(datetime.date(2008, 11, 14)), "Fri, 14 Nov 2008 00:00:00 -0000", ) def test_rfc3339_date(self): """ rfc3339_date() correctly formats datetime objects. """ self.assertEqual( feedgenerator.rfc3339_date(datetime.datetime(2008, 11, 14, 13, 37, 0)), "2008-11-14T13:37:00Z", ) def test_rfc3339_date_with_timezone(self): """ rfc3339_date() correctly formats datetime objects with tzinfo. """ self.assertEqual( feedgenerator.rfc3339_date( datetime.datetime( 2008, 11, 14, 13, 37, 0, tzinfo=get_fixed_timezone(120) ) ), "2008-11-14T13:37:00+02:00", ) def test_rfc3339_date_without_time(self): """ rfc3339_date() correctly formats date objects. """ self.assertEqual( feedgenerator.rfc3339_date(datetime.date(2008, 11, 14)), "2008-11-14T00:00:00Z", ) def test_atom1_mime_type(self): """ Atom MIME type has UTF8 Charset parameter set """ atom_feed = feedgenerator.Atom1Feed("title", "link", "description") self.assertEqual(atom_feed.content_type, "application/atom+xml; charset=utf-8") def test_rss_mime_type(self): """ RSS MIME type has UTF8 Charset parameter set """ rss_feed = feedgenerator.Rss201rev2Feed("title", "link", "description") self.assertEqual(rss_feed.content_type, "application/rss+xml; charset=utf-8") # Two regression tests for #14202 def test_feed_without_feed_url_gets_rendered_without_atom_link(self): feed = feedgenerator.Rss201rev2Feed("title", "/link/", "descr") self.assertIsNone(feed.feed["feed_url"]) feed_content = feed.writeString("utf-8") self.assertNotIn("<atom:link", feed_content) self.assertNotIn('href="/feed/"', feed_content) self.assertNotIn('rel="self"', feed_content) def test_feed_with_feed_url_gets_rendered_with_atom_link(self): feed = feedgenerator.Rss201rev2Feed( "title", "/link/", "descr", feed_url="/feed/" ) self.assertEqual(feed.feed["feed_url"], "/feed/") feed_content = feed.writeString("utf-8") self.assertIn("<atom:link", feed_content) self.assertIn('href="/feed/"', feed_content) self.assertIn('rel="self"', feed_content) def test_atom_add_item(self): # Not providing any optional arguments to Atom1Feed.add_item() feed = feedgenerator.Atom1Feed("title", "/link/", "descr") feed.add_item("item_title", "item_link", "item_description") feed.writeString("utf-8") def test_deterministic_attribute_order(self): feed = feedgenerator.Atom1Feed("title", "/link/", "desc") feed_content = feed.writeString("utf-8") self.assertIn('href="/link/" rel="alternate"', feed_content) def test_latest_post_date_returns_utc_time(self): for use_tz in (True, False): with self.settings(USE_TZ=use_tz): rss_feed = feedgenerator.Rss201rev2Feed("title", "link", "description") self.assertEqual( rss_feed.latest_post_date().tzinfo, datetime.UTC, ) def test_stylesheet_keeps_lazy_urls(self): m = mock.Mock(return_value="test.css") stylesheet = feedgenerator.Stylesheet(SimpleLazyObject(m)) m.assert_not_called() self.assertEqual( str(stylesheet), 'href="test.css" media="screen" type="text/css"' ) m.assert_called_once() def test_stylesheet_attribute_escaping(self): style = feedgenerator.Stylesheet( url='http://example.com/style.css?foo="bar"&baz=<>', mimetype='text/css; charset="utf-8"', media='screen and (max-width: "600px")', ) self.assertEqual( str(style), 'href="http://example.com/style.css?foo=%22bar%22&amp;baz=%3C%3E" ' 'media="screen and (max-width: &quot;600px&quot;)" ' 'type="text/css; charset=&quot;utf-8&quot;"', )
django
python
from collections.abc import Callable, Iterable, Iterator, Mapping from itertools import islice, tee, zip_longest from django.utils.functional import Promise __all__ = [ "BaseChoiceIterator", "BlankChoiceIterator", "CallableChoiceIterator", "flatten_choices", "normalize_choices", ] class BaseChoiceIterator: """Base class for lazy iterators for choices.""" def __eq__(self, other): if isinstance(other, Iterable): return all(a == b for a, b in zip_longest(self, other, fillvalue=object())) return super().__eq__(other) def __getitem__(self, index): if isinstance(index, slice) or index < 0: # Suboptimally consume whole iterator to handle slices and negative # indexes. return list(self)[index] try: return next(islice(self, index, index + 1)) except StopIteration: raise IndexError("index out of range") from None def __iter__(self): raise NotImplementedError( "BaseChoiceIterator subclasses must implement __iter__()." ) class BlankChoiceIterator(BaseChoiceIterator): """Iterator to lazily inject a blank choice.""" def __init__(self, choices, blank_choice): self.choices = choices self.blank_choice = blank_choice def __iter__(self): choices, other = tee(self.choices) if not any(value in ("", None) for value, _ in flatten_choices(other)): yield from self.blank_choice yield from choices class CallableChoiceIterator(BaseChoiceIterator): """Iterator to lazily normalize choices generated by a callable.""" def __init__(self, func): self.func = func def __iter__(self): yield from normalize_choices(self.func()) def flatten_choices(choices): """Flatten choices by removing nested values.""" for value_or_group, label_or_nested in choices or (): if isinstance(label_or_nested, (list, tuple)): yield from label_or_nested else: yield value_or_group, label_or_nested def normalize_choices(value, *, depth=0): """Normalize choices values consistently for fields and widgets.""" # Avoid circular import when importing django.forms. from django.db.models.enums import ChoicesType match value: case BaseChoiceIterator() | Promise() | bytes() | str(): # Avoid prematurely normalizing iterators that should be lazy. # Because string-like types are iterable, return early to avoid # iterating over them in the guard for the Iterable case below. return value case ChoicesType(): # Choices enumeration helpers already output in canonical form. return value.choices case Mapping() if depth < 2: value = value.items() case Iterator() if depth < 2: # Although Iterator would be handled by the Iterable case below, # the iterator would be consumed prematurely while checking that # its elements are not string-like in the guard, so we handle it # separately. pass case Iterable() if depth < 2 and not any( isinstance(x, (Promise, bytes, str)) for x in value ): # String-like types are iterable, so the guard above ensures that # they're handled by the default case below. pass case Callable() if depth == 0: # If at the top level, wrap callables to be evaluated lazily. return CallableChoiceIterator(value) case Callable() if depth < 2: value = value() case _: return value try: # Recursive call to convert any nested values to a list of 2-tuples. return [(k, normalize_choices(v, depth=depth + 1)) for k, v in value] except (TypeError, ValueError): # Return original value for the system check to raise if it has items # that are not iterable or not 2-tuples: # - TypeError: cannot unpack non-iterable <type> object # - ValueError: <not enough / too many> values to unpack return value
import collections.abc from unittest import mock from django.db.models import TextChoices from django.test import SimpleTestCase from django.utils.choices import ( BaseChoiceIterator, CallableChoiceIterator, flatten_choices, normalize_choices, ) from django.utils.translation import gettext_lazy as _ class SimpleChoiceIterator(BaseChoiceIterator): def __iter__(self): return ((i, f"Item #{i}") for i in range(1, 4)) class ChoiceIteratorTests(SimpleTestCase): def test_not_implemented_error_on_missing_iter(self): class InvalidChoiceIterator(BaseChoiceIterator): pass # Not overriding __iter__(). msg = "BaseChoiceIterator subclasses must implement __iter__()." with self.assertRaisesMessage(NotImplementedError, msg): iter(InvalidChoiceIterator()) def test_eq(self): unrolled = [(1, "Item #1"), (2, "Item #2"), (3, "Item #3")] self.assertEqual(SimpleChoiceIterator(), unrolled) self.assertEqual(unrolled, SimpleChoiceIterator()) def test_eq_instances(self): self.assertEqual(SimpleChoiceIterator(), SimpleChoiceIterator()) def test_not_equal_subset(self): self.assertNotEqual(SimpleChoiceIterator(), [(1, "Item #1"), (2, "Item #2")]) def test_not_equal_superset(self): self.assertNotEqual( SimpleChoiceIterator(), [(1, "Item #1"), (2, "Item #2"), (3, "Item #3"), None], ) def test_getitem(self): choices = SimpleChoiceIterator() for i, expected in [(0, (1, "Item #1")), (-1, (3, "Item #3"))]: with self.subTest(index=i): self.assertEqual(choices[i], expected) def test_getitem_indexerror(self): choices = SimpleChoiceIterator() for i in (4, -4): with self.subTest(index=i): with self.assertRaises(IndexError) as ctx: choices[i] self.assertTrue(str(ctx.exception).endswith("index out of range")) class FlattenChoicesTests(SimpleTestCase): def test_empty(self): def generator(): yield from () for choices in ({}, [], (), set(), frozenset(), generator(), None, ""): with self.subTest(choices=choices): result = flatten_choices(choices) self.assertIsInstance(result, collections.abc.Generator) self.assertEqual(list(result), []) def test_non_empty(self): choices = [ ("C", _("Club")), ("D", _("Diamond")), ("H", _("Heart")), ("S", _("Spade")), ] result = flatten_choices(choices) self.assertIsInstance(result, collections.abc.Generator) self.assertEqual(list(result), choices) def test_nested_choices(self): choices = [ ("Audio", [("vinyl", _("Vinyl")), ("cd", _("CD"))]), ("Video", [("vhs", _("VHS Tape")), ("dvd", _("DVD"))]), ("unknown", _("Unknown")), ] expected = [ ("vinyl", _("Vinyl")), ("cd", _("CD")), ("vhs", _("VHS Tape")), ("dvd", _("DVD")), ("unknown", _("Unknown")), ] result = flatten_choices(choices) self.assertIsInstance(result, collections.abc.Generator) self.assertEqual(list(result), expected) class NormalizeFieldChoicesTests(SimpleTestCase): expected = [ ("C", _("Club")), ("D", _("Diamond")), ("H", _("Heart")), ("S", _("Spade")), ] expected_nested = [ ("Audio", [("vinyl", _("Vinyl")), ("cd", _("CD"))]), ("Video", [("vhs", _("VHS Tape")), ("dvd", _("DVD"))]), ("unknown", _("Unknown")), ] invalid = [ 1j, 123, 123.45, "invalid", b"invalid", _("invalid"), object(), None, True, False, ] invalid_iterable = [ # Special cases of a string-likes which would unpack incorrectly. ["ab"], [b"ab"], [_("ab")], # Non-iterable items or iterable items with incorrect number of # elements that cannot be unpacked. [123], [("value",)], [("value", "label", "other")], ] invalid_nested = [ # Nested choices can only be two-levels deep, so return callables, # mappings, iterables, etc. at deeper levels unmodified. [("Group", [("Value", lambda: "Label")])], [("Group", [("Value", {"Label 1?": "Label 2?"})])], [("Group", [("Value", [("Label 1?", "Label 2?")])])], ] def test_empty(self): def generator(): yield from () for choices in ({}, [], (), set(), frozenset(), generator()): with self.subTest(choices=choices): self.assertEqual(normalize_choices(choices), []) def test_choices(self): class Medal(TextChoices): GOLD = "GOLD", _("Gold") SILVER = "SILVER", _("Silver") BRONZE = "BRONZE", _("Bronze") expected = [ ("GOLD", _("Gold")), ("SILVER", _("Silver")), ("BRONZE", _("Bronze")), ] self.assertEqual(normalize_choices(Medal), expected) def test_callable(self): def get_choices(): return { "C": _("Club"), "D": _("Diamond"), "H": _("Heart"), "S": _("Spade"), } get_choices_spy = mock.Mock(wraps=get_choices) output = normalize_choices(get_choices_spy) get_choices_spy.assert_not_called() self.assertIsInstance(output, CallableChoiceIterator) self.assertEqual(output, self.expected) get_choices_spy.assert_called_once() def test_mapping(self): choices = { "C": _("Club"), "D": _("Diamond"), "H": _("Heart"), "S": _("Spade"), } self.assertEqual(normalize_choices(choices), self.expected) def test_iterable(self): choices = [ ("C", _("Club")), ("D", _("Diamond")), ("H", _("Heart")), ("S", _("Spade")), ] self.assertEqual(normalize_choices(choices), self.expected) def test_iterator(self): def generator(): yield "C", _("Club") yield "D", _("Diamond") yield "H", _("Heart") yield "S", _("Spade") choices = generator() self.assertEqual(normalize_choices(choices), self.expected) def test_nested_callable(self): def get_audio_choices(): return [("vinyl", _("Vinyl")), ("cd", _("CD"))] def get_video_choices(): return [("vhs", _("VHS Tape")), ("dvd", _("DVD"))] def get_media_choices(): return [ ("Audio", get_audio_choices), ("Video", get_video_choices), ("unknown", _("Unknown")), ] get_media_choices_spy = mock.Mock(wraps=get_media_choices) output = normalize_choices(get_media_choices_spy) get_media_choices_spy.assert_not_called() self.assertIsInstance(output, CallableChoiceIterator) self.assertEqual(output, self.expected_nested) get_media_choices_spy.assert_called_once() def test_nested_mapping(self): choices = { "Audio": {"vinyl": _("Vinyl"), "cd": _("CD")}, "Video": {"vhs": _("VHS Tape"), "dvd": _("DVD")}, "unknown": _("Unknown"), } self.assertEqual(normalize_choices(choices), self.expected_nested) def test_nested_iterable(self): choices = [ ("Audio", [("vinyl", _("Vinyl")), ("cd", _("CD"))]), ("Video", [("vhs", _("VHS Tape")), ("dvd", _("DVD"))]), ("unknown", _("Unknown")), ] self.assertEqual(normalize_choices(choices), self.expected_nested) def test_nested_iterator(self): def generate_audio_choices(): yield "vinyl", _("Vinyl") yield "cd", _("CD") def generate_video_choices(): yield "vhs", _("VHS Tape") yield "dvd", _("DVD") def generate_media_choices(): yield "Audio", generate_audio_choices() yield "Video", generate_video_choices() yield "unknown", _("Unknown") choices = generate_media_choices() self.assertEqual(normalize_choices(choices), self.expected_nested) def test_callable_non_canonical(self): # Canonical form is list of 2-tuple, but nested lists should work. def get_choices(): return [ ["C", _("Club")], ["D", _("Diamond")], ["H", _("Heart")], ["S", _("Spade")], ] get_choices_spy = mock.Mock(wraps=get_choices) output = normalize_choices(get_choices_spy) get_choices_spy.assert_not_called() self.assertIsInstance(output, CallableChoiceIterator) self.assertEqual(output, self.expected) get_choices_spy.assert_called_once() def test_iterable_non_canonical(self): # Canonical form is list of 2-tuple, but nested lists should work. choices = [ ["C", _("Club")], ["D", _("Diamond")], ["H", _("Heart")], ["S", _("Spade")], ] self.assertEqual(normalize_choices(choices), self.expected) def test_iterator_non_canonical(self): # Canonical form is list of 2-tuple, but nested lists should work. def generator(): yield ["C", _("Club")] yield ["D", _("Diamond")] yield ["H", _("Heart")] yield ["S", _("Spade")] choices = generator() self.assertEqual(normalize_choices(choices), self.expected) def test_nested_callable_non_canonical(self): # Canonical form is list of 2-tuple, but nested lists should work. def get_audio_choices(): return [["vinyl", _("Vinyl")], ["cd", _("CD")]] def get_video_choices(): return [["vhs", _("VHS Tape")], ["dvd", _("DVD")]] def get_media_choices(): return [ ["Audio", get_audio_choices], ["Video", get_video_choices], ["unknown", _("Unknown")], ] get_media_choices_spy = mock.Mock(wraps=get_media_choices) output = normalize_choices(get_media_choices_spy) get_media_choices_spy.assert_not_called() self.assertIsInstance(output, CallableChoiceIterator) self.assertEqual(output, self.expected_nested) get_media_choices_spy.assert_called_once() def test_nested_iterable_non_canonical(self): # Canonical form is list of 2-tuple, but nested lists should work. choices = [ ["Audio", [["vinyl", _("Vinyl")], ["cd", _("CD")]]], ["Video", [["vhs", _("VHS Tape")], ["dvd", _("DVD")]]], ["unknown", _("Unknown")], ] self.assertEqual(normalize_choices(choices), self.expected_nested) def test_nested_iterator_non_canonical(self): # Canonical form is list of 2-tuple, but nested lists should work. def generator(): yield ["Audio", [["vinyl", _("Vinyl")], ["cd", _("CD")]]] yield ["Video", [["vhs", _("VHS Tape")], ["dvd", _("DVD")]]] yield ["unknown", _("Unknown")] choices = generator() self.assertEqual(normalize_choices(choices), self.expected_nested) def test_nested_mixed_mapping_and_iterable(self): # Although not documented, as it's better to stick to either mappings # or iterables, nesting of mappings within iterables and vice versa # works and is likely to occur in the wild. This is supported by the # recursive call to `normalize_choices()` which will normalize nested # choices. choices = { "Audio": [("vinyl", _("Vinyl")), ("cd", _("CD"))], "Video": [("vhs", _("VHS Tape")), ("dvd", _("DVD"))], "unknown": _("Unknown"), } self.assertEqual(normalize_choices(choices), self.expected_nested) choices = [ ("Audio", {"vinyl": _("Vinyl"), "cd": _("CD")}), ("Video", {"vhs": _("VHS Tape"), "dvd": _("DVD")}), ("unknown", _("Unknown")), ] self.assertEqual(normalize_choices(choices), self.expected_nested) def test_iterable_set(self): # Although not documented, as sets are unordered which results in # randomised order in form fields, passing a set of 2-tuples works. # Consistent ordering of choices on model fields in migrations is # enforced by the migrations serializer. choices = { ("C", _("Club")), ("D", _("Diamond")), ("H", _("Heart")), ("S", _("Spade")), } self.assertEqual(sorted(normalize_choices(choices)), sorted(self.expected)) def test_unsupported_values_returned_unmodified(self): # Unsupported values must be returned unmodified for model system check # to work correctly. for value in self.invalid + self.invalid_iterable + self.invalid_nested: with self.subTest(value=value): self.assertEqual(normalize_choices(value), value) def test_unsupported_values_from_callable_returned_unmodified(self): for value in self.invalid_iterable + self.invalid_nested: with self.subTest(value=value): self.assertEqual(normalize_choices(lambda: value), value) def test_unsupported_values_from_iterator_returned_unmodified(self): for value in self.invalid_nested: with self.subTest(value=value): self.assertEqual( normalize_choices((lambda: (yield from value))()), value, )
django
python
"""HTML utilities suitable for global use.""" import html import json import re import warnings from collections import deque from collections.abc import Mapping from html.parser import HTMLParser from itertools import chain from urllib.parse import parse_qsl, quote, unquote, urlencode, urlsplit, urlunsplit from django.conf import settings from django.core.exceptions import SuspiciousOperation, ValidationError from django.core.validators import DomainNameValidator, EmailValidator from django.utils.deprecation import RemovedInDjango70Warning from django.utils.functional import Promise, cached_property, keep_lazy, keep_lazy_text from django.utils.http import MAX_URL_LENGTH, RFC3986_GENDELIMS, RFC3986_SUBDELIMS from django.utils.regex_helper import _lazy_re_compile from django.utils.safestring import SafeData, SafeString, mark_safe from django.utils.text import normalize_newlines # https://html.spec.whatwg.org/#void-elements VOID_ELEMENTS = frozenset( ( "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr", # Deprecated tags. "frame", "spacer", ) ) MAX_STRIP_TAGS_DEPTH = 50 # HTML tag that opens but has no closing ">" after 1k+ chars. long_open_tag_without_closing_re = _lazy_re_compile(r"<[a-zA-Z][^>]{1000,}") @keep_lazy(SafeString) def escape(text): """ Return the given text with ampersands, quotes and angle brackets encoded for use in HTML. Always escape input, even if it's already escaped and marked as such. This may result in double-escaping. If this is a concern, use conditional_escape() instead. """ return SafeString(html.escape(str(text))) _js_escapes = { ord("\\"): "\\u005C", ord("'"): "\\u0027", ord('"'): "\\u0022", ord(">"): "\\u003E", ord("<"): "\\u003C", ord("&"): "\\u0026", ord("="): "\\u003D", ord("-"): "\\u002D", ord(";"): "\\u003B", ord("`"): "\\u0060", ord("\u2028"): "\\u2028", ord("\u2029"): "\\u2029", } # Escape every ASCII character with a value less than 32 (C0), 127(C0), # or 128-159(C1). _js_escapes.update( (ord("%c" % z), "\\u%04X" % z) for z in chain(range(32), range(0x7F, 0xA0)) ) @keep_lazy(SafeString) def escapejs(value): """Hex encode characters for use in JavaScript strings.""" return mark_safe(str(value).translate(_js_escapes)) _json_script_escapes = { ord(">"): "\\u003E", ord("<"): "\\u003C", ord("&"): "\\u0026", } def json_script(value, element_id=None, encoder=None): """ Escape all the HTML/XML special characters with their unicode escapes, so value is safe to be output anywhere except for inside a tag attribute. Wrap the escaped JSON in a script tag. """ from django.core.serializers.json import DjangoJSONEncoder json_str = json.dumps(value, cls=encoder or DjangoJSONEncoder).translate( _json_script_escapes ) if element_id: template = '<script id="{}" type="application/json">{}</script>' args = (element_id, mark_safe(json_str)) else: template = '<script type="application/json">{}</script>' args = (mark_safe(json_str),) return format_html(template, *args) def conditional_escape(text): """ Similar to escape(), except that it doesn't operate on pre-escaped strings. This function relies on the __html__ convention used both by Django's SafeData class and by third-party libraries like markupsafe. """ if isinstance(text, Promise): text = str(text) if hasattr(text, "__html__"): return text.__html__() else: return escape(text) def format_html(format_string, *args, **kwargs): """ Similar to str.format, but pass all arguments through conditional_escape(), and call mark_safe() on the result. This function should be used instead of str.format or % interpolation to build up small HTML fragments. """ if not (args or kwargs): raise TypeError("args or kwargs must be provided.") args_safe = map(conditional_escape, args) kwargs_safe = {k: conditional_escape(v) for (k, v) in kwargs.items()} return mark_safe(format_string.format(*args_safe, **kwargs_safe)) def format_html_join(sep, format_string, args_generator): """ A wrapper of format_html, for the common case of a group of arguments that need to be formatted using the same format string, and then joined using 'sep'. 'sep' is also passed through conditional_escape. 'args_generator' should be an iterator that returns the sequence of 'args' that will be passed to format_html. Example: format_html_join('\n', "<li>{} {}</li>", ((u.first_name, u.last_name) for u in users)) """ return mark_safe( conditional_escape(sep).join( ( format_html(format_string, **args) if isinstance(args, Mapping) else format_html(format_string, *args) ) for args in args_generator ) ) @keep_lazy_text def linebreaks(value, autoescape=False): """Convert newlines into <p> and <br>s.""" value = normalize_newlines(value) paras = re.split("\n{2,}", str(value)) if autoescape: paras = ["<p>%s</p>" % escape(p).replace("\n", "<br>") for p in paras] else: paras = ["<p>%s</p>" % p.replace("\n", "<br>") for p in paras] return "\n\n".join(paras) class MLStripper(HTMLParser): def __init__(self): super().__init__(convert_charrefs=False) self.reset() self.fed = [] def handle_data(self, d): self.fed.append(d) def handle_entityref(self, name): self.fed.append("&%s;" % name) def handle_charref(self, name): self.fed.append("&#%s;" % name) def get_data(self): return "".join(self.fed) def _strip_once(value): """ Internal tag stripping utility used by strip_tags. """ s = MLStripper() s.feed(value) s.close() return s.get_data() @keep_lazy_text def strip_tags(value): """Return the given HTML with all tags stripped.""" value = str(value) for long_open_tag in long_open_tag_without_closing_re.finditer(value): if long_open_tag.group().count("<") >= MAX_STRIP_TAGS_DEPTH: raise SuspiciousOperation # Note: in typical case this loop executes _strip_once twice (the second # execution does not remove any more tags). strip_tags_depth = 0 while "<" in value and ">" in value: if strip_tags_depth >= MAX_STRIP_TAGS_DEPTH: raise SuspiciousOperation new_value = _strip_once(value) if value.count("<") == new_value.count("<"): # _strip_once wasn't able to detect more tags. break value = new_value strip_tags_depth += 1 return value @keep_lazy_text def strip_spaces_between_tags(value): """Return the given HTML with spaces between tags removed.""" return re.sub(r">\s+<", "><", str(value)) def smart_urlquote(url): """Quote a URL if it isn't already quoted.""" def unquote_quote(segment): segment = unquote(segment) # Tilde is part of RFC 3986 Section 2.3 Unreserved Characters, # see also https://bugs.python.org/issue16285 return quote(segment, safe=RFC3986_SUBDELIMS + RFC3986_GENDELIMS + "~") try: scheme, netloc, path, query, fragment = urlsplit(url) except ValueError: # invalid IPv6 URL (normally square brackets in hostname part). return unquote_quote(url) # Handle IDN as percent-encoded UTF-8 octets, per WHATWG URL Specification # section 3.5 and RFC 3986 section 3.2.2. Defer any IDNA to the user agent. # See #36013. netloc = unquote_quote(netloc) if query: # Separately unquoting key/value, so as to not mix querystring # separators included in query values. See #22267. query_parts = [ (unquote(q[0]), unquote(q[1])) for q in parse_qsl(query, keep_blank_values=True) ] # urlencode will take care of quoting query = urlencode(query_parts) path = unquote_quote(path) fragment = unquote_quote(fragment) return urlunsplit((scheme, netloc, path, query, fragment)) class CountsDict(dict): def __init__(self, *args, word, **kwargs): super().__init__(*args, *kwargs) self.word = word def __missing__(self, key): self[key] = self.word.count(key) return self[key] class Urlizer: """ Convert any URLs in text into clickable links. Work on http://, https://, www. links, and also on links ending in one of the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org). Links can have trailing punctuation (periods, commas, close-parens) and leading punctuation (opening parens) and it'll still do the right thing. """ trailing_punctuation_chars = ".,:;!" wrapping_punctuation = [("(", ")"), ("[", "]")] simple_url_re = _lazy_re_compile(r"^https?://\[?\w", re.IGNORECASE) simple_url_2_re = _lazy_re_compile( rf"^www\.|^(?!http)(?:{DomainNameValidator.hostname_re})" rf"(?:{DomainNameValidator.domain_re})" r"\.(com|edu|gov|int|mil|net|org)($|/.*)$", re.IGNORECASE, ) word_split_re = _lazy_re_compile(r"""([\s<>"']+)""") mailto_template = "mailto:{local}@{domain}" url_template = '<a href="{href}"{attrs}>{url}</a>' def __call__(self, text, trim_url_limit=None, nofollow=False, autoescape=False): """ If trim_url_limit is not None, truncate the URLs in the link text longer than this limit to trim_url_limit - 1 characters and append an ellipsis. If nofollow is True, give the links a rel="nofollow" attribute. If autoescape is True, autoescape the link text and URLs. """ safe_input = isinstance(text, SafeData) words = self.word_split_re.split(str(text)) local_cache = {} urlized_words = [] for word in words: if (urlized_word := local_cache.get(word)) is None: urlized_word = self.handle_word( word, safe_input=safe_input, trim_url_limit=trim_url_limit, nofollow=nofollow, autoescape=autoescape, ) local_cache[word] = urlized_word urlized_words.append(urlized_word) return "".join(urlized_words) def handle_word( self, word, *, safe_input, trim_url_limit=None, nofollow=False, autoescape=False, ): if "." in word or "@" in word or ":" in word: # lead: Punctuation trimmed from the beginning of the word. # middle: State of the word. # trail: Punctuation trimmed from the end of the word. lead, middle, trail = self.trim_punctuation(word) # Make URL we want to point to. url = None nofollow_attr = ' rel="nofollow"' if nofollow else "" if len(middle) <= MAX_URL_LENGTH and self.simple_url_re.match(middle): url = smart_urlquote(html.unescape(middle)) elif len(middle) <= MAX_URL_LENGTH and self.simple_url_2_re.match(middle): unescaped_middle = html.unescape(middle) # RemovedInDjango70Warning: When the deprecation ends, replace # with: # url = smart_urlquote(f"https://{unescaped_middle}") protocol = ( "https" if getattr(settings, "URLIZE_ASSUME_HTTPS", False) else "http" ) if not settings.URLIZE_ASSUME_HTTPS: warnings.warn( "The default protocol will be changed from HTTP to " "HTTPS in Django 7.0. Set the URLIZE_ASSUME_HTTPS " "transitional setting to True to opt into using HTTPS as the " "new default protocol.", RemovedInDjango70Warning, stacklevel=2, ) url = smart_urlquote(f"{protocol}://{unescaped_middle}") elif ":" not in middle and self.is_email_simple(middle): local, domain = middle.rsplit("@", 1) # Encode per RFC 6068 Section 2 (items 1, 4, 5). Defer any IDNA # to the user agent. See #36013. local = quote(local, safe="") domain = quote(domain, safe="") url = self.mailto_template.format(local=local, domain=domain) nofollow_attr = "" # Make link. if url: trimmed = self.trim_url(middle, limit=trim_url_limit) if autoescape and not safe_input: lead, trail = escape(lead), escape(trail) trimmed = escape(trimmed) middle = self.url_template.format( href=escape(url), attrs=nofollow_attr, url=trimmed, ) return mark_safe(f"{lead}{middle}{trail}") else: if safe_input: return mark_safe(word) elif autoescape: return escape(word) elif safe_input: return mark_safe(word) elif autoescape: return escape(word) return word def trim_url(self, x, *, limit): if limit is None or len(x) <= limit: return x return "%s…" % x[: max(0, limit - 1)] @cached_property def wrapping_punctuation_openings(self): return "".join(dict(self.wrapping_punctuation).keys()) @cached_property def trailing_punctuation_chars_no_semicolon(self): return self.trailing_punctuation_chars.replace(";", "") @cached_property def trailing_punctuation_chars_has_semicolon(self): return ";" in self.trailing_punctuation_chars def trim_punctuation(self, word): """ Trim trailing and wrapping punctuation from `word`. Return the items of the new state. """ # Strip all opening wrapping punctuation. middle = word.lstrip(self.wrapping_punctuation_openings) lead = word[: len(word) - len(middle)] trail = deque() # Continue trimming until middle remains unchanged. trimmed_something = True counts = CountsDict(word=middle) while trimmed_something and middle: trimmed_something = False # Trim wrapping punctuation. for opening, closing in self.wrapping_punctuation: if counts[opening] < counts[closing]: rstripped = middle.rstrip(closing) if rstripped != middle: strip = counts[closing] - counts[opening] trail.appendleft(middle[-strip:]) middle = middle[:-strip] trimmed_something = True counts[closing] -= strip amp = middle.rfind("&") if amp == -1: rstripped = middle.rstrip(self.trailing_punctuation_chars) else: rstripped = middle.rstrip(self.trailing_punctuation_chars_no_semicolon) if rstripped != middle: trail.appendleft(middle[len(rstripped) :]) middle = rstripped trimmed_something = True if self.trailing_punctuation_chars_has_semicolon and middle.endswith(";"): # Only strip if not part of an HTML entity. potential_entity = middle[amp:] escaped = html.unescape(potential_entity) if escaped == potential_entity or escaped.endswith(";"): rstripped = middle.rstrip(self.trailing_punctuation_chars) trail_start = len(rstripped) amount_trailing_semicolons = len(middle) - len(middle.rstrip(";")) if amp > -1 and amount_trailing_semicolons > 1: # Leave up to most recent semicolon as might be an # entity. recent_semicolon = middle[trail_start:].index(";") middle_semicolon_index = recent_semicolon + trail_start + 1 trail.appendleft(middle[middle_semicolon_index:]) middle = rstripped + middle[trail_start:middle_semicolon_index] else: trail.appendleft(middle[trail_start:]) middle = rstripped trimmed_something = True trail = "".join(trail) return lead, middle, trail @staticmethod def is_email_simple(value): """Return True if value looks like an email address.""" try: EmailValidator(allowlist=[])(value) except ValidationError: return False return True urlizer = Urlizer() @keep_lazy_text def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): return urlizer( text, trim_url_limit=trim_url_limit, nofollow=nofollow, autoescape=autoescape ) def avoid_wrapping(value): """ Avoid text wrapping in the middle of a phrase by adding non-breaking spaces where there previously were normal spaces. """ return value.replace(" ", "\xa0") def html_safe(klass): """ A decorator that defines the __html__ method. This helps non-Django templates to detect classes whose __str__ methods return SafeString. """ if "__html__" in klass.__dict__: raise ValueError( "can't apply @html_safe to %s because it defines " "__html__()." % klass.__name__ ) if "__str__" not in klass.__dict__: raise ValueError( "can't apply @html_safe to %s because it doesn't " "define __str__()." % klass.__name__ ) klass_str = klass.__str__ klass.__str__ = lambda self: mark_safe(klass_str(self)) klass.__html__ = lambda self: str(self) return klass
import os import sys from datetime import datetime from django.core.exceptions import SuspiciousOperation from django.core.serializers.json import DjangoJSONEncoder from django.test import SimpleTestCase from django.test.utils import override_settings from django.utils.deprecation import RemovedInDjango70Warning from django.utils.functional import lazystr from django.utils.html import ( conditional_escape, escape, escapejs, format_html, format_html_join, html_safe, json_script, linebreaks, smart_urlquote, strip_spaces_between_tags, strip_tags, urlize, ) from django.utils.safestring import mark_safe @override_settings(URLIZE_ASSUME_HTTPS=True) class TestUtilsHtml(SimpleTestCase): def check_output(self, function, value, output=None): """ function(value) equals output. If output is None, function(value) equals value. """ if output is None: output = value self.assertEqual(function(value), output) def test_escape(self): items = ( ("&", "&amp;"), ("<", "&lt;"), (">", "&gt;"), ('"', "&quot;"), ("'", "&#x27;"), ) # Substitution patterns for testing the above items. patterns = ("%s", "asdf%sfdsa", "%s1", "1%sb") for value, output in items: with self.subTest(value=value, output=output): for pattern in patterns: with self.subTest(value=value, output=output, pattern=pattern): self.check_output(escape, pattern % value, pattern % output) self.check_output( escape, lazystr(pattern % value), pattern % output ) # Check repeated values. self.check_output(escape, value * 2, output * 2) # Verify it doesn't double replace &. self.check_output(escape, "<&", "&lt;&amp;") def test_format_html(self): self.assertEqual( format_html( "{} {} {third} {fourth}", "< Dangerous >", mark_safe("<b>safe</b>"), third="< dangerous again", fourth=mark_safe("<i>safe again</i>"), ), "&lt; Dangerous &gt; <b>safe</b> &lt; dangerous again <i>safe again</i>", ) def test_format_html_no_params(self): msg = "args or kwargs must be provided." with self.assertRaisesMessage(TypeError, msg): name = "Adam" self.assertEqual(format_html(f"<i>{name}</i>"), "<i>Adam</i>") def test_format_html_join_with_positional_arguments(self): self.assertEqual( format_html_join( "\n", "<li>{}) {}</li>", [(1, "Emma"), (2, "Matilda")], ), "<li>1) Emma</li>\n<li>2) Matilda</li>", ) def test_format_html_join_with_keyword_arguments(self): self.assertEqual( format_html_join( "\n", "<li>{id}) {text}</li>", [{"id": 1, "text": "Emma"}, {"id": 2, "text": "Matilda"}], ), "<li>1) Emma</li>\n<li>2) Matilda</li>", ) def test_linebreaks(self): items = ( ("para1\n\npara2\r\rpara3", "<p>para1</p>\n\n<p>para2</p>\n\n<p>para3</p>"), ( "para1\nsub1\rsub2\n\npara2", "<p>para1<br>sub1<br>sub2</p>\n\n<p>para2</p>", ), ( "para1\r\n\r\npara2\rsub1\r\rpara4", "<p>para1</p>\n\n<p>para2<br>sub1</p>\n\n<p>para4</p>", ), ("para1\tmore\n\npara2", "<p>para1\tmore</p>\n\n<p>para2</p>"), ) for value, output in items: with self.subTest(value=value, output=output): self.check_output(linebreaks, value, output) self.check_output(linebreaks, lazystr(value), output) def test_strip_tags(self): # Python fixed a quadratic-time issue in HTMLParser in 3.13.6, 3.12.12. # The fix slightly changes HTMLParser's output, so tests for # particularly malformed input must handle both old and new results. # The check below is temporary until all supported Python versions and # CI workers include the fix. See: # https://github.com/python/cpython/commit/6eb6c5db min_fixed = { (3, 13): (3, 13, 6), (3, 12): (3, 12, 12), } major_version = sys.version_info[:2] htmlparser_fixed = sys.version_info >= min_fixed.get( major_version, major_version ) items = ( ( "<p>See: &#39;&eacute; is an apostrophe followed by e acute</p>", "See: &#39;&eacute; is an apostrophe followed by e acute", ), ( "<p>See: &#x27;&eacute; is an apostrophe followed by e acute</p>", "See: &#x27;&eacute; is an apostrophe followed by e acute", ), ("<adf>a", "a"), ("</adf>a", "a"), ("<asdf><asdf>e", "e"), ("hi, <f x", "hi, <f x"), ("234<235, right?", "234<235, right?"), ("a4<a5 right?", "a4<a5 right?"), ("b7>b2!", "b7>b2!"), ("</fe", "</fe"), ("<x>b<y>", "b"), ("a<p onclick=\"alert('<test>')\">b</p>c", "abc"), ("a<p a >b</p>c", "abc"), ("d<a:b c:d>e</p>f", "def"), ('<strong>foo</strong><a href="http://example.com">bar</a>', "foobar"), # caused infinite loop on Pythons not patched with # https://bugs.python.org/issue20288 ("&gotcha&#;<>", "&gotcha&#;<>"), ("<sc<!-- -->ript>test<<!-- -->/script>", "ript>test"), ("<script>alert()</script>&h", "alert()h"), ( "><!" + ("&" * 16000) + "D", ">" if htmlparser_fixed else "><!" + ("&" * 16000) + "D", ), ("X<<<<br>br>br>br>X", "XX"), ("<" * 50 + "a>" * 50, ""), ( ">" + "<a" * 500 + "a", ">" if htmlparser_fixed else ">" + "<a" * 500 + "a", ), ("<a" * 49 + "a" * 951, "<a" * 49 + "a" * 951), ("<" + "a" * 1_002, "<" + "a" * 1_002), ) for value, output in items: with self.subTest(value=value, output=output): self.check_output(strip_tags, value, output) self.check_output(strip_tags, lazystr(value), output) def test_strip_tags_suspicious_operation_max_depth(self): value = "<" * 51 + "a>" * 51, "<a>" with self.assertRaises(SuspiciousOperation): strip_tags(value) def test_strip_tags_suspicious_operation_large_open_tags(self): items = [ ">" + "<a" * 501, "<a" * 50 + "a" * 950, ] for value in items: with self.subTest(value=value): with self.assertRaises(SuspiciousOperation): strip_tags(value) def test_strip_tags_files(self): # Test with more lengthy content (also catching performance # regressions) for filename in ("strip_tags1.html", "strip_tags2.txt"): with self.subTest(filename=filename): path = os.path.join(os.path.dirname(__file__), "files", filename) with open(path) as fp: content = fp.read() start = datetime.now() stripped = strip_tags(content) elapsed = datetime.now() - start self.assertEqual(elapsed.seconds, 0) self.assertIn("Test string that has not been stripped.", stripped) self.assertNotIn("<", stripped) def test_strip_spaces_between_tags(self): # Strings that should come out untouched. items = (" <adf>", "<adf> ", " </adf> ", " <f> x</f>") for value in items: with self.subTest(value=value): self.check_output(strip_spaces_between_tags, value) self.check_output(strip_spaces_between_tags, lazystr(value)) # Strings that have spaces to strip. items = ( ("<d> </d>", "<d></d>"), ("<p>hello </p>\n<p> world</p>", "<p>hello </p><p> world</p>"), ("\n<p>\t</p>\n<p> </p>\n", "\n<p></p><p></p>\n"), ) for value, output in items: with self.subTest(value=value, output=output): self.check_output(strip_spaces_between_tags, value, output) self.check_output(strip_spaces_between_tags, lazystr(value), output) def test_escapejs(self): items = ( ( "\"double quotes\" and 'single quotes'", "\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027", ), (r"\ : backslashes, too", "\\u005C : backslashes, too"), ( "and lots of whitespace: \r\n\t\v\f\b", "and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008", ), ( r"<script>and this</script>", "\\u003Cscript\\u003Eand this\\u003C/script\\u003E", ), ( "paragraph separator:\u2029and line separator:\u2028", "paragraph separator:\\u2029and line separator:\\u2028", ), ("`", "\\u0060"), ("\u007f", "\\u007F"), ("\u0080", "\\u0080"), ("\u009f", "\\u009F"), ) for value, output in items: with self.subTest(value=value, output=output): self.check_output(escapejs, value, output) self.check_output(escapejs, lazystr(value), output) def test_json_script(self): tests = ( # "<", ">" and "&" are quoted inside JSON strings ( ( "&<>", '<script id="test_id" type="application/json">' '"\\u0026\\u003C\\u003E"</script>', ) ), # "<", ">" and "&" are quoted inside JSON objects ( {"a": "<script>test&ing</script>"}, '<script id="test_id" type="application/json">' '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}' "</script>", ), # Lazy strings are quoted ( lazystr("&<>"), '<script id="test_id" type="application/json">"\\u0026\\u003C\\u003E"' "</script>", ), ( {"a": lazystr("<script>test&ing</script>")}, '<script id="test_id" type="application/json">' '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}' "</script>", ), ) for arg, expected in tests: with self.subTest(arg=arg): self.assertEqual(json_script(arg, "test_id"), expected) def test_json_script_custom_encoder(self): class CustomDjangoJSONEncoder(DjangoJSONEncoder): def encode(self, o): return '{"hello": "world"}' self.assertHTMLEqual( json_script({}, encoder=CustomDjangoJSONEncoder), '<script type="application/json">{"hello": "world"}</script>', ) def test_json_script_without_id(self): self.assertHTMLEqual( json_script({"key": "value"}), '<script type="application/json">{"key": "value"}</script>', ) def test_smart_urlquote(self): items = ( # IDN is encoded as percent-encoded ("quoted") UTF-8 (#36013). ("http://öäü.com/", "http://%C3%B6%C3%A4%C3%BC.com/"), ("https://faß.example.com", "https://fa%C3%9F.example.com"), ( "http://öäü.com/öäü/", "http://%C3%B6%C3%A4%C3%BC.com/%C3%B6%C3%A4%C3%BC/", ), ( # Valid under IDNA 2008, but was invalid in IDNA 2003. "https://މިހާރު.com", "https://%DE%89%DE%A8%DE%80%DE%A7%DE%83%DE%AA.com", ), ( # Valid under WHATWG URL Specification but not IDNA 2008. "http://👓.ws", "http://%F0%9F%91%93.ws", ), # Pre-encoded IDNA is left unchanged. ("http://xn--iny-zx5a.com/idna2003", "http://xn--iny-zx5a.com/idna2003"), ("http://xn--fa-hia.com/idna2008", "http://xn--fa-hia.com/idna2008"), # Everything unsafe is quoted, !*'();:@&=+$,/?#[]~ is considered # safe as per RFC. ( "http://example.com/path/öäü/", "http://example.com/path/%C3%B6%C3%A4%C3%BC/", ), ("http://example.com/%C3%B6/ä/", "http://example.com/%C3%B6/%C3%A4/"), ("http://example.com/?x=1&y=2+3&z=", "http://example.com/?x=1&y=2+3&z="), ("http://example.com/?x=<>\"'", "http://example.com/?x=%3C%3E%22%27"), ( "http://example.com/?q=http://example.com/?x=1%26q=django", "http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3D" "django", ), ( "http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3D" "django", "http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3D" "django", ), ("http://.www.f oo.bar/", "http://.www.f%20oo.bar/"), ('http://example.com">', "http://example.com%22%3E"), ("http://10.22.1.1/", "http://10.22.1.1/"), ("http://[fd00::1]/", "http://[fd00::1]/"), ) for value, output in items: with self.subTest(value=value, output=output): self.assertEqual(smart_urlquote(value), output) def test_conditional_escape(self): s = "<h1>interop</h1>" self.assertEqual(conditional_escape(s), "&lt;h1&gt;interop&lt;/h1&gt;") self.assertEqual(conditional_escape(mark_safe(s)), s) self.assertEqual(conditional_escape(lazystr(mark_safe(s))), s) def test_html_safe(self): @html_safe class HtmlClass: def __str__(self): return "<h1>I'm a html class!</h1>" html_obj = HtmlClass() self.assertTrue(hasattr(HtmlClass, "__html__")) self.assertTrue(hasattr(html_obj, "__html__")) self.assertEqual(str(html_obj), html_obj.__html__()) def test_html_safe_subclass(self): class BaseClass: def __html__(self): # defines __html__ on its own return "some html content" def __str__(self): return "some non html content" @html_safe class Subclass(BaseClass): def __str__(self): # overrides __str__ and is marked as html_safe return "some html safe content" subclass_obj = Subclass() self.assertEqual(str(subclass_obj), subclass_obj.__html__()) def test_html_safe_defines_html_error(self): msg = "can't apply @html_safe to HtmlClass because it defines __html__()." with self.assertRaisesMessage(ValueError, msg): @html_safe class HtmlClass: def __html__(self): return "<h1>I'm a html class!</h1>" def test_html_safe_doesnt_define_str(self): msg = "can't apply @html_safe to HtmlClass because it doesn't define __str__()." with self.assertRaisesMessage(ValueError, msg): @html_safe class HtmlClass: pass def test_urlize(self): tests = ( ( "Search for google.com/?q=! and see.", 'Search for <a href="https://google.com/?q=">google.com/?q=</a>! and ' "see.", ), ( "Search for google.com/?q=1&lt! and see.", 'Search for <a href="https://google.com/?q=1%3C">google.com/?q=1&lt' "</a>! and see.", ), ( lazystr("Search for google.com/?q=!"), 'Search for <a href="https://google.com/?q=">google.com/?q=</a>!', ), ( "http://www.foo.bar/", '<a href="http://www.foo.bar/">http://www.foo.bar/</a>', ), ( "Look on www.نامه‌ای.com.", "Look on <a " 'href="https://www.%D9%86%D8%A7%D9%85%D9%87%E2%80%8C%D8%A7%DB%8C.com"' ">www.نامه‌ای.com</a>.", ), ("[email protected]", '<a href="mailto:[email protected]">[email protected]</a>'), ( "test@" + "한.글." * 15 + "aaa", '<a href="mailto:test@' + "%ED%95%9C.%EA%B8%80." * 15 + 'aaa">' + "test@" + "한.글." * 15 + "aaa</a>", ), ( # RFC 6068 requires a mailto URI to percent-encode a number of # characters that can appear in <addr-spec>. "yes+this=is&a%[email protected]", '<a href="mailto:yes%2Bthis%3Dis%26a%25valid%[email protected]"' ">yes+this=is&a%[email protected]</a>", ), ( "foo@faß.example.com", '<a href="mailto:foo@fa%C3%9F.example.com">foo@faß.example.com</a>', ), ( "idna-2008@މިހާރު.example.mv", '<a href="mailto:idna-2008@%DE%89%DE%A8%DE%80%DE%A7%DE%83%DE%AA.ex' 'ample.mv">idna-2008@މިހާރު.example.mv</a>', ), ( "host.djangoproject.com", '<a href="https://host.djangoproject.com">host.djangoproject.com</a>', ), ) for value, output in tests: with self.subTest(value=value): self.assertEqual(urlize(value), output) @override_settings(URLIZE_ASSUME_HTTPS=False) def test_urlize_http_default_warning(self): msg = ( "The default protocol will be changed from HTTP to HTTPS in Django 7.0. " "Set the URLIZE_ASSUME_HTTPS transitional setting to True to opt into " "using HTTPS as the new default protocol." ) with self.assertWarnsMessage(RemovedInDjango70Warning, msg): self.assertEqual( urlize("Visit example.com"), 'Visit <a href="http://example.com">example.com</a>', ) def test_urlize_unchanged_inputs(self): tests = ( ("a" + "@a" * 50000) + "a", # simple_email_re catastrophic test # Unicode domain catastrophic tests. "a@" + "한.글." * 1_000_000 + "a", "http://" + "한.글." * 1_000_000 + "com", "www." + "한.글." * 1_000_000 + "com", ("a" + "." * 1000000) + "a", # trailing_punctuation catastrophic test "foo@", "@foo.com", "[email protected]", "foo@localhost", "foo@localhost.", "test@example?;+!.com", "email [email protected],then I'll respond", "[a link](https://www.djangoproject.com/)", # trim_punctuation catastrophic tests "(" * 100_000 + ":" + ")" * 100_000, "(" * 100_000 + "&:" + ")" * 100_000, "([" * 100_000 + ":" + "])" * 100_000, "[(" * 100_000 + ":" + ")]" * 100_000, "([[" * 100_000 + ":" + "]])" * 100_000, "&:" + ";" * 100_000, "&.;" * 100_000, ".;" * 100_000, "&" + ";:" * 100_000, ) for value in tests: with self.subTest(value=value): self.assertEqual(urlize(value), value)
django
python
"""Functions to parse datetime objects.""" # We're using regular expressions rather than time.strptime because: # - They provide both validation and parsing. # - They're more flexible for datetimes. # - The date/datetime/time constructors produce friendlier error messages. import datetime from django.utils.regex_helper import _lazy_re_compile from django.utils.timezone import get_fixed_timezone date_re = _lazy_re_compile(r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$") time_re = _lazy_re_compile( r"(?P<hour>\d{1,2}):(?P<minute>\d{1,2})" r"(?::(?P<second>\d{1,2})(?:[.,](?P<microsecond>\d{1,6})\d{0,6})?)?$" ) datetime_re = _lazy_re_compile( r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})" r"[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})" r"(?::(?P<second>\d{1,2})(?:[.,](?P<microsecond>\d{1,6})\d{0,6})?)?" r"\s*(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$" ) standard_duration_re = _lazy_re_compile( r"^" r"(?:(?P<days>-?\d+) (days?, )?)?" r"(?P<sign>-?)" r"((?:(?P<hours>\d+):)(?=\d+:\d+))?" r"(?:(?P<minutes>\d+):)?" r"(?P<seconds>\d+)" r"(?:[.,](?P<microseconds>\d{1,6})\d{0,6})?" r"$" ) # Support the sections of ISO 8601 date representation that are accepted by # timedelta iso8601_duration_re = _lazy_re_compile( r"^(?P<sign>[-+]?)" r"P" r"(?:(?P<days>\d+([.,]\d+)?)D)?" r"(?:T" r"(?:(?P<hours>\d+([.,]\d+)?)H)?" r"(?:(?P<minutes>\d+([.,]\d+)?)M)?" r"(?:(?P<seconds>\d+([.,]\d+)?)S)?" r")?" r"$" ) # Support PostgreSQL's day-time interval format, e.g. "3 days 04:05:06". The # year-month and mixed intervals cannot be converted to a timedelta and thus # aren't accepted. postgres_interval_re = _lazy_re_compile( r"^" r"(?:(?P<days>-?\d+) (days? ?))?" r"(?:(?P<sign>[-+])?" r"(?P<hours>\d+):" r"(?P<minutes>\d\d):" r"(?P<seconds>\d\d)" r"(?:\.(?P<microseconds>\d{1,6}))?" r")?$" ) def parse_date(value): """Parse a string and return a datetime.date. Raise ValueError if the input is well formatted but not a valid date. Return None if the input isn't well formatted. """ try: return datetime.date.fromisoformat(value) except ValueError: if match := date_re.match(value): kw = {k: int(v) for k, v in match.groupdict().items()} return datetime.date(**kw) def parse_time(value): """Parse a string and return a datetime.time. This function doesn't support time zone offsets. Raise ValueError if the input is well formatted but not a valid time. Return None if the input isn't well formatted, in particular if it contains an offset. """ try: # The fromisoformat() method takes time zone info into account and # returns a time with a tzinfo component, if possible. However, there # are no circumstances where aware datetime.time objects make sense, so # remove the time zone offset. return datetime.time.fromisoformat(value).replace(tzinfo=None) except ValueError: if match := time_re.match(value): kw = match.groupdict() kw["microsecond"] = kw["microsecond"] and kw["microsecond"].ljust(6, "0") kw = {k: int(v) for k, v in kw.items() if v is not None} return datetime.time(**kw) def parse_datetime(value): """Parse a string and return a datetime.datetime. This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC. Raise ValueError if the input is well formatted but not a valid datetime. Return None if the input isn't well formatted. """ try: return datetime.datetime.fromisoformat(value) except ValueError: if match := datetime_re.match(value): kw = match.groupdict() kw["microsecond"] = kw["microsecond"] and kw["microsecond"].ljust(6, "0") tzinfo = kw.pop("tzinfo") if tzinfo == "Z": tzinfo = datetime.UTC elif tzinfo is not None: offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0 offset = 60 * int(tzinfo[1:3]) + offset_mins if tzinfo[0] == "-": offset = -offset tzinfo = get_fixed_timezone(offset) kw = {k: int(v) for k, v in kw.items() if v is not None} return datetime.datetime(**kw, tzinfo=tzinfo) def parse_duration(value): """Parse a duration string and return a datetime.timedelta. The preferred format for durations in Django is '%d %H:%M:%S.%f'. Also supports ISO 8601 representation and PostgreSQL's day-time interval format. """ match = ( standard_duration_re.match(value) or iso8601_duration_re.match(value) or postgres_interval_re.match(value) ) if match: kw = match.groupdict() sign = -1 if kw.pop("sign", "+") == "-" else 1 if kw.get("microseconds"): kw["microseconds"] = kw["microseconds"].ljust(6, "0") kw = {k: float(v.replace(",", ".")) for k, v in kw.items() if v is not None} days = datetime.timedelta(kw.pop("days", 0.0) or 0.0) if match.re == iso8601_duration_re: days *= sign return days + sign * datetime.timedelta(**kw)
import unittest from datetime import date, datetime, time, timedelta from django.utils.dateparse import ( parse_date, parse_datetime, parse_duration, parse_time, ) from django.utils.timezone import get_fixed_timezone class DateParseTests(unittest.TestCase): def test_parse_date(self): # Valid inputs self.assertEqual(parse_date("2012-04-23"), date(2012, 4, 23)) self.assertEqual(parse_date("2012-4-9"), date(2012, 4, 9)) self.assertEqual(parse_date("20120423"), date(2012, 4, 23)) # Invalid inputs self.assertIsNone(parse_date("2012423")) with self.assertRaises(ValueError): parse_date("2012-04-56") def test_parse_time(self): # Valid inputs self.assertEqual(parse_time("09:15:00"), time(9, 15)) self.assertEqual(parse_time("091500"), time(9, 15)) self.assertEqual(parse_time("10:10"), time(10, 10)) self.assertEqual(parse_time("10:20:30.400"), time(10, 20, 30, 400000)) self.assertEqual(parse_time("10:20:30,400"), time(10, 20, 30, 400000)) self.assertEqual(parse_time("4:8:16"), time(4, 8, 16)) # Time zone offset is ignored. self.assertEqual(parse_time("00:05:23+04:00"), time(0, 5, 23)) # Invalid inputs self.assertIsNone(parse_time("00:05:")) self.assertIsNone(parse_time("00:05:23,")) self.assertIsNone(parse_time("00:05:23+")) self.assertIsNone(parse_time("00:05:23+25:00")) self.assertIsNone(parse_time("4:18:101")) self.assertIsNone(parse_time("91500")) with self.assertRaises(ValueError): parse_time("09:15:90") def test_parse_datetime(self): valid_inputs = ( ("2012-04-23", datetime(2012, 4, 23)), ("2012-04-23T09:15:00", datetime(2012, 4, 23, 9, 15)), ("2012-4-9 4:8:16", datetime(2012, 4, 9, 4, 8, 16)), ( "2012-04-23T09:15:00Z", datetime(2012, 4, 23, 9, 15, 0, 0, get_fixed_timezone(0)), ), ( "2012-4-9 4:8:16-0320", datetime(2012, 4, 9, 4, 8, 16, 0, get_fixed_timezone(-200)), ), ( "2012-04-23T10:20:30.400+02:30", datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(150)), ), ( "2012-04-23T10:20:30.400+02", datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(120)), ), ( "2012-04-23T10:20:30.400-02", datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(-120)), ), ( "2012-04-23T10:20:30,400-02", datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(-120)), ), ( "2012-04-23T10:20:30.400 +0230", datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(150)), ), ( "2012-04-23T10:20:30,400 +00", datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(0)), ), ( "2012-04-23T10:20:30 -02", datetime(2012, 4, 23, 10, 20, 30, 0, get_fixed_timezone(-120)), ), ) for source, expected in valid_inputs: with self.subTest(source=source): self.assertEqual(parse_datetime(source), expected) # Invalid inputs self.assertIsNone(parse_datetime("20120423091500")) with self.assertRaises(ValueError): parse_datetime("2012-04-56T09:15:90") class DurationParseTests(unittest.TestCase): def test_parse_python_format(self): timedeltas = [ timedelta( days=4, minutes=15, seconds=30, milliseconds=100 ), # fractions of seconds timedelta(hours=10, minutes=15, seconds=30), # hours, minutes, seconds timedelta(days=4, minutes=15, seconds=30), # multiple days timedelta(days=1, minutes=00, seconds=00), # single day timedelta(days=-4, minutes=15, seconds=30), # negative durations timedelta(minutes=15, seconds=30), # minute & seconds timedelta(seconds=30), # seconds ] for delta in timedeltas: with self.subTest(delta=delta): self.assertEqual(parse_duration(format(delta)), delta) def test_parse_postgresql_format(self): test_values = ( ("1 day", timedelta(1)), ("-1 day", timedelta(-1)), ("1 day 0:00:01", timedelta(days=1, seconds=1)), ("1 day -0:00:01", timedelta(days=1, seconds=-1)), ("-1 day -0:00:01", timedelta(days=-1, seconds=-1)), ("-1 day +0:00:01", timedelta(days=-1, seconds=1)), ( "4 days 0:15:30.1", timedelta(days=4, minutes=15, seconds=30, milliseconds=100), ), ( "4 days 0:15:30.0001", timedelta(days=4, minutes=15, seconds=30, microseconds=100), ), ("-4 days -15:00:30", timedelta(days=-4, hours=-15, seconds=-30)), ) for source, expected in test_values: with self.subTest(source=source): self.assertEqual(parse_duration(source), expected) def test_seconds(self): self.assertEqual(parse_duration("30"), timedelta(seconds=30)) def test_minutes_seconds(self): self.assertEqual(parse_duration("15:30"), timedelta(minutes=15, seconds=30)) self.assertEqual(parse_duration("5:30"), timedelta(minutes=5, seconds=30)) def test_hours_minutes_seconds(self): self.assertEqual( parse_duration("10:15:30"), timedelta(hours=10, minutes=15, seconds=30) ) self.assertEqual( parse_duration("1:15:30"), timedelta(hours=1, minutes=15, seconds=30) ) self.assertEqual( parse_duration("100:200:300"), timedelta(hours=100, minutes=200, seconds=300), ) def test_days(self): self.assertEqual( parse_duration("4 15:30"), timedelta(days=4, minutes=15, seconds=30) ) self.assertEqual( parse_duration("4 10:15:30"), timedelta(days=4, hours=10, minutes=15, seconds=30), ) def test_fractions_of_seconds(self): test_values = ( ("15:30.1", timedelta(minutes=15, seconds=30, milliseconds=100)), ("15:30.01", timedelta(minutes=15, seconds=30, milliseconds=10)), ("15:30.001", timedelta(minutes=15, seconds=30, milliseconds=1)), ("15:30.0001", timedelta(minutes=15, seconds=30, microseconds=100)), ("15:30.00001", timedelta(minutes=15, seconds=30, microseconds=10)), ("15:30.000001", timedelta(minutes=15, seconds=30, microseconds=1)), ("15:30,000001", timedelta(minutes=15, seconds=30, microseconds=1)), ) for source, expected in test_values: with self.subTest(source=source): self.assertEqual(parse_duration(source), expected) def test_negative(self): test_values = ( ("-4 15:30", timedelta(days=-4, minutes=15, seconds=30)), ("-172800", timedelta(days=-2)), ("-15:30", timedelta(minutes=-15, seconds=-30)), ("-1:15:30", timedelta(hours=-1, minutes=-15, seconds=-30)), ("-30.1", timedelta(seconds=-30, milliseconds=-100)), ("-30,1", timedelta(seconds=-30, milliseconds=-100)), ("-00:01:01", timedelta(minutes=-1, seconds=-1)), ("-01:01", timedelta(seconds=-61)), ("-01:-01", None), ) for source, expected in test_values: with self.subTest(source=source): self.assertEqual(parse_duration(source), expected) def test_iso_8601(self): test_values = ( ("P4Y", None), ("P4M", None), ("P4W", None), ("P4D", timedelta(days=4)), ("-P1D", timedelta(days=-1)), ("P0.5D", timedelta(hours=12)), ("P0,5D", timedelta(hours=12)), ("-P0.5D", timedelta(hours=-12)), ("-P0,5D", timedelta(hours=-12)), ("PT5H", timedelta(hours=5)), ("-PT5H", timedelta(hours=-5)), ("PT5M", timedelta(minutes=5)), ("-PT5M", timedelta(minutes=-5)), ("PT5S", timedelta(seconds=5)), ("-PT5S", timedelta(seconds=-5)), ("PT0.000005S", timedelta(microseconds=5)), ("PT0,000005S", timedelta(microseconds=5)), ("-PT0.000005S", timedelta(microseconds=-5)), ("-PT0,000005S", timedelta(microseconds=-5)), ("-P4DT1H", timedelta(days=-4, hours=-1)), # Invalid separators for decimal fractions. ("P3(3D", None), ("PT3)3H", None), ("PT3|3M", None), ("PT3/3S", None), ) for source, expected in test_values: with self.subTest(source=source): self.assertEqual(parse_duration(source), expected)
django
python
import copy import os import sys from importlib import import_module from importlib.util import find_spec as importlib_find def cached_import(module_path, class_name): # Check whether module is loaded and fully initialized. if not ( (module := sys.modules.get(module_path)) and (spec := getattr(module, "__spec__", None)) and getattr(spec, "_initializing", False) is False ): module = import_module(module_path) return getattr(module, class_name) def import_string(dotted_path): """ Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import failed. """ try: module_path, class_name = dotted_path.rsplit(".", 1) except ValueError as err: raise ImportError("%s doesn't look like a module path" % dotted_path) from err try: return cached_import(module_path, class_name) except AttributeError as err: raise ImportError( 'Module "%s" does not define a "%s" attribute/class' % (module_path, class_name) ) from err def autodiscover_modules(*args, **kwargs): """ Auto-discover INSTALLED_APPS modules and fail silently when not present. This forces an import on them to register any admin bits they may want. You may provide a register_to keyword parameter as a way to access a registry. This register_to object must have a _registry instance variable to access it. """ from django.apps import apps register_to = kwargs.get("register_to") for app_config in apps.get_app_configs(): for module_to_search in args: # Attempt to import the app's module. try: if register_to: before_import_registry = copy.copy(register_to._registry) import_module("%s.%s" % (app_config.name, module_to_search)) except Exception: # Reset the registry to the state before the last import # as this import will have to reoccur on the next request and # this could raise NotRegistered and AlreadyRegistered # exceptions (see #8245). if register_to: register_to._registry = before_import_registry # Decide whether to bubble up this error. If the app just # doesn't have the module in question, we can ignore the error # attempting to import it, otherwise we want it to bubble up. if module_has_submodule(app_config.module, module_to_search): raise def module_has_submodule(package, module_name): """See if 'module' is in 'package'.""" try: package_name = package.__name__ package_path = package.__path__ except AttributeError: # package isn't a package. return False full_module_name = package_name + "." + module_name try: return importlib_find(full_module_name, package_path) is not None except ModuleNotFoundError: # When module_name is an invalid dotted path, Python raises # ModuleNotFoundError. return False def module_dir(module): """ Find the name of the directory that contains a module, if possible. Raise ValueError otherwise, e.g. for namespace packages that are split over several directories. """ # Convert to list because __path__ may not support indexing. paths = list(getattr(module, "__path__", [])) if len(paths) == 1: return paths[0] else: filename = getattr(module, "__file__", None) if filename is not None: return os.path.dirname(filename) raise ValueError("Cannot determine directory containing %s" % module)
import os import sys import unittest from importlib import import_module from zipimport import zipimporter from django.test import SimpleTestCase, modify_settings from django.test.utils import extend_sys_path from django.utils.module_loading import ( autodiscover_modules, import_string, module_has_submodule, ) class DefaultLoader(unittest.TestCase): def test_loader(self): "Normal module existence can be tested" test_module = import_module("utils_tests.test_module") test_no_submodule = import_module("utils_tests.test_no_submodule") # An importable child self.assertTrue(module_has_submodule(test_module, "good_module")) mod = import_module("utils_tests.test_module.good_module") self.assertEqual(mod.content, "Good Module") # A child that exists, but will generate an import error if loaded self.assertTrue(module_has_submodule(test_module, "bad_module")) with self.assertRaises(ImportError): import_module("utils_tests.test_module.bad_module") # A child that doesn't exist self.assertFalse(module_has_submodule(test_module, "no_such_module")) with self.assertRaises(ImportError): import_module("utils_tests.test_module.no_such_module") # A child that doesn't exist, but is the name of a package on the path self.assertFalse(module_has_submodule(test_module, "django")) with self.assertRaises(ImportError): import_module("utils_tests.test_module.django") # Don't be confused by caching of import misses import types # NOQA: causes attempted import of utils_tests.types self.assertFalse(module_has_submodule(sys.modules["utils_tests"], "types")) # A module which doesn't have a __path__ (so no submodules) self.assertFalse(module_has_submodule(test_no_submodule, "anything")) with self.assertRaises(ImportError): import_module("utils_tests.test_no_submodule.anything") def test_has_sumbodule_with_dotted_path(self): """Nested module existence can be tested.""" test_module = import_module("utils_tests.test_module") # A grandchild that exists. self.assertIs( module_has_submodule(test_module, "child_module.grandchild_module"), True ) # A grandchild that doesn't exist. self.assertIs( module_has_submodule(test_module, "child_module.no_such_module"), False ) # A grandchild whose parent doesn't exist. self.assertIs( module_has_submodule(test_module, "no_such_module.grandchild_module"), False ) # A grandchild whose parent is not a package. self.assertIs( module_has_submodule(test_module, "good_module.no_such_module"), False ) class EggLoader(unittest.TestCase): def setUp(self): self.egg_dir = "%s/eggs" % os.path.dirname(__file__) def tearDown(self): sys.path_importer_cache.clear() sys.modules.pop("egg_module.sub1.sub2.bad_module", None) sys.modules.pop("egg_module.sub1.sub2.good_module", None) sys.modules.pop("egg_module.sub1.sub2", None) sys.modules.pop("egg_module.sub1", None) sys.modules.pop("egg_module.bad_module", None) sys.modules.pop("egg_module.good_module", None) sys.modules.pop("egg_module", None) def test_shallow_loader(self): "Module existence can be tested inside eggs" egg_name = "%s/test_egg.egg" % self.egg_dir with extend_sys_path(egg_name): egg_module = import_module("egg_module") # An importable child self.assertTrue(module_has_submodule(egg_module, "good_module")) mod = import_module("egg_module.good_module") self.assertEqual(mod.content, "Good Module") # A child that exists, but will generate an import error if loaded self.assertTrue(module_has_submodule(egg_module, "bad_module")) with self.assertRaises(ImportError): import_module("egg_module.bad_module") # A child that doesn't exist self.assertFalse(module_has_submodule(egg_module, "no_such_module")) with self.assertRaises(ImportError): import_module("egg_module.no_such_module") def test_deep_loader(self): "Modules deep inside an egg can still be tested for existence" egg_name = "%s/test_egg.egg" % self.egg_dir with extend_sys_path(egg_name): egg_module = import_module("egg_module.sub1.sub2") # An importable child self.assertTrue(module_has_submodule(egg_module, "good_module")) mod = import_module("egg_module.sub1.sub2.good_module") self.assertEqual(mod.content, "Deep Good Module") # A child that exists, but will generate an import error if loaded self.assertTrue(module_has_submodule(egg_module, "bad_module")) with self.assertRaises(ImportError): import_module("egg_module.sub1.sub2.bad_module") # A child that doesn't exist self.assertFalse(module_has_submodule(egg_module, "no_such_module")) with self.assertRaises(ImportError): import_module("egg_module.sub1.sub2.no_such_module") class ModuleImportTests(SimpleTestCase): def test_import_string(self): cls = import_string("django.utils.module_loading.import_string") self.assertEqual(cls, import_string) # Test exceptions raised with self.assertRaises(ImportError): import_string("no_dots_in_path") msg = 'Module "utils_tests" does not define a "unexistent" attribute' with self.assertRaisesMessage(ImportError, msg): import_string("utils_tests.unexistent") @modify_settings(INSTALLED_APPS={"append": "utils_tests.test_module"}) class AutodiscoverModulesTestCase(SimpleTestCase): def tearDown(self): sys.path_importer_cache.clear() sys.modules.pop("utils_tests.test_module.another_bad_module", None) sys.modules.pop("utils_tests.test_module.another_good_module", None) sys.modules.pop("utils_tests.test_module.bad_module", None) sys.modules.pop("utils_tests.test_module.good_module", None) sys.modules.pop("utils_tests.test_module", None) def test_autodiscover_modules_found(self): autodiscover_modules("good_module") def test_autodiscover_modules_not_found(self): autodiscover_modules("missing_module") def test_autodiscover_modules_found_but_bad_module(self): with self.assertRaisesMessage( ImportError, "No module named 'a_package_name_that_does_not_exist'" ): autodiscover_modules("bad_module") def test_autodiscover_modules_several_one_bad_module(self): with self.assertRaisesMessage( ImportError, "No module named 'a_package_name_that_does_not_exist'" ): autodiscover_modules("good_module", "bad_module") def test_autodiscover_modules_several_found(self): autodiscover_modules("good_module", "another_good_module") def test_autodiscover_modules_several_found_with_registry(self): from .test_module import site autodiscover_modules("good_module", "another_good_module", register_to=site) self.assertEqual(site._registry, {"lorem": "ipsum"}) def test_validate_registry_keeps_intact(self): from .test_module import site with self.assertRaisesMessage(Exception, "Some random exception."): autodiscover_modules("another_bad_module", register_to=site) self.assertEqual(site._registry, {}) def test_validate_registry_resets_after_erroneous_module(self): from .test_module import site with self.assertRaisesMessage(Exception, "Some random exception."): autodiscover_modules( "another_good_module", "another_bad_module", register_to=site ) self.assertEqual(site._registry, {"lorem": "ipsum"}) def test_validate_registry_resets_after_missing_module(self): from .test_module import site autodiscover_modules( "does_not_exist", "another_good_module", "does_not_exist2", register_to=site ) self.assertEqual(site._registry, {"lorem": "ipsum"}) class TestFinder: def __init__(self, *args, **kwargs): self.importer = zipimporter(*args, **kwargs) def find_spec(self, path, target=None): return self.importer.find_spec(path, target) class CustomLoader(EggLoader): """The Custom Loader test is exactly the same as the EggLoader, but it uses a custom defined Loader class. Although the EggLoader combines both functions into one class, this isn't required. """ def setUp(self): super().setUp() sys.path_hooks.insert(0, TestFinder) sys.path_importer_cache.clear() def tearDown(self): super().tearDown() sys.path_hooks.pop(0)
django
python
from django.apps import apps from django.contrib.sites.models import Site from django.core.cache import cache from django.test import TestCase, modify_settings, override_settings from .models import I18nTestModel, TestModel @modify_settings(INSTALLED_APPS={"append": "django.contrib.sitemaps"}) @override_settings(ROOT_URLCONF="sitemaps_tests.urls.http") class SitemapTestsBase(TestCase): protocol = "http" sites_installed = apps.is_installed("django.contrib.sites") domain = "example.com" if sites_installed else "testserver" @classmethod def setUpTestData(cls): # Create an object for sitemap content. TestModel.objects.create(name="Test Object") cls.i18n_model = I18nTestModel.objects.create(name="Test Object") def setUp(self): self.base_url = "%s://%s" % (self.protocol, self.domain) cache.clear() @classmethod def setUpClass(cls): super().setUpClass() # This cleanup is necessary because contrib.sites cache # makes tests interfere with each other, see #11505 Site.objects.clear_cache()
import logging import time from logging_tests.tests import LoggingAssertionMixin from django.core.exceptions import ImproperlyConfigured from django.http import HttpResponse from django.test import RequestFactory, SimpleTestCase, override_settings from django.test.utils import require_jinja2 from django.urls import resolve from django.views.generic import RedirectView, TemplateView, View from . import views class SimpleView(View): """ A simple view with a docstring. """ def get(self, request): return HttpResponse("This is a simple view") class SimplePostView(SimpleView): post = SimpleView.get class PostOnlyView(View): def post(self, request): return HttpResponse("This view only accepts POST") class CustomizableView(SimpleView): parameter = {} def decorator(view): view.is_decorated = True return view class DecoratedDispatchView(SimpleView): @decorator def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) class AboutTemplateView(TemplateView): def get(self, request): return self.render_to_response({}) def get_template_names(self): return ["generic_views/about.html"] class AboutTemplateAttributeView(TemplateView): template_name = "generic_views/about.html" def get(self, request): return self.render_to_response(context={}) class InstanceView(View): def get(self, request): return self class ViewTest(LoggingAssertionMixin, SimpleTestCase): rf = RequestFactory() def _assert_simple(self, response): self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"This is a simple view") def test_no_init_kwargs(self): """ A view can't be accidentally instantiated before deployment """ msg = "This method is available only on the class, not on instances." with self.assertRaisesMessage(AttributeError, msg): SimpleView(key="value").as_view() def test_no_init_args(self): """ A view can't be accidentally instantiated before deployment """ msg = "as_view() takes 1 positional argument but 2 were given" with self.assertRaisesMessage(TypeError, msg): SimpleView.as_view("value") def test_pathological_http_method(self): """ The edge case of an HTTP request that spoofs an existing method name is caught. """ self.assertEqual( SimpleView.as_view()( self.rf.get("/", REQUEST_METHOD="DISPATCH") ).status_code, 405, ) def test_get_only(self): """ Test a view which only allows GET doesn't allow other methods. """ self._assert_simple(SimpleView.as_view()(self.rf.get("/"))) self.assertEqual(SimpleView.as_view()(self.rf.post("/")).status_code, 405) self.assertEqual( SimpleView.as_view()(self.rf.get("/", REQUEST_METHOD="FAKE")).status_code, 405, ) def test_get_and_head(self): """ Test a view which supplies a GET method also responds correctly to HEAD. """ self._assert_simple(SimpleView.as_view()(self.rf.get("/"))) response = SimpleView.as_view()(self.rf.head("/")) self.assertEqual(response.status_code, 200) def test_setup_get_and_head(self): view_instance = SimpleView() self.assertFalse(hasattr(view_instance, "head")) view_instance.setup(self.rf.get("/")) self.assertTrue(hasattr(view_instance, "head")) self.assertEqual(view_instance.head, view_instance.get) def test_head_no_get(self): """ Test a view which supplies no GET method responds to HEAD with HTTP 405. """ response = PostOnlyView.as_view()(self.rf.head("/")) self.assertEqual(response.status_code, 405) def test_get_and_post(self): """ Test a view which only allows both GET and POST. """ self._assert_simple(SimplePostView.as_view()(self.rf.get("/"))) self._assert_simple(SimplePostView.as_view()(self.rf.post("/"))) self.assertEqual( SimplePostView.as_view()( self.rf.get("/", REQUEST_METHOD="FAKE") ).status_code, 405, ) def test_invalid_keyword_argument(self): """ View arguments must be predefined on the class and can't be named like an HTTP method. """ msg = ( "The method name %s is not accepted as a keyword argument to " "SimpleView()." ) # Check each of the allowed method names for method in SimpleView.http_method_names: with self.assertRaisesMessage(TypeError, msg % method): SimpleView.as_view(**{method: "value"}) # Check the case view argument is ok if predefined on the class... CustomizableView.as_view(parameter="value") # ...but raises errors otherwise. msg = ( "CustomizableView() received an invalid keyword 'foobar'. " "as_view only accepts arguments that are already attributes of " "the class." ) with self.assertRaisesMessage(TypeError, msg): CustomizableView.as_view(foobar="value") def test_calling_more_than_once(self): """ Test a view can only be called once. """ request = self.rf.get("/") view = InstanceView.as_view() self.assertNotEqual(view(request), view(request)) def test_class_attributes(self): """ The callable returned from as_view() has proper special attributes. """ cls = SimpleView view = cls.as_view() self.assertEqual(view.__doc__, cls.__doc__) self.assertEqual(view.__name__, "view") self.assertEqual(view.__module__, cls.__module__) self.assertEqual(view.__qualname__, f"{cls.as_view.__qualname__}.<locals>.view") self.assertEqual(view.__annotations__, cls.dispatch.__annotations__) self.assertFalse(hasattr(view, "__wrapped__")) def test_dispatch_decoration(self): """ Attributes set by decorators on the dispatch method are also present on the closure. """ self.assertTrue(DecoratedDispatchView.as_view().is_decorated) def test_options(self): """ Views respond to HTTP OPTIONS requests with an Allow header appropriate for the methods implemented by the view class. """ request = self.rf.options("/") view = SimpleView.as_view() response = view(request) self.assertEqual(200, response.status_code) self.assertTrue(response.headers["Allow"]) def test_options_for_get_view(self): """ A view implementing GET allows GET and HEAD. """ request = self.rf.options("/") view = SimpleView.as_view() response = view(request) self._assert_allows(response, "GET", "HEAD") def test_options_for_get_and_post_view(self): """ A view implementing GET and POST allows GET, HEAD, and POST. """ request = self.rf.options("/") view = SimplePostView.as_view() response = view(request) self._assert_allows(response, "GET", "HEAD", "POST") def test_options_for_post_view(self): """ A view implementing POST allows POST. """ request = self.rf.options("/") view = PostOnlyView.as_view() response = view(request) self._assert_allows(response, "POST") def _assert_allows(self, response, *expected_methods): "Assert allowed HTTP methods reported in the Allow response header" response_allows = set(response.headers["Allow"].split(", ")) self.assertEqual(set(expected_methods + ("OPTIONS",)), response_allows) def test_args_kwargs_request_on_self(self): """ Test a view only has args, kwargs & request once `as_view` has been called. """ bare_view = InstanceView() view = InstanceView.as_view()(self.rf.get("/")) for attribute in ("args", "kwargs", "request"): self.assertNotIn(attribute, dir(bare_view)) self.assertIn(attribute, dir(view)) def test_overridden_setup(self): class SetAttributeMixin: def setup(self, request, *args, **kwargs): self.attr = True super().setup(request, *args, **kwargs) class CheckSetupView(SetAttributeMixin, SimpleView): def dispatch(self, request, *args, **kwargs): assert hasattr(self, "attr") return super().dispatch(request, *args, **kwargs) response = CheckSetupView.as_view()(self.rf.get("/")) self.assertEqual(response.status_code, 200) def test_not_calling_parent_setup_error(self): class TestView(View): def setup(self, request, *args, **kwargs): pass # Not calling super().setup() msg = ( "TestView instance has no 'request' attribute. Did you override " "setup() and forget to call super()?" ) with self.assertRaisesMessage(AttributeError, msg): TestView.as_view()(self.rf.get("/")) def test_setup_adds_args_kwargs_request(self): request = self.rf.get("/") args = ("arg 1", "arg 2") kwargs = {"kwarg_1": 1, "kwarg_2": "year"} view = View() view.setup(request, *args, **kwargs) self.assertEqual(request, view.request) self.assertEqual(args, view.args) self.assertEqual(kwargs, view.kwargs) def test_direct_instantiation(self): """ It should be possible to use the view by directly instantiating it without going through .as_view() (#21564). """ view = PostOnlyView() response = view.dispatch(self.rf.head("/")) self.assertEqual(response.status_code, 405) def test_method_not_allowed_response_logged(self): for path, escaped in [ ("/foo/", "/foo/"), (r"/%1B[1;31mNOW IN RED!!!1B[0m/", r"/\x1b[1;31mNOW IN RED!!!1B[0m/"), ]: with self.subTest(path=path): request = self.rf.get(path, REQUEST_METHOD="BOGUS") with self.assertLogs("django.request", "WARNING") as handler: response = SimpleView.as_view()(request) self.assertLogRecord( handler, f"Method Not Allowed (BOGUS): {escaped}", logging.WARNING, 405, request, ) self.assertEqual(response.status_code, 405) @override_settings(ROOT_URLCONF="generic_views.urls") class TemplateViewTest(SimpleTestCase): rf = RequestFactory() def _assert_about(self, response): response.render() self.assertContains(response, "<h1>About</h1>") def test_get(self): """ Test a view that simply renders a template on GET """ self._assert_about(AboutTemplateView.as_view()(self.rf.get("/about/"))) def test_head(self): """ Test a TemplateView responds correctly to HEAD """ response = AboutTemplateView.as_view()(self.rf.head("/about/")) self.assertEqual(response.status_code, 200) def test_get_template_attribute(self): """ Test a view that renders a template on GET with the template name as an attribute on the class. """ self._assert_about(AboutTemplateAttributeView.as_view()(self.rf.get("/about/"))) def test_get_generic_template(self): """ Test a completely generic view that renders a template on GET with the template name as an argument at instantiation. """ self._assert_about( TemplateView.as_view(template_name="generic_views/about.html")( self.rf.get("/about/") ) ) def test_template_name_required(self): """ A template view must provide a template name. """ msg = ( "TemplateResponseMixin requires either a definition of " "'template_name' or an implementation of 'get_template_names()'" ) with self.assertRaisesMessage(ImproperlyConfigured, msg): self.client.get("/template/no_template/") @require_jinja2 def test_template_engine(self): """ A template view may provide a template engine. """ request = self.rf.get("/using/") view = TemplateView.as_view(template_name="generic_views/using.html") self.assertEqual(view(request).render().content, b"DTL\n") view = TemplateView.as_view( template_name="generic_views/using.html", template_engine="django" ) self.assertEqual(view(request).render().content, b"DTL\n") view = TemplateView.as_view( template_name="generic_views/using.html", template_engine="jinja2" ) self.assertEqual(view(request).render().content, b"Jinja2\n") def test_template_params(self): """ A generic template view passes kwargs as context. """ response = self.client.get("/template/simple/bar/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["foo"], "bar") self.assertIsInstance(response.context["view"], View) def test_extra_template_params(self): """ A template view can be customized to return extra context. """ response = self.client.get("/template/custom/bar/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["foo"], "bar") self.assertEqual(response.context["key"], "value") self.assertIsInstance(response.context["view"], View) def test_cached_views(self): """ A template view can be cached """ response = self.client.get("/template/cached/bar/") self.assertEqual(response.status_code, 200) time.sleep(1.0) response2 = self.client.get("/template/cached/bar/") self.assertEqual(response2.status_code, 200) self.assertEqual(response.content, response2.content) time.sleep(2.0) # Let the cache expire and test again response2 = self.client.get("/template/cached/bar/") self.assertEqual(response2.status_code, 200) self.assertNotEqual(response.content, response2.content) def test_content_type(self): response = self.client.get("/template/content_type/") self.assertEqual(response.headers["Content-Type"], "text/plain") def test_resolve_view(self): match = resolve("/template/content_type/") self.assertIs(match.func.view_class, TemplateView) self.assertEqual(match.func.view_initkwargs["content_type"], "text/plain") def test_resolve_login_required_view(self): match = resolve("/template/login_required/") self.assertIs(match.func.view_class, TemplateView) def test_extra_context(self): response = self.client.get("/template/extra_context/") self.assertEqual(response.context["title"], "Title") @override_settings(ROOT_URLCONF="generic_views.urls") class RedirectViewTest(LoggingAssertionMixin, SimpleTestCase): rf = RequestFactory() def test_no_url(self): "Without any configuration, returns HTTP 410 GONE" response = RedirectView.as_view()(self.rf.get("/foo/")) self.assertEqual(response.status_code, 410) def test_default_redirect(self): "Default is a temporary redirect" response = RedirectView.as_view(url="/bar/")(self.rf.get("/foo/")) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, "/bar/") def test_permanent_redirect(self): "Permanent redirects are an option" response = RedirectView.as_view(url="/bar/", permanent=True)( self.rf.get("/foo/") ) self.assertEqual(response.status_code, 301) self.assertEqual(response.url, "/bar/") def test_temporary_redirect(self): "Temporary redirects are an option" response = RedirectView.as_view(url="/bar/", permanent=False)( self.rf.get("/foo/") ) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, "/bar/") def test_include_args(self): "GET arguments can be included in the redirected URL" response = RedirectView.as_view(url="/bar/")(self.rf.get("/foo/")) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, "/bar/") response = RedirectView.as_view(url="/bar/", query_string=True)( self.rf.get("/foo/?pork=spam") ) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, "/bar/?pork=spam") def test_include_urlencoded_args(self): "GET arguments can be URL-encoded when included in the redirected URL" response = RedirectView.as_view(url="/bar/", query_string=True)( self.rf.get("/foo/?unicode=%E2%9C%93") ) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, "/bar/?unicode=%E2%9C%93") def test_parameter_substitution(self): "Redirection URLs can be parameterized" response = RedirectView.as_view(url="/bar/%(object_id)d/")( self.rf.get("/foo/42/"), object_id=42 ) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, "/bar/42/") def test_named_url_pattern(self): "Named pattern parameter should reverse to the matching pattern" response = RedirectView.as_view(pattern_name="artist_detail")( self.rf.get("/foo/"), pk=1 ) self.assertEqual(response.status_code, 302) self.assertEqual(response.headers["Location"], "/detail/artist/1/") def test_named_url_pattern_using_args(self): response = RedirectView.as_view(pattern_name="artist_detail")( self.rf.get("/foo/"), 1 ) self.assertEqual(response.status_code, 302) self.assertEqual(response.headers["Location"], "/detail/artist/1/") def test_redirect_POST(self): "Default is a temporary redirect" response = RedirectView.as_view(url="/bar/")(self.rf.post("/foo/")) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, "/bar/") def test_redirect_HEAD(self): "Default is a temporary redirect" response = RedirectView.as_view(url="/bar/")(self.rf.head("/foo/")) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, "/bar/") def test_redirect_OPTIONS(self): "Default is a temporary redirect" response = RedirectView.as_view(url="/bar/")(self.rf.options("/foo/")) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, "/bar/") def test_redirect_PUT(self): "Default is a temporary redirect" response = RedirectView.as_view(url="/bar/")(self.rf.put("/foo/")) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, "/bar/") def test_redirect_PATCH(self): "Default is a temporary redirect" response = RedirectView.as_view(url="/bar/")(self.rf.patch("/foo/")) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, "/bar/") def test_redirect_DELETE(self): "Default is a temporary redirect" response = RedirectView.as_view(url="/bar/")(self.rf.delete("/foo/")) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, "/bar/") def test_redirect_when_meta_contains_no_query_string(self): "regression for #16705" # we can't use self.rf.get because it always sets QUERY_STRING response = RedirectView.as_view(url="/bar/")(self.rf.request(PATH_INFO="/foo/")) self.assertEqual(response.status_code, 302) def test_direct_instantiation(self): """ It should be possible to use the view without going through .as_view() (#21564). """ view = RedirectView() response = view.dispatch(self.rf.head("/foo/")) self.assertEqual(response.status_code, 410) def test_gone_response_logged(self): for path, escaped in [ ("/foo/", "/foo/"), (r"/%1B[1;31mNOW IN RED!!!1B[0m/", r"/\x1b[1;31mNOW IN RED!!!1B[0m/"), ]: with self.subTest(path=path): request = self.rf.get(path) with self.assertLogs("django.request", "WARNING") as handler: RedirectView().dispatch(request) self.assertLogRecord( handler, f"Gone: {escaped}", logging.WARNING, 410, request ) def test_redirect_with_querry_string_in_destination(self): response = RedirectView.as_view(url="/bar/?pork=spam", query_string=True)( self.rf.get("/foo") ) self.assertEqual(response.status_code, 302) self.assertEqual(response.headers["Location"], "/bar/?pork=spam") def test_redirect_with_query_string_in_destination_and_request(self): response = RedirectView.as_view(url="/bar/?pork=spam", query_string=True)( self.rf.get("/foo/?utm_source=social") ) self.assertEqual(response.status_code, 302) self.assertEqual( response.headers["Location"], "/bar/?pork=spam&utm_source=social" ) def test_redirect_with_same_query_string_param_will_append_not_replace(self): response = RedirectView.as_view(url="/bar/?pork=spam", query_string=True)( self.rf.get("/foo/?utm_source=social&pork=ham") ) self.assertEqual(response.status_code, 302) self.assertEqual( response.headers["Location"], "/bar/?pork=spam&utm_source=social&pork=ham" ) class GetContextDataTest(SimpleTestCase): def test_get_context_data_super(self): test_view = views.CustomContextView() context = test_view.get_context_data(kwarg_test="kwarg_value") # the test_name key is inserted by the test classes parent self.assertIn("test_name", context) self.assertEqual(context["kwarg_test"], "kwarg_value") self.assertEqual(context["custom_key"], "custom_value") # test that kwarg overrides values assigned higher up context = test_view.get_context_data(test_name="test_value") self.assertEqual(context["test_name"], "test_value") def test_object_at_custom_name_in_context_data(self): # Checks 'pony' key presence in dict returned by get_context_date test_view = views.CustomSingleObjectView() test_view.context_object_name = "pony" context = test_view.get_context_data() self.assertEqual(context["pony"], test_view.object) def test_object_in_get_context_data(self): # Checks 'object' key presence in dict returned by get_context_date # #20234 test_view = views.CustomSingleObjectView() context = test_view.get_context_data() self.assertEqual(context["object"], test_view.object) class UseMultipleObjectMixinTest(SimpleTestCase): rf = RequestFactory() def test_use_queryset_from_view(self): test_view = views.CustomMultipleObjectMixinView() test_view.get(self.rf.get("/")) # Don't pass queryset as argument context = test_view.get_context_data() self.assertEqual(context["object_list"], test_view.queryset) def test_overwrite_queryset(self): test_view = views.CustomMultipleObjectMixinView() test_view.get(self.rf.get("/")) queryset = [{"name": "Lennon"}, {"name": "Ono"}] self.assertNotEqual(test_view.queryset, queryset) # Overwrite the view's queryset with queryset from kwarg context = test_view.get_context_data(object_list=queryset) self.assertEqual(context["object_list"], queryset) class SingleObjectTemplateResponseMixinTest(SimpleTestCase): def test_template_mixin_without_template(self): """ We want to makes sure that if you use a template mixin, but forget the template, it still tells you it's ImproperlyConfigured instead of TemplateDoesNotExist. """ view = views.TemplateResponseWithoutTemplate() msg = ( "SingleObjectTemplateResponseMixin requires a definition " "of 'template_name', 'template_name_field', or 'model'; " "or an implementation of 'get_template_names()'." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): view.get_template_names()
django
python
import datetime from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db import models from django.http import Http404 from django.utils import timezone from django.utils.functional import cached_property from django.utils.translation import gettext as _ from django.views.generic.base import View from django.views.generic.detail import ( BaseDetailView, SingleObjectTemplateResponseMixin, ) from django.views.generic.list import ( MultipleObjectMixin, MultipleObjectTemplateResponseMixin, ) class YearMixin: """Mixin for views manipulating year-based data.""" year_format = "%Y" year = None def get_year_format(self): """ Get a year format string in strptime syntax to be used to parse the year from url variables. """ return self.year_format def get_year(self): """Return the year for which this view should display data.""" year = self.year if year is None: try: year = self.kwargs["year"] except KeyError: try: year = self.request.GET["year"] except KeyError: raise Http404(_("No year specified")) return year def get_next_year(self, date): """Get the next valid year.""" return _get_next_prev(self, date, is_previous=False, period="year") def get_previous_year(self, date): """Get the previous valid year.""" return _get_next_prev(self, date, is_previous=True, period="year") def _get_next_year(self, date): """ Return the start date of the next interval. The interval is defined by start date <= item date < next start date. """ try: return date.replace(year=date.year + 1, month=1, day=1) except ValueError: raise Http404(_("Date out of range")) def _get_current_year(self, date): """Return the start date of the current interval.""" return date.replace(month=1, day=1) class MonthMixin: """Mixin for views manipulating month-based data.""" month_format = "%b" month = None def get_month_format(self): """ Get a month format string in strptime syntax to be used to parse the month from url variables. """ return self.month_format def get_month(self): """Return the month for which this view should display data.""" month = self.month if month is None: try: month = self.kwargs["month"] except KeyError: try: month = self.request.GET["month"] except KeyError: raise Http404(_("No month specified")) return month def get_next_month(self, date): """Get the next valid month.""" return _get_next_prev(self, date, is_previous=False, period="month") def get_previous_month(self, date): """Get the previous valid month.""" return _get_next_prev(self, date, is_previous=True, period="month") def _get_next_month(self, date): """ Return the start date of the next interval. The interval is defined by start date <= item date < next start date. """ if date.month == 12: try: return date.replace(year=date.year + 1, month=1, day=1) except ValueError: raise Http404(_("Date out of range")) else: return date.replace(month=date.month + 1, day=1) def _get_current_month(self, date): """Return the start date of the previous interval.""" return date.replace(day=1) class DayMixin: """Mixin for views manipulating day-based data.""" day_format = "%d" day = None def get_day_format(self): """ Get a day format string in strptime syntax to be used to parse the day from url variables. """ return self.day_format def get_day(self): """Return the day for which this view should display data.""" day = self.day if day is None: try: day = self.kwargs["day"] except KeyError: try: day = self.request.GET["day"] except KeyError: raise Http404(_("No day specified")) return day def get_next_day(self, date): """Get the next valid day.""" return _get_next_prev(self, date, is_previous=False, period="day") def get_previous_day(self, date): """Get the previous valid day.""" return _get_next_prev(self, date, is_previous=True, period="day") def _get_next_day(self, date): """ Return the start date of the next interval. The interval is defined by start date <= item date < next start date. """ return date + datetime.timedelta(days=1) def _get_current_day(self, date): """Return the start date of the current interval.""" return date class WeekMixin: """Mixin for views manipulating week-based data.""" week_format = "%U" week = None def get_week_format(self): """ Get a week format string in strptime syntax to be used to parse the week from url variables. """ return self.week_format def get_week(self): """Return the week for which this view should display data.""" week = self.week if week is None: try: week = self.kwargs["week"] except KeyError: try: week = self.request.GET["week"] except KeyError: raise Http404(_("No week specified")) return week def get_next_week(self, date): """Get the next valid week.""" return _get_next_prev(self, date, is_previous=False, period="week") def get_previous_week(self, date): """Get the previous valid week.""" return _get_next_prev(self, date, is_previous=True, period="week") def _get_next_week(self, date): """ Return the start date of the next interval. The interval is defined by start date <= item date < next start date. """ try: return date + datetime.timedelta(days=7 - self._get_weekday(date)) except OverflowError: raise Http404(_("Date out of range")) def _get_current_week(self, date): """Return the start date of the current interval.""" return date - datetime.timedelta(self._get_weekday(date)) def _get_weekday(self, date): """ Return the weekday for a given date. The first day according to the week format is 0 and the last day is 6. """ week_format = self.get_week_format() if week_format in {"%W", "%V"}: # week starts on Monday return date.weekday() elif week_format == "%U": # week starts on Sunday return (date.weekday() + 1) % 7 else: raise ValueError("unknown week format: %s" % week_format) class DateMixin: """Mixin class for views manipulating date-based data.""" date_field = None allow_future = False def get_date_field(self): """Get the name of the date field to be used to filter by.""" if self.date_field is None: raise ImproperlyConfigured( "%s.date_field is required." % self.__class__.__name__ ) return self.date_field def get_allow_future(self): """ Return `True` if the view should be allowed to display objects from the future. """ return self.allow_future # Note: the following three methods only work in subclasses that also # inherit SingleObjectMixin or MultipleObjectMixin. @cached_property def uses_datetime_field(self): """ Return `True` if the date field is a `DateTimeField` and `False` if it's a `DateField`. """ model = self.get_queryset().model if self.model is None else self.model field = model._meta.get_field(self.get_date_field()) return isinstance(field, models.DateTimeField) def _make_date_lookup_arg(self, value): """ Convert a date into a datetime when the date field is a DateTimeField. When time zone support is enabled, `date` is assumed to be in the current time zone, so that displayed items are consistent with the URL. """ if self.uses_datetime_field: value = datetime.datetime.combine(value, datetime.time.min) if settings.USE_TZ: value = timezone.make_aware(value) return value def _make_single_date_lookup(self, date): """ Get the lookup kwargs for filtering on a single date. If the date field is a DateTimeField, we can't just filter on date_field=date because that doesn't take the time into account. """ date_field = self.get_date_field() if self.uses_datetime_field: since = self._make_date_lookup_arg(date) until = self._make_date_lookup_arg(date + datetime.timedelta(days=1)) return { "%s__gte" % date_field: since, "%s__lt" % date_field: until, } else: # Skip self._make_date_lookup_arg, it's a no-op in this branch. return {date_field: date} class BaseDateListView(MultipleObjectMixin, DateMixin, View): """ Base class for date-based views displaying a list of objects. This requires subclassing to provide a response mixin. """ allow_empty = False date_list_period = "year" def get(self, request, *args, **kwargs): self.date_list, self.object_list, extra_context = self.get_dated_items() context = self.get_context_data( object_list=self.object_list, date_list=self.date_list, **extra_context ) return self.render_to_response(context) def get_dated_items(self): """Obtain the list of dates and items.""" raise NotImplementedError( "A DateView must provide an implementation of get_dated_items()" ) def get_ordering(self): """ Return the field or fields to use for ordering the queryset; use the date field by default. """ return "-%s" % self.get_date_field() if self.ordering is None else self.ordering def get_dated_queryset(self, **lookup): """ Get a queryset properly filtered according to `allow_future` and any extra lookup kwargs. """ qs = self.get_queryset().filter(**lookup) date_field = self.get_date_field() allow_future = self.get_allow_future() allow_empty = self.get_allow_empty() paginate_by = self.get_paginate_by(qs) if not allow_future: now = timezone.now() if self.uses_datetime_field else timezone_today() qs = qs.filter(**{"%s__lte" % date_field: now}) if not allow_empty: # When pagination is enabled, it's better to do a cheap query # than to load the unpaginated queryset in memory. is_empty = not qs if paginate_by is None else not qs.exists() if is_empty: raise Http404( _("No %(verbose_name_plural)s available") % { "verbose_name_plural": qs.model._meta.verbose_name_plural, } ) return qs def get_date_list_period(self): """ Get the aggregation period for the list of dates: 'year', 'month', or 'day'. """ return self.date_list_period def get_date_list(self, queryset, date_type=None, ordering="ASC"): """ Get a date list by calling `queryset.dates/datetimes()`, checking along the way for empty lists that aren't allowed. """ date_field = self.get_date_field() allow_empty = self.get_allow_empty() if date_type is None: date_type = self.get_date_list_period() if self.uses_datetime_field: date_list = queryset.datetimes(date_field, date_type, ordering) else: date_list = queryset.dates(date_field, date_type, ordering) if date_list is not None and not date_list and not allow_empty: raise Http404( _("No %(verbose_name_plural)s available") % { "verbose_name_plural": queryset.model._meta.verbose_name_plural, } ) return date_list class BaseArchiveIndexView(BaseDateListView): """ Base view for archives of date-based items. This requires subclassing to provide a response mixin. """ context_object_name = "latest" def get_dated_items(self): """Return (date_list, items, extra_context) for this request.""" qs = self.get_dated_queryset() date_list = self.get_date_list(qs, ordering="DESC") if not date_list: qs = qs.none() return (date_list, qs, {}) class ArchiveIndexView(MultipleObjectTemplateResponseMixin, BaseArchiveIndexView): """Top-level archive of date-based items.""" template_name_suffix = "_archive" class BaseYearArchiveView(YearMixin, BaseDateListView): """ Base view for a list of objects published in a given year. This requires subclassing to provide a response mixin. """ date_list_period = "month" make_object_list = False def get_dated_items(self): """Return (date_list, items, extra_context) for this request.""" year = self.get_year() date_field = self.get_date_field() date = _date_from_string(year, self.get_year_format()) since = self._make_date_lookup_arg(date) until = self._make_date_lookup_arg(self._get_next_year(date)) lookup_kwargs = { "%s__gte" % date_field: since, "%s__lt" % date_field: until, } qs = self.get_dated_queryset(**lookup_kwargs) date_list = self.get_date_list(qs) if not self.get_make_object_list(): # We need this to be a queryset since parent classes introspect it # to find information about the model. qs = qs.none() return ( date_list, qs, { "year": date, "next_year": self.get_next_year(date), "previous_year": self.get_previous_year(date), }, ) def get_make_object_list(self): """ Return `True` if this view should contain the full list of objects in the given year. """ return self.make_object_list class YearArchiveView(MultipleObjectTemplateResponseMixin, BaseYearArchiveView): """List of objects published in a given year.""" template_name_suffix = "_archive_year" class BaseMonthArchiveView(YearMixin, MonthMixin, BaseDateListView): """ Base view for a list of objects published in a given month. This requires subclassing to provide a response mixin. """ date_list_period = "day" def get_dated_items(self): """Return (date_list, items, extra_context) for this request.""" year = self.get_year() month = self.get_month() date_field = self.get_date_field() date = _date_from_string( year, self.get_year_format(), month, self.get_month_format() ) since = self._make_date_lookup_arg(date) until = self._make_date_lookup_arg(self._get_next_month(date)) lookup_kwargs = { "%s__gte" % date_field: since, "%s__lt" % date_field: until, } qs = self.get_dated_queryset(**lookup_kwargs) date_list = self.get_date_list(qs) return ( date_list, qs, { "month": date, "next_month": self.get_next_month(date), "previous_month": self.get_previous_month(date), }, ) class MonthArchiveView(MultipleObjectTemplateResponseMixin, BaseMonthArchiveView): """List of objects published in a given month.""" template_name_suffix = "_archive_month" class BaseWeekArchiveView(YearMixin, WeekMixin, BaseDateListView): """ Base view for a list of objects published in a given week. This requires subclassing to provide a response mixin. """ def get_dated_items(self): """Return (date_list, items, extra_context) for this request.""" year = self.get_year() week = self.get_week() date_field = self.get_date_field() week_format = self.get_week_format() week_choices = {"%W": "1", "%U": "0", "%V": "1"} try: week_start = week_choices[week_format] except KeyError: raise ValueError( "Unknown week format %r. Choices are: %s" % ( week_format, ", ".join(sorted(week_choices)), ) ) year_format = self.get_year_format() if week_format == "%V" and year_format != "%G": raise ValueError( "ISO week directive '%s' is incompatible with the year " "directive '%s'. Use the ISO year '%%G' instead." % ( week_format, year_format, ) ) date = _date_from_string(year, year_format, week_start, "%w", week, week_format) since = self._make_date_lookup_arg(date) until = self._make_date_lookup_arg(self._get_next_week(date)) lookup_kwargs = { "%s__gte" % date_field: since, "%s__lt" % date_field: until, } qs = self.get_dated_queryset(**lookup_kwargs) return ( None, qs, { "week": date, "next_week": self.get_next_week(date), "previous_week": self.get_previous_week(date), }, ) class WeekArchiveView(MultipleObjectTemplateResponseMixin, BaseWeekArchiveView): """List of objects published in a given week.""" template_name_suffix = "_archive_week" class BaseDayArchiveView(YearMixin, MonthMixin, DayMixin, BaseDateListView): """ Base view for a list of objects published on a given day. This requires subclassing to provide a response mixin. """ def get_dated_items(self): """Return (date_list, items, extra_context) for this request.""" year = self.get_year() month = self.get_month() day = self.get_day() date = _date_from_string( year, self.get_year_format(), month, self.get_month_format(), day, self.get_day_format(), ) return self._get_dated_items(date) def _get_dated_items(self, date): """ Do the actual heavy lifting of getting the dated items; this accepts a date object so that TodayArchiveView can be trivial. """ lookup_kwargs = self._make_single_date_lookup(date) qs = self.get_dated_queryset(**lookup_kwargs) return ( None, qs, { "day": date, "previous_day": self.get_previous_day(date), "next_day": self.get_next_day(date), "previous_month": self.get_previous_month(date), "next_month": self.get_next_month(date), }, ) class DayArchiveView(MultipleObjectTemplateResponseMixin, BaseDayArchiveView): """List of objects published on a given day.""" template_name_suffix = "_archive_day" class BaseTodayArchiveView(BaseDayArchiveView): """ Base view for a list of objects published today. This requires subclassing to provide a response mixin. """ def get_dated_items(self): """Return (date_list, items, extra_context) for this request.""" return self._get_dated_items(datetime.date.today()) class TodayArchiveView(MultipleObjectTemplateResponseMixin, BaseTodayArchiveView): """List of objects published today.""" template_name_suffix = "_archive_day" class BaseDateDetailView(YearMixin, MonthMixin, DayMixin, DateMixin, BaseDetailView): """ Base detail view for a single object on a single date; this differs from the standard DetailView by accepting a year/month/day in the URL. This requires subclassing to provide a response mixin. """ def get_object(self, queryset=None): """Get the object this request displays.""" year = self.get_year() month = self.get_month() day = self.get_day() date = _date_from_string( year, self.get_year_format(), month, self.get_month_format(), day, self.get_day_format(), ) # Use a custom queryset if provided qs = self.get_queryset() if queryset is None else queryset if not self.get_allow_future() and date > datetime.date.today(): raise Http404( _( "Future %(verbose_name_plural)s not available because " "%(class_name)s.allow_future is False." ) % { "verbose_name_plural": qs.model._meta.verbose_name_plural, "class_name": self.__class__.__name__, } ) # Filter down a queryset from self.queryset using the date from the # URL. This'll get passed as the queryset to DetailView.get_object, # which'll handle the 404 lookup_kwargs = self._make_single_date_lookup(date) qs = qs.filter(**lookup_kwargs) return super().get_object(queryset=qs) class DateDetailView(SingleObjectTemplateResponseMixin, BaseDateDetailView): """ Detail view of a single object on a single date; this differs from the standard DetailView by accepting a year/month/day in the URL. """ template_name_suffix = "_detail" def _date_from_string( year, year_format, month="", month_format="", day="", day_format="", delim="__" ): """ Get a datetime.date object given a format string and a year, month, and day (only year is mandatory). Raise a 404 for an invalid date. """ format = year_format + delim + month_format + delim + day_format datestr = str(year) + delim + str(month) + delim + str(day) try: return datetime.datetime.strptime(datestr, format).date() except ValueError: raise Http404( _("Invalid date string “%(datestr)s” given format “%(format)s”") % { "datestr": datestr, "format": format, } ) def _get_next_prev(generic_view, date, is_previous, period): """ Get the next or the previous valid date. The idea is to allow links on month/day views to never be 404s by never providing a date that'll be invalid for the given view. This is a bit complicated since it handles different intervals of time, hence the coupling to generic_view. However in essence the logic comes down to: * If allow_empty and allow_future are both true, this is easy: just return the naive result (just the next/previous day/week/month, regardless of object existence.) * If allow_empty is true, allow_future is false, and the naive result isn't in the future, then return it; otherwise return None. * If allow_empty is false and allow_future is true, return the next date *that contains a valid object*, even if it's in the future. If there are no next objects, return None. * If allow_empty is false and allow_future is false, return the next date that contains a valid object. If that date is in the future, or if there are no next objects, return None. """ date_field = generic_view.get_date_field() allow_empty = generic_view.get_allow_empty() allow_future = generic_view.get_allow_future() get_current = getattr(generic_view, "_get_current_%s" % period) get_next = getattr(generic_view, "_get_next_%s" % period) # Bounds of the current interval start, end = get_current(date), get_next(date) # If allow_empty is True, the naive result will be valid if allow_empty: if is_previous: result = get_current(start - datetime.timedelta(days=1)) else: result = end if allow_future or result <= timezone_today(): return result else: return None # Otherwise, we'll need to go to the database to look for an object # whose date_field is at least (greater than/less than) the given # naive result else: # Construct a lookup and an ordering depending on whether we're doing # a previous date or a next date lookup. if is_previous: lookup = {"%s__lt" % date_field: generic_view._make_date_lookup_arg(start)} ordering = "-%s" % date_field else: lookup = {"%s__gte" % date_field: generic_view._make_date_lookup_arg(end)} ordering = date_field # Filter out objects in the future if appropriate. if not allow_future: # Fortunately, to match the implementation of allow_future, # we need __lte, which doesn't conflict with __lt above. if generic_view.uses_datetime_field: now = timezone.now() else: now = timezone_today() lookup["%s__lte" % date_field] = now qs = generic_view.get_queryset().filter(**lookup).order_by(ordering) # Snag the first object from the queryset; if it doesn't exist that # means there's no next/previous link available. try: result = getattr(qs[0], date_field) except IndexError: return None # Convert datetimes to dates in the current time zone. if generic_view.uses_datetime_field: if settings.USE_TZ: result = timezone.localtime(result) result = result.date() # Return the first day of the period. return get_current(result) def timezone_today(): """Return the current date in the current time zone.""" if settings.USE_TZ: return timezone.localdate() else: return datetime.date.today()
import datetime from unittest import mock from django.core.exceptions import ImproperlyConfigured from django.test import TestCase, override_settings, skipUnlessDBFeature from django.test.utils import requires_tz_support from .models import Artist, Author, Book, BookSigning, Page def _make_books(n, base_date): for i in range(n): Book.objects.create( name="Book %d" % i, slug="book-%d" % i, pages=100 + i, pubdate=base_date - datetime.timedelta(days=i), ) class TestDataMixin: @classmethod def setUpTestData(cls): cls.artist1 = Artist.objects.create(name="Rene Magritte") cls.author1 = Author.objects.create( name="Roberto Bolaño", slug="roberto-bolano" ) cls.author2 = Author.objects.create( name="Scott Rosenberg", slug="scott-rosenberg" ) cls.book1 = Book.objects.create( name="2066", slug="2066", pages=800, pubdate=datetime.date(2008, 10, 1) ) cls.book1.authors.add(cls.author1) cls.book2 = Book.objects.create( name="Dreaming in Code", slug="dreaming-in-code", pages=300, pubdate=datetime.date(2006, 5, 1), ) cls.page1 = Page.objects.create( content="I was once bitten by a moose.", template="generic_views/page_template.html", ) @override_settings(ROOT_URLCONF="generic_views.urls") class ArchiveIndexViewTests(TestDataMixin, TestCase): def test_archive_view(self): res = self.client.get("/dates/books/") self.assertEqual(res.status_code, 200) self.assertEqual( list(res.context["date_list"]), list(Book.objects.dates("pubdate", "year", "DESC")), ) self.assertEqual(list(res.context["latest"]), list(Book.objects.all())) self.assertTemplateUsed(res, "generic_views/book_archive.html") def test_archive_view_context_object_name(self): res = self.client.get("/dates/books/context_object_name/") self.assertEqual(res.status_code, 200) self.assertEqual( list(res.context["date_list"]), list(Book.objects.dates("pubdate", "year", "DESC")), ) self.assertEqual(list(res.context["thingies"]), list(Book.objects.all())) self.assertNotIn("latest", res.context) self.assertTemplateUsed(res, "generic_views/book_archive.html") def test_empty_archive_view(self): Book.objects.all().delete() res = self.client.get("/dates/books/") self.assertEqual(res.status_code, 404) def test_allow_empty_archive_view(self): Book.objects.all().delete() res = self.client.get("/dates/books/allow_empty/") self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context["date_list"]), []) self.assertTemplateUsed(res, "generic_views/book_archive.html") def test_archive_view_template(self): res = self.client.get("/dates/books/template_name/") self.assertEqual(res.status_code, 200) self.assertEqual( list(res.context["date_list"]), list(Book.objects.dates("pubdate", "year", "DESC")), ) self.assertEqual(list(res.context["latest"]), list(Book.objects.all())) self.assertTemplateUsed(res, "generic_views/list.html") def test_archive_view_template_suffix(self): res = self.client.get("/dates/books/template_name_suffix/") self.assertEqual(res.status_code, 200) self.assertEqual( list(res.context["date_list"]), list(Book.objects.dates("pubdate", "year", "DESC")), ) self.assertEqual(list(res.context["latest"]), list(Book.objects.all())) self.assertTemplateUsed(res, "generic_views/book_detail.html") def test_archive_view_invalid(self): msg = ( "BookArchive is missing a QuerySet. Define BookArchive.model, " "BookArchive.queryset, or override BookArchive.get_queryset()." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): self.client.get("/dates/books/invalid/") def test_archive_view_by_month(self): res = self.client.get("/dates/books/by_month/") self.assertEqual(res.status_code, 200) self.assertEqual( list(res.context["date_list"]), list(Book.objects.dates("pubdate", "month", "DESC")), ) def test_paginated_archive_view(self): _make_books(20, base_date=datetime.date.today()) res = self.client.get("/dates/books/paginated/") self.assertEqual(res.status_code, 200) self.assertEqual( list(res.context["date_list"]), list(Book.objects.dates("pubdate", "year", "DESC")), ) self.assertEqual(list(res.context["latest"]), list(Book.objects.all()[0:10])) self.assertTemplateUsed(res, "generic_views/book_archive.html") res = self.client.get("/dates/books/paginated/?page=2") self.assertEqual(res.status_code, 200) self.assertEqual(res.context["page_obj"].number, 2) self.assertEqual(list(res.context["latest"]), list(Book.objects.all()[10:20])) def test_paginated_archive_view_does_not_load_entire_table(self): # Regression test for #18087 _make_books(20, base_date=datetime.date.today()) # 1 query for years list + 1 query for books with self.assertNumQueries(2): self.client.get("/dates/books/") # same as above + 1 query to test if books exist + 1 query to count # them with self.assertNumQueries(4): self.client.get("/dates/books/paginated/") def test_no_duplicate_query(self): # Regression test for #18354 with self.assertNumQueries(2): self.client.get("/dates/books/reverse/") def test_datetime_archive_view(self): BookSigning.objects.create(event_date=datetime.datetime(2008, 4, 2, 12, 0)) res = self.client.get("/dates/booksignings/") self.assertEqual(res.status_code, 200) @requires_tz_support @skipUnlessDBFeature("has_zoneinfo_database") @override_settings(USE_TZ=True, TIME_ZONE="Africa/Nairobi") def test_aware_datetime_archive_view(self): BookSigning.objects.create( event_date=datetime.datetime(2008, 4, 2, 12, 0, tzinfo=datetime.UTC) ) res = self.client.get("/dates/booksignings/") self.assertEqual(res.status_code, 200) def test_date_list_order(self): """date_list should be sorted descending in index""" _make_books(5, base_date=datetime.date(2011, 12, 25)) res = self.client.get("/dates/books/") self.assertEqual(res.status_code, 200) self.assertEqual( list(res.context["date_list"]), sorted(res.context["date_list"], reverse=True), ) def test_archive_view_custom_sorting(self): Book.objects.create( name="Zebras for Dummies", pages=600, pubdate=datetime.date(2007, 5, 1) ) res = self.client.get("/dates/books/sortedbyname/") self.assertEqual(res.status_code, 200) self.assertEqual( list(res.context["date_list"]), list(Book.objects.dates("pubdate", "year", "DESC")), ) self.assertEqual( list(res.context["latest"]), list(Book.objects.order_by("name").all()) ) self.assertTemplateUsed(res, "generic_views/book_archive.html") def test_archive_view_custom_sorting_dec(self): Book.objects.create( name="Zebras for Dummies", pages=600, pubdate=datetime.date(2007, 5, 1) ) res = self.client.get("/dates/books/sortedbynamedec/") self.assertEqual(res.status_code, 200) self.assertEqual( list(res.context["date_list"]), list(Book.objects.dates("pubdate", "year", "DESC")), ) self.assertEqual( list(res.context["latest"]), list(Book.objects.order_by("-name").all()) ) self.assertTemplateUsed(res, "generic_views/book_archive.html") def test_archive_view_without_date_field(self): msg = "BookArchiveWithoutDateField.date_field is required." with self.assertRaisesMessage(ImproperlyConfigured, msg): self.client.get("/dates/books/without_date_field/") @override_settings(ROOT_URLCONF="generic_views.urls") class YearArchiveViewTests(TestDataMixin, TestCase): def test_year_view(self): res = self.client.get("/dates/books/2008/") self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context["date_list"]), [datetime.date(2008, 10, 1)]) self.assertEqual(res.context["year"], datetime.date(2008, 1, 1)) self.assertTemplateUsed(res, "generic_views/book_archive_year.html") # Since allow_empty=False, next/prev years must be valid (#7164) self.assertIsNone(res.context["next_year"]) self.assertEqual(res.context["previous_year"], datetime.date(2006, 1, 1)) def test_year_view_make_object_list(self): res = self.client.get("/dates/books/2006/make_object_list/") self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context["date_list"]), [datetime.date(2006, 5, 1)]) self.assertEqual( list(res.context["book_list"]), list(Book.objects.filter(pubdate__year=2006)), ) self.assertEqual( list(res.context["object_list"]), list(Book.objects.filter(pubdate__year=2006)), ) self.assertTemplateUsed(res, "generic_views/book_archive_year.html") def test_year_view_empty(self): res = self.client.get("/dates/books/1999/") self.assertEqual(res.status_code, 404) res = self.client.get("/dates/books/1999/allow_empty/") self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context["date_list"]), []) self.assertEqual(list(res.context["book_list"]), []) # Since allow_empty=True, next/prev are allowed to be empty years # (#7164) self.assertEqual(res.context["next_year"], datetime.date(2000, 1, 1)) self.assertEqual(res.context["previous_year"], datetime.date(1998, 1, 1)) def test_year_view_allow_future(self): # Create a new book in the future year = datetime.date.today().year + 1 Book.objects.create( name="The New New Testement", pages=600, pubdate=datetime.date(year, 1, 1) ) res = self.client.get("/dates/books/%s/" % year) self.assertEqual(res.status_code, 404) res = self.client.get("/dates/books/%s/allow_empty/" % year) self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context["book_list"]), []) res = self.client.get("/dates/books/%s/allow_future/" % year) self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context["date_list"]), [datetime.date(year, 1, 1)]) def test_year_view_paginated(self): res = self.client.get("/dates/books/2006/paginated/") self.assertEqual(res.status_code, 200) self.assertEqual( list(res.context["book_list"]), list(Book.objects.filter(pubdate__year=2006)), ) self.assertEqual( list(res.context["object_list"]), list(Book.objects.filter(pubdate__year=2006)), ) self.assertTemplateUsed(res, "generic_views/book_archive_year.html") def test_year_view_custom_sort_order(self): # Zebras comes after Dreaming by name, but before on '-pubdate' which # is the default sorting. Book.objects.create( name="Zebras for Dummies", pages=600, pubdate=datetime.date(2006, 9, 1) ) res = self.client.get("/dates/books/2006/sortedbyname/") self.assertEqual(res.status_code, 200) self.assertEqual( list(res.context["date_list"]), [datetime.date(2006, 5, 1), datetime.date(2006, 9, 1)], ) self.assertEqual( list(res.context["book_list"]), list(Book.objects.filter(pubdate__year=2006).order_by("name")), ) self.assertEqual( list(res.context["object_list"]), list(Book.objects.filter(pubdate__year=2006).order_by("name")), ) self.assertTemplateUsed(res, "generic_views/book_archive_year.html") def test_year_view_two_custom_sort_orders(self): Book.objects.create( name="Zebras for Dummies", pages=300, pubdate=datetime.date(2006, 9, 1) ) Book.objects.create( name="Hunting Hippos", pages=400, pubdate=datetime.date(2006, 3, 1) ) res = self.client.get("/dates/books/2006/sortedbypageandnamedec/") self.assertEqual(res.status_code, 200) self.assertEqual( list(res.context["date_list"]), [ datetime.date(2006, 3, 1), datetime.date(2006, 5, 1), datetime.date(2006, 9, 1), ], ) self.assertEqual( list(res.context["book_list"]), list(Book.objects.filter(pubdate__year=2006).order_by("pages", "-name")), ) self.assertEqual( list(res.context["object_list"]), list(Book.objects.filter(pubdate__year=2006).order_by("pages", "-name")), ) self.assertTemplateUsed(res, "generic_views/book_archive_year.html") def test_year_view_invalid_pattern(self): res = self.client.get("/dates/books/no_year/") self.assertEqual(res.status_code, 404) def test_no_duplicate_query(self): # Regression test for #18354 with self.assertNumQueries(4): self.client.get("/dates/books/2008/reverse/") def test_datetime_year_view(self): BookSigning.objects.create(event_date=datetime.datetime(2008, 4, 2, 12, 0)) res = self.client.get("/dates/booksignings/2008/") self.assertEqual(res.status_code, 200) @skipUnlessDBFeature("has_zoneinfo_database") @override_settings(USE_TZ=True, TIME_ZONE="Africa/Nairobi") def test_aware_datetime_year_view(self): BookSigning.objects.create( event_date=datetime.datetime(2008, 4, 2, 12, 0, tzinfo=datetime.UTC) ) res = self.client.get("/dates/booksignings/2008/") self.assertEqual(res.status_code, 200) def test_date_list_order(self): """date_list should be sorted ascending in year view""" _make_books(10, base_date=datetime.date(2011, 12, 25)) res = self.client.get("/dates/books/2011/") self.assertEqual( list(res.context["date_list"]), sorted(res.context["date_list"]) ) @mock.patch("django.views.generic.list.MultipleObjectMixin.get_context_data") def test_get_context_data_receives_extra_context(self, mock): """ MultipleObjectMixin.get_context_data() receives the context set by BaseYearArchiveView.get_dated_items(). This behavior is implemented in BaseDateListView.get(). """ BookSigning.objects.create(event_date=datetime.datetime(2008, 4, 2, 12, 0)) with self.assertRaisesMessage( TypeError, "context must be a dict rather than MagicMock." ): self.client.get("/dates/booksignings/2008/") args, kwargs = mock.call_args # These are context values from get_dated_items(). self.assertEqual(kwargs["year"], datetime.date(2008, 1, 1)) self.assertIsNone(kwargs["previous_year"]) self.assertIsNone(kwargs["next_year"]) def test_get_dated_items_not_implemented(self): msg = "A DateView must provide an implementation of get_dated_items()" with self.assertRaisesMessage(NotImplementedError, msg): self.client.get("/BaseDateListViewTest/") @override_settings(ROOT_URLCONF="generic_views.urls") class MonthArchiveViewTests(TestDataMixin, TestCase): def test_month_view(self): res = self.client.get("/dates/books/2008/oct/") self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, "generic_views/book_archive_month.html") self.assertEqual(list(res.context["date_list"]), [datetime.date(2008, 10, 1)]) self.assertEqual( list(res.context["book_list"]), list(Book.objects.filter(pubdate=datetime.date(2008, 10, 1))), ) self.assertEqual(res.context["month"], datetime.date(2008, 10, 1)) # Since allow_empty=False, next/prev months must be valid (#7164) self.assertIsNone(res.context["next_month"]) self.assertEqual(res.context["previous_month"], datetime.date(2006, 5, 1)) def test_month_view_allow_empty(self): # allow_empty = False, empty month res = self.client.get("/dates/books/2000/jan/") self.assertEqual(res.status_code, 404) # allow_empty = True, empty month res = self.client.get("/dates/books/2000/jan/allow_empty/") self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context["date_list"]), []) self.assertEqual(list(res.context["book_list"]), []) self.assertEqual(res.context["month"], datetime.date(2000, 1, 1)) # Since allow_empty=True, next/prev are allowed to be empty months # (#7164) self.assertEqual(res.context["next_month"], datetime.date(2000, 2, 1)) self.assertEqual(res.context["previous_month"], datetime.date(1999, 12, 1)) # allow_empty but not allow_future: next_month should be empty (#7164) url = datetime.date.today().strftime("/dates/books/%Y/%b/allow_empty/").lower() res = self.client.get(url) self.assertEqual(res.status_code, 200) self.assertIsNone(res.context["next_month"]) def test_month_view_allow_future(self): future = (datetime.date.today() + datetime.timedelta(days=60)).replace(day=1) urlbit = future.strftime("%Y/%b").lower() b = Book.objects.create(name="The New New Testement", pages=600, pubdate=future) # allow_future = False, future month res = self.client.get("/dates/books/%s/" % urlbit) self.assertEqual(res.status_code, 404) # allow_future = True, valid future month res = self.client.get("/dates/books/%s/allow_future/" % urlbit) self.assertEqual(res.status_code, 200) self.assertEqual(res.context["date_list"][0], b.pubdate) self.assertEqual(list(res.context["book_list"]), [b]) self.assertEqual(res.context["month"], future) # Since allow_future = True but not allow_empty, next/prev are not # allowed to be empty months (#7164) self.assertIsNone(res.context["next_month"]) self.assertEqual(res.context["previous_month"], datetime.date(2008, 10, 1)) # allow_future, but not allow_empty, with a current month. So next # should be in the future (yup, #7164, again) res = self.client.get("/dates/books/2008/oct/allow_future/") self.assertEqual(res.status_code, 200) self.assertEqual(res.context["next_month"], future) self.assertEqual(res.context["previous_month"], datetime.date(2006, 5, 1)) def test_month_view_paginated(self): res = self.client.get("/dates/books/2008/oct/paginated/") self.assertEqual(res.status_code, 200) self.assertEqual( list(res.context["book_list"]), list(Book.objects.filter(pubdate__year=2008, pubdate__month=10)), ) self.assertEqual( list(res.context["object_list"]), list(Book.objects.filter(pubdate__year=2008, pubdate__month=10)), ) self.assertTemplateUsed(res, "generic_views/book_archive_month.html") def test_custom_month_format(self): res = self.client.get("/dates/books/2008/10/") self.assertEqual(res.status_code, 200) def test_month_view_invalid_pattern(self): res = self.client.get("/dates/books/2007/no_month/") self.assertEqual(res.status_code, 404) def test_previous_month_without_content(self): "Content can exist on any day of the previous month. Refs #14711" self.pubdate_list = [ datetime.date(2010, month, day) for month, day in ((9, 1), (10, 2), (11, 3)) ] for pubdate in self.pubdate_list: name = str(pubdate) Book.objects.create(name=name, slug=name, pages=100, pubdate=pubdate) res = self.client.get("/dates/books/2010/nov/allow_empty/") self.assertEqual(res.status_code, 200) self.assertEqual(res.context["previous_month"], datetime.date(2010, 10, 1)) # The following test demonstrates the bug res = self.client.get("/dates/books/2010/nov/") self.assertEqual(res.status_code, 200) self.assertEqual(res.context["previous_month"], datetime.date(2010, 10, 1)) # The bug does not occur here because a Book with pubdate of Sep 1 # exists res = self.client.get("/dates/books/2010/oct/") self.assertEqual(res.status_code, 200) self.assertEqual(res.context["previous_month"], datetime.date(2010, 9, 1)) def test_datetime_month_view(self): BookSigning.objects.create(event_date=datetime.datetime(2008, 2, 1, 12, 0)) BookSigning.objects.create(event_date=datetime.datetime(2008, 4, 2, 12, 0)) BookSigning.objects.create(event_date=datetime.datetime(2008, 6, 3, 12, 0)) res = self.client.get("/dates/booksignings/2008/apr/") self.assertEqual(res.status_code, 200) def test_month_view_get_month_from_request(self): oct1 = datetime.date(2008, 10, 1) res = self.client.get("/dates/books/without_month/2008/?month=oct") self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, "generic_views/book_archive_month.html") self.assertEqual(list(res.context["date_list"]), [oct1]) self.assertEqual( list(res.context["book_list"]), list(Book.objects.filter(pubdate=oct1)) ) self.assertEqual(res.context["month"], oct1) def test_month_view_without_month_in_url(self): res = self.client.get("/dates/books/without_month/2008/") self.assertEqual(res.status_code, 404) self.assertEqual(res.context["exception"], "No month specified") @skipUnlessDBFeature("has_zoneinfo_database") @override_settings(USE_TZ=True, TIME_ZONE="Africa/Nairobi") def test_aware_datetime_month_view(self): BookSigning.objects.create( event_date=datetime.datetime(2008, 2, 1, 12, 0, tzinfo=datetime.UTC) ) BookSigning.objects.create( event_date=datetime.datetime(2008, 4, 2, 12, 0, tzinfo=datetime.UTC) ) BookSigning.objects.create( event_date=datetime.datetime(2008, 6, 3, 12, 0, tzinfo=datetime.UTC) ) res = self.client.get("/dates/booksignings/2008/apr/") self.assertEqual(res.status_code, 200) def test_date_list_order(self): """date_list should be sorted ascending in month view""" _make_books(10, base_date=datetime.date(2011, 12, 25)) res = self.client.get("/dates/books/2011/dec/") self.assertEqual( list(res.context["date_list"]), sorted(res.context["date_list"]) ) @override_settings(ROOT_URLCONF="generic_views.urls") class WeekArchiveViewTests(TestDataMixin, TestCase): def test_week_view(self): res = self.client.get("/dates/books/2008/week/39/") self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, "generic_views/book_archive_week.html") self.assertEqual( res.context["book_list"][0], Book.objects.get(pubdate=datetime.date(2008, 10, 1)), ) self.assertEqual(res.context["week"], datetime.date(2008, 9, 28)) # Since allow_empty=False, next/prev weeks must be valid self.assertIsNone(res.context["next_week"]) self.assertEqual(res.context["previous_week"], datetime.date(2006, 4, 30)) def test_week_view_allow_empty(self): # allow_empty = False, empty week res = self.client.get("/dates/books/2008/week/12/") self.assertEqual(res.status_code, 404) # allow_empty = True, empty month res = self.client.get("/dates/books/2008/week/12/allow_empty/") self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context["book_list"]), []) self.assertEqual(res.context["week"], datetime.date(2008, 3, 23)) # Since allow_empty=True, next/prev are allowed to be empty weeks self.assertEqual(res.context["next_week"], datetime.date(2008, 3, 30)) self.assertEqual(res.context["previous_week"], datetime.date(2008, 3, 16)) # allow_empty but not allow_future: next_week should be empty url = ( datetime.date.today() .strftime("/dates/books/%Y/week/%U/allow_empty/") .lower() ) res = self.client.get(url) self.assertEqual(res.status_code, 200) self.assertIsNone(res.context["next_week"]) def test_week_view_allow_future(self): # January 7th always falls in week 1, given Python's definition of week # numbers future = datetime.date(datetime.date.today().year + 1, 1, 7) future_sunday = future - datetime.timedelta(days=(future.weekday() + 1) % 7) b = Book.objects.create(name="The New New Testement", pages=600, pubdate=future) res = self.client.get("/dates/books/%s/week/1/" % future.year) self.assertEqual(res.status_code, 404) res = self.client.get("/dates/books/%s/week/1/allow_future/" % future.year) self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context["book_list"]), [b]) self.assertEqual(res.context["week"], future_sunday) # Since allow_future = True but not allow_empty, next/prev are not # allowed to be empty weeks self.assertIsNone(res.context["next_week"]) self.assertEqual(res.context["previous_week"], datetime.date(2008, 9, 28)) # allow_future, but not allow_empty, with a current week. So next # should be in the future res = self.client.get("/dates/books/2008/week/39/allow_future/") self.assertEqual(res.status_code, 200) self.assertEqual(res.context["next_week"], future_sunday) self.assertEqual(res.context["previous_week"], datetime.date(2006, 4, 30)) def test_week_view_paginated(self): week_start = datetime.date(2008, 9, 28) week_end = week_start + datetime.timedelta(days=7) res = self.client.get("/dates/books/2008/week/39/") self.assertEqual(res.status_code, 200) self.assertEqual( list(res.context["book_list"]), list(Book.objects.filter(pubdate__gte=week_start, pubdate__lt=week_end)), ) self.assertEqual( list(res.context["object_list"]), list(Book.objects.filter(pubdate__gte=week_start, pubdate__lt=week_end)), ) self.assertTemplateUsed(res, "generic_views/book_archive_week.html") def test_week_view_invalid_pattern(self): res = self.client.get("/dates/books/2007/week/no_week/") self.assertEqual(res.status_code, 404) def test_week_start_Monday(self): # Regression for #14752 res = self.client.get("/dates/books/2008/week/39/") self.assertEqual(res.status_code, 200) self.assertEqual(res.context["week"], datetime.date(2008, 9, 28)) res = self.client.get("/dates/books/2008/week/39/monday/") self.assertEqual(res.status_code, 200) self.assertEqual(res.context["week"], datetime.date(2008, 9, 29)) def test_week_iso_format(self): res = self.client.get("/dates/books/2008/week/40/iso_format/") self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, "generic_views/book_archive_week.html") self.assertEqual( list(res.context["book_list"]), [Book.objects.get(pubdate=datetime.date(2008, 10, 1))], ) self.assertEqual(res.context["week"], datetime.date(2008, 9, 29)) def test_unknown_week_format(self): msg = "Unknown week format '%T'. Choices are: %U, %V, %W" with self.assertRaisesMessage(ValueError, msg): self.client.get("/dates/books/2008/week/39/unknown_week_format/") def test_incompatible_iso_week_format_view(self): msg = ( "ISO week directive '%V' is incompatible with the year directive " "'%Y'. Use the ISO year '%G' instead." ) with self.assertRaisesMessage(ValueError, msg): self.client.get("/dates/books/2008/week/40/invalid_iso_week_year_format/") def test_datetime_week_view(self): BookSigning.objects.create(event_date=datetime.datetime(2008, 4, 2, 12, 0)) res = self.client.get("/dates/booksignings/2008/week/13/") self.assertEqual(res.status_code, 200) @override_settings(USE_TZ=True, TIME_ZONE="Africa/Nairobi") def test_aware_datetime_week_view(self): BookSigning.objects.create( event_date=datetime.datetime(2008, 4, 2, 12, 0, tzinfo=datetime.UTC) ) res = self.client.get("/dates/booksignings/2008/week/13/") self.assertEqual(res.status_code, 200) @override_settings(ROOT_URLCONF="generic_views.urls") class DayArchiveViewTests(TestDataMixin, TestCase): def test_day_view(self): res = self.client.get("/dates/books/2008/oct/01/") self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, "generic_views/book_archive_day.html") self.assertEqual( list(res.context["book_list"]), list(Book.objects.filter(pubdate=datetime.date(2008, 10, 1))), ) self.assertEqual(res.context["day"], datetime.date(2008, 10, 1)) # Since allow_empty=False, next/prev days must be valid. self.assertIsNone(res.context["next_day"]) self.assertEqual(res.context["previous_day"], datetime.date(2006, 5, 1)) def test_day_view_allow_empty(self): # allow_empty = False, empty month res = self.client.get("/dates/books/2000/jan/1/") self.assertEqual(res.status_code, 404) # allow_empty = True, empty month res = self.client.get("/dates/books/2000/jan/1/allow_empty/") self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context["book_list"]), []) self.assertEqual(res.context["day"], datetime.date(2000, 1, 1)) # Since it's allow empty, next/prev are allowed to be empty months # (#7164) self.assertEqual(res.context["next_day"], datetime.date(2000, 1, 2)) self.assertEqual(res.context["previous_day"], datetime.date(1999, 12, 31)) # allow_empty but not allow_future: next_month should be empty (#7164) url = ( datetime.date.today().strftime("/dates/books/%Y/%b/%d/allow_empty/").lower() ) res = self.client.get(url) self.assertEqual(res.status_code, 200) self.assertIsNone(res.context["next_day"]) def test_day_view_allow_future(self): future = datetime.date.today() + datetime.timedelta(days=60) urlbit = future.strftime("%Y/%b/%d").lower() b = Book.objects.create(name="The New New Testement", pages=600, pubdate=future) # allow_future = False, future month res = self.client.get("/dates/books/%s/" % urlbit) self.assertEqual(res.status_code, 404) # allow_future = True, valid future month res = self.client.get("/dates/books/%s/allow_future/" % urlbit) self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context["book_list"]), [b]) self.assertEqual(res.context["day"], future) # allow_future but not allow_empty, next/prev must be valid self.assertIsNone(res.context["next_day"]) self.assertEqual(res.context["previous_day"], datetime.date(2008, 10, 1)) # allow_future, but not allow_empty, with a current month. res = self.client.get("/dates/books/2008/oct/01/allow_future/") self.assertEqual(res.status_code, 200) self.assertEqual(res.context["next_day"], future) self.assertEqual(res.context["previous_day"], datetime.date(2006, 5, 1)) # allow_future for yesterday, next_day is today (#17192) today = datetime.date.today() yesterday = today - datetime.timedelta(days=1) res = self.client.get( "/dates/books/%s/allow_empty_and_future/" % yesterday.strftime("%Y/%b/%d").lower() ) self.assertEqual(res.context["next_day"], today) def test_day_view_paginated(self): res = self.client.get("/dates/books/2008/oct/1/") self.assertEqual(res.status_code, 200) self.assertEqual( list(res.context["book_list"]), list( Book.objects.filter( pubdate__year=2008, pubdate__month=10, pubdate__day=1 ) ), ) self.assertEqual( list(res.context["object_list"]), list( Book.objects.filter( pubdate__year=2008, pubdate__month=10, pubdate__day=1 ) ), ) self.assertTemplateUsed(res, "generic_views/book_archive_day.html") def test_next_prev_context(self): res = self.client.get("/dates/books/2008/oct/01/") self.assertEqual( res.content, b"Archive for Oct. 1, 2008. Previous day is May 1, 2006\n" ) def test_custom_month_format(self): res = self.client.get("/dates/books/2008/10/01/") self.assertEqual(res.status_code, 200) def test_day_view_invalid_pattern(self): res = self.client.get("/dates/books/2007/oct/no_day/") self.assertEqual(res.status_code, 404) def test_today_view(self): res = self.client.get("/dates/books/today/") self.assertEqual(res.status_code, 404) res = self.client.get("/dates/books/today/allow_empty/") self.assertEqual(res.status_code, 200) self.assertEqual(res.context["day"], datetime.date.today()) def test_datetime_day_view(self): BookSigning.objects.create(event_date=datetime.datetime(2008, 4, 2, 12, 0)) res = self.client.get("/dates/booksignings/2008/apr/2/") self.assertEqual(res.status_code, 200) @requires_tz_support @override_settings(USE_TZ=True, TIME_ZONE="Africa/Nairobi") def test_aware_datetime_day_view(self): bs = BookSigning.objects.create( event_date=datetime.datetime(2008, 4, 2, 12, 0, tzinfo=datetime.UTC) ) res = self.client.get("/dates/booksignings/2008/apr/2/") self.assertEqual(res.status_code, 200) # 2008-04-02T00:00:00+03:00 (beginning of day) > # 2008-04-01T22:00:00+00:00 (book signing event date). bs.event_date = datetime.datetime(2008, 4, 1, 22, 0, tzinfo=datetime.UTC) bs.save() res = self.client.get("/dates/booksignings/2008/apr/2/") self.assertEqual(res.status_code, 200) # 2008-04-03T00:00:00+03:00 (end of day) > 2008-04-02T22:00:00+00:00 # (book signing event date). bs.event_date = datetime.datetime(2008, 4, 2, 22, 0, tzinfo=datetime.UTC) bs.save() res = self.client.get("/dates/booksignings/2008/apr/2/") self.assertEqual(res.status_code, 404) @override_settings(ROOT_URLCONF="generic_views.urls") class DateDetailViewTests(TestDataMixin, TestCase): def test_date_detail_by_pk(self): res = self.client.get("/dates/books/2008/oct/01/%s/" % self.book1.pk) self.assertEqual(res.status_code, 200) self.assertEqual(res.context["object"], self.book1) self.assertEqual(res.context["book"], self.book1) self.assertTemplateUsed(res, "generic_views/book_detail.html") def test_date_detail_by_slug(self): res = self.client.get("/dates/books/2006/may/01/byslug/dreaming-in-code/") self.assertEqual(res.status_code, 200) self.assertEqual(res.context["book"], Book.objects.get(slug="dreaming-in-code")) def test_date_detail_custom_month_format(self): res = self.client.get("/dates/books/2008/10/01/%s/" % self.book1.pk) self.assertEqual(res.status_code, 200) self.assertEqual(res.context["book"], self.book1) def test_date_detail_allow_future(self): future = datetime.date.today() + datetime.timedelta(days=60) urlbit = future.strftime("%Y/%b/%d").lower() b = Book.objects.create( name="The New New Testement", slug="new-new", pages=600, pubdate=future ) res = self.client.get("/dates/books/%s/new-new/" % urlbit) self.assertEqual(res.status_code, 404) res = self.client.get("/dates/books/%s/%s/allow_future/" % (urlbit, b.id)) self.assertEqual(res.status_code, 200) self.assertEqual(res.context["book"], b) self.assertTemplateUsed(res, "generic_views/book_detail.html") def test_year_out_of_range(self): urls = [ "/dates/books/9999/", "/dates/books/9999/12/", "/dates/books/9999/week/52/", ] for url in urls: with self.subTest(url=url): res = self.client.get(url) self.assertEqual(res.status_code, 404) self.assertEqual(res.context["exception"], "Date out of range") def test_invalid_url(self): msg = ( "Generic detail view BookDetail must be called with either an " "object pk or a slug in the URLconf." ) with self.assertRaisesMessage(AttributeError, msg): self.client.get("/dates/books/2008/oct/01/nopk/") def test_get_object_custom_queryset(self): """ Custom querysets are used when provided to BaseDateDetailView.get_object(). """ res = self.client.get( "/dates/books/get_object_custom_queryset/2006/may/01/%s/" % self.book2.pk ) self.assertEqual(res.status_code, 200) self.assertEqual(res.context["object"], self.book2) self.assertEqual(res.context["book"], self.book2) self.assertTemplateUsed(res, "generic_views/book_detail.html") res = self.client.get( "/dates/books/get_object_custom_queryset/2008/oct/01/9999999/" ) self.assertEqual(res.status_code, 404) def test_get_object_custom_queryset_numqueries(self): with self.assertNumQueries(1): self.client.get("/dates/books/get_object_custom_queryset/2006/may/01/2/") def test_datetime_date_detail(self): bs = BookSigning.objects.create(event_date=datetime.datetime(2008, 4, 2, 12, 0)) res = self.client.get("/dates/booksignings/2008/apr/2/%d/" % bs.pk) self.assertEqual(res.status_code, 200) @requires_tz_support @override_settings(USE_TZ=True, TIME_ZONE="Africa/Nairobi") def test_aware_datetime_date_detail(self): bs = BookSigning.objects.create( event_date=datetime.datetime(2008, 4, 2, 12, 0, tzinfo=datetime.UTC) ) res = self.client.get("/dates/booksignings/2008/apr/2/%d/" % bs.pk) self.assertEqual(res.status_code, 200) # 2008-04-02T00:00:00+03:00 (beginning of day) > # 2008-04-01T22:00:00+00:00 (book signing event date). bs.event_date = datetime.datetime(2008, 4, 1, 22, 0, tzinfo=datetime.UTC) bs.save() res = self.client.get("/dates/booksignings/2008/apr/2/%d/" % bs.pk) self.assertEqual(res.status_code, 200) # 2008-04-03T00:00:00+03:00 (end of day) > 2008-04-02T22:00:00+00:00 # (book signing event date). bs.event_date = datetime.datetime(2008, 4, 2, 22, 0, tzinfo=datetime.UTC) bs.save() res = self.client.get("/dates/booksignings/2008/apr/2/%d/" % bs.pk) self.assertEqual(res.status_code, 404)
django
python
import platform def on_macos_with_hfs(): """ MacOS 10.13 (High Sierra) and lower can use HFS+ as a filesystem. HFS+ has a time resolution of only one second which can be too low for some of the tests. """ macos_version = platform.mac_ver()[0] if macos_version != "": parsed_macos_version = tuple(int(x) for x in macos_version.split(".")) return parsed_macos_version < (10, 14) return False
import unittest from django.contrib.admindocs.utils import ( docutils_is_available, parse_docstring, parse_rst, ) from django.test.utils import captured_stderr from .tests import AdminDocsSimpleTestCase @unittest.skipUnless(docutils_is_available, "no docutils installed.") class TestUtils(AdminDocsSimpleTestCase): """ This __doc__ output is required for testing. I copied this example from `admindocs` documentation. (TITLE) Display an individual :model:`myapp.MyModel`. **Context** ``RequestContext`` ``mymodel`` An instance of :model:`myapp.MyModel`. **Template:** :template:`myapp/my_template.html` (DESCRIPTION) some_metadata: some data """ def setUp(self): self.docstring = self.__doc__ def test_parse_docstring(self): title, description, metadata = parse_docstring(self.docstring) docstring_title = ( "This __doc__ output is required for testing. I copied this example from\n" "`admindocs` documentation. (TITLE)" ) docstring_description = ( "Display an individual :model:`myapp.MyModel`.\n\n" "**Context**\n\n``RequestContext``\n\n``mymodel``\n" " An instance of :model:`myapp.MyModel`.\n\n" "**Template:**\n\n:template:`myapp/my_template.html` " "(DESCRIPTION)" ) self.assertEqual(title, docstring_title) self.assertEqual(description, docstring_description) self.assertEqual(metadata, {"some_metadata": "some data"}) def test_title_output(self): title, description, metadata = parse_docstring(self.docstring) title_output = parse_rst(title, "model", "model:admindocs") self.assertIn("TITLE", title_output) title_rendered = ( "<p>This __doc__ output is required for testing. I copied this " 'example from\n<a class="reference external" ' 'href="/admindocs/models/admindocs/">admindocs</a> documentation. ' "(TITLE)</p>\n" ) self.assertHTMLEqual(title_output, title_rendered) def test_description_output(self): title, description, metadata = parse_docstring(self.docstring) description_output = parse_rst(description, "model", "model:admindocs") description_rendered = ( '<p>Display an individual <a class="reference external" ' 'href="/admindocs/models/myapp.mymodel/">myapp.MyModel</a>.</p>\n' '<p><strong>Context</strong></p>\n<p><tt class="docutils literal">' 'RequestContext</tt></p>\n<dl class="docutils">\n<dt><tt class="' 'docutils literal">mymodel</tt></dt>\n<dd>An instance of <a class="' 'reference external" href="/admindocs/models/myapp.mymodel/">' "myapp.MyModel</a>.</dd>\n</dl>\n<p><strong>Template:</strong></p>" '\n<p><a class="reference external" href="/admindocs/templates/' 'myapp/my_template.html/">myapp/my_template.html</a> (DESCRIPTION)' "</p>\n" ) self.assertHTMLEqual(description_output, description_rendered) def test_initial_header_level(self): header = "should be h3...\n\nHeader\n------\n" output = parse_rst(header, "header") self.assertIn("<h3>Header</h3>", output) def test_parse_rst(self): """ parse_rst() should use `cmsreference` as the default role. """ markup = '<p><a class="reference external" href="/admindocs/%s">title</a></p>\n' self.assertEqual(parse_rst("`title`", "model"), markup % "models/title/") self.assertEqual(parse_rst("`title`", "view"), markup % "views/title/") self.assertEqual(parse_rst("`title`", "template"), markup % "templates/title/") self.assertEqual(parse_rst("`title`", "filter"), markup % "filters/#title") self.assertEqual(parse_rst("`title`", "tag"), markup % "tags/#title") def test_parse_rst_with_docstring_no_leading_line_feed(self): title, body, _ = parse_docstring("firstline\n\n second line") with captured_stderr() as stderr: self.assertEqual(parse_rst(title, ""), "<p>firstline</p>\n") self.assertEqual(parse_rst(body, ""), "<p>second line</p>\n") self.assertEqual(stderr.getvalue(), "") def test_parse_rst_view_case_sensitive(self): source = ":view:`myapp.views.Index`" rendered = ( '<p><a class="reference external" ' 'href="/admindocs/views/myapp.views.Index/">myapp.views.Index</a></p>' ) self.assertHTMLEqual(parse_rst(source, "view"), rendered) def test_parse_rst_template_case_sensitive(self): source = ":template:`Index.html`" rendered = ( '<p><a class="reference external" href="/admindocs/templates/Index.html/">' "Index.html</a></p>" ) self.assertHTMLEqual(parse_rst(source, "template"), rendered) def test_publish_parts(self): """ Django shouldn't break the default role for interpreted text when ``publish_parts`` is used directly, by setting it to ``cmsreference`` (#6681). """ import docutils self.assertNotEqual( docutils.parsers.rst.roles.DEFAULT_INTERPRETED_ROLE, "cmsreference" ) source = "reST, `interpreted text`, default role." markup = "<p>reST, <cite>interpreted text</cite>, default role.</p>\n" parts = docutils.core.publish_parts(source=source, writer="html4css1") self.assertEqual(parts["fragment"], markup)
django
python
import datetime import decimal import logging import sys from pathlib import Path from django.core.exceptions import BadRequest, PermissionDenied, SuspiciousOperation from django.http import Http404, HttpResponse, JsonResponse from django.shortcuts import render from django.template import Context, Template, TemplateDoesNotExist from django.urls import get_resolver from django.views import View from django.views.debug import ( ExceptionReporter, SafeExceptionReporterFilter, technical_500_response, ) from django.views.decorators.debug import sensitive_post_parameters, sensitive_variables TEMPLATES_PATH = Path(__file__).resolve().parent / "templates" def index_page(request): """Dummy index page""" return HttpResponse("<html><body>Dummy page</body></html>") def with_parameter(request, parameter): return HttpResponse("ok") def raises(request): # Make sure that a callable that raises an exception in the stack frame's # local vars won't hijack the technical 500 response (#15025). def callable(): raise Exception try: raise Exception except Exception: return technical_500_response(request, *sys.exc_info()) def raises500(request): # We need to inspect the HTML generated by the fancy 500 debug view but # the test client ignores it, so we send it explicitly. try: raise Exception except Exception: return technical_500_response(request, *sys.exc_info()) class Raises500View(View): def get(self, request): try: raise Exception except Exception: return technical_500_response(request, *sys.exc_info()) def raises400(request): raise SuspiciousOperation def raises400_bad_request(request): raise BadRequest("Malformed request syntax") def raises403(request): raise PermissionDenied("Insufficient Permissions") def raises404(request): resolver = get_resolver(None) resolver.resolve("/not-in-urls") def technical404(request): raise Http404("Testing technical 404.") class Http404View(View): def get(self, request): raise Http404("Testing class-based technical 404.") def template_exception(request): return render(request, "debug/template_exception.html") def safestring_in_template_exception(request): """ Trigger an exception in the template machinery which causes a SafeString to be inserted as args[0] of the Exception. """ template = Template('{% extends "<script>alert(1);</script>" %}') try: template.render(Context()) except Exception: return technical_500_response(request, *sys.exc_info()) def jsi18n(request): return render(request, "jsi18n.html") def jsi18n_multi_catalogs(request): return render(request, "jsi18n-multi-catalogs.html") def raises_template_does_not_exist(request, path="i_dont_exist.html"): # We need to inspect the HTML generated by the fancy 500 debug view but # the test client ignores it, so we send it explicitly. try: return render(request, path) except TemplateDoesNotExist: return technical_500_response(request, *sys.exc_info()) def render_no_template(request): # If we do not specify a template, we need to make sure the debug # view doesn't blow up. return render(request, [], {}) def send_log(request, exc_info): logger = logging.getLogger("django") # The default logging config has a logging filter to ensure admin emails # are only sent with DEBUG=False, but since someone might choose to remove # that filter, we still want to be able to test the behavior of error # emails with DEBUG=True. So we need to remove the filter temporarily. admin_email_handler = [ h for h in logger.handlers if h.__class__.__name__ == "AdminEmailHandler" ][0] orig_filters = admin_email_handler.filters admin_email_handler.filters = [] admin_email_handler.include_html = True logger.error( "Internal Server Error: %s", request.path, exc_info=exc_info, extra={"status_code": 500, "request": request}, ) admin_email_handler.filters = orig_filters def non_sensitive_view(request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables("sauce") @sensitive_post_parameters("bacon-key", "sausage-key") def sensitive_view(request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables("sauce") @sensitive_post_parameters("bacon-key", "sausage-key") async def async_sensitive_view(request): # Do not just use plain strings for the variables' values in the code so # that the tests don't return false positives when the function's source is # displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables("sauce") @sensitive_post_parameters("bacon-key", "sausage-key") async def async_sensitive_function(request): # Do not just use plain strings for the variables' values in the code so # that the tests don't return false positives when the function's source is # displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) raise Exception async def async_sensitive_view_nested(request): try: await async_sensitive_function(request) except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables() @sensitive_post_parameters() def paranoid_view(request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) def sensitive_args_function_caller(request): try: sensitive_args_function( "".join( ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) ) except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables("sauce") def sensitive_args_function(sauce): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA raise Exception def sensitive_kwargs_function_caller(request): try: sensitive_kwargs_function( "".join( ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) ) except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables("sauce") def sensitive_kwargs_function(sauce=None): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA raise Exception class UnsafeExceptionReporterFilter(SafeExceptionReporterFilter): """ Ignores all the filtering done by its parent class. """ def get_post_parameters(self, request): return request.POST def get_traceback_frame_variables(self, request, tb_frame): return tb_frame.f_locals.items() @sensitive_variables() @sensitive_post_parameters() def custom_exception_reporter_filter_view(request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) request.exception_reporter_filter = UnsafeExceptionReporterFilter() try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) class CustomExceptionReporter(ExceptionReporter): custom_traceback_text = "custom traceback text" def get_traceback_html(self): return self.custom_traceback_text class TemplateOverrideExceptionReporter(ExceptionReporter): html_template_path = TEMPLATES_PATH / "my_technical_500.html" text_template_path = TEMPLATES_PATH / "my_technical_500.txt" def custom_reporter_class_view(request): request.exception_reporter_class = CustomExceptionReporter try: raise Exception except Exception: exc_info = sys.exc_info() return technical_500_response(request, *exc_info) class Klass: @sensitive_variables("sauce") def method(self, request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's # source is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables("sauce") async def async_method(self, request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's # source is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables("sauce") async def _async_method_inner(self, request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's # source is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) raise Exception async def async_method_nested(self, request): try: await self._async_method_inner(request) except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) def sensitive_method_view(request): return Klass().method(request) async def async_sensitive_method_view(request): return await Klass().async_method(request) async def async_sensitive_method_view_nested(request): return await Klass().async_method_nested(request) @sensitive_variables("sauce") @sensitive_post_parameters("bacon-key", "sausage-key") def multivalue_dict_key_error(request): cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: request.POST["bar"] except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) def json_response_view(request): return JsonResponse( { "a": [1, 2, 3], "foo": {"bar": "baz"}, # Make sure datetime and Decimal objects would be serialized # properly "timestamp": datetime.datetime(2013, 5, 19, 20), "value": decimal.Decimal("3.14"), } )
import sys import unittest from django.conf import settings from django.contrib import admin from django.contrib.admindocs import utils, views from django.contrib.admindocs.views import get_return_data_type, simplify_regex from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django.db import models from django.db.models import fields from django.test import SimpleTestCase, modify_settings, override_settings from django.test.utils import captured_stderr from django.urls import include, path, reverse from django.utils.functional import SimpleLazyObject from .models import Company, Person from .tests import AdminDocsTestCase, TestDataMixin @unittest.skipUnless(utils.docutils_is_available, "no docutils installed.") class AdminDocViewTests(TestDataMixin, AdminDocsTestCase): def setUp(self): self.client.force_login(self.superuser) def test_index(self): response = self.client.get(reverse("django-admindocs-docroot")) self.assertContains(response, "<h1>Documentation</h1>", html=True) self.assertContains( response, '<div id="site-name"><a href="/admin/">Django administration</a></div>', ) self.client.logout() response = self.client.get(reverse("django-admindocs-docroot"), follow=True) # Should display the login screen self.assertContains( response, '<input type="hidden" name="next" value="/admindocs/">', html=True ) def test_bookmarklets(self): response = self.client.get(reverse("django-admindocs-bookmarklets")) self.assertContains(response, "/admindocs/views/") def test_templatetag_index(self): response = self.client.get(reverse("django-admindocs-tags")) self.assertContains( response, '<h3 id="built_in-extends">extends</h3>', html=True ) def test_templatefilter_index(self): response = self.client.get(reverse("django-admindocs-filters")) self.assertContains(response, '<h3 id="built_in-first">first</h3>', html=True) def test_view_index(self): response = self.client.get(reverse("django-admindocs-views-index")) self.assertContains( response, '<h3><a href="/admindocs/views/django.contrib.admindocs.views.' 'BaseAdminDocsView/">/admindocs/</a></h3>', html=True, ) self.assertContains(response, "Views by namespace test") self.assertContains(response, "Name: <code>test:func</code>.") self.assertContains( response, '<h3><a href="/admindocs/views/admin_docs.views.XViewCallableObject/">' "/xview/callable_object_without_xview/</a></h3>", html=True, ) def test_view_index_with_method(self): """ Views that are methods are listed correctly. """ response = self.client.get(reverse("django-admindocs-views-index")) self.assertContains( response, "<h3>" '<a href="/admindocs/views/django.contrib.admin.sites.AdminSite.index/">' "/admin/</a></h3>", html=True, ) def test_view_detail(self): url = reverse( "django-admindocs-views-detail", args=["django.contrib.admindocs.views.BaseAdminDocsView"], ) response = self.client.get(url) # View docstring self.assertContains(response, "Base view for admindocs views.") def testview_docstring_links(self): summary = ( '<h2 class="subhead">This is a view for ' '<a class="reference external" href="/admindocs/models/myapp.company/">' "myapp.Company</a></h2>" ) url = reverse( "django-admindocs-views-detail", args=["admin_docs.views.CompanyView"] ) response = self.client.get(url) self.assertContains(response, summary, html=True) @override_settings(ROOT_URLCONF="admin_docs.namespace_urls") def test_namespaced_view_detail(self): url = reverse( "django-admindocs-views-detail", args=["admin_docs.views.XViewClass"] ) response = self.client.get(url) self.assertContains(response, "<h1>admin_docs.views.XViewClass</h1>") def test_view_detail_illegal_import(self): url = reverse( "django-admindocs-views-detail", args=["urlpatterns_reverse.nonimported_module.view"], ) response = self.client.get(url) self.assertEqual(response.status_code, 404) self.assertNotIn("urlpatterns_reverse.nonimported_module", sys.modules) def test_view_detail_as_method(self): """ Views that are methods can be displayed. """ url = reverse( "django-admindocs-views-detail", args=["django.contrib.admin.sites.AdminSite.index"], ) response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_model_index(self): response = self.client.get(reverse("django-admindocs-models-index")) self.assertContains( response, '<h2 id="app-auth">Authentication and Authorization (django.contrib.auth)' "</h2>", html=True, ) def test_template_detail(self): response = self.client.get( reverse( "django-admindocs-templates", args=["admin_doc/template_detail.html"] ) ) self.assertContains( response, "<h1>Template: <q>admin_doc/template_detail.html</q></h1>", html=True, ) def test_template_detail_loader(self): response = self.client.get( reverse("django-admindocs-templates", args=["view_for_loader_test.html"]) ) self.assertContains(response, "view_for_loader_test.html</code></li>") def test_missing_docutils(self): utils.docutils_is_available = False try: response = self.client.get(reverse("django-admindocs-docroot")) self.assertContains( response, "<h3>The admin documentation system requires Python’s " '<a href="https://docutils.sourceforge.io/">docutils</a> ' "library.</h3>" "<p>Please ask your administrators to install " '<a href="https://pypi.org/project/docutils/">docutils</a>.</p>', html=True, ) self.assertContains( response, '<div id="site-name"><a href="/admin/">Django administration</a></div>', ) finally: utils.docutils_is_available = True @modify_settings(INSTALLED_APPS={"remove": "django.contrib.sites"}) @override_settings(SITE_ID=None) # will restore SITE_ID after the test def test_no_sites_framework(self): """ Without the sites framework, should not access SITE_ID or Site objects. Deleting settings is fine here as UserSettingsHolder is used. """ Site.objects.all().delete() del settings.SITE_ID response = self.client.get(reverse("django-admindocs-views-index")) self.assertContains(response, "View documentation") def test_callable_urlconf(self): """ Index view should correctly resolve view patterns when ROOT_URLCONF is not a string. """ def urlpatterns(): return ( path("admin/doc/", include("django.contrib.admindocs.urls")), path("admin/", admin.site.urls), ) with self.settings(ROOT_URLCONF=SimpleLazyObject(urlpatterns)): response = self.client.get(reverse("django-admindocs-views-index")) self.assertEqual(response.status_code, 200) @unittest.skipUnless(utils.docutils_is_available, "no docutils installed.") class AdminDocViewDefaultEngineOnly(TestDataMixin, AdminDocsTestCase): def setUp(self): self.client.force_login(self.superuser) def test_template_detail_path_traversal(self): cases = ["/etc/passwd", "../passwd"] for fpath in cases: with self.subTest(path=fpath): response = self.client.get( reverse("django-admindocs-templates", args=[fpath]), ) self.assertEqual(response.status_code, 400) @override_settings( TEMPLATES=[ { "NAME": "ONE", "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, }, { "NAME": "TWO", "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, }, ] ) @unittest.skipUnless(utils.docutils_is_available, "no docutils installed.") class AdminDocViewWithMultipleEngines(AdminDocViewTests): def test_templatefilter_index(self): # Overridden because non-trivial TEMPLATES settings aren't supported # but the page shouldn't crash (#24125). response = self.client.get(reverse("django-admindocs-filters")) self.assertContains(response, "<title>Template filters</title>", html=True) def test_templatetag_index(self): # Overridden because non-trivial TEMPLATES settings aren't supported # but the page shouldn't crash (#24125). response = self.client.get(reverse("django-admindocs-tags")) self.assertContains(response, "<title>Template tags</title>", html=True) @unittest.skipUnless(utils.docutils_is_available, "no docutils installed.") class TestModelDetailView(TestDataMixin, AdminDocsTestCase): def setUp(self): self.client.force_login(self.superuser) with captured_stderr() as self.docutils_stderr: self.response = self.client.get( reverse("django-admindocs-models-detail", args=["admin_docs", "Person"]) ) def test_table_headers(self): tests = [ ("Method", 1), ("Arguments", 1), ("Description", 2), ("Field", 1), ("Type", 1), ("Method", 1), ] for table_header, count in tests: self.assertContains( self.response, f'<th scope="col">{table_header}</th>', count=count ) def test_method_excludes(self): """ Methods that begin with strings defined in ``django.contrib.admindocs.views.MODEL_METHODS_EXCLUDE`` shouldn't be displayed in the admin docs. """ self.assertContains(self.response, "<td>get_full_name</td>") self.assertNotContains(self.response, "<td>_get_full_name</td>") self.assertNotContains(self.response, "<td>add_image</td>") self.assertNotContains(self.response, "<td>delete_image</td>") self.assertNotContains(self.response, "<td>set_status</td>") self.assertNotContains(self.response, "<td>save_changes</td>") def test_methods_with_arguments(self): """ Methods that take arguments should also displayed. """ self.assertContains(self.response, "<h3>Methods with arguments</h3>") self.assertContains(self.response, "<td>rename_company</td>") self.assertContains(self.response, "<td>dummy_function</td>") self.assertContains(self.response, "<td>dummy_function_keyword_only_arg</td>") self.assertContains(self.response, "<td>all_kinds_arg_function</td>") self.assertContains(self.response, "<td>suffix_company_name</td>") def test_methods_with_arguments_display_arguments(self): """ Methods with arguments should have their arguments displayed. """ self.assertContains(self.response, "<td>new_name</td>") self.assertContains(self.response, "<td>keyword_only_arg</td>") def test_methods_with_arguments_display_arguments_default_value(self): """ Methods with keyword arguments should have their arguments displayed. """ self.assertContains(self.response, "<td>suffix=&#x27;ltd&#x27;</td>") def test_methods_with_multiple_arguments_display_arguments(self): """ Methods with multiple arguments should have all their arguments displayed, but omitting 'self'. """ self.assertContains( self.response, "<td>baz, rox, *some_args, **some_kwargs</td>" ) self.assertContains(self.response, "<td>position_only_arg, arg, kwarg</td>") def test_instance_of_property_methods_are_displayed(self): """Model properties are displayed as fields.""" self.assertContains(self.response, "<td>a_property</td>") def test_instance_of_cached_property_methods_are_displayed(self): """Model cached properties are displayed as fields.""" self.assertContains(self.response, "<td>a_cached_property</td>") def test_method_data_types(self): company = Company.objects.create(name="Django") person = Person.objects.create( first_name="Human", last_name="User", company=company ) self.assertEqual( get_return_data_type(person.get_status_count.__name__), "Integer" ) self.assertEqual(get_return_data_type(person.get_groups_list.__name__), "List") def test_descriptions_render_correctly(self): """ The ``description`` field should render correctly for each field type. """ # help text in fields self.assertContains( self.response, "<td>first name - The person's first name</td>" ) self.assertContains( self.response, "<td>last name - The person's last name</td>" ) # method docstrings self.assertContains(self.response, "<p>Get the full name of the person</p>") link = '<a class="reference external" href="/admindocs/models/%s/">%s</a>' markup = "<p>the related %s object</p>" company_markup = markup % (link % ("admin_docs.company", "admin_docs.Company")) # foreign keys self.assertContains(self.response, company_markup) # foreign keys with help text self.assertContains(self.response, "%s\n - place of work" % company_markup) # many to many fields self.assertContains( self.response, "number of related %s objects" % (link % ("admin_docs.group", "admin_docs.Group")), ) self.assertContains( self.response, "all related %s objects" % (link % ("admin_docs.group", "admin_docs.Group")), ) # "raw" and "include" directives are disabled self.assertContains( self.response, "<p>&quot;raw&quot; directive disabled.</p>", ) self.assertContains( self.response, ".. raw:: html\n :file: admin_docs/evilfile.txt" ) self.assertContains( self.response, "<p>&quot;include&quot; directive disabled.</p>", ) self.assertContains(self.response, ".. include:: admin_docs/evilfile.txt") out = self.docutils_stderr.getvalue() self.assertIn('"raw" directive disabled', out) self.assertIn('"include" directive disabled', out) def test_model_with_many_to_one(self): link = '<a class="reference external" href="/admindocs/models/%s/">%s</a>' response = self.client.get( reverse("django-admindocs-models-detail", args=["admin_docs", "company"]) ) self.assertContains( response, "number of related %s objects" % (link % ("admin_docs.person", "admin_docs.Person")), ) self.assertContains( response, "all related %s objects" % (link % ("admin_docs.person", "admin_docs.Person")), ) def test_model_with_no_backward_relations_render_only_relevant_fields(self): """ A model with ``related_name`` of `+` shouldn't show backward relationship links. """ response = self.client.get( reverse("django-admindocs-models-detail", args=["admin_docs", "family"]) ) fields = response.context_data.get("fields") self.assertEqual(len(fields), 2) def test_model_docstring_renders_correctly(self): summary = ( '<h2 class="subhead">Stores information about a person, related to ' '<a class="reference external" href="/admindocs/models/myapp.company/">' "myapp.Company</a>.</h2>" ) subheading = "<p><strong>Notes</strong></p>" body = ( '<p>Use <tt class="docutils literal">save_changes()</tt> when saving this ' "object.</p>" ) model_body = ( '<dl class="docutils"><dt><tt class="' 'docutils literal">company</tt></dt><dd>Field storing <a class="' 'reference external" href="/admindocs/models/myapp.company/">' "myapp.Company</a> where the person works.</dd></dl>" ) self.assertContains(self.response, "DESCRIPTION") self.assertContains(self.response, summary, html=True) self.assertContains(self.response, subheading, html=True) self.assertContains(self.response, body, html=True) self.assertContains(self.response, model_body, html=True) def test_model_docstring_built_in_tag_links(self): summary = "Links with different link text." body = ( '<p>This is a line with tag <a class="reference external" ' 'href="/admindocs/tags/#built_in-extends">extends</a>\n' 'This is a line with model <a class="reference external" ' 'href="/admindocs/models/myapp.family/">Family</a>\n' 'This is a line with view <a class="reference external" ' 'href="/admindocs/views/myapp.views.Index/">Index</a>\n' 'This is a line with template <a class="reference external" ' 'href="/admindocs/templates/Index.html/">index template</a>\n' 'This is a line with filter <a class="reference external" ' 'href="/admindocs/filters/#filtername">example filter</a></p>' ) url = reverse("django-admindocs-models-detail", args=["admin_docs", "family"]) response = self.client.get(url) self.assertContains(response, summary, html=True) self.assertContains(response, body, html=True) def test_model_detail_title(self): self.assertContains(self.response, "<h1>admin_docs.Person</h1>", html=True) def test_app_not_found(self): response = self.client.get( reverse("django-admindocs-models-detail", args=["doesnotexist", "Person"]) ) self.assertEqual(response.context["exception"], "App 'doesnotexist' not found") self.assertEqual(response.status_code, 404) def test_model_not_found(self): response = self.client.get( reverse( "django-admindocs-models-detail", args=["admin_docs", "doesnotexist"] ) ) self.assertEqual( response.context["exception"], "Model 'doesnotexist' not found in app 'admin_docs'", ) self.assertEqual(response.status_code, 404) def test_model_permission_denied(self): person_url = reverse( "django-admindocs-models-detail", args=["admin_docs", "person"] ) company_url = reverse( "django-admindocs-models-detail", args=["admin_docs", "company"] ) staff_user = User.objects.create_user( username="staff", password="secret", is_staff=True ) self.client.force_login(staff_user) response_for_person = self.client.get(person_url) response_for_company = self.client.get(company_url) # No access without permissions. self.assertEqual(response_for_person.status_code, 403) self.assertEqual(response_for_company.status_code, 403) company_content_type = ContentType.objects.get_for_model(Company) person_content_type = ContentType.objects.get_for_model(Person) view_company = Permission.objects.get( codename="view_company", content_type=company_content_type ) change_person = Permission.objects.get( codename="change_person", content_type=person_content_type ) staff_user.user_permissions.add(view_company, change_person) with captured_stderr(): response_for_person = self.client.get(person_url) response_for_company = self.client.get(company_url) # View or change permission grants access. self.assertEqual(response_for_person.status_code, 200) self.assertEqual(response_for_company.status_code, 200) @unittest.skipUnless(utils.docutils_is_available, "no docutils installed.") class TestModelIndexView(TestDataMixin, AdminDocsTestCase): def test_model_index_superuser(self): self.client.force_login(self.superuser) index_url = reverse("django-admindocs-models-index") response = self.client.get(index_url) self.assertContains( response, '<a href="/admindocs/models/admin_docs.family/">Family</a>', html=True, ) self.assertContains( response, '<a href="/admindocs/models/admin_docs.person/">Person</a>', html=True, ) self.assertContains( response, '<a href="/admindocs/models/admin_docs.company/">Company</a>', html=True, ) def test_model_index_with_model_permission(self): staff_user = User.objects.create_user( username="staff", password="secret", is_staff=True ) self.client.force_login(staff_user) index_url = reverse("django-admindocs-models-index") response = self.client.get(index_url) # Models are not listed without permissions. self.assertNotContains( response, '<a href="/admindocs/models/admin_docs.family/">Family</a>', html=True, ) self.assertNotContains( response, '<a href="/admindocs/models/admin_docs.person/">Person</a>', html=True, ) self.assertNotContains( response, '<a href="/admindocs/models/admin_docs.company/">Company</a>', html=True, ) company_content_type = ContentType.objects.get_for_model(Company) person_content_type = ContentType.objects.get_for_model(Person) view_company = Permission.objects.get( codename="view_company", content_type=company_content_type ) change_person = Permission.objects.get( codename="change_person", content_type=person_content_type ) staff_user.user_permissions.add(view_company, change_person) response = self.client.get(index_url) # View or change permission grants access. self.assertNotContains( response, '<a href="/admindocs/models/admin_docs.family/">Family</a>', html=True, ) self.assertContains( response, '<a href="/admindocs/models/admin_docs.person/">Person</a>', html=True, ) self.assertContains( response, '<a href="/admindocs/models/admin_docs.company/">Company</a>', html=True, ) class CustomField(models.Field): description = "A custom field type" class DescriptionLackingField(models.Field): pass class TestFieldType(unittest.TestCase): def test_field_name(self): with self.assertRaises(AttributeError): views.get_readable_field_data_type("NotAField") def test_builtin_fields(self): self.assertEqual( views.get_readable_field_data_type(fields.BooleanField()), "Boolean (Either True or False)", ) def test_char_fields(self): self.assertEqual( views.get_readable_field_data_type(fields.CharField(max_length=255)), "String (up to 255)", ) self.assertEqual( views.get_readable_field_data_type(fields.CharField()), "String (unlimited)", ) def test_custom_fields(self): self.assertEqual( views.get_readable_field_data_type(CustomField()), "A custom field type" ) self.assertEqual( views.get_readable_field_data_type(DescriptionLackingField()), "Field of type: DescriptionLackingField", ) class AdminDocViewFunctionsTests(SimpleTestCase): def test_simplify_regex(self): tests = ( # Named and unnamed groups. (r"^(?P<a>\w+)/b/(?P<c>\w+)/$", "/<a>/b/<c>/"), (r"^(?P<a>\w+)/b/(?P<c>\w+)$", "/<a>/b/<c>"), (r"^(?P<a>\w+)/b/(?P<c>\w+)", "/<a>/b/<c>"), (r"^(?P<a>\w+)/b/(\w+)$", "/<a>/b/<var>"), (r"^(?P<a>\w+)/b/(\w+)", "/<a>/b/<var>"), (r"^(?P<a>\w+)/b/((x|y)\w+)$", "/<a>/b/<var>"), (r"^(?P<a>\w+)/b/((x|y)\w+)", "/<a>/b/<var>"), (r"^(?P<a>(x|y))/b/(?P<c>\w+)$", "/<a>/b/<c>"), (r"^(?P<a>(x|y))/b/(?P<c>\w+)", "/<a>/b/<c>"), (r"^(?P<a>(x|y))/b/(?P<c>\w+)ab", "/<a>/b/<c>ab"), (r"^(?P<a>(x|y)(\(|\)))/b/(?P<c>\w+)ab", "/<a>/b/<c>ab"), # Non-capturing groups. (r"^a(?:\w+)b", "/ab"), (r"^a(?:(x|y))", "/a"), (r"^(?:\w+(?:\w+))a", "/a"), (r"^a(?:\w+)/b(?:\w+)", "/a/b"), (r"(?P<a>\w+)/b/(?:\w+)c(?:\w+)", "/<a>/b/c"), (r"(?P<a>\w+)/b/(\w+)/(?:\w+)c(?:\w+)", "/<a>/b/<var>/c"), # Single and repeated metacharacters. (r"^a", "/a"), (r"^^a", "/a"), (r"^^^a", "/a"), (r"a$", "/a"), (r"a$$", "/a"), (r"a$$$", "/a"), (r"a?", "/a"), (r"a??", "/a"), (r"a???", "/a"), (r"a*", "/a"), (r"a**", "/a"), (r"a***", "/a"), (r"a+", "/a"), (r"a++", "/a"), (r"a+++", "/a"), (r"\Aa", "/a"), (r"\A\Aa", "/a"), (r"\A\A\Aa", "/a"), (r"a\Z", "/a"), (r"a\Z\Z", "/a"), (r"a\Z\Z\Z", "/a"), (r"\ba", "/a"), (r"\b\ba", "/a"), (r"\b\b\ba", "/a"), (r"a\B", "/a"), (r"a\B\B", "/a"), (r"a\B\B\B", "/a"), # Multiple mixed metacharacters. (r"^a/?$", "/a/"), (r"\Aa\Z", "/a"), (r"\ba\B", "/a"), # Escaped single metacharacters. (r"\^a", r"/^a"), (r"\\^a", r"/\\a"), (r"\\\^a", r"/\\^a"), (r"\\\\^a", r"/\\\\a"), (r"\\\\\^a", r"/\\\\^a"), (r"a\$", r"/a$"), (r"a\\$", r"/a\\"), (r"a\\\$", r"/a\\$"), (r"a\\\\$", r"/a\\\\"), (r"a\\\\\$", r"/a\\\\$"), (r"a\?", r"/a?"), (r"a\\?", r"/a\\"), (r"a\\\?", r"/a\\?"), (r"a\\\\?", r"/a\\\\"), (r"a\\\\\?", r"/a\\\\?"), (r"a\*", r"/a*"), (r"a\\*", r"/a\\"), (r"a\\\*", r"/a\\*"), (r"a\\\\*", r"/a\\\\"), (r"a\\\\\*", r"/a\\\\*"), (r"a\+", r"/a+"), (r"a\\+", r"/a\\"), (r"a\\\+", r"/a\\+"), (r"a\\\\+", r"/a\\\\"), (r"a\\\\\+", r"/a\\\\+"), (r"\\Aa", r"/\Aa"), (r"\\\Aa", r"/\\a"), (r"\\\\Aa", r"/\\\Aa"), (r"\\\\\Aa", r"/\\\\a"), (r"\\\\\\Aa", r"/\\\\\Aa"), (r"a\\Z", r"/a\Z"), (r"a\\\Z", r"/a\\"), (r"a\\\\Z", r"/a\\\Z"), (r"a\\\\\Z", r"/a\\\\"), (r"a\\\\\\Z", r"/a\\\\\Z"), # Escaped mixed metacharacters. (r"^a\?$", r"/a?"), (r"^a\\?$", r"/a\\"), (r"^a\\\?$", r"/a\\?"), (r"^a\\\\?$", r"/a\\\\"), (r"^a\\\\\?$", r"/a\\\\?"), # Adjacent escaped metacharacters. (r"^a\?\$", r"/a?$"), (r"^a\\?\\$", r"/a\\\\"), (r"^a\\\?\\\$", r"/a\\?\\$"), (r"^a\\\\?\\\\$", r"/a\\\\\\\\"), (r"^a\\\\\?\\\\\$", r"/a\\\\?\\\\$"), # Complex examples with metacharacters and (un)named groups. (r"^\b(?P<slug>\w+)\B/(\w+)?", "/<slug>/<var>"), (r"^\A(?P<slug>\w+)\Z", "/<slug>"), ) for pattern, output in tests: with self.subTest(pattern=pattern): self.assertEqual(simplify_regex(pattern), output)
django
python
""" Creates the default Site object. """ from django.apps import apps as global_apps from django.conf import settings from django.core.management.color import no_style from django.db import DEFAULT_DB_ALIAS, connections, router def create_default_site( app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, apps=global_apps, **kwargs, ): try: Site = apps.get_model("sites", "Site") except LookupError: return if not router.allow_migrate_model(using, Site): return if not Site.objects.using(using).exists(): # The default settings set SITE_ID = 1, and some tests in Django's test # suite rely on this value. However, if database sequences are reused # (e.g. in the test suite after flush/syncdb), it isn't guaranteed that # the next id will be 1, so we coerce it. See #15573 and #16353. This # can also crop up outside of tests - see #15346. if verbosity >= 2: print("Creating example.com Site object") Site( pk=getattr(settings, "SITE_ID", 1), domain="example.com", name="example.com" ).save(using=using) # We set an explicit pk instead of relying on auto-incrementation, # so we need to reset the database sequence. See #17415. sequence_sql = connections[using].ops.sequence_reset_sql(no_style(), [Site]) if sequence_sql: if verbosity >= 2: print("Resetting sequence") with connections[using].cursor() as cursor: for command in sequence_sql: cursor.execute(command)
import datetime import os import shutil import tempfile import unittest from io import StringIO from pathlib import Path from unittest import mock from admin_scripts.tests import AdminScriptTestCase from django.conf import STATICFILES_STORAGE_ALIAS, settings from django.contrib.staticfiles import storage from django.contrib.staticfiles.management.commands import collectstatic, runserver from django.core.exceptions import ImproperlyConfigured from django.core.management import CommandError, call_command from django.core.management.base import SystemCheckError from django.test import RequestFactory, override_settings from django.test.utils import extend_sys_path from django.utils._os import symlinks_supported from django.utils.functional import empty from .cases import CollectionTestCase, StaticFilesTestCase, TestDefaults from .settings import TEST_ROOT, TEST_SETTINGS from .storage import DummyStorage class TestNoFilesCreated: def test_no_files_created(self): """ Make sure no files were create in the destination directory. """ self.assertEqual(os.listdir(settings.STATIC_ROOT), []) class TestRunserver(StaticFilesTestCase): @override_settings(MIDDLEWARE=["django.middleware.common.CommonMiddleware"]) def test_middleware_loaded_only_once(self): command = runserver.Command() with mock.patch("django.middleware.common.CommonMiddleware") as mocked: command.get_handler(use_static_handler=True, insecure_serving=True) self.assertEqual(mocked.call_count, 1) def test_404_response(self): command = runserver.Command() handler = command.get_handler(use_static_handler=True, insecure_serving=True) missing_static_file = os.path.join(settings.STATIC_URL, "unknown.css") req = RequestFactory().get(missing_static_file) with override_settings(DEBUG=False): response = handler.get_response(req) self.assertEqual(response.status_code, 404) with override_settings(DEBUG=True): response = handler.get_response(req) self.assertEqual(response.status_code, 404) class TestFindStatic(TestDefaults, CollectionTestCase): """ Test ``findstatic`` management command. """ def _get_file(self, filepath): path = call_command( "findstatic", filepath, all=False, verbosity=0, stdout=StringIO() ) with open(path, encoding="utf-8") as f: return f.read() def test_all_files(self): """ findstatic returns all candidate files if run without --first and -v1. """ result = call_command( "findstatic", "test/file.txt", verbosity=1, stdout=StringIO() ) lines = [line.strip() for line in result.split("\n")] self.assertEqual( len(lines), 3 ) # three because there is also the "Found <file> here" line self.assertIn("project", lines[1]) self.assertIn("apps", lines[2]) def test_all_files_less_verbose(self): """ findstatic returns all candidate files if run without --first and -v0. """ result = call_command( "findstatic", "test/file.txt", verbosity=0, stdout=StringIO() ) lines = [line.strip() for line in result.split("\n")] self.assertEqual(len(lines), 2) self.assertIn("project", lines[0]) self.assertIn("apps", lines[1]) def test_all_files_more_verbose(self): """ findstatic returns all candidate files if run without --first and -v2. Also, test that findstatic returns the searched locations with -v2. """ result = call_command( "findstatic", "test/file.txt", verbosity=2, stdout=StringIO() ) lines = [line.strip() for line in result.split("\n")] self.assertIn("project", lines[1]) self.assertIn("apps", lines[2]) self.assertIn("Looking in the following locations:", lines[3]) searched_locations = ", ".join(lines[4:]) # AppDirectoriesFinder searched locations self.assertIn( os.path.join("staticfiles_tests", "apps", "test", "static"), searched_locations, ) self.assertIn( os.path.join("staticfiles_tests", "apps", "no_label", "static"), searched_locations, ) # FileSystemFinder searched locations self.assertIn(TEST_SETTINGS["STATICFILES_DIRS"][1][1], searched_locations) self.assertIn(TEST_SETTINGS["STATICFILES_DIRS"][0], searched_locations) self.assertIn(str(TEST_SETTINGS["STATICFILES_DIRS"][2]), searched_locations) # DefaultStorageFinder searched locations self.assertIn( os.path.join("staticfiles_tests", "project", "site_media", "media"), searched_locations, ) def test_missing_args_message(self): msg = "Enter at least one staticfile." with self.assertRaisesMessage(CommandError, msg): call_command("findstatic") class TestConfiguration(StaticFilesTestCase): def test_location_empty(self): msg = "without having set the STATIC_ROOT setting to a filesystem path" err = StringIO() for root in ["", None]: with override_settings(STATIC_ROOT=root): with self.assertRaisesMessage(ImproperlyConfigured, msg): call_command( "collectstatic", interactive=False, verbosity=0, stderr=err ) def test_local_storage_detection_helper(self): staticfiles_storage = storage.staticfiles_storage try: storage.staticfiles_storage._wrapped = empty with self.settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": ( "django.contrib.staticfiles.storage.StaticFilesStorage" ) }, } ): command = collectstatic.Command() self.assertTrue(command.is_local_storage()) storage.staticfiles_storage._wrapped = empty with self.settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.DummyStorage" }, } ): command = collectstatic.Command() self.assertFalse(command.is_local_storage()) collectstatic.staticfiles_storage = storage.FileSystemStorage() command = collectstatic.Command() self.assertTrue(command.is_local_storage()) collectstatic.staticfiles_storage = DummyStorage() command = collectstatic.Command() self.assertFalse(command.is_local_storage()) finally: staticfiles_storage._wrapped = empty collectstatic.staticfiles_storage = staticfiles_storage storage.staticfiles_storage = staticfiles_storage @override_settings(STATICFILES_DIRS=("test")) def test_collectstatis_check(self): msg = "The STATICFILES_DIRS setting is not a tuple or list." with self.assertRaisesMessage(SystemCheckError, msg): call_command("collectstatic", skip_checks=False) class TestCollectionHelpSubcommand(AdminScriptTestCase): @override_settings(STATIC_ROOT=None) def test_missing_settings_dont_prevent_help(self): """ Even if the STATIC_ROOT setting is not set, one can still call the `manage.py help collectstatic` command. """ self.write_settings("settings.py", apps=["django.contrib.staticfiles"]) out, err = self.run_manage(["help", "collectstatic"]) self.assertNoOutput(err) class TestCollection(TestDefaults, CollectionTestCase): """ Test ``collectstatic`` management command. """ def test_ignore(self): """ -i patterns are ignored. """ self.assertFileNotFound("test/test.ignoreme") def test_common_ignore_patterns(self): """ Common ignore patterns (*~, .*, CVS) are ignored. """ self.assertFileNotFound("test/.hidden") self.assertFileNotFound("test/backup~") self.assertFileNotFound("test/CVS") def test_pathlib(self): self.assertFileContains("pathlib.txt", "pathlib") class TestCollectionPathLib(TestCollection): def mkdtemp(self): tmp_dir = super().mkdtemp() return Path(tmp_dir) class TestCollectionVerbosity(CollectionTestCase): copying_msg = "Copying " run_collectstatic_in_setUp = False post_process_msg = "Post-processed" staticfiles_copied_msg = "static files copied to" def test_verbosity_0(self): stdout = StringIO() self.run_collectstatic(verbosity=0, stdout=stdout) self.assertEqual(stdout.getvalue(), "") def test_verbosity_1(self): stdout = StringIO() self.run_collectstatic(verbosity=1, stdout=stdout) output = stdout.getvalue() self.assertIn(self.staticfiles_copied_msg, output) self.assertNotIn(self.copying_msg, output) def test_verbosity_2(self): stdout = StringIO() self.run_collectstatic(verbosity=2, stdout=stdout) output = stdout.getvalue() self.assertIn(self.staticfiles_copied_msg, output) self.assertIn(self.copying_msg, output) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": ( "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" ) }, } ) def test_verbosity_1_with_post_process(self): stdout = StringIO() self.run_collectstatic(verbosity=1, stdout=stdout, post_process=True) self.assertNotIn(self.post_process_msg, stdout.getvalue()) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": ( "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" ) }, } ) def test_verbosity_2_with_post_process(self): stdout = StringIO() self.run_collectstatic(verbosity=2, stdout=stdout, post_process=True) self.assertIn(self.post_process_msg, stdout.getvalue()) class TestCollectionClear(CollectionTestCase): """ Test the ``--clear`` option of the ``collectstatic`` management command. """ run_collectstatic_in_setUp = False def run_collectstatic(self, **kwargs): clear_filepath = os.path.join(settings.STATIC_ROOT, "cleared.txt") with open(clear_filepath, "w") as f: f.write("should be cleared") super().run_collectstatic(clear=True, **kwargs) def test_cleared_not_found(self): self.assertFileNotFound("cleared.txt") def test_dir_not_exists(self, **kwargs): shutil.rmtree(settings.STATIC_ROOT) super().run_collectstatic(clear=True) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.PathNotImplementedStorage" }, } ) def test_handle_path_notimplemented(self): self.run_collectstatic() self.assertFileNotFound("cleared.txt") def test_verbosity_0(self): for kwargs in [{}, {"dry_run": True}]: with self.subTest(kwargs=kwargs): stdout = StringIO() self.run_collectstatic(verbosity=0, stdout=stdout, **kwargs) self.assertEqual(stdout.getvalue(), "") def test_verbosity_1(self): for deletion_message, kwargs in [ ("Deleting", {}), ("Pretending to delete", {"dry_run": True}), ]: with self.subTest(kwargs=kwargs): stdout = StringIO() self.run_collectstatic(verbosity=1, stdout=stdout, **kwargs) output = stdout.getvalue() self.assertIn("static file", output) self.assertIn("deleted", output) self.assertNotIn(deletion_message, output) def test_verbosity_2(self): for deletion_message, kwargs in [ ("Deleting", {}), ("Pretending to delete", {"dry_run": True}), ]: with self.subTest(kwargs=kwargs): stdout = StringIO() self.run_collectstatic(verbosity=2, stdout=stdout, **kwargs) output = stdout.getvalue() self.assertIn("static file", output) self.assertIn("deleted", output) self.assertIn(deletion_message, output) class TestInteractiveMessages(CollectionTestCase): overwrite_warning_msg = "This will overwrite existing files!" delete_warning_msg = "This will DELETE ALL FILES in this location!" files_copied_msg = "static files copied" @staticmethod def mock_input(stdout): def _input(msg): stdout.write(msg) return "yes" return _input def test_warning_when_clearing_staticdir(self): stdout = StringIO() self.run_collectstatic() with mock.patch("builtins.input", side_effect=self.mock_input(stdout)): call_command("collectstatic", interactive=True, clear=True, stdout=stdout) output = stdout.getvalue() self.assertNotIn(self.overwrite_warning_msg, output) self.assertIn(self.delete_warning_msg, output) def test_warning_when_overwriting_files_in_staticdir(self): stdout = StringIO() self.run_collectstatic() with mock.patch("builtins.input", side_effect=self.mock_input(stdout)): call_command("collectstatic", interactive=True, stdout=stdout) output = stdout.getvalue() self.assertIn(self.overwrite_warning_msg, output) self.assertNotIn(self.delete_warning_msg, output) def test_no_warning_when_staticdir_does_not_exist(self): stdout = StringIO() shutil.rmtree(settings.STATIC_ROOT) call_command("collectstatic", interactive=True, stdout=stdout) output = stdout.getvalue() self.assertNotIn(self.overwrite_warning_msg, output) self.assertNotIn(self.delete_warning_msg, output) self.assertIn(self.files_copied_msg, output) def test_no_warning_for_empty_staticdir(self): stdout = StringIO() with tempfile.TemporaryDirectory( prefix="collectstatic_empty_staticdir_test" ) as static_dir: with override_settings(STATIC_ROOT=static_dir): call_command("collectstatic", interactive=True, stdout=stdout) output = stdout.getvalue() self.assertNotIn(self.overwrite_warning_msg, output) self.assertNotIn(self.delete_warning_msg, output) self.assertIn(self.files_copied_msg, output) def test_cancelled(self): self.run_collectstatic() with mock.patch("builtins.input", side_effect=lambda _: "no"): with self.assertRaisesMessage( CommandError, "Collecting static files cancelled" ): call_command("collectstatic", interactive=True) class TestCollectionNoDefaultIgnore(TestDefaults, CollectionTestCase): """ The ``--no-default-ignore`` option of the ``collectstatic`` management command. """ def run_collectstatic(self): super().run_collectstatic(use_default_ignore_patterns=False) def test_no_common_ignore_patterns(self): """ With --no-default-ignore, common ignore patterns (*~, .*, CVS) are not ignored. """ self.assertFileContains("test/.hidden", "should be ignored") self.assertFileContains("test/backup~", "should be ignored") self.assertFileContains("test/CVS", "should be ignored") @override_settings( INSTALLED_APPS=[ "staticfiles_tests.apps.staticfiles_config.IgnorePatternsAppConfig", "staticfiles_tests.apps.test", ] ) class TestCollectionCustomIgnorePatterns(CollectionTestCase): def test_custom_ignore_patterns(self): """ A custom ignore_patterns list, ['*.css', '*/vendor/*.js'] in this case, can be specified in an AppConfig definition. """ self.assertFileNotFound("test/nonascii.css") self.assertFileContains("test/.hidden", "should be ignored") self.assertFileNotFound(os.path.join("test", "vendor", "module.js")) class TestCollectionDryRun(TestNoFilesCreated, CollectionTestCase): """ Test ``--dry-run`` option for ``collectstatic`` management command. """ def run_collectstatic(self): super().run_collectstatic(dry_run=True) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" }, } ) class TestCollectionDryRunManifestStaticFilesStorage(TestCollectionDryRun): pass class TestCollectionFilesOverride(CollectionTestCase): """ Test overriding duplicated files by ``collectstatic`` management command. Check for proper handling of apps order in installed apps even if file modification dates are in different order: 'staticfiles_test_app', 'staticfiles_tests.apps.no_label', """ def setUp(self): self.temp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.temp_dir) # get modification and access times for no_label/static/file2.txt self.orig_path = os.path.join( TEST_ROOT, "apps", "no_label", "static", "file2.txt" ) self.orig_mtime = os.path.getmtime(self.orig_path) self.orig_atime = os.path.getatime(self.orig_path) # prepare duplicate of file2.txt from a temporary app # this file will have modification time older than # no_label/static/file2.txt anyway it should be taken to STATIC_ROOT # because the temporary app is before 'no_label' app in installed apps self.temp_app_path = os.path.join(self.temp_dir, "staticfiles_test_app") self.testfile_path = os.path.join(self.temp_app_path, "static", "file2.txt") os.makedirs(self.temp_app_path) with open(os.path.join(self.temp_app_path, "__init__.py"), "w+"): pass os.makedirs(os.path.dirname(self.testfile_path)) with open(self.testfile_path, "w+") as f: f.write("duplicate of file2.txt") os.utime(self.testfile_path, (self.orig_atime - 1, self.orig_mtime - 1)) settings_with_test_app = self.modify_settings( INSTALLED_APPS={"prepend": "staticfiles_test_app"}, ) with extend_sys_path(self.temp_dir): settings_with_test_app.enable() self.addCleanup(settings_with_test_app.disable) super().setUp() def test_ordering_override(self): """ Test if collectstatic takes files in proper order """ self.assertFileContains("file2.txt", "duplicate of file2.txt") # run collectstatic again self.run_collectstatic() self.assertFileContains("file2.txt", "duplicate of file2.txt") # The collectstatic test suite already has conflicting files since both # project/test/file.txt and apps/test/static/test/file.txt are collected. To # properly test for the warning not happening unless we tell it to explicitly, # we remove the project directory and will add back a conflicting file later. @override_settings(STATICFILES_DIRS=[]) class TestCollectionOverwriteWarning(CollectionTestCase): """ Test warning in ``collectstatic`` output when a file is skipped because a previous file was already written to the same path. """ # If this string is in the collectstatic output, it means the warning we're # looking for was emitted. warning_string = "Found another file" def _collectstatic_output(self, verbosity=3, **kwargs): """ Run collectstatic, and capture and return the output. """ out = StringIO() call_command( "collectstatic", interactive=False, verbosity=verbosity, stdout=out, **kwargs, ) return out.getvalue() def test_no_warning(self): """ There isn't a warning if there isn't a duplicate destination. """ output = self._collectstatic_output(clear=True) self.assertNotIn(self.warning_string, output) def test_warning_at_verbosity_2(self): """ There is a warning when there are duplicate destinations at verbosity 2+. """ with tempfile.TemporaryDirectory() as static_dir: duplicate = os.path.join(static_dir, "test", "file.txt") os.mkdir(os.path.dirname(duplicate)) with open(duplicate, "w+") as f: f.write("duplicate of file.txt") with self.settings(STATICFILES_DIRS=[static_dir]): output = self._collectstatic_output(clear=True, verbosity=2) self.assertIn(self.warning_string, output) def test_no_warning_at_verbosity_1(self): """ There is no individual warning at verbosity 1, but summary is shown. """ with tempfile.TemporaryDirectory() as static_dir: duplicate = os.path.join(static_dir, "test", "file.txt") os.mkdir(os.path.dirname(duplicate)) with open(duplicate, "w+") as f: f.write("duplicate of file.txt") with self.settings(STATICFILES_DIRS=[static_dir]): output = self._collectstatic_output(clear=True, verbosity=1) self.assertNotIn(self.warning_string, output) self.assertIn("1 skipped due to conflict", output) def test_summary_multiple_conflicts(self): """ Summary shows correct count for multiple conflicts. """ with tempfile.TemporaryDirectory() as static_dir: duplicate1 = os.path.join(static_dir, "test", "file.txt") os.makedirs(os.path.dirname(duplicate1)) with open(duplicate1, "w+") as f: f.write("duplicate of file.txt") duplicate2 = os.path.join(static_dir, "test", "file1.txt") with open(duplicate2, "w+") as f: f.write("duplicate of file1.txt") duplicate3 = os.path.join(static_dir, "test", "nonascii.css") shutil.copy2(duplicate1, duplicate3) with self.settings(STATICFILES_DIRS=[static_dir]): output = self._collectstatic_output(clear=True, verbosity=1) self.assertIn("3 skipped due to conflict", output) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.DummyStorage" }, } ) class TestCollectionNonLocalStorage(TestNoFilesCreated, CollectionTestCase): """ Tests for a Storage that implements get_modified_time() but not path() (#15035). """ def test_storage_properties(self): # Properties of the Storage as described in the ticket. storage = DummyStorage() self.assertEqual( storage.get_modified_time("name"), datetime.datetime(1970, 1, 1, tzinfo=datetime.UTC), ) with self.assertRaisesMessage( NotImplementedError, "This backend doesn't support absolute paths." ): storage.path("name") class TestCollectionNeverCopyStorage(CollectionTestCase): @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.NeverCopyRemoteStorage" }, } ) def test_skips_newer_files_in_remote_storage(self): """ collectstatic skips newer files in a remote storage. run_collectstatic() in setUp() copies the static files, then files are always skipped after NeverCopyRemoteStorage is activated since NeverCopyRemoteStorage.get_modified_time() returns a datetime in the future to simulate an unmodified file. """ stdout = StringIO() self.run_collectstatic(stdout=stdout, verbosity=2) output = stdout.getvalue() self.assertIn("Skipping 'test.txt' (not modified)", output) @unittest.skipUnless(symlinks_supported(), "Must be able to symlink to run this test.") class TestCollectionLinks(TestDefaults, CollectionTestCase): """ Test ``--link`` option for ``collectstatic`` management command. Note that by inheriting ``TestDefaults`` we repeat all the standard file resolving tests here, to make sure using ``--link`` does not change the file-selection semantics. """ def run_collectstatic(self, clear=False, link=True, **kwargs): super().run_collectstatic(link=link, clear=clear, **kwargs) def test_links_created(self): """ With ``--link``, symbolic links are created. """ self.assertTrue(os.path.islink(os.path.join(settings.STATIC_ROOT, "test.txt"))) def test_broken_symlink(self): """ Test broken symlink gets deleted. """ path = os.path.join(settings.STATIC_ROOT, "test.txt") os.unlink(path) self.run_collectstatic() self.assertTrue(os.path.islink(path)) def test_symlinks_and_files_replaced(self): """ Running collectstatic in non-symlink mode replaces symlinks with files, while symlink mode replaces files with symlinks. """ path = os.path.join(settings.STATIC_ROOT, "test.txt") self.assertTrue(os.path.islink(path)) self.run_collectstatic(link=False) self.assertFalse(os.path.islink(path)) self.run_collectstatic(link=True) self.assertTrue(os.path.islink(path)) def test_clear_broken_symlink(self): """ With ``--clear``, broken symbolic links are deleted. """ nonexistent_file_path = os.path.join(settings.STATIC_ROOT, "nonexistent.txt") broken_symlink_path = os.path.join(settings.STATIC_ROOT, "symlink.txt") os.symlink(nonexistent_file_path, broken_symlink_path) self.run_collectstatic(clear=True) self.assertFalse(os.path.lexists(broken_symlink_path)) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.PathNotImplementedStorage" }, } ) def test_no_remote_link(self): with self.assertRaisesMessage( CommandError, "Can't symlink to a remote destination." ): self.run_collectstatic()
django
python
from django.core.management.base import BaseCommand class Command(BaseCommand): requires_system_checks = [] def handle(self, *args, **options): pass
from pathlib import Path from unittest import mock from django.conf import DEFAULT_STORAGE_ALIAS, STATICFILES_STORAGE_ALIAS, settings from django.contrib.staticfiles.checks import E005, check_finders, check_storages from django.contrib.staticfiles.finders import BaseFinder, get_finder from django.core.checks import Error, Warning from django.test import SimpleTestCase, override_settings from .cases import CollectionTestCase from .settings import TEST_ROOT class FindersCheckTests(CollectionTestCase): run_collectstatic_in_setUp = False def test_base_finder_check_not_implemented(self): finder = BaseFinder() msg = ( "subclasses may provide a check() method to verify the finder is " "configured correctly." ) with self.assertRaisesMessage(NotImplementedError, msg): finder.check() def test_check_finders(self): """check_finders() concatenates all errors.""" error1 = Error("1") error2 = Error("2") error3 = Error("3") def get_finders(): class Finder1(BaseFinder): def check(self, **kwargs): return [error1] class Finder2(BaseFinder): def check(self, **kwargs): return [] class Finder3(BaseFinder): def check(self, **kwargs): return [error2, error3] class Finder4(BaseFinder): pass return [Finder1(), Finder2(), Finder3(), Finder4()] with mock.patch("django.contrib.staticfiles.checks.get_finders", get_finders): errors = check_finders(None) self.assertEqual(errors, [error1, error2, error3]) def test_no_errors_with_test_settings(self): self.assertEqual(check_finders(None), []) @override_settings(STATICFILES_DIRS="a string") def test_dirs_not_tuple_or_list(self): self.assertEqual( check_finders(None), [ Error( "The STATICFILES_DIRS setting is not a tuple or list.", hint="Perhaps you forgot a trailing comma?", id="staticfiles.E001", ) ], ) def test_dirs_contains_static_root(self): with self.settings(STATICFILES_DIRS=[settings.STATIC_ROOT]): self.assertEqual( check_finders(None), [ Error( "The STATICFILES_DIRS setting should not contain the " "STATIC_ROOT setting.", id="staticfiles.E002", ) ], ) def test_dirs_contains_static_root_in_tuple(self): with self.settings(STATICFILES_DIRS=[("prefix", settings.STATIC_ROOT)]): self.assertEqual( check_finders(None), [ Error( "The STATICFILES_DIRS setting should not contain the " "STATIC_ROOT setting.", id="staticfiles.E002", ) ], ) def test_prefix_contains_trailing_slash(self): static_dir = Path(TEST_ROOT) / "project" / "documents" with self.settings(STATICFILES_DIRS=[("prefix/", static_dir)]): self.assertEqual( check_finders(None), [ Error( "The prefix 'prefix/' in the STATICFILES_DIRS setting must " "not end with a slash.", id="staticfiles.E003", ), ], ) def test_nonexistent_directories(self): with self.settings( STATICFILES_DIRS=[ "/fake/path", ("prefix", "/fake/prefixed/path"), ] ): self.assertEqual( check_finders(None), [ Warning( "The directory '/fake/path' in the STATICFILES_DIRS " "setting does not exist.", id="staticfiles.W004", ), Warning( "The directory '/fake/prefixed/path' in the " "STATICFILES_DIRS setting does not exist.", id="staticfiles.W004", ), ], ) # Nonexistent directories are skipped. finder = get_finder("django.contrib.staticfiles.finders.FileSystemFinder") self.assertEqual(list(finder.list(None)), []) class StoragesCheckTests(SimpleTestCase): @override_settings(STORAGES={}) def test_error_empty_storages(self): errors = check_storages(None) self.assertEqual(errors, [E005]) @override_settings( STORAGES={ DEFAULT_STORAGE_ALIAS: { "BACKEND": "django.core.files.storage.FileSystemStorage", }, "example": { "BACKEND": "ignore.me", }, } ) def test_error_missing_staticfiles(self): errors = check_storages(None) self.assertEqual(errors, [E005]) @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage", }, } ) def test_staticfiles_no_errors(self): errors = check_storages(None) self.assertEqual(errors, [])
django
python
import os from datetime import UTC, datetime, timedelta from django.conf import settings from django.contrib.staticfiles.storage import ManifestStaticFilesStorage from django.core.files import storage class DummyStorage(storage.Storage): """ A storage class that implements get_modified_time() but raises NotImplementedError for path(). """ def _save(self, name, content): return "dummy" def delete(self, name): pass def exists(self, name): pass def get_modified_time(self, name): return datetime(1970, 1, 1, tzinfo=UTC) class PathNotImplementedStorage(storage.Storage): def _save(self, name, content): return "dummy" def _path(self, name): return os.path.join(settings.STATIC_ROOT, name) def exists(self, name): return os.path.exists(self._path(name)) def listdir(self, path): path = self._path(path) directories, files = [], [] with os.scandir(path) as entries: for entry in entries: if entry.is_dir(): directories.append(entry.name) else: files.append(entry.name) return directories, files def delete(self, name): name = self._path(name) try: os.remove(name) except FileNotFoundError: pass def path(self, name): raise NotImplementedError class NeverCopyRemoteStorage(PathNotImplementedStorage): """ Return a future modified time for all files so that nothing is collected. """ def get_modified_time(self, name): return datetime.now() + timedelta(days=30) class QueryStringStorage(storage.Storage): def url(self, path): return path + "?a=b&c=d" class SimpleStorage(ManifestStaticFilesStorage): def file_hash(self, name, content=None): return "deploy12345" class ExtraPatternsStorage(ManifestStaticFilesStorage): """ A storage class to test pattern substitutions with more than one pattern entry. The added pattern rewrites strings like "url(...)" to JS_URL("..."). """ patterns = tuple(ManifestStaticFilesStorage.patterns) + ( ( "*.js", ( ( r"""(?P<matched>url\(['"]{0,1}\s*(?P<url>.*?)["']{0,1}\))""", 'JS_URL("%(url)s")', ), ), ), ) class NoneHashStorage(ManifestStaticFilesStorage): def file_hash(self, name, content=None): return None class NoPostProcessReplacedPathStorage(ManifestStaticFilesStorage): max_post_process_passes = 0
import json import os import shutil import sys import tempfile import unittest from io import StringIO from pathlib import Path from unittest import mock from django.conf import STATICFILES_STORAGE_ALIAS, settings from django.contrib.staticfiles import finders, storage from django.contrib.staticfiles.management.commands.collectstatic import ( Command as CollectstaticCommand, ) from django.core.management import call_command from django.test import SimpleTestCase, override_settings from .cases import CollectionTestCase from .settings import TEST_ROOT def hashed_file_path(test, path): fullpath = test.render_template(test.static_template_snippet(path)) return fullpath.removeprefix(settings.STATIC_URL) class TestHashedFiles: hashed_file_path = hashed_file_path def tearDown(self): # Clear hashed files to avoid side effects among tests. storage.staticfiles_storage.hashed_files.clear() def assertPostCondition(self): """ Assert post conditions for a test are met. Must be manually called at the end of each test. """ pass def test_template_tag_return(self): self.assertStaticRaises( ValueError, "does/not/exist.png", "/static/does/not/exist.png" ) self.assertStaticRenders("test/file.txt", "/static/test/file.dad0999e4f8f.txt") self.assertStaticRenders( "test/file.txt", "/static/test/file.dad0999e4f8f.txt", asvar=True ) self.assertStaticRenders( "cached/styles.css", "/static/cached/styles.5e0040571e1a.css" ) self.assertStaticRenders("path/", "/static/path/") self.assertStaticRenders("path/?query", "/static/path/?query") self.assertPostCondition() def test_template_tag_simple_content(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_ignored_completely(self): relpath = self.hashed_file_path("cached/css/ignored.css") self.assertEqual(relpath, "cached/css/ignored.55e7c226dda1.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"#foobar", content) self.assertIn(b"http:foobar", content) self.assertIn(b"https:foobar", content) self.assertIn(b"data:foobar", content) self.assertIn(b"chrome:foobar", content) self.assertIn(b"//foobar", content) self.assertIn(b"url()", content) self.assertPostCondition() def test_path_with_querystring(self): relpath = self.hashed_file_path("cached/styles.css?spam=eggs") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css?spam=eggs") with storage.staticfiles_storage.open( "cached/styles.5e0040571e1a.css" ) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_with_fragment(self): relpath = self.hashed_file_path("cached/styles.css#eggs") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css#eggs") with storage.staticfiles_storage.open( "cached/styles.5e0040571e1a.css" ) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_with_querystring_and_fragment(self): relpath = self.hashed_file_path("cached/css/fragments.css") self.assertEqual(relpath, "cached/css/fragments.7fe344dee895.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"fonts/font.b9b105392eb8.eot?#iefix", content) self.assertIn(b"fonts/font.b8d603e42714.svg#webfontIyfZbseF", content) self.assertIn( b"fonts/font.b8d603e42714.svg#path/to/../../fonts/font.svg", content ) self.assertIn( b"data:font/woff;charset=utf-8;" b"base64,d09GRgABAAAAADJoAA0AAAAAR2QAAQAAAAAAAAAAAAA", content, ) self.assertIn(b"#default#VML", content) self.assertPostCondition() def test_template_tag_absolute(self): relpath = self.hashed_file_path("cached/absolute.css") self.assertEqual(relpath, "cached/absolute.eb04def9f9a4.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/static/cached/styles.css", content) self.assertIn(b"/static/cached/styles.5e0040571e1a.css", content) self.assertNotIn(b"/static/styles_root.css", content) self.assertIn(b"/static/styles_root.401f2509a628.css", content) self.assertIn(b"/static/cached/img/relative.acae32e4532b.png", content) self.assertPostCondition() def test_template_tag_absolute_root(self): """ Like test_template_tag_absolute, but for a file in STATIC_ROOT (#26249). """ relpath = self.hashed_file_path("absolute_root.css") self.assertEqual(relpath, "absolute_root.f821df1b64f7.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/static/styles_root.css", content) self.assertIn(b"/static/styles_root.401f2509a628.css", content) self.assertPostCondition() def test_template_tag_relative(self): relpath = self.hashed_file_path("cached/relative.css") self.assertEqual(relpath, "cached/relative.c3e9e1ea6f2e.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"../cached/styles.css", content) self.assertNotIn(b'@import "styles.css"', content) self.assertNotIn(b"url(img/relative.png)", content) self.assertIn(b'url("img/relative.acae32e4532b.png")', content) self.assertIn(b"../cached/styles.5e0040571e1a.css", content) self.assertPostCondition() def test_import_replacement(self): "See #18050" relpath = self.hashed_file_path("cached/import.css") self.assertEqual(relpath, "cached/import.f53576679e5a.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b"""import url("styles.5e0040571e1a.css")""", relfile.read()) self.assertPostCondition() def test_template_tag_deep_relative(self): relpath = self.hashed_file_path("cached/css/window.css") self.assertEqual(relpath, "cached/css/window.5d5c10836967.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"url(img/window.png)", content) self.assertIn(b'url("img/window.acae32e4532b.png")', content) self.assertPostCondition() def test_template_tag_url(self): relpath = self.hashed_file_path("cached/url.css") self.assertEqual(relpath, "cached/url.902310b73412.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b"https://", relfile.read()) self.assertPostCondition() @override_settings( STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "loop")], STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ) def test_import_loop(self): finders.get_finder.cache_clear() err = StringIO() with self.assertRaisesMessage(RuntimeError, "Max post-process passes exceeded"): call_command("collectstatic", interactive=False, verbosity=0, stderr=err) self.assertEqual( "Post-processing 'bar.css, foo.css' failed!\n\n", err.getvalue() ) self.assertPostCondition() def test_post_processing(self): """ post_processing behaves correctly. Files that are alterable should always be post-processed; files that aren't should be skipped. collectstatic has already been called once in setUp() for this testcase, therefore we check by verifying behavior on a second run. """ collectstatic_args = { "interactive": False, "verbosity": 0, "link": False, "clear": False, "dry_run": False, "post_process": True, "use_default_ignore_patterns": True, "ignore_patterns": ["*.ignoreme"], } collectstatic_cmd = CollectstaticCommand() collectstatic_cmd.set_options(**collectstatic_args) stats = collectstatic_cmd.collect() self.assertIn( os.path.join("cached", "css", "window.css"), stats["post_processed"] ) self.assertIn( os.path.join("cached", "css", "img", "window.png"), stats["unmodified"] ) self.assertIn(os.path.join("test", "nonascii.css"), stats["post_processed"]) # No file should be yielded twice. self.assertCountEqual(stats["post_processed"], set(stats["post_processed"])) self.assertPostCondition() def test_css_import_case_insensitive(self): relpath = self.hashed_file_path("cached/styles_insensitive.css") self.assertEqual(relpath, "cached/styles_insensitive.3fa427592a53.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_css_data_uri_with_nested_url(self): relpath = self.hashed_file_path("cached/data_uri_with_nested_url.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b'url("data:image/svg+xml,url(%23b) url(%23c)")', content) self.assertPostCondition() def test_css_source_map(self): relpath = self.hashed_file_path("cached/source_map.css") self.assertEqual(relpath, "cached/source_map.b2fceaf426aa.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/*# sourceMappingURL=source_map.css.map*/", content) self.assertIn( b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */", content, ) self.assertPostCondition() def test_css_source_map_tabs(self): relpath = self.hashed_file_path("cached/source_map_tabs.css") self.assertEqual(relpath, "cached/source_map_tabs.b2fceaf426aa.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/*#\tsourceMappingURL=source_map.css.map\t*/", content) self.assertIn( b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */", content, ) self.assertPostCondition() def test_css_source_map_sensitive(self): relpath = self.hashed_file_path("cached/source_map_sensitive.css") self.assertEqual(relpath, "cached/source_map_sensitive.456683f2106f.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"/*# sOuRcEMaPpInGURL=source_map.css.map */", content) self.assertNotIn( b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */", content, ) self.assertPostCondition() def test_css_source_map_data_uri(self): relpath = self.hashed_file_path("cached/source_map_data_uri.css") self.assertEqual(relpath, "cached/source_map_data_uri.3166be10260d.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() source_map_data_uri = ( b"/*# sourceMappingURL=data:application/json;charset=utf8;base64," b"eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMv*/" ) self.assertIn(source_map_data_uri, content) self.assertPostCondition() def test_js_source_map(self): relpath = self.hashed_file_path("cached/source_map.js") self.assertEqual(relpath, "cached/source_map.cd45b8534a87.js") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"//# sourceMappingURL=source_map.js.map", content) self.assertIn( b"//# sourceMappingURL=source_map.js.99914b932bd3.map", content, ) self.assertPostCondition() def test_js_source_map_trailing_whitespace(self): relpath = self.hashed_file_path("cached/source_map_trailing_whitespace.js") self.assertEqual( relpath, "cached/source_map_trailing_whitespace.cd45b8534a87.js" ) with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"//# sourceMappingURL=source_map.js.map\t ", content) self.assertIn( b"//# sourceMappingURL=source_map.js.99914b932bd3.map", content, ) self.assertPostCondition() def test_js_source_map_sensitive(self): relpath = self.hashed_file_path("cached/source_map_sensitive.js") self.assertEqual(relpath, "cached/source_map_sensitive.5da96fdd3cb3.js") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"//# sOuRcEMaPpInGURL=source_map.js.map", content) self.assertNotIn( b"//# sourceMappingURL=source_map.js.99914b932bd3.map", content, ) self.assertPostCondition() def test_js_source_map_data_uri(self): relpath = self.hashed_file_path("cached/source_map_data_uri.js") self.assertEqual(relpath, "cached/source_map_data_uri.a68d23cbf6dd.js") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() source_map_data_uri = ( b"//# sourceMappingURL=data:application/json;charset=utf8;base64," b"eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMv" ) self.assertIn(source_map_data_uri, content) self.assertPostCondition() @override_settings( STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "faulty")], STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ) def test_post_processing_failure(self): """ post_processing indicates the origin of the error when it fails. """ finders.get_finder.cache_clear() err = StringIO() with self.assertRaises(Exception): call_command("collectstatic", interactive=False, verbosity=0, stderr=err) self.assertEqual("Post-processing 'faulty.css' failed!\n\n", err.getvalue()) self.assertPostCondition() @override_settings( STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "nonutf8")], STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ) def test_post_processing_nonutf8(self): finders.get_finder.cache_clear() err = StringIO() with self.assertRaises(UnicodeDecodeError): call_command("collectstatic", interactive=False, verbosity=0, stderr=err) self.assertEqual("Post-processing 'nonutf8.css' failed!\n\n", err.getvalue()) self.assertPostCondition() @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.ExtraPatternsStorage", }, } ) class TestExtraPatternsStorage(CollectionTestCase): def setUp(self): storage.staticfiles_storage.hashed_files.clear() # avoid cache interference super().setUp() def cached_file_path(self, path): fullpath = self.render_template(self.static_template_snippet(path)) return fullpath.replace(settings.STATIC_URL, "") def test_multi_extension_patterns(self): """ With storage classes having several file extension patterns, only the files matching a specific file pattern should be affected by the substitution (#19670). """ # CSS files shouldn't be touched by JS patterns. relpath = self.cached_file_path("cached/import.css") self.assertEqual(relpath, "cached/import.f53576679e5a.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b'import url("styles.5e0040571e1a.css")', relfile.read()) # Confirm JS patterns have been applied to JS files. relpath = self.cached_file_path("cached/test.js") self.assertEqual(relpath, "cached/test.388d7a790d46.js") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b'JS_URL("import.f53576679e5a.css")', relfile.read()) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage", }, } ) class TestCollectionManifestStorage(TestHashedFiles, CollectionTestCase): """ Tests for the Cache busting storage """ def setUp(self): super().setUp() temp_dir = tempfile.mkdtemp() os.makedirs(os.path.join(temp_dir, "test")) self._clear_filename = os.path.join(temp_dir, "test", "cleared.txt") with open(self._clear_filename, "w") as f: f.write("to be deleted in one test") patched_settings = self.settings( STATICFILES_DIRS=settings.STATICFILES_DIRS + [temp_dir], ) patched_settings.enable() self.addCleanup(patched_settings.disable) self.addCleanup(shutil.rmtree, temp_dir) self._manifest_strict = storage.staticfiles_storage.manifest_strict def tearDown(self): if os.path.exists(self._clear_filename): os.unlink(self._clear_filename) storage.staticfiles_storage.manifest_strict = self._manifest_strict super().tearDown() def assertPostCondition(self): hashed_files = storage.staticfiles_storage.hashed_files # The in-memory version of the manifest matches the one on disk # since a properly created manifest should cover all filenames. if hashed_files: manifest, _ = storage.staticfiles_storage.load_manifest() self.assertEqual(hashed_files, manifest) def test_manifest_exists(self): filename = storage.staticfiles_storage.manifest_name path = storage.staticfiles_storage.path(filename) self.assertTrue(os.path.exists(path)) def test_manifest_does_not_exist(self): storage.staticfiles_storage.manifest_name = "does.not.exist.json" self.assertIsNone(storage.staticfiles_storage.read_manifest()) def test_manifest_does_not_ignore_permission_error(self): with mock.patch("builtins.open", side_effect=PermissionError): with self.assertRaises(PermissionError): storage.staticfiles_storage.read_manifest() def test_loaded_cache(self): self.assertNotEqual(storage.staticfiles_storage.hashed_files, {}) manifest_content = storage.staticfiles_storage.read_manifest() self.assertIn( '"version": "%s"' % storage.staticfiles_storage.manifest_version, manifest_content, ) def test_parse_cache(self): hashed_files = storage.staticfiles_storage.hashed_files manifest, _ = storage.staticfiles_storage.load_manifest() self.assertEqual(hashed_files, manifest) def test_clear_empties_manifest(self): cleared_file_name = storage.staticfiles_storage.clean_name( os.path.join("test", "cleared.txt") ) # collect the additional file self.run_collectstatic() hashed_files = storage.staticfiles_storage.hashed_files self.assertIn(cleared_file_name, hashed_files) manifest_content, _ = storage.staticfiles_storage.load_manifest() self.assertIn(cleared_file_name, manifest_content) original_path = storage.staticfiles_storage.path(cleared_file_name) self.assertTrue(os.path.exists(original_path)) # delete the original file form the app, collect with clear os.unlink(self._clear_filename) self.run_collectstatic(clear=True) self.assertFileNotFound(original_path) hashed_files = storage.staticfiles_storage.hashed_files self.assertNotIn(cleared_file_name, hashed_files) manifest_content, _ = storage.staticfiles_storage.load_manifest() self.assertNotIn(cleared_file_name, manifest_content) def test_missing_entry(self): missing_file_name = "cached/missing.css" configured_storage = storage.staticfiles_storage self.assertNotIn(missing_file_name, configured_storage.hashed_files) # File name not found in manifest with self.assertRaisesMessage( ValueError, "Missing staticfiles manifest entry for '%s'" % missing_file_name, ): self.hashed_file_path(missing_file_name) configured_storage.manifest_strict = False # File doesn't exist on disk err_msg = "The file '%s' could not be found with %r." % ( missing_file_name, configured_storage._wrapped, ) with self.assertRaisesMessage(ValueError, err_msg): self.hashed_file_path(missing_file_name) content = StringIO() content.write("Found") configured_storage.save(missing_file_name, content) # File exists on disk self.hashed_file_path(missing_file_name) def test_intermediate_files(self): cached_files = os.listdir(os.path.join(settings.STATIC_ROOT, "cached")) # Intermediate files shouldn't be created for reference. self.assertEqual( len( [ cached_file for cached_file in cached_files if cached_file.startswith("relative.") ] ), 2, ) def test_manifest_hash(self): # Collect the additional file. self.run_collectstatic() _, manifest_hash_orig = storage.staticfiles_storage.load_manifest() self.assertNotEqual(manifest_hash_orig, "") self.assertEqual(storage.staticfiles_storage.manifest_hash, manifest_hash_orig) # Saving doesn't change the hash. storage.staticfiles_storage.save_manifest() self.assertEqual(storage.staticfiles_storage.manifest_hash, manifest_hash_orig) # Delete the original file from the app, collect with clear. os.unlink(self._clear_filename) self.run_collectstatic(clear=True) # Hash is changed. _, manifest_hash = storage.staticfiles_storage.load_manifest() self.assertNotEqual(manifest_hash, manifest_hash_orig) def test_manifest_hash_v1(self): storage.staticfiles_storage.manifest_name = "staticfiles_v1.json" manifest_content, manifest_hash = storage.staticfiles_storage.load_manifest() self.assertEqual(manifest_hash, "") self.assertEqual(manifest_content, {"dummy.txt": "dummy.txt"}) def test_manifest_file_consistent_content(self): original_manifest_content = storage.staticfiles_storage.read_manifest() hashed_files = storage.staticfiles_storage.hashed_files # Force a change in the order of the hashed files. with mock.patch.object( storage.staticfiles_storage, "hashed_files", dict(reversed(hashed_files.items())), ): storage.staticfiles_storage.save_manifest() manifest_file_content = storage.staticfiles_storage.read_manifest() # The manifest file content should not change. self.assertEqual(original_manifest_content, manifest_file_content) @override_settings( STATIC_URL="/", STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage", }, }, ) class TestCollectionManifestStorageStaticUrlSlash(CollectionTestCase): run_collectstatic_in_setUp = False hashed_file_path = hashed_file_path def test_protocol_relative_url_ignored(self): with override_settings( STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "static_url_slash")], STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ): self.run_collectstatic() relpath = self.hashed_file_path("ignored.css") self.assertEqual(relpath, "ignored.61707f5f4942.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"//foobar", content) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.NoneHashStorage", }, } ) class TestCollectionNoneHashStorage(CollectionTestCase): hashed_file_path = hashed_file_path def test_hashed_name(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.css") @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.NoPostProcessReplacedPathStorage", }, } ) class TestCollectionNoPostProcessReplacedPaths(CollectionTestCase): run_collectstatic_in_setUp = False def test_collectstatistic_no_post_process_replaced_paths(self): stdout = StringIO() self.run_collectstatic(verbosity=1, stdout=stdout) self.assertIn("post-processed", stdout.getvalue()) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.SimpleStorage", }, } ) class TestCollectionSimpleStorage(CollectionTestCase): hashed_file_path = hashed_file_path def setUp(self): storage.staticfiles_storage.hashed_files.clear() # avoid cache interference super().setUp() def test_template_tag_return(self): self.assertStaticRaises( ValueError, "does/not/exist.png", "/static/does/not/exist.png" ) self.assertStaticRenders("test/file.txt", "/static/test/file.deploy12345.txt") self.assertStaticRenders( "cached/styles.css", "/static/cached/styles.deploy12345.css" ) self.assertStaticRenders("path/", "/static/path/") self.assertStaticRenders("path/?query", "/static/path/?query") def test_template_tag_simple_content(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.deploy12345.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.deploy12345.css", content) class JSModuleImportAggregationManifestStorage(storage.ManifestStaticFilesStorage): support_js_module_import_aggregation = True @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": ( "staticfiles_tests.test_storage." "JSModuleImportAggregationManifestStorage" ), }, } ) class TestCollectionJSModuleImportAggregationManifestStorage(CollectionTestCase): hashed_file_path = hashed_file_path def test_module_import(self): relpath = self.hashed_file_path("cached/module.js") self.assertEqual(relpath, "cached/module.4326210cf0bd.js") tests = [ # Relative imports. b'import testConst from "./module_test.477bbebe77f0.js";', b'import relativeModule from "../nested/js/nested.866475c46bb4.js";', b'import { firstConst, secondConst } from "./module_test.477bbebe77f0.js";', # Absolute import. b'import rootConst from "/static/absolute_root.5586327fe78c.js";', # Dynamic import. b'const dynamicModule = import("./module_test.477bbebe77f0.js");', # Creating a module object. b'import * as NewModule from "./module_test.477bbebe77f0.js";', # Creating a minified module object. b'import*as m from "./module_test.477bbebe77f0.js";', b'import* as m from "./module_test.477bbebe77f0.js";', b'import *as m from "./module_test.477bbebe77f0.js";', b'import* as m from "./module_test.477bbebe77f0.js";', # Aliases. b'import { testConst as alias } from "./module_test.477bbebe77f0.js";', b"import {\n" b" firstVar1 as firstVarAlias,\n" b" $second_var_2 as secondVarAlias\n" b'} from "./module_test.477bbebe77f0.js";', ] with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() for module_import in tests: with self.subTest(module_import=module_import): self.assertIn(module_import, content) def test_aggregating_modules(self): relpath = self.hashed_file_path("cached/module.js") self.assertEqual(relpath, "cached/module.4326210cf0bd.js") tests = [ b'export * from "./module_test.477bbebe77f0.js";', b'export { testConst } from "./module_test.477bbebe77f0.js";', b"export {\n" b" firstVar as firstVarAlias,\n" b" secondVar as secondVarAlias\n" b'} from "./module_test.477bbebe77f0.js";', ] with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() for module_import in tests: with self.subTest(module_import=module_import): self.assertIn(module_import, content) class CustomManifestStorage(storage.ManifestStaticFilesStorage): def __init__(self, *args, manifest_storage=None, **kwargs): manifest_storage = storage.StaticFilesStorage( location=kwargs.pop("manifest_location"), ) super().__init__(*args, manifest_storage=manifest_storage, **kwargs) class TestCustomManifestStorage(SimpleTestCase): def setUp(self): manifest_path = Path(tempfile.mkdtemp()) self.addCleanup(shutil.rmtree, manifest_path) self.staticfiles_storage = CustomManifestStorage( manifest_location=manifest_path, ) self.manifest_file = manifest_path / self.staticfiles_storage.manifest_name # Manifest without paths. self.manifest = {"version": self.staticfiles_storage.manifest_version} with self.manifest_file.open("w") as manifest_file: json.dump(self.manifest, manifest_file) def test_read_manifest(self): self.assertEqual( self.staticfiles_storage.read_manifest(), json.dumps(self.manifest), ) def test_read_manifest_nonexistent(self): os.remove(self.manifest_file) self.assertIsNone(self.staticfiles_storage.read_manifest()) def test_save_manifest_override(self): self.assertIs(self.manifest_file.exists(), True) self.staticfiles_storage.save_manifest() self.assertIs(self.manifest_file.exists(), True) new_manifest = json.loads(self.staticfiles_storage.read_manifest()) self.assertIn("paths", new_manifest) self.assertNotEqual(new_manifest, self.manifest) def test_save_manifest_create(self): os.remove(self.manifest_file) self.staticfiles_storage.save_manifest() self.assertIs(self.manifest_file.exists(), True) new_manifest = json.loads(self.staticfiles_storage.read_manifest()) self.assertIn("paths", new_manifest) self.assertNotEqual(new_manifest, self.manifest) class CustomStaticFilesStorage(storage.StaticFilesStorage): """ Used in TestStaticFilePermissions """ def __init__(self, *args, **kwargs): kwargs["file_permissions_mode"] = 0o640 kwargs["directory_permissions_mode"] = 0o740 super().__init__(*args, **kwargs) @unittest.skipIf(sys.platform == "win32", "Windows only partially supports chmod.") class TestStaticFilePermissions(CollectionTestCase): command_params = { "interactive": False, "verbosity": 0, "ignore_patterns": ["*.ignoreme"], } def setUp(self): self.umask = 0o027 old_umask = os.umask(self.umask) self.addCleanup(os.umask, old_umask) super().setUp() # Don't run collectstatic command in this test class. def run_collectstatic(self, **kwargs): pass @override_settings( FILE_UPLOAD_PERMISSIONS=0o655, FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765, ) def test_collect_static_files_permissions(self): call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / "test.txt" file_mode = test_file.stat().st_mode & 0o777 self.assertEqual(file_mode, 0o655) tests = [ static_root / "subdir", static_root / "nested", static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): dir_mode = directory.stat().st_mode & 0o777 self.assertEqual(dir_mode, 0o765) @override_settings( FILE_UPLOAD_PERMISSIONS=None, FILE_UPLOAD_DIRECTORY_PERMISSIONS=None, ) def test_collect_static_files_default_permissions(self): call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / "test.txt" file_mode = test_file.stat().st_mode & 0o777 self.assertEqual(file_mode, 0o666 & ~self.umask) tests = [ static_root / "subdir", static_root / "nested", static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): dir_mode = directory.stat().st_mode & 0o777 self.assertEqual(dir_mode, 0o777 & ~self.umask) @override_settings( FILE_UPLOAD_PERMISSIONS=0o655, FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765, STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.test_storage.CustomStaticFilesStorage", }, }, ) def test_collect_static_files_subclass_of_static_storage(self): call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / "test.txt" file_mode = test_file.stat().st_mode & 0o777 self.assertEqual(file_mode, 0o640) tests = [ static_root / "subdir", static_root / "nested", static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): dir_mode = directory.stat().st_mode & 0o777 self.assertEqual(dir_mode, 0o740) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage", }, } ) class TestCollectionHashedFilesCache(CollectionTestCase): """ Files referenced from CSS use the correct final hashed name regardless of the order in which the files are post-processed. """ hashed_file_path = hashed_file_path def setUp(self): super().setUp() self._temp_dir = temp_dir = tempfile.mkdtemp() os.makedirs(os.path.join(temp_dir, "test")) self.addCleanup(shutil.rmtree, temp_dir) def _get_filename_path(self, filename): return os.path.join(self._temp_dir, "test", filename) def test_file_change_after_collectstatic(self): # Create initial static files. file_contents = ( ("foo.png", "foo"), ("bar.css", 'url("foo.png")\nurl("xyz.png")'), ("xyz.png", "xyz"), ) for filename, content in file_contents: with open(self._get_filename_path(filename), "w") as f: f.write(content) with self.modify_settings(STATICFILES_DIRS={"append": self._temp_dir}): finders.get_finder.cache_clear() err = StringIO() # First collectstatic run. call_command("collectstatic", interactive=False, verbosity=0, stderr=err) relpath = self.hashed_file_path("test/bar.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"foo.acbd18db4cc2.png", content) self.assertIn(b"xyz.d16fb36f0911.png", content) # Change the contents of the png files. for filename in ("foo.png", "xyz.png"): with open(self._get_filename_path(filename), "w+b") as f: f.write(b"new content of file to change its hash") # The hashes of the png files in the CSS file are updated after # a second collectstatic. call_command("collectstatic", interactive=False, verbosity=0, stderr=err) relpath = self.hashed_file_path("test/bar.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"foo.57a5cb9ba68d.png", content) self.assertIn(b"xyz.57a5cb9ba68d.png", content)
django
python
from django.db.migrations.operations.base import Operation class TestOperation(Operation): def __init__(self): pass def deconstruct(self): return (self.__class__.__name__, [], {}) @property def reversible(self): return True def state_forwards(self, app_label, state): pass def database_forwards(self, app_label, schema_editor, from_state, to_state): pass def state_backwards(self, app_label, state): pass def database_backwards(self, app_label, schema_editor, from_state, to_state): pass class CreateModel(TestOperation): pass class ArgsOperation(TestOperation): def __init__(self, arg1, arg2): self.arg1, self.arg2 = arg1, arg2 def deconstruct(self): return (self.__class__.__name__, [self.arg1, self.arg2], {}) class KwargsOperation(TestOperation): def __init__(self, kwarg1=None, kwarg2=None): self.kwarg1, self.kwarg2 = kwarg1, kwarg2 def deconstruct(self): kwargs = {} if self.kwarg1 is not None: kwargs["kwarg1"] = self.kwarg1 if self.kwarg2 is not None: kwargs["kwarg2"] = self.kwarg2 return (self.__class__.__name__, [], kwargs) class ArgsKwargsOperation(TestOperation): def __init__(self, arg1, arg2, kwarg1=None, kwarg2=None): self.arg1, self.arg2 = arg1, arg2 self.kwarg1, self.kwarg2 = kwarg1, kwarg2 def deconstruct(self): kwargs = {} if self.kwarg1 is not None: kwargs["kwarg1"] = self.kwarg1 if self.kwarg2 is not None: kwargs["kwarg2"] = self.kwarg2 return ( self.__class__.__name__, [self.arg1, self.arg2], kwargs, ) class ArgsAndKeywordOnlyArgsOperation(ArgsKwargsOperation): def __init__(self, arg1, arg2, *, kwarg1, kwarg2): super().__init__(arg1, arg2, kwarg1=kwarg1, kwarg2=kwarg2) class ExpandArgsOperation(TestOperation): serialization_expand_args = ["arg"] def __init__(self, arg): self.arg = arg def deconstruct(self): return (self.__class__.__name__, [self.arg], {})
import unittest from django.core.management.color import no_style from django.db import connection from django.test import SimpleTestCase from ..models import Person, Tag @unittest.skipUnless(connection.vendor == "mysql", "MySQL tests.") class MySQLOperationsTests(SimpleTestCase): def test_sql_flush(self): # allow_cascade doesn't change statements on MySQL. for allow_cascade in [False, True]: with self.subTest(allow_cascade=allow_cascade): self.assertEqual( connection.ops.sql_flush( no_style(), [Person._meta.db_table, Tag._meta.db_table], allow_cascade=allow_cascade, ), [ "SET FOREIGN_KEY_CHECKS = 0;", "DELETE FROM `backends_person`;", "DELETE FROM `backends_tag`;", "SET FOREIGN_KEY_CHECKS = 1;", ], ) def test_sql_flush_sequences(self): # allow_cascade doesn't change statements on MySQL. for allow_cascade in [False, True]: with self.subTest(allow_cascade=allow_cascade): self.assertEqual( connection.ops.sql_flush( no_style(), [Person._meta.db_table, Tag._meta.db_table], reset_sequences=True, allow_cascade=allow_cascade, ), [ "SET FOREIGN_KEY_CHECKS = 0;", "TRUNCATE `backends_person`;", "TRUNCATE `backends_tag`;", "SET FOREIGN_KEY_CHECKS = 1;", ], )
django
python
import multiprocessing import os import shutil import sqlite3 import sys from pathlib import Path from django.db import NotSupportedError from django.db.backends.base.creation import BaseDatabaseCreation class DatabaseCreation(BaseDatabaseCreation): @staticmethod def is_in_memory_db(database_name): return not isinstance(database_name, Path) and ( database_name == ":memory:" or "mode=memory" in database_name ) def _get_test_db_name(self): test_database_name = self.connection.settings_dict["TEST"]["NAME"] or ":memory:" if test_database_name == ":memory:": return "file:memorydb_%s?mode=memory&cache=shared" % self.connection.alias return test_database_name def _create_test_db(self, verbosity, autoclobber, keepdb=False): test_database_name = self._get_test_db_name() if keepdb: return test_database_name if not self.is_in_memory_db(test_database_name): # Erase the old test database if verbosity >= 1: self.log( "Destroying old test database for alias %s..." % (self._get_database_display_str(verbosity, test_database_name),) ) if os.access(test_database_name, os.F_OK): if not autoclobber: confirm = input( "Type 'yes' if you would like to try deleting the test " "database '%s', or 'no' to cancel: " % test_database_name ) if autoclobber or confirm == "yes": try: os.remove(test_database_name) except Exception as e: self.log("Got an error deleting the old test database: %s" % e) sys.exit(2) else: self.log("Tests cancelled.") sys.exit(1) return test_database_name def get_test_db_clone_settings(self, suffix): orig_settings_dict = self.connection.settings_dict source_database_name = orig_settings_dict["NAME"] or ":memory:" if not self.is_in_memory_db(source_database_name): root, ext = os.path.splitext(source_database_name) return {**orig_settings_dict, "NAME": f"{root}_{suffix}{ext}"} start_method = multiprocessing.get_start_method() if start_method == "fork": return orig_settings_dict if start_method in {"forkserver", "spawn"}: return { **orig_settings_dict, "NAME": f"{self.connection.alias}_{suffix}.sqlite3", } raise NotSupportedError( f"Cloning with start method {start_method!r} is not supported." ) def _clone_test_db(self, suffix, verbosity, keepdb=False): source_database_name = self.connection.settings_dict["NAME"] target_database_name = self.get_test_db_clone_settings(suffix)["NAME"] if not self.is_in_memory_db(source_database_name): # Erase the old test database if os.access(target_database_name, os.F_OK): if keepdb: return if verbosity >= 1: self.log( "Destroying old test database for alias %s..." % ( self._get_database_display_str( verbosity, target_database_name ), ) ) try: os.remove(target_database_name) except Exception as e: self.log("Got an error deleting the old test database: %s" % e) sys.exit(2) try: shutil.copy(source_database_name, target_database_name) except Exception as e: self.log("Got an error cloning the test database: %s" % e) sys.exit(2) # Forking automatically makes a copy of an in-memory database. # Forkserver and spawn require migrating to disk which will be # re-opened in setup_worker_connection. elif multiprocessing.get_start_method() in {"forkserver", "spawn"}: ondisk_db = sqlite3.connect(target_database_name, uri=True) self.connection.connection.backup(ondisk_db) ondisk_db.close() def _destroy_test_db(self, test_database_name, verbosity): if test_database_name and not self.is_in_memory_db(test_database_name): # Remove the SQLite database file os.remove(test_database_name) def test_db_signature(self): """ Return a tuple that uniquely identifies a test database. This takes into account the special cases of ":memory:" and "" for SQLite since the databases will be distinct despite having the same TEST NAME. See https://www.sqlite.org/inmemorydb.html """ test_database_name = self._get_test_db_name() sig = [self.connection.settings_dict["NAME"]] if self.is_in_memory_db(test_database_name): sig.append(self.connection.alias) else: sig.append(test_database_name) return tuple(sig) def setup_worker_connection(self, _worker_id): settings_dict = self.get_test_db_clone_settings(_worker_id) # connection.settings_dict must be updated in place for changes to be # reflected in django.db.connections. Otherwise new threads would # connect to the default database instead of the appropriate clone. start_method = multiprocessing.get_start_method() if start_method == "fork": # Update settings_dict in place. self.connection.settings_dict.update(settings_dict) self.connection.close() elif start_method in {"forkserver", "spawn"}: alias = self.connection.alias connection_str = ( f"file:memorydb_{alias}_{_worker_id}?mode=memory&cache=shared" ) source_db = self.connection.Database.connect( f"file:{alias}_{_worker_id}.sqlite3?mode=ro", uri=True ) target_db = sqlite3.connect(connection_str, uri=True) source_db.backup(target_db) source_db.close() # Update settings_dict in place. self.connection.settings_dict.update(settings_dict) self.connection.settings_dict["NAME"] = connection_str # Re-open connection to in-memory database before closing copy # connection. self.connection.connect() target_db.close()
import subprocess import unittest from io import BytesIO, StringIO from unittest import mock from django.db import DatabaseError, connection from django.db.backends.base.creation import BaseDatabaseCreation from django.db.backends.mysql.creation import DatabaseCreation from django.test import SimpleTestCase from django.test.utils import captured_stderr @unittest.skipUnless(connection.vendor == "mysql", "MySQL tests") class DatabaseCreationTests(SimpleTestCase): def _execute_raise_database_exists(self, cursor, parameters, keepdb=False): raise DatabaseError( 1007, "Can't create database '%s'; database exists" % parameters["dbname"] ) def _execute_raise_access_denied(self, cursor, parameters, keepdb=False): raise DatabaseError(1044, "Access denied for user") def patch_test_db_creation(self, execute_create_test_db): return mock.patch.object( BaseDatabaseCreation, "_execute_create_test_db", execute_create_test_db ) @mock.patch("sys.stdout", new_callable=StringIO) @mock.patch("sys.stderr", new_callable=StringIO) def test_create_test_db_database_exists(self, *mocked_objects): # Simulate test database creation raising "database exists" creation = DatabaseCreation(connection) with self.patch_test_db_creation(self._execute_raise_database_exists): with mock.patch("builtins.input", return_value="no"): with self.assertRaises(SystemExit): # SystemExit is raised if the user answers "no" to the # prompt asking if it's okay to delete the test database. creation._create_test_db( verbosity=0, autoclobber=False, keepdb=False ) # "Database exists" shouldn't appear when keepdb is on creation._create_test_db(verbosity=0, autoclobber=False, keepdb=True) @mock.patch("sys.stdout", new_callable=StringIO) @mock.patch("sys.stderr", new_callable=StringIO) def test_create_test_db_unexpected_error(self, *mocked_objects): # Simulate test database creation raising unexpected error creation = DatabaseCreation(connection) with self.patch_test_db_creation(self._execute_raise_access_denied): with self.assertRaises(SystemExit): creation._create_test_db(verbosity=0, autoclobber=False, keepdb=False) def test_clone_test_db_database_exists(self): creation = DatabaseCreation(connection) with self.patch_test_db_creation(self._execute_raise_database_exists): with mock.patch.object(DatabaseCreation, "_clone_db") as _clone_db: creation._clone_test_db("suffix", verbosity=0, keepdb=True) _clone_db.assert_not_called() def test_clone_test_db_options_ordering(self): creation = DatabaseCreation(connection) mock_subprocess_call = mock.MagicMock() mock_subprocess_call.returncode = 0 try: saved_settings = connection.settings_dict connection.settings_dict = { "NAME": "source_db", "USER": "", "PASSWORD": "", "PORT": "", "HOST": "", "ENGINE": "django.db.backends.mysql", "OPTIONS": { "read_default_file": "my.cnf", }, } with mock.patch.object(subprocess, "Popen") as mocked_popen: mocked_popen.return_value.__enter__.return_value = mock_subprocess_call creation._clone_db("source_db", "target_db") mocked_popen.assert_has_calls( [ mock.call( [ "mysqldump", "--defaults-file=my.cnf", "--routines", "--events", "source_db", ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=None, ), ] ) finally: connection.settings_dict = saved_settings def test_clone_test_db_subprocess_mysqldump_error(self): creation = DatabaseCreation(connection) mock_subprocess_call = mock.MagicMock() mock_subprocess_call.returncode = 0 # Simulate mysqldump in test database cloning raises an error. msg = "Couldn't execute 'SELECT ...'" mock_subprocess_call_error = mock.MagicMock() mock_subprocess_call_error.returncode = 2 mock_subprocess_call_error.stderr = BytesIO(msg.encode()) with mock.patch.object(subprocess, "Popen") as mocked_popen: mocked_popen.return_value.__enter__.side_effect = [ mock_subprocess_call_error, # mysqldump mock mock_subprocess_call, # load mock ] with captured_stderr() as err, self.assertRaises(SystemExit) as cm: creation._clone_db("source_db", "target_db") self.assertEqual(cm.exception.code, 2) self.assertIn( f"Got an error on mysqldump when cloning the test database: {msg}", err.getvalue(), ) def test_clone_test_db_subprocess_mysql_error(self): creation = DatabaseCreation(connection) mock_subprocess_call = mock.MagicMock() mock_subprocess_call.returncode = 0 # Simulate load in test database cloning raises an error. msg = "Some error" mock_subprocess_call_error = mock.MagicMock() mock_subprocess_call_error.returncode = 3 mock_subprocess_call_error.stderr = BytesIO(msg.encode()) with mock.patch.object(subprocess, "Popen") as mocked_popen: mocked_popen.return_value.__enter__.side_effect = [ mock_subprocess_call, # mysqldump mock mock_subprocess_call_error, # load mock ] with captured_stderr() as err, self.assertRaises(SystemExit) as cm: creation._clone_db("source_db", "target_db") self.assertEqual(cm.exception.code, 3) self.assertIn(f"Got an error cloning the test database: {msg}", err.getvalue())
django
python
import copy from decimal import Decimal from django.apps.registry import Apps from django.db import NotSupportedError from django.db.backends.base.schema import BaseDatabaseSchemaEditor from django.db.backends.ddl_references import Statement from django.db.backends.utils import strip_quotes from django.db.models import CompositePrimaryKey, UniqueConstraint class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): sql_delete_table = "DROP TABLE %(table)s" sql_create_fk = None sql_create_inline_fk = ( "REFERENCES %(to_table)s (%(to_column)s)%(on_delete_db)s DEFERRABLE INITIALLY " "DEFERRED" ) sql_create_column_inline_fk = sql_create_inline_fk sql_create_unique = "CREATE UNIQUE INDEX %(name)s ON %(table)s (%(columns)s)" sql_delete_unique = "DROP INDEX %(name)s" sql_alter_table_comment = None sql_alter_column_comment = None def __enter__(self): # Some SQLite schema alterations need foreign key constraints to be # disabled. Enforce it here for the duration of the schema edition. if not self.connection.disable_constraint_checking(): raise NotSupportedError( "SQLite schema editor cannot be used while foreign key " "constraint checks are enabled. Make sure to disable them " "before entering a transaction.atomic() context because " "SQLite does not support disabling them in the middle of " "a multi-statement transaction." ) return super().__enter__() def __exit__(self, exc_type, exc_value, traceback): self.connection.check_constraints() super().__exit__(exc_type, exc_value, traceback) self.connection.enable_constraint_checking() def quote_value(self, value): # The backend "mostly works" without this function and there are use # cases for compiling Python without the sqlite3 libraries (e.g. # security hardening). try: import sqlite3 value = sqlite3.adapt(value) except ImportError: pass except sqlite3.ProgrammingError: pass # Manual emulation of SQLite parameter quoting if isinstance(value, bool): return str(int(value)) elif isinstance(value, (Decimal, float, int)): return str(value) elif isinstance(value, str): return "'%s'" % value.replace("'", "''") elif value is None: return "NULL" elif isinstance(value, (bytes, bytearray, memoryview)): # Bytes are only allowed for BLOB fields, encoded as string # literals containing hexadecimal data and preceded by a single "X" # character. return "X'%s'" % value.hex() else: raise ValueError( "Cannot quote parameter value %r of type %s" % (value, type(value)) ) def prepare_default(self, value): return self.quote_value(value) def _remake_table( self, model, create_field=None, delete_field=None, alter_fields=None ): """ Shortcut to transform a model from old_model into new_model This follows the correct procedure to perform non-rename or column addition operations based on SQLite's documentation https://www.sqlite.org/lang_altertable.html#caution The essential steps are: 1. Create a table with the updated definition called "new__app_model" 2. Copy the data from the existing "app_model" table to the new table 3. Drop the "app_model" table 4. Rename the "new__app_model" table to "app_model" 5. Restore any index of the previous "app_model" table. """ # Self-referential fields must be recreated rather than copied from # the old model to ensure their remote_field.field_name doesn't refer # to an altered field. def is_self_referential(f): return f.is_relation and f.remote_field.model is model # Work out the new fields dict / mapping body = { f.name: f.clone() if is_self_referential(f) else f for f in model._meta.local_concrete_fields } # Since CompositePrimaryKey is not a concrete field (column is None), # it's not copied by default. pk = model._meta.pk if isinstance(pk, CompositePrimaryKey): body[pk.name] = pk.clone() # Since mapping might mix column names and default values, # its values must be already quoted. mapping = { f.column: self.quote_name(f.column) for f in model._meta.local_concrete_fields if f.generated is False } # This maps field names (not columns) for things like unique_together rename_mapping = {} # If any of the new or altered fields is introducing a new PK, # remove the old one restore_pk_field = None alter_fields = alter_fields or [] if getattr(create_field, "primary_key", False) or any( getattr(new_field, "primary_key", False) for _, new_field in alter_fields ): for name, field in list(body.items()): if field.primary_key and not any( # Do not remove the old primary key when an altered field # that introduces a primary key is the same field. name == new_field.name for _, new_field in alter_fields ): field.primary_key = False restore_pk_field = field if field.auto_created: del body[name] del mapping[field.column] # Add in any created fields if create_field: body[create_field.name] = create_field # Choose a default and insert it into the copy map if ( not create_field.has_db_default() and not create_field.generated and create_field.concrete ): mapping[create_field.column] = self.prepare_default( self.effective_default(create_field) ) # Add in any altered fields for alter_field in alter_fields: old_field, new_field = alter_field body.pop(old_field.name, None) mapping.pop(old_field.column, None) body[new_field.name] = new_field rename_mapping[old_field.name] = new_field.name if new_field.generated: continue if old_field.null and not new_field.null: if not new_field.has_db_default(): default = self.prepare_default(self.effective_default(new_field)) else: default, _ = self.db_default_sql(new_field) case_sql = "coalesce(%(col)s, %(default)s)" % { "col": self.quote_name(old_field.column), "default": default, } mapping[new_field.column] = case_sql else: mapping[new_field.column] = self.quote_name(old_field.column) # Remove any deleted fields if delete_field: del body[delete_field.name] mapping.pop(delete_field.column, None) # Remove any implicit M2M tables if ( delete_field.many_to_many and delete_field.remote_field.through._meta.auto_created ): return self.delete_model(delete_field.remote_field.through) # Work inside a new app registry apps = Apps() # Work out the new value of unique_together, taking renames into # account unique_together = [ [rename_mapping.get(n, n) for n in unique] for unique in model._meta.unique_together ] indexes = model._meta.indexes if delete_field: indexes = [ index for index in indexes if delete_field.name not in index.fields ] constraints = list(model._meta.constraints) # Provide isolated instances of the fields to the new model body so # that the existing model's internals aren't interfered with when # the dummy model is constructed. body_copy = copy.deepcopy(body) # Construct a new model with the new fields to allow self referential # primary key to resolve to. This model won't ever be materialized as a # table and solely exists for foreign key reference resolution # purposes. This wouldn't be required if the schema editor was # operating on model states instead of rendered models. meta_contents = { "app_label": model._meta.app_label, "db_table": model._meta.db_table, "unique_together": unique_together, "indexes": indexes, "constraints": constraints, "apps": apps, } meta = type("Meta", (), meta_contents) body_copy["Meta"] = meta body_copy["__module__"] = model.__module__ type(model._meta.object_name, model.__bases__, body_copy) # Construct a model with a renamed table name. body_copy = copy.deepcopy(body) meta_contents = { "app_label": model._meta.app_label, "db_table": "new__%s" % strip_quotes(model._meta.db_table), "unique_together": unique_together, "indexes": indexes, "constraints": constraints, "apps": apps, } meta = type("Meta", (), meta_contents) body_copy["Meta"] = meta body_copy["__module__"] = model.__module__ new_model = type("New%s" % model._meta.object_name, model.__bases__, body_copy) # Remove the automatically recreated default primary key, if it has # been deleted. if delete_field and delete_field.attname == new_model._meta.pk.attname: auto_pk = new_model._meta.pk delattr(new_model, auto_pk.attname) new_model._meta.local_fields.remove(auto_pk) new_model.pk = None # Create a new table with the updated schema. self.create_model(new_model) # Copy data from the old table into the new table self.execute( "INSERT INTO %s (%s) SELECT %s FROM %s" % ( self.quote_name(new_model._meta.db_table), ", ".join(self.quote_name(x) for x in mapping), ", ".join(mapping.values()), self.quote_name(model._meta.db_table), ) ) # Delete the old table to make way for the new self.delete_model(model, handle_autom2m=False) # Rename the new table to take way for the old self.alter_db_table( new_model, new_model._meta.db_table, model._meta.db_table, ) # Run deferred SQL on correct table for sql in self.deferred_sql: self.execute(sql) self.deferred_sql = [] # Fix any PK-removed field if restore_pk_field: restore_pk_field.primary_key = True def delete_model(self, model, handle_autom2m=True): if handle_autom2m: super().delete_model(model) else: # Delete the table (and only that) self.execute( self.sql_delete_table % { "table": self.quote_name(model._meta.db_table), } ) # Remove all deferred statements referencing the deleted table. for sql in list(self.deferred_sql): if isinstance(sql, Statement) and sql.references_table( model._meta.db_table ): self.deferred_sql.remove(sql) def add_field(self, model, field): """Create a field on a model.""" from django.db.models.expressions import Value # Special-case implicit M2M tables. if field.many_to_many and field.remote_field.through._meta.auto_created: self.create_model(field.remote_field.through) elif isinstance(field, CompositePrimaryKey): # If a CompositePrimaryKey field was added, the existing primary # key field had to be altered too, resulting in an AddField, # AlterField migration. The table cannot be re-created on AddField, # it would result in a duplicate primary key error. return elif ( # Primary keys and unique fields are not supported in ALTER TABLE # ADD COLUMN. field.primary_key or field.unique or not field.null # Fields with default values cannot by handled by ALTER TABLE ADD # COLUMN statement because DROP DEFAULT is not supported in # ALTER TABLE. or self.effective_default(field) is not None # Fields with non-constant defaults cannot by handled by ALTER # TABLE ADD COLUMN statement. or (field.has_db_default() and not isinstance(field.db_default, Value)) ): self._remake_table(model, create_field=field) else: super().add_field(model, field) def remove_field(self, model, field): """ Remove a field from a model. Usually involves deleting a column, but for M2Ms may involve deleting a table. """ # M2M fields are a special case if field.many_to_many: # For implicit M2M tables, delete the auto-created table if field.remote_field.through._meta.auto_created: self.delete_model(field.remote_field.through) # For explicit "through" M2M fields, do nothing elif ( # Primary keys, unique fields, indexed fields, and foreign keys are # not supported in ALTER TABLE DROP COLUMN. not field.primary_key and not field.unique and not field.db_index and not (field.remote_field and field.db_constraint) ): super().remove_field(model, field) # For everything else, remake. else: # It might not actually have a column behind it if field.db_parameters(connection=self.connection)["type"] is None: return self._remake_table(model, delete_field=field) def _alter_field( self, model, old_field, new_field, old_type, new_type, old_db_params, new_db_params, strict=False, ): """Perform a "physical" (non-ManyToMany) field update.""" # Use "ALTER TABLE ... RENAME COLUMN" if only the column name # changed and there aren't any constraints. if ( old_field.column != new_field.column and self.column_sql(model, old_field) == self.column_sql(model, new_field) and not ( old_field.remote_field and old_field.db_constraint or new_field.remote_field and new_field.db_constraint ) ): return self.execute( self._rename_field_sql( model._meta.db_table, old_field, new_field, new_type ) ) # Alter by remaking table self._remake_table(model, alter_fields=[(old_field, new_field)]) # Rebuild tables with FKs pointing to this field. old_collation = old_db_params.get("collation") new_collation = new_db_params.get("collation") if new_field.unique and ( old_type != new_type or old_collation != new_collation ): related_models = set() opts = new_field.model._meta for remote_field in opts.related_objects: # Ignore self-relationship since the table was already rebuilt. if remote_field.related_model == model: continue if not remote_field.many_to_many: if remote_field.field_name == new_field.name: related_models.add(remote_field.related_model) elif new_field.primary_key and remote_field.through._meta.auto_created: related_models.add(remote_field.through) if new_field.primary_key: for many_to_many in opts.many_to_many: # Ignore self-relationship since the table was already # rebuilt. if many_to_many.related_model == model: continue if many_to_many.remote_field.through._meta.auto_created: related_models.add(many_to_many.remote_field.through) for related_model in related_models: self._remake_table(related_model) def _alter_many_to_many(self, model, old_field, new_field, strict): """Alter M2Ms to repoint their to= endpoints.""" if ( old_field.remote_field.through._meta.db_table == new_field.remote_field.through._meta.db_table ): # The field name didn't change, but some options did, so we have to # propagate this altering. self._remake_table( old_field.remote_field.through, alter_fields=[ ( # The field that points to the target model is needed, # so that table can be remade with the new m2m field - # this is m2m_reverse_field_name(). old_field.remote_field.through._meta.get_field( old_field.m2m_reverse_field_name() ), new_field.remote_field.through._meta.get_field( new_field.m2m_reverse_field_name() ), ), ( # The field that points to the model itself is needed, # so that table can be remade with the new self field - # this is m2m_field_name(). old_field.remote_field.through._meta.get_field( old_field.m2m_field_name() ), new_field.remote_field.through._meta.get_field( new_field.m2m_field_name() ), ), ], ) return # Make a new through table self.create_model(new_field.remote_field.through) # Copy the data across self.execute( "INSERT INTO %s (%s) SELECT %s FROM %s" % ( self.quote_name(new_field.remote_field.through._meta.db_table), ", ".join( [ "id", new_field.m2m_column_name(), new_field.m2m_reverse_name(), ] ), ", ".join( [ "id", old_field.m2m_column_name(), old_field.m2m_reverse_name(), ] ), self.quote_name(old_field.remote_field.through._meta.db_table), ) ) # Delete the old through table self.delete_model(old_field.remote_field.through) def add_constraint(self, model, constraint): if isinstance(constraint, UniqueConstraint) and ( constraint.condition or constraint.contains_expressions or constraint.include or constraint.deferrable ): super().add_constraint(model, constraint) else: self._remake_table(model) def remove_constraint(self, model, constraint): if isinstance(constraint, UniqueConstraint) and ( constraint.condition or constraint.contains_expressions or constraint.include or constraint.deferrable ): super().remove_constraint(model, constraint) else: self._remake_table(model) def _collate_sql(self, collation): return "COLLATE " + collation
import unittest from django.db import connection from django.test import TestCase @unittest.skipUnless(connection.vendor == "mysql", "MySQL tests") class SchemaEditorTests(TestCase): def test_quote_value(self): import MySQLdb editor = connection.schema_editor() tested_values = [ ("string", "'string'"), ("¿Tú hablas inglés?", "'¿Tú hablas inglés?'"), (b"bytes", b"'bytes'"), (42, "42"), (1.754, "1.754e0" if MySQLdb.version_info >= (1, 3, 14) else "1.754"), (False, b"0" if MySQLdb.version_info >= (1, 4, 0) else "0"), ] for value, expected in tested_values: with self.subTest(value=value): self.assertEqual(editor.quote_value(value), expected)
django
python
import operator import sqlite3 from django.db import transaction from django.db.backends.base.features import BaseDatabaseFeatures from django.db.utils import OperationalError from django.utils.functional import cached_property from .base import Database class DatabaseFeatures(BaseDatabaseFeatures): minimum_database_version = (3, 37) test_db_allows_multiple_connections = False supports_unspecified_pk = True supports_timezones = False supports_transactions = True atomic_transactions = False can_rollback_ddl = True can_create_inline_fk = False requires_literal_defaults = True can_clone_databases = True supports_temporal_subtraction = True ignores_table_name_case = True supports_cast_with_precision = False time_cast_precision = 3 can_release_savepoints = True has_case_insensitive_like = True supports_parentheses_in_compound = False can_defer_constraint_checks = True supports_over_clause = True supports_frame_range_fixed_distance = True supports_frame_exclusion = True supports_aggregate_filter_clause = True supports_aggregate_order_by_clause = Database.sqlite_version_info >= (3, 44, 0) supports_aggregate_distinct_multiple_argument = False supports_any_value = True order_by_nulls_first = True supports_json_field_contains = False supports_update_conflicts = True supports_update_conflicts_with_target = True supports_stored_generated_columns = True supports_virtual_generated_columns = True test_collations = { "ci": "nocase", "cs": "binary", "non_default": "nocase", "virtual": "nocase", } django_test_expected_failures = { # The django_format_dtdelta() function doesn't properly handle mixed # Date/DateTime fields and timedeltas. "expressions.tests.FTimeDeltaTests.test_mixed_comparisons1", } insert_test_table_with_defaults = 'INSERT INTO {} ("null") VALUES (1)' supports_default_keyword_in_insert = False supports_unlimited_charfield = True supports_no_precision_decimalfield = True can_return_columns_from_insert = True can_return_rows_from_bulk_insert = True can_return_rows_from_update = True @cached_property def django_test_skips(self): skips = { "SQLite stores values rounded to 15 significant digits.": { "model_fields.test_decimalfield.DecimalFieldTests." "test_fetch_from_db_without_float_rounding", }, "SQLite naively remakes the table on field alteration.": { "schema.tests.SchemaTests.test_unique_no_unnecessary_fk_drops", "schema.tests.SchemaTests.test_unique_and_reverse_m2m", "schema.tests.SchemaTests." "test_alter_field_default_doesnt_perform_queries", "schema.tests.SchemaTests." "test_rename_column_renames_deferred_sql_references", }, "SQLite doesn't support negative precision for ROUND().": { "db_functions.math.test_round.RoundTests." "test_null_with_negative_precision", "db_functions.math.test_round.RoundTests." "test_decimal_with_negative_precision", "db_functions.math.test_round.RoundTests." "test_float_with_negative_precision", "db_functions.math.test_round.RoundTests." "test_integer_with_negative_precision", }, "The actual query cannot be determined on SQLite": { "backends.base.test_base.ExecuteWrapperTests.test_wrapper_debug", }, } if self.connection.is_in_memory_db(): skips.update( { "the sqlite backend's close() method is a no-op when using an " "in-memory database": { "servers.test_liveserverthread.LiveServerThreadTest." "test_closes_connections", "servers.tests.LiveServerTestCloseConnectionTest." "test_closes_connections", }, "For SQLite in-memory tests, closing the connection destroys " "the database.": { "test_utils.tests.AssertNumQueriesUponConnectionTests." "test_ignores_connection_configuration_queries", }, } ) else: skips.update( { "Only connections to in-memory SQLite databases are passed to the " "server thread.": { "servers.tests.LiveServerInMemoryDatabaseLockTest." "test_in_memory_database_lock", }, "multiprocessing's start method is checked only for in-memory " "SQLite databases": { "backends.sqlite.test_creation.TestDbSignatureTests." "test_get_test_db_clone_settings_not_supported", }, } ) if Database.sqlite_version_info < (3, 47): skips.update( { "SQLite does not parse escaped double quotes in the JSON path " "notation": { "model_fields.test_jsonfield.TestQuerying." "test_lookups_special_chars_double_quotes", }, } ) return skips @cached_property def introspected_field_types(self): return { **super().introspected_field_types, "BigAutoField": "AutoField", "DurationField": "BigIntegerField", "GenericIPAddressField": "CharField", "SmallAutoField": "AutoField", } @property def max_query_params(self): """ SQLite has a variable limit per query. The limit can be changed using the SQLITE_MAX_VARIABLE_NUMBER compile-time option (which defaults to 32766) or lowered per connection at run-time with setlimit(SQLITE_LIMIT_VARIABLE_NUMBER, N). """ return self.connection.connection.getlimit(sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER) @cached_property def supports_json_field(self): with self.connection.cursor() as cursor: try: with transaction.atomic(self.connection.alias): cursor.execute('SELECT JSON(\'{"a": "b"}\')') except OperationalError: return False return True can_introspect_json_field = property(operator.attrgetter("supports_json_field")) has_json_object_function = property(operator.attrgetter("supports_json_field"))
from unittest import mock, skipUnless from django.db import connection from django.db.backends.mysql.features import DatabaseFeatures from django.test import TestCase @skipUnless(connection.vendor == "mysql", "MySQL tests") class TestFeatures(TestCase): def test_supports_transactions(self): """ All storage engines except MyISAM support transactions. """ del connection.features.supports_transactions with mock.patch( "django.db.connection.features._mysql_storage_engine", "InnoDB" ): self.assertTrue(connection.features.supports_transactions) del connection.features.supports_transactions with mock.patch( "django.db.connection.features._mysql_storage_engine", "MyISAM" ): self.assertFalse(connection.features.supports_transactions) del connection.features.supports_transactions def test_allows_auto_pk_0(self): with mock.MagicMock() as _connection: _connection.sql_mode = {"NO_AUTO_VALUE_ON_ZERO"} database_features = DatabaseFeatures(_connection) self.assertIs(database_features.allows_auto_pk_0, True) def test_allows_group_by_selected_pks(self): with mock.MagicMock() as _connection: _connection.mysql_is_mariadb = False database_features = DatabaseFeatures(_connection) self.assertIs(database_features.allows_group_by_selected_pks, True) with mock.MagicMock() as _connection: _connection.mysql_is_mariadb = False _connection.sql_mode = {} database_features = DatabaseFeatures(_connection) self.assertIs(database_features.allows_group_by_selected_pks, True) with mock.MagicMock() as _connection: _connection.mysql_is_mariadb = True _connection.sql_mode = {"ONLY_FULL_GROUP_BY"} database_features = DatabaseFeatures(_connection) self.assertIs(database_features.allows_group_by_selected_pks, False)
django
python
from collections import namedtuple import sqlparse from django.db import DatabaseError from django.db.backends.base.introspection import BaseDatabaseIntrospection from django.db.backends.base.introspection import FieldInfo as BaseFieldInfo from django.db.backends.base.introspection import TableInfo from django.db.models import Index from django.utils.regex_helper import _lazy_re_compile FieldInfo = namedtuple( "FieldInfo", [*BaseFieldInfo._fields, "pk", "has_json_constraint"] ) field_size_re = _lazy_re_compile(r"^\s*(?:var)?char\s*\(\s*(\d+)\s*\)\s*$") def get_field_size(name): """Extract the size number from a "varchar(11)" type name""" m = field_size_re.search(name) return int(m[1]) if m else None # This light wrapper "fakes" a dictionary interface, because some SQLite data # types include variables in them -- e.g. "varchar(30)" -- and can't be matched # as a simple dictionary lookup. class FlexibleFieldLookupDict: # Maps SQL types to Django Field types. Some of the SQL types have multiple # entries here because SQLite allows for anything and doesn't normalize the # field type; it uses whatever was given. base_data_types_reverse = { "bool": "BooleanField", "boolean": "BooleanField", "smallint": "SmallIntegerField", "smallint unsigned": "PositiveSmallIntegerField", "smallinteger": "SmallIntegerField", "int": "IntegerField", "integer": "IntegerField", "bigint": "BigIntegerField", "integer unsigned": "PositiveIntegerField", "bigint unsigned": "PositiveBigIntegerField", "decimal": "DecimalField", "real": "FloatField", "text": "TextField", "char": "CharField", "varchar": "CharField", "blob": "BinaryField", "date": "DateField", "datetime": "DateTimeField", "time": "TimeField", } def __getitem__(self, key): key = key.lower().split("(", 1)[0].strip() return self.base_data_types_reverse[key] class DatabaseIntrospection(BaseDatabaseIntrospection): data_types_reverse = FlexibleFieldLookupDict() def get_field_type(self, data_type, description): field_type = super().get_field_type(data_type, description) if description.pk and field_type in { "BigIntegerField", "IntegerField", "SmallIntegerField", }: # No support for BigAutoField or SmallAutoField as SQLite treats # all integer primary keys as signed 64-bit integers. return "AutoField" if description.has_json_constraint: return "JSONField" return field_type def get_table_list(self, cursor): """Return a list of table and view names in the current database.""" # Skip the sqlite_sequence system table used for autoincrement key # generation. cursor.execute( """ SELECT name, type FROM sqlite_master WHERE type in ('table', 'view') AND NOT name='sqlite_sequence' ORDER BY name""" ) return [TableInfo(row[0], row[1][0]) for row in cursor.fetchall()] def get_table_description(self, cursor, table_name): """ Return a description of the table with the DB-API cursor.description interface. """ cursor.execute( "PRAGMA table_xinfo(%s)" % self.connection.ops.quote_name(table_name) ) table_info = cursor.fetchall() if not table_info: raise DatabaseError(f"Table {table_name} does not exist (empty pragma).") collations = self._get_column_collations(cursor, table_name) json_columns = set() if self.connection.features.can_introspect_json_field: for line in table_info: column = line[1] json_constraint_sql = '%%json_valid("%s")%%' % column has_json_constraint = cursor.execute( """ SELECT sql FROM sqlite_master WHERE type = 'table' AND name = %s AND sql LIKE %s """, [table_name, json_constraint_sql], ).fetchone() if has_json_constraint: json_columns.add(column) table_description = [ FieldInfo( name, data_type, get_field_size(data_type), None, None, None, not notnull, default, collations.get(name), bool(pk), name in json_columns, ) for cid, name, data_type, notnull, default, pk, hidden in table_info if hidden in [ 0, # Normal column. 2, # Virtual generated column. 3, # Stored generated column. ] ] # If the primary key is composed of multiple columns they should not # be individually marked as pk. primary_key = [ index for index, field_info in enumerate(table_description) if field_info.pk ] if len(primary_key) > 1: for index in primary_key: table_description[index] = table_description[index]._replace(pk=False) return table_description def get_sequences(self, cursor, table_name, table_fields=()): pk_col = self.get_primary_key_column(cursor, table_name) return [{"table": table_name, "column": pk_col}] def get_relations(self, cursor, table_name): """ Return a dictionary of {column_name: (ref_column_name, ref_table_name, db_on_delete)} representing all foreign keys in the given table. """ cursor.execute( "PRAGMA foreign_key_list(%s)" % self.connection.ops.quote_name(table_name) ) return { column_name: ( ref_column_name, ref_table_name, self.on_delete_types.get(on_delete), ) for ( _, _, ref_table_name, column_name, ref_column_name, _, on_delete, *_, ) in cursor.fetchall() } def get_primary_key_columns(self, cursor, table_name): cursor.execute( "PRAGMA table_info(%s)" % self.connection.ops.quote_name(table_name) ) return [name for _, name, *_, pk in cursor.fetchall() if pk] def _parse_column_or_constraint_definition(self, tokens, columns): token = None is_constraint_definition = None field_name = None constraint_name = None unique = False unique_columns = [] check = False check_columns = [] braces_deep = 0 for token in tokens: if token.match(sqlparse.tokens.Punctuation, "("): braces_deep += 1 elif token.match(sqlparse.tokens.Punctuation, ")"): braces_deep -= 1 if braces_deep < 0: # End of columns and constraints for table definition. break elif braces_deep == 0 and token.match(sqlparse.tokens.Punctuation, ","): # End of current column or constraint definition. break # Detect column or constraint definition by first token. if is_constraint_definition is None: is_constraint_definition = token.match( sqlparse.tokens.Keyword, "CONSTRAINT" ) if is_constraint_definition: continue if is_constraint_definition: # Detect constraint name by second token. if constraint_name is None: if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): constraint_name = token.value elif token.ttype == sqlparse.tokens.Literal.String.Symbol: constraint_name = token.value[1:-1] # Start constraint columns parsing after UNIQUE keyword. if token.match(sqlparse.tokens.Keyword, "UNIQUE"): unique = True unique_braces_deep = braces_deep elif unique: if unique_braces_deep == braces_deep: if unique_columns: # Stop constraint parsing. unique = False continue if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): unique_columns.append(token.value) elif token.ttype == sqlparse.tokens.Literal.String.Symbol: unique_columns.append(token.value[1:-1]) else: # Detect field name by first token. if field_name is None: if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): field_name = token.value elif token.ttype == sqlparse.tokens.Literal.String.Symbol: field_name = token.value[1:-1] if token.match(sqlparse.tokens.Keyword, "UNIQUE"): unique_columns = [field_name] # Start constraint columns parsing after CHECK keyword. if token.match(sqlparse.tokens.Keyword, "CHECK"): check = True check_braces_deep = braces_deep elif check: if check_braces_deep == braces_deep: if check_columns: # Stop constraint parsing. check = False continue if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): if token.value in columns: check_columns.append(token.value) elif token.ttype == sqlparse.tokens.Literal.String.Symbol: if token.value[1:-1] in columns: check_columns.append(token.value[1:-1]) unique_constraint = ( { "unique": True, "columns": unique_columns, "primary_key": False, "foreign_key": None, "check": False, "index": False, } if unique_columns else None ) check_constraint = ( { "check": True, "columns": check_columns, "primary_key": False, "unique": False, "foreign_key": None, "index": False, } if check_columns else None ) return constraint_name, unique_constraint, check_constraint, token def _parse_table_constraints(self, sql, columns): # Check constraint parsing is based of SQLite syntax diagram. # https://www.sqlite.org/syntaxdiagrams.html#table-constraint statement = sqlparse.parse(sql)[0] constraints = {} unnamed_constrains_index = 0 tokens = (token for token in statement.flatten() if not token.is_whitespace) # Go to columns and constraint definition for token in tokens: if token.match(sqlparse.tokens.Punctuation, "("): break # Parse columns and constraint definition while True: ( constraint_name, unique, check, end_token, ) = self._parse_column_or_constraint_definition(tokens, columns) if unique: if constraint_name: constraints[constraint_name] = unique else: unnamed_constrains_index += 1 constraints[ "__unnamed_constraint_%s__" % unnamed_constrains_index ] = unique if check: if constraint_name: constraints[constraint_name] = check else: unnamed_constrains_index += 1 constraints[ "__unnamed_constraint_%s__" % unnamed_constrains_index ] = check if end_token.match(sqlparse.tokens.Punctuation, ")"): break return constraints def get_constraints(self, cursor, table_name): """ Retrieve any constraints or keys (unique, pk, fk, check, index) across one or more columns. """ constraints = {} # Find inline check constraints. try: table_schema = cursor.execute( "SELECT sql FROM sqlite_master WHERE type='table' and name=%s", [table_name], ).fetchone()[0] except TypeError: # table_name is a view. pass else: columns = { info.name for info in self.get_table_description(cursor, table_name) } constraints.update(self._parse_table_constraints(table_schema, columns)) # Get the index info cursor.execute( "PRAGMA index_list(%s)" % self.connection.ops.quote_name(table_name) ) for row in cursor.fetchall(): # Discard last 2 columns. number, index, unique = row[:3] cursor.execute( "SELECT sql FROM sqlite_master WHERE type='index' AND name=%s", [index], ) # There's at most one row. (sql,) = cursor.fetchone() or (None,) # Inline constraints are already detected in # _parse_table_constraints(). The reasons to avoid fetching inline # constraints from `PRAGMA index_list` are: # - Inline constraints can have a different name and information # than what `PRAGMA index_list` gives. # - Not all inline constraints may appear in `PRAGMA index_list`. if not sql: # An inline constraint continue # Get the index info for that index cursor.execute( "PRAGMA index_info(%s)" % self.connection.ops.quote_name(index) ) for index_rank, column_rank, column in cursor.fetchall(): if index not in constraints: constraints[index] = { "columns": [], "primary_key": False, "unique": bool(unique), "foreign_key": None, "check": False, "index": True, } constraints[index]["columns"].append(column) # Add type and column orders for indexes if constraints[index]["index"]: # SQLite doesn't support any index type other than b-tree constraints[index]["type"] = Index.suffix orders = self._get_index_columns_orders(sql) if orders is not None: constraints[index]["orders"] = orders # Get the PK pk_columns = self.get_primary_key_columns(cursor, table_name) if pk_columns: # SQLite doesn't actually give a name to the PK constraint, # so we invent one. This is fine, as the SQLite backend never # deletes PK constraints by name, as you can't delete constraints # in SQLite; we remake the table with a new PK instead. constraints["__primary__"] = { "columns": pk_columns, "primary_key": True, "unique": False, # It's not actually a unique constraint. "foreign_key": None, "check": False, "index": False, } relations = enumerate(self.get_relations(cursor, table_name).items()) constraints.update( { f"fk_{index}": { "columns": [column_name], "primary_key": False, "unique": False, "foreign_key": (ref_table_name, ref_column_name), "check": False, "index": False, } for index, ( column_name, (ref_column_name, ref_table_name, _), ) in relations } ) return constraints def _get_index_columns_orders(self, sql): tokens = sqlparse.parse(sql)[0] for token in tokens: if isinstance(token, sqlparse.sql.Parenthesis): columns = str(token).strip("()").split(", ") return ["DESC" if info.endswith("DESC") else "ASC" for info in columns] return None def _get_column_collations(self, cursor, table_name): row = cursor.execute( """ SELECT sql FROM sqlite_master WHERE type = 'table' AND name = %s """, [table_name], ).fetchone() if not row: return {} sql = row[0] columns = str(sqlparse.parse(sql)[0][-1]).strip("()").split(", ") collations = {} for column in columns: tokens = column[1:].split() column_name = tokens[0].strip('"') for index, token in enumerate(tokens): if token == "COLLATE": collation = tokens[index + 1] break else: collation = None collations[column_name] = collation return collations
from unittest import skipUnless from django.db import connection, connections from django.test import TestCase @skipUnless(connection.vendor == "mysql", "MySQL tests") class ParsingTests(TestCase): def test_parse_constraint_columns(self): _parse_constraint_columns = connection.introspection._parse_constraint_columns tests = ( ("`height` >= 0", ["height"], ["height"]), ("`cost` BETWEEN 1 AND 10", ["cost"], ["cost"]), ("`ref1` > `ref2`", ["id", "ref1", "ref2"], ["ref1", "ref2"]), ( "`start` IS NULL OR `end` IS NULL OR `start` < `end`", ["id", "start", "end"], ["start", "end"], ), ("JSON_VALID(`json_field`)", ["json_field"], ["json_field"]), ("CHAR_LENGTH(`name`) > 2", ["name"], ["name"]), ("lower(`ref1`) != 'test'", ["id", "owe", "ref1"], ["ref1"]), ("lower(`ref1`) != 'test'", ["id", "lower", "ref1"], ["ref1"]), ("`name` LIKE 'test%'", ["name"], ["name"]), ) for check_clause, table_columns, expected_columns in tests: with self.subTest(check_clause): check_columns = _parse_constraint_columns(check_clause, table_columns) self.assertEqual(list(check_columns), expected_columns) @skipUnless(connection.vendor == "mysql", "MySQL tests") class StorageEngineTests(TestCase): databases = {"default", "other"} def test_get_storage_engine(self): table_name = "test_storage_engine" create_sql = "CREATE TABLE %s (id INTEGER) ENGINE = %%s" % table_name drop_sql = "DROP TABLE %s" % table_name default_connection = connections["default"] other_connection = connections["other"] try: with default_connection.cursor() as cursor: cursor.execute(create_sql % "InnoDB") self.assertEqual( default_connection.introspection.get_storage_engine( cursor, table_name ), "InnoDB", ) with other_connection.cursor() as cursor: cursor.execute(create_sql % "MyISAM") self.assertEqual( other_connection.introspection.get_storage_engine( cursor, table_name ), "MyISAM", ) finally: with default_connection.cursor() as cursor: cursor.execute(drop_sql) with other_connection.cursor() as cursor: cursor.execute(drop_sql) @skipUnless(connection.vendor == "mysql", "MySQL specific SQL") class TestCrossDatabaseRelations(TestCase): databases = {"default", "other"} def test_omit_cross_database_relations(self): default_connection = connections["default"] other_connection = connections["other"] main_table = "cross_schema_get_relations_main_table" main_table_quoted = default_connection.ops.quote_name(main_table) other_schema_quoted = other_connection.ops.quote_name( other_connection.settings_dict["NAME"] ) rel_table = "cross_schema_get_relations_rel_table" rel_table_quoted = other_connection.ops.quote_name(rel_table) rel_column = "cross_schema_get_relations_rel_table_id" rel_column_quoted = other_connection.ops.quote_name(rel_column) try: with other_connection.cursor() as other_cursor: other_cursor.execute( f""" CREATE TABLE {rel_table_quoted} ( id integer AUTO_INCREMENT, PRIMARY KEY (id) ) """ ) with default_connection.cursor() as default_cursor: # Create table in the default schema with a cross-database # relation. default_cursor.execute( f""" CREATE TABLE {main_table_quoted} ( id integer AUTO_INCREMENT, {rel_column_quoted} integer NOT NULL, PRIMARY KEY (id), FOREIGN KEY ({rel_column_quoted}) REFERENCES {other_schema_quoted}.{rel_table_quoted}(id) ) """ ) relations = default_connection.introspection.get_relations( default_cursor, main_table ) constraints = default_connection.introspection.get_constraints( default_cursor, main_table ) self.assertEqual(len(relations), 0) rel_column_fk_constraints = [ spec for name, spec in constraints.items() if spec["columns"] == [rel_column] and spec["foreign_key"] is not None ] self.assertEqual(len(rel_column_fk_constraints), 0) finally: with default_connection.cursor() as default_cursor: default_cursor.execute(f"DROP TABLE IF EXISTS {main_table_quoted}") with other_connection.cursor() as other_cursor: other_cursor.execute(f"DROP TABLE IF EXISTS {rel_table_quoted}")
django
python
import multiprocessing import os import shutil import sqlite3 import sys from pathlib import Path from django.db import NotSupportedError from django.db.backends.base.creation import BaseDatabaseCreation class DatabaseCreation(BaseDatabaseCreation): @staticmethod def is_in_memory_db(database_name): return not isinstance(database_name, Path) and ( database_name == ":memory:" or "mode=memory" in database_name ) def _get_test_db_name(self): test_database_name = self.connection.settings_dict["TEST"]["NAME"] or ":memory:" if test_database_name == ":memory:": return "file:memorydb_%s?mode=memory&cache=shared" % self.connection.alias return test_database_name def _create_test_db(self, verbosity, autoclobber, keepdb=False): test_database_name = self._get_test_db_name() if keepdb: return test_database_name if not self.is_in_memory_db(test_database_name): # Erase the old test database if verbosity >= 1: self.log( "Destroying old test database for alias %s..." % (self._get_database_display_str(verbosity, test_database_name),) ) if os.access(test_database_name, os.F_OK): if not autoclobber: confirm = input( "Type 'yes' if you would like to try deleting the test " "database '%s', or 'no' to cancel: " % test_database_name ) if autoclobber or confirm == "yes": try: os.remove(test_database_name) except Exception as e: self.log("Got an error deleting the old test database: %s" % e) sys.exit(2) else: self.log("Tests cancelled.") sys.exit(1) return test_database_name def get_test_db_clone_settings(self, suffix): orig_settings_dict = self.connection.settings_dict source_database_name = orig_settings_dict["NAME"] or ":memory:" if not self.is_in_memory_db(source_database_name): root, ext = os.path.splitext(source_database_name) return {**orig_settings_dict, "NAME": f"{root}_{suffix}{ext}"} start_method = multiprocessing.get_start_method() if start_method == "fork": return orig_settings_dict if start_method in {"forkserver", "spawn"}: return { **orig_settings_dict, "NAME": f"{self.connection.alias}_{suffix}.sqlite3", } raise NotSupportedError( f"Cloning with start method {start_method!r} is not supported." ) def _clone_test_db(self, suffix, verbosity, keepdb=False): source_database_name = self.connection.settings_dict["NAME"] target_database_name = self.get_test_db_clone_settings(suffix)["NAME"] if not self.is_in_memory_db(source_database_name): # Erase the old test database if os.access(target_database_name, os.F_OK): if keepdb: return if verbosity >= 1: self.log( "Destroying old test database for alias %s..." % ( self._get_database_display_str( verbosity, target_database_name ), ) ) try: os.remove(target_database_name) except Exception as e: self.log("Got an error deleting the old test database: %s" % e) sys.exit(2) try: shutil.copy(source_database_name, target_database_name) except Exception as e: self.log("Got an error cloning the test database: %s" % e) sys.exit(2) # Forking automatically makes a copy of an in-memory database. # Forkserver and spawn require migrating to disk which will be # re-opened in setup_worker_connection. elif multiprocessing.get_start_method() in {"forkserver", "spawn"}: ondisk_db = sqlite3.connect(target_database_name, uri=True) self.connection.connection.backup(ondisk_db) ondisk_db.close() def _destroy_test_db(self, test_database_name, verbosity): if test_database_name and not self.is_in_memory_db(test_database_name): # Remove the SQLite database file os.remove(test_database_name) def test_db_signature(self): """ Return a tuple that uniquely identifies a test database. This takes into account the special cases of ":memory:" and "" for SQLite since the databases will be distinct despite having the same TEST NAME. See https://www.sqlite.org/inmemorydb.html """ test_database_name = self._get_test_db_name() sig = [self.connection.settings_dict["NAME"]] if self.is_in_memory_db(test_database_name): sig.append(self.connection.alias) else: sig.append(test_database_name) return tuple(sig) def setup_worker_connection(self, _worker_id): settings_dict = self.get_test_db_clone_settings(_worker_id) # connection.settings_dict must be updated in place for changes to be # reflected in django.db.connections. Otherwise new threads would # connect to the default database instead of the appropriate clone. start_method = multiprocessing.get_start_method() if start_method == "fork": # Update settings_dict in place. self.connection.settings_dict.update(settings_dict) self.connection.close() elif start_method in {"forkserver", "spawn"}: alias = self.connection.alias connection_str = ( f"file:memorydb_{alias}_{_worker_id}?mode=memory&cache=shared" ) source_db = self.connection.Database.connect( f"file:{alias}_{_worker_id}.sqlite3?mode=ro", uri=True ) target_db = sqlite3.connect(connection_str, uri=True) source_db.backup(target_db) source_db.close() # Update settings_dict in place. self.connection.settings_dict.update(settings_dict) self.connection.settings_dict["NAME"] = connection_str # Re-open connection to in-memory database before closing copy # connection. self.connection.connect() target_db.close()
import copy import datetime import os from unittest import mock from django.db import DEFAULT_DB_ALIAS, connection, connections from django.db.backends.base.creation import TEST_DATABASE_PREFIX, BaseDatabaseCreation from django.test import SimpleTestCase, TransactionTestCase from django.test.utils import override_settings from django.utils.deprecation import RemovedInDjango70Warning from ..models import ( CircularA, CircularB, Object, ObjectReference, ObjectSelfReference, SchoolBus, SchoolClass, ) def get_connection_copy(): # Get a copy of the default connection. (Can't use django.db.connection # because it'll modify the default connection itself.) test_connection = copy.copy(connections[DEFAULT_DB_ALIAS]) test_connection.settings_dict = copy.deepcopy( connections[DEFAULT_DB_ALIAS].settings_dict ) return test_connection class TestDbSignatureTests(SimpleTestCase): def test_default_name(self): # A test db name isn't set. prod_name = "hodor" test_connection = get_connection_copy() test_connection.settings_dict["NAME"] = prod_name test_connection.settings_dict["TEST"] = {"NAME": None} signature = BaseDatabaseCreation(test_connection).test_db_signature() self.assertEqual(signature[3], TEST_DATABASE_PREFIX + prod_name) def test_custom_test_name(self): # A regular test db name is set. test_name = "hodor" test_connection = get_connection_copy() test_connection.settings_dict["TEST"] = {"NAME": test_name} signature = BaseDatabaseCreation(test_connection).test_db_signature() self.assertEqual(signature[3], test_name) def test_custom_test_name_with_test_prefix(self): # A test db name prefixed with TEST_DATABASE_PREFIX is set. test_name = TEST_DATABASE_PREFIX + "hodor" test_connection = get_connection_copy() test_connection.settings_dict["TEST"] = {"NAME": test_name} signature = BaseDatabaseCreation(test_connection).test_db_signature() self.assertEqual(signature[3], test_name) @override_settings(INSTALLED_APPS=["backends.base.app_unmigrated"]) @mock.patch.object(connection, "ensure_connection") @mock.patch.object(connection, "prepare_database") @mock.patch( "django.db.migrations.recorder.MigrationRecorder.has_table", return_value=False ) @mock.patch("django.core.management.commands.migrate.Command.sync_apps") class TestDbCreationTests(SimpleTestCase): available_apps = ["backends.base.app_unmigrated"] @mock.patch("django.db.migrations.executor.MigrationExecutor.migrate") def test_migrate_test_setting_false( self, mocked_migrate, mocked_sync_apps, *mocked_objects ): test_connection = get_connection_copy() test_connection.settings_dict["TEST"]["MIGRATE"] = False creation = test_connection.creation_class(test_connection) if connection.vendor == "oracle": # Don't close connection on Oracle. creation.connection.close = mock.Mock() old_database_name = test_connection.settings_dict["NAME"] try: with mock.patch.object(creation, "_create_test_db"): creation.create_test_db(verbosity=0, autoclobber=True) # Migrations don't run. mocked_migrate.assert_called() args, kwargs = mocked_migrate.call_args self.assertEqual(args, ([],)) self.assertEqual(kwargs["plan"], []) # App is synced. mocked_sync_apps.assert_called() mocked_args, _ = mocked_sync_apps.call_args self.assertEqual(mocked_args[1], {"app_unmigrated"}) finally: with mock.patch.object(creation, "_destroy_test_db"): creation.destroy_test_db(old_database_name, verbosity=0) @mock.patch("django.db.migrations.executor.MigrationRecorder.ensure_schema") def test_migrate_test_setting_false_ensure_schema( self, mocked_ensure_schema, mocked_sync_apps, *mocked_objects, ): test_connection = get_connection_copy() test_connection.settings_dict["TEST"]["MIGRATE"] = False creation = test_connection.creation_class(test_connection) if connection.vendor == "oracle": # Don't close connection on Oracle. creation.connection.close = mock.Mock() old_database_name = test_connection.settings_dict["NAME"] try: with mock.patch.object(creation, "_create_test_db"): creation.create_test_db(verbosity=0, autoclobber=True) # The django_migrations table is not created. mocked_ensure_schema.assert_not_called() # App is synced. mocked_sync_apps.assert_called() mocked_args, _ = mocked_sync_apps.call_args self.assertEqual(mocked_args[1], {"app_unmigrated"}) finally: with mock.patch.object(creation, "_destroy_test_db"): creation.destroy_test_db(old_database_name, verbosity=0) @mock.patch("django.db.migrations.executor.MigrationExecutor.migrate") def test_migrate_test_setting_true( self, mocked_migrate, mocked_sync_apps, *mocked_objects ): test_connection = get_connection_copy() test_connection.settings_dict["TEST"]["MIGRATE"] = True creation = test_connection.creation_class(test_connection) if connection.vendor == "oracle": # Don't close connection on Oracle. creation.connection.close = mock.Mock() old_database_name = test_connection.settings_dict["NAME"] try: with mock.patch.object(creation, "_create_test_db"): creation.create_test_db(verbosity=0, autoclobber=True) # Migrations run. mocked_migrate.assert_called() args, kwargs = mocked_migrate.call_args self.assertEqual(args, ([("app_unmigrated", "0001_initial")],)) self.assertEqual(len(kwargs["plan"]), 1) # App is not synced. mocked_sync_apps.assert_not_called() finally: with mock.patch.object(creation, "_destroy_test_db"): creation.destroy_test_db(old_database_name, verbosity=0) @mock.patch.dict(os.environ, {"RUNNING_DJANGOS_TEST_SUITE": ""}) @mock.patch("django.db.migrations.executor.MigrationExecutor.migrate") @mock.patch.object(BaseDatabaseCreation, "mark_expected_failures_and_skips") def test_mark_expected_failures_and_skips_call( self, mark_expected_failures_and_skips, *mocked_objects ): """ mark_expected_failures_and_skips() isn't called unless RUNNING_DJANGOS_TEST_SUITE is 'true'. """ test_connection = get_connection_copy() creation = test_connection.creation_class(test_connection) if connection.vendor == "oracle": # Don't close connection on Oracle. creation.connection.close = mock.Mock() old_database_name = test_connection.settings_dict["NAME"] try: with mock.patch.object(creation, "_create_test_db"): creation.create_test_db(verbosity=0, autoclobber=True) self.assertIs(mark_expected_failures_and_skips.called, False) finally: with mock.patch.object(creation, "_destroy_test_db"): creation.destroy_test_db(old_database_name, verbosity=0) @mock.patch("django.db.migrations.executor.MigrationExecutor.migrate") @mock.patch.object(BaseDatabaseCreation, "serialize_db_to_string") def test_serialize_deprecation(self, serialize_db_to_string, *mocked_objects): test_connection = get_connection_copy() creation = test_connection.creation_class(test_connection) if connection.vendor == "oracle": # Don't close connection on Oracle. creation.connection.close = mock.Mock() old_database_name = test_connection.settings_dict["NAME"] msg = ( "DatabaseCreation.create_test_db(serialize) is deprecated. Call " "DatabaseCreation.serialize_test_db() once all test databases are set up " "instead if you need fixtures persistence between tests." ) try: with ( self.assertWarnsMessage(RemovedInDjango70Warning, msg) as ctx, mock.patch.object(creation, "_create_test_db"), ): creation.create_test_db(verbosity=0, serialize=True) self.assertEqual(ctx.filename, __file__) serialize_db_to_string.assert_called_once_with() finally: with mock.patch.object(creation, "_destroy_test_db"): creation.destroy_test_db(old_database_name, verbosity=0) # Now with `serialize` False. serialize_db_to_string.reset_mock() try: with ( self.assertWarnsMessage(RemovedInDjango70Warning, msg) as ctx, mock.patch.object(creation, "_create_test_db"), ): creation.create_test_db(verbosity=0, serialize=False) self.assertEqual(ctx.filename, __file__) serialize_db_to_string.assert_not_called() finally: with mock.patch.object(creation, "_destroy_test_db"): creation.destroy_test_db(old_database_name, verbosity=0) class TestDeserializeDbFromString(TransactionTestCase): available_apps = ["backends"] def test_circular_reference(self): # deserialize_db_from_string() handles circular references. data = """ [ { "model": "backends.object", "pk": 1, "fields": {"obj_ref": 1, "related_objects": []} }, { "model": "backends.objectreference", "pk": 1, "fields": {"obj": 1} } ] """ connection.creation.deserialize_db_from_string(data) obj = Object.objects.get() obj_ref = ObjectReference.objects.get() self.assertEqual(obj.obj_ref, obj_ref) self.assertEqual(obj_ref.obj, obj) def test_self_reference(self): # serialize_db_to_string() and deserialize_db_from_string() handles # self references. obj_1 = ObjectSelfReference.objects.create(key="X") obj_2 = ObjectSelfReference.objects.create(key="Y", obj=obj_1) obj_1.obj = obj_2 obj_1.save() # Serialize objects. with mock.patch("django.db.migrations.loader.MigrationLoader") as loader: # serialize_db_to_string() serializes only migrated apps, so mark # the backends app as migrated. loader_instance = loader.return_value loader_instance.migrated_apps = {"backends"} data = connection.creation.serialize_db_to_string() ObjectSelfReference.objects.all().delete() # Deserialize objects. connection.creation.deserialize_db_from_string(data) obj_1 = ObjectSelfReference.objects.get(key="X") obj_2 = ObjectSelfReference.objects.get(key="Y") self.assertEqual(obj_1.obj, obj_2) self.assertEqual(obj_2.obj, obj_1) def test_circular_reference_with_natural_key(self): # serialize_db_to_string() and deserialize_db_from_string() handles # circular references for models with natural keys. obj_a = CircularA.objects.create(key="A") obj_b = CircularB.objects.create(key="B", obj=obj_a) obj_a.obj = obj_b obj_a.save() # Serialize objects. with mock.patch("django.db.migrations.loader.MigrationLoader") as loader: # serialize_db_to_string() serializes only migrated apps, so mark # the backends app as migrated. loader_instance = loader.return_value loader_instance.migrated_apps = {"backends"} data = connection.creation.serialize_db_to_string() CircularA.objects.all().delete() CircularB.objects.all().delete() # Deserialize objects. connection.creation.deserialize_db_from_string(data) obj_a = CircularA.objects.get() obj_b = CircularB.objects.get() self.assertEqual(obj_a.obj, obj_b) self.assertEqual(obj_b.obj, obj_a) def test_serialize_db_to_string_base_manager(self): SchoolClass.objects.create(year=1000, last_updated=datetime.datetime.now()) with mock.patch("django.db.migrations.loader.MigrationLoader") as loader: # serialize_db_to_string() serializes only migrated apps, so mark # the backends app as migrated. loader_instance = loader.return_value loader_instance.migrated_apps = {"backends"} data = connection.creation.serialize_db_to_string() self.assertIn('"model": "backends.schoolclass"', data) self.assertIn('"year": 1000', data) def test_serialize_db_to_string_base_manager_with_prefetch_related(self): sclass = SchoolClass.objects.create( year=2000, last_updated=datetime.datetime.now() ) bus = SchoolBus.objects.create(number=1) bus.schoolclasses.add(sclass) with mock.patch("django.db.migrations.loader.MigrationLoader") as loader: # serialize_db_to_string() serializes only migrated apps, so mark # the backends app as migrated. loader_instance = loader.return_value loader_instance.migrated_apps = {"backends"} data = connection.creation.serialize_db_to_string() self.assertIn('"model": "backends.schoolbus"', data) self.assertIn('"model": "backends.schoolclass"', data) self.assertIn(f'"schoolclasses": [{sclass.pk}]', data) class SkipTestClass: def skip_function(self): pass def skip_test_function(): pass def expected_failure_test_function(): pass class TestMarkTests(SimpleTestCase): def test_mark_expected_failures_and_skips(self): test_connection = get_connection_copy() creation = BaseDatabaseCreation(test_connection) creation.connection.features.django_test_expected_failures = { "backends.base.test_creation.expected_failure_test_function", } creation.connection.features.django_test_skips = { "skip test class": { "backends.base.test_creation.SkipTestClass", }, "skip test function": { "backends.base.test_creation.skip_test_function", }, } creation.mark_expected_failures_and_skips() self.assertIs( expected_failure_test_function.__unittest_expecting_failure__, True, ) self.assertIs(SkipTestClass.__unittest_skip__, True) self.assertEqual( SkipTestClass.__unittest_skip_why__, "skip test class", ) self.assertIs(skip_test_function.__unittest_skip__, True) self.assertEqual( skip_test_function.__unittest_skip_why__, "skip test function", )
django
python
from django.apps import apps from django.contrib.sites.models import Site from django.core.cache import cache from django.test import TestCase, modify_settings, override_settings from .models import I18nTestModel, TestModel @modify_settings(INSTALLED_APPS={"append": "django.contrib.sitemaps"}) @override_settings(ROOT_URLCONF="sitemaps_tests.urls.http") class SitemapTestsBase(TestCase): protocol = "http" sites_installed = apps.is_installed("django.contrib.sites") domain = "example.com" if sites_installed else "testserver" @classmethod def setUpTestData(cls): # Create an object for sitemap content. TestModel.objects.create(name="Test Object") cls.i18n_model = I18nTestModel.objects.create(name="Test Object") def setUp(self): self.base_url = "%s://%s" % (self.protocol, self.domain) cache.clear() @classmethod def setUpClass(cls): super().setUpClass() # This cleanup is necessary because contrib.sites cache # makes tests interfere with each other, see #11505 Site.objects.clear_cache()
import gc from unittest.mock import MagicMock, patch from django.db import DEFAULT_DB_ALIAS, connection, connections, transaction from django.db.backends.base.base import BaseDatabaseWrapper from django.test import ( SimpleTestCase, TestCase, TransactionTestCase, skipUnlessDBFeature, ) from django.test.runner import DebugSQLTextTestResult from django.test.utils import CaptureQueriesContext, override_settings from ..models import Person, Square class DatabaseWrapperTests(SimpleTestCase): def test_repr(self): conn = connections[DEFAULT_DB_ALIAS] self.assertEqual( repr(conn), f"<DatabaseWrapper vendor={connection.vendor!r} alias='default'>", ) def test_initialization_class_attributes(self): """ The "initialization" class attributes like client_class and creation_class should be set on the class and reflected in the corresponding instance attributes of the instantiated backend. """ conn = connections[DEFAULT_DB_ALIAS] conn_class = type(conn) attr_names = [ ("client_class", "client"), ("creation_class", "creation"), ("features_class", "features"), ("introspection_class", "introspection"), ("ops_class", "ops"), ("validation_class", "validation"), ] for class_attr_name, instance_attr_name in attr_names: class_attr_value = getattr(conn_class, class_attr_name) self.assertIsNotNone(class_attr_value) instance_attr_value = getattr(conn, instance_attr_name) self.assertIsInstance(instance_attr_value, class_attr_value) def test_initialization_display_name(self): self.assertEqual(BaseDatabaseWrapper.display_name, "unknown") self.assertNotEqual(connection.display_name, "unknown") def test_get_database_version(self): with patch.object(BaseDatabaseWrapper, "__init__", return_value=None): msg = ( "subclasses of BaseDatabaseWrapper may require a " "get_database_version() method." ) with self.assertRaisesMessage(NotImplementedError, msg): BaseDatabaseWrapper().get_database_version() def test_check_database_version_supported_with_none_as_database_version(self): with patch.object(connection.features, "minimum_database_version", None): connection.check_database_version_supported() def test_release_memory_without_garbage_collection(self): # Schedule the restore of the garbage collection settings. self.addCleanup(gc.set_debug, 0) self.addCleanup(gc.enable) # Disable automatic garbage collection to control when it's triggered, # then run a full collection cycle to ensure `gc.garbage` is empty. gc.disable() gc.collect() # The garbage list isn't automatically populated to avoid CPU overhead, # so debugging needs to be enabled to track all unreachable items and # have them stored in `gc.garbage`. gc.set_debug(gc.DEBUG_SAVEALL) # Create a new connection that will be closed during the test, and also # ensure that a `DatabaseErrorWrapper` is created for this connection. test_connection = connection.copy() with test_connection.wrap_database_errors: self.assertEqual(test_connection.queries, []) # Close the connection and remove references to it. This will mark all # objects related to the connection as garbage to be collected. test_connection.close() test_connection = None # Enforce garbage collection to populate `gc.garbage` for inspection. gc.collect() self.assertEqual(gc.garbage, []) class DatabaseWrapperLoggingTests(TransactionTestCase): available_apps = ["backends"] @override_settings(DEBUG=True) def test_commit_debug_log(self): conn = connections[DEFAULT_DB_ALIAS] with CaptureQueriesContext(conn): with self.assertLogs("django.db.backends", "DEBUG") as cm: with transaction.atomic(): Person.objects.create(first_name="first", last_name="last") self.assertGreaterEqual(len(conn.queries_log), 3) self.assertEqual(conn.queries_log[-3]["sql"], "BEGIN") self.assertRegex( cm.output[0], r"DEBUG:django.db.backends:\(\d+.\d{3}\) " rf"BEGIN; args=None; alias={DEFAULT_DB_ALIAS}", ) self.assertEqual(conn.queries_log[-1]["sql"], "COMMIT") self.assertRegex( cm.output[-1], r"DEBUG:django.db.backends:\(\d+.\d{3}\) " rf"COMMIT; args=None; alias={DEFAULT_DB_ALIAS}", ) @override_settings(DEBUG=True) def test_rollback_debug_log(self): conn = connections[DEFAULT_DB_ALIAS] with CaptureQueriesContext(conn): with self.assertLogs("django.db.backends", "DEBUG") as cm: with self.assertRaises(Exception), transaction.atomic(): Person.objects.create(first_name="first", last_name="last") raise Exception("Force rollback") self.assertEqual(conn.queries_log[-1]["sql"], "ROLLBACK") self.assertRegex( cm.output[-1], r"DEBUG:django.db.backends:\(\d+.\d{3}\) " rf"ROLLBACK; args=None; alias={DEFAULT_DB_ALIAS}", ) def test_no_logs_without_debug(self): if isinstance(self._outcome.result, DebugSQLTextTestResult): self.skipTest("--debug-sql interferes with this test") with self.assertNoLogs("django.db.backends", "DEBUG"): with self.assertRaises(Exception), transaction.atomic(): Person.objects.create(first_name="first", last_name="last") raise Exception("Force rollback") conn = connections[DEFAULT_DB_ALIAS] self.assertEqual(len(conn.queries_log), 0) class ExecuteWrapperTests(TestCase): @staticmethod def call_execute(connection, params=None): ret_val = "1" if params is None else "%s" sql = "SELECT " + ret_val + connection.features.bare_select_suffix with connection.cursor() as cursor: cursor.execute(sql, params) def call_executemany(self, connection, params=None): # executemany() must use an update query. Make sure it does nothing # by putting a false condition in the WHERE clause. sql = "DELETE FROM {} WHERE 0=1 AND 0=%s".format(Square._meta.db_table) if params is None: params = [(i,) for i in range(3)] with connection.cursor() as cursor: cursor.executemany(sql, params) @staticmethod def mock_wrapper(): return MagicMock(side_effect=lambda execute, *args: execute(*args)) def test_wrapper_invoked(self): wrapper = self.mock_wrapper() with connection.execute_wrapper(wrapper): self.call_execute(connection) self.assertTrue(wrapper.called) (_, sql, params, many, context), _ = wrapper.call_args self.assertIn("SELECT", sql) self.assertIsNone(params) self.assertIs(many, False) self.assertEqual(context["connection"], connection) def test_wrapper_invoked_many(self): wrapper = self.mock_wrapper() with connection.execute_wrapper(wrapper): self.call_executemany(connection) self.assertTrue(wrapper.called) (_, sql, param_list, many, context), _ = wrapper.call_args self.assertIn("DELETE", sql) self.assertIsInstance(param_list, (list, tuple)) self.assertIs(many, True) self.assertEqual(context["connection"], connection) def test_database_queried(self): wrapper = self.mock_wrapper() with connection.execute_wrapper(wrapper): with connection.cursor() as cursor: sql = "SELECT 17" + connection.features.bare_select_suffix cursor.execute(sql) seventeen = cursor.fetchall() self.assertEqual(list(seventeen), [(17,)]) self.call_executemany(connection) def test_nested_wrapper_invoked(self): outer_wrapper = self.mock_wrapper() inner_wrapper = self.mock_wrapper() with ( connection.execute_wrapper(outer_wrapper), connection.execute_wrapper(inner_wrapper), ): self.call_execute(connection) self.assertEqual(inner_wrapper.call_count, 1) self.call_executemany(connection) self.assertEqual(inner_wrapper.call_count, 2) def test_outer_wrapper_blocks(self): def blocker(*args): pass wrapper = self.mock_wrapper() c = connection # This alias shortens the next line. with ( c.execute_wrapper(wrapper), c.execute_wrapper(blocker), c.execute_wrapper(wrapper), ): with c.cursor() as cursor: cursor.execute("The database never sees this") self.assertEqual(wrapper.call_count, 1) cursor.executemany("The database never sees this %s", [("either",)]) self.assertEqual(wrapper.call_count, 2) def test_wrapper_gets_sql(self): wrapper = self.mock_wrapper() sql = "SELECT 'aloha'" + connection.features.bare_select_suffix with connection.execute_wrapper(wrapper), connection.cursor() as cursor: cursor.execute(sql) (_, reported_sql, _, _, _), _ = wrapper.call_args self.assertEqual(reported_sql, sql) def test_wrapper_connection_specific(self): wrapper = self.mock_wrapper() with connections["other"].execute_wrapper(wrapper): self.assertEqual(connections["other"].execute_wrappers, [wrapper]) self.call_execute(connection) self.assertFalse(wrapper.called) self.assertEqual(connection.execute_wrappers, []) self.assertEqual(connections["other"].execute_wrappers, []) def test_wrapper_debug(self): def wrap_with_comment(execute, sql, params, many, context): return execute(f"/* My comment */ {sql}", params, many, context) with CaptureQueriesContext(connection) as ctx: with connection.execute_wrapper(wrap_with_comment): list(Person.objects.all()) last_query = ctx.captured_queries[-1]["sql"] self.assertTrue(last_query.startswith("/* My comment */")) class ConnectionHealthChecksTests(SimpleTestCase): databases = {"default"} def setUp(self): # All test cases here need newly configured and created connections. # Use the default db connection for convenience. connection.close() self.addCleanup(connection.close) def patch_settings_dict(self, conn_health_checks): self.settings_dict_patcher = patch.dict( connection.settings_dict, { **connection.settings_dict, "CONN_MAX_AGE": None, "CONN_HEALTH_CHECKS": conn_health_checks, }, ) self.settings_dict_patcher.start() self.addCleanup(self.settings_dict_patcher.stop) def run_query(self): with connection.cursor() as cursor: cursor.execute("SELECT 42" + connection.features.bare_select_suffix) @skipUnlessDBFeature("test_db_allows_multiple_connections") def test_health_checks_enabled(self): self.patch_settings_dict(conn_health_checks=True) self.assertIsNone(connection.connection) # Newly created connections are considered healthy without performing # the health check. with patch.object(connection, "is_usable", side_effect=AssertionError): self.run_query() old_connection = connection.connection # Simulate request_finished. connection.close_if_unusable_or_obsolete() self.assertIs(old_connection, connection.connection) # Simulate connection health check failing. with patch.object( connection, "is_usable", return_value=False ) as mocked_is_usable: self.run_query() new_connection = connection.connection # A new connection is established. self.assertIsNot(new_connection, old_connection) # Only one health check per "request" is performed, so the next # query will carry on even if the health check fails. Next query # succeeds because the real connection is healthy and only the # health check failure is mocked. self.run_query() self.assertIs(new_connection, connection.connection) self.assertEqual(mocked_is_usable.call_count, 1) # Simulate request_finished. connection.close_if_unusable_or_obsolete() # The underlying connection is being reused further with health checks # succeeding. self.run_query() self.run_query() self.assertIs(new_connection, connection.connection) @skipUnlessDBFeature("test_db_allows_multiple_connections") def test_health_checks_enabled_errors_occurred(self): self.patch_settings_dict(conn_health_checks=True) self.assertIsNone(connection.connection) # Newly created connections are considered healthy without performing # the health check. with patch.object(connection, "is_usable", side_effect=AssertionError): self.run_query() old_connection = connection.connection # Simulate errors_occurred. connection.errors_occurred = True # Simulate request_started (the connection is healthy). connection.close_if_unusable_or_obsolete() # Persistent connections are enabled. self.assertIs(old_connection, connection.connection) # No additional health checks after the one in # close_if_unusable_or_obsolete() are executed during this "request" # when running queries. with patch.object(connection, "is_usable", side_effect=AssertionError): self.run_query() @skipUnlessDBFeature("test_db_allows_multiple_connections") def test_health_checks_disabled(self): self.patch_settings_dict(conn_health_checks=False) self.assertIsNone(connection.connection) # Newly created connections are considered healthy without performing # the health check. with patch.object(connection, "is_usable", side_effect=AssertionError): self.run_query() old_connection = connection.connection # Simulate request_finished. connection.close_if_unusable_or_obsolete() # Persistent connections are enabled (connection is not). self.assertIs(old_connection, connection.connection) # Health checks are not performed. with patch.object(connection, "is_usable", side_effect=AssertionError): self.run_query() # Health check wasn't performed and the connection is unchanged. self.assertIs(old_connection, connection.connection) self.run_query() # The connection is unchanged after the next query either during # the current "request". self.assertIs(old_connection, connection.connection) @skipUnlessDBFeature("test_db_allows_multiple_connections") def test_set_autocommit_health_checks_enabled(self): self.patch_settings_dict(conn_health_checks=True) self.assertIsNone(connection.connection) # Newly created connections are considered healthy without performing # the health check. with patch.object(connection, "is_usable", side_effect=AssertionError): # Simulate outermost atomic block: changing autocommit for # a connection. connection.set_autocommit(False) self.run_query() connection.commit() connection.set_autocommit(True) old_connection = connection.connection # Simulate request_finished. connection.close_if_unusable_or_obsolete() # Persistent connections are enabled. self.assertIs(old_connection, connection.connection) # Simulate connection health check failing. with patch.object( connection, "is_usable", return_value=False ) as mocked_is_usable: # Simulate outermost atomic block: changing autocommit for # a connection. connection.set_autocommit(False) new_connection = connection.connection self.assertIsNot(new_connection, old_connection) # Only one health check per "request" is performed, so a query will # carry on even if the health check fails. This query succeeds # because the real connection is healthy and only the health check # failure is mocked. self.run_query() connection.commit() connection.set_autocommit(True) # The connection is unchanged. self.assertIs(new_connection, connection.connection) self.assertEqual(mocked_is_usable.call_count, 1) # Simulate request_finished. connection.close_if_unusable_or_obsolete() # The underlying connection is being reused further with health checks # succeeding. connection.set_autocommit(False) self.run_query() connection.commit() connection.set_autocommit(True) self.assertIs(new_connection, connection.connection) class MultiDatabaseTests(TestCase): databases = {"default", "other"} def test_multi_database_init_connection_state_called_once(self): for db in self.databases: with self.subTest(database=db): with patch.object(connections[db], "commit", return_value=None): with patch.object( connections[db], "check_database_version_supported", ) as mocked_check_database_version_supported: connections[db].init_connection_state() after_first_calls = len( mocked_check_database_version_supported.mock_calls ) connections[db].init_connection_state() self.assertEqual( len(mocked_check_database_version_supported.mock_calls), after_first_calls, )
django
python
import sys sys.exit(1)
from unittest import mock from django.db import connection from django.db.backends.base.client import BaseDatabaseClient from django.test import SimpleTestCase class SimpleDatabaseClientTests(SimpleTestCase): def setUp(self): self.client = BaseDatabaseClient(connection=connection) def test_settings_to_cmd_args_env(self): msg = ( "subclasses of BaseDatabaseClient must provide a " "settings_to_cmd_args_env() method or override a runshell()." ) with self.assertRaisesMessage(NotImplementedError, msg): self.client.settings_to_cmd_args_env(None, None) def test_runshell_use_environ(self): for env in [None, {}]: with self.subTest(env=env): with mock.patch("subprocess.run") as run: with mock.patch.object( BaseDatabaseClient, "settings_to_cmd_args_env", return_value=([], env), ): self.client.runshell(None) run.assert_called_once_with([], env=None, check=True)
django
python
from django.db.migrations.operations.base import Operation class TestOperation(Operation): def __init__(self): pass def deconstruct(self): return (self.__class__.__name__, [], {}) @property def reversible(self): return True def state_forwards(self, app_label, state): pass def database_forwards(self, app_label, schema_editor, from_state, to_state): pass def state_backwards(self, app_label, state): pass def database_backwards(self, app_label, schema_editor, from_state, to_state): pass class CreateModel(TestOperation): pass class ArgsOperation(TestOperation): def __init__(self, arg1, arg2): self.arg1, self.arg2 = arg1, arg2 def deconstruct(self): return (self.__class__.__name__, [self.arg1, self.arg2], {}) class KwargsOperation(TestOperation): def __init__(self, kwarg1=None, kwarg2=None): self.kwarg1, self.kwarg2 = kwarg1, kwarg2 def deconstruct(self): kwargs = {} if self.kwarg1 is not None: kwargs["kwarg1"] = self.kwarg1 if self.kwarg2 is not None: kwargs["kwarg2"] = self.kwarg2 return (self.__class__.__name__, [], kwargs) class ArgsKwargsOperation(TestOperation): def __init__(self, arg1, arg2, kwarg1=None, kwarg2=None): self.arg1, self.arg2 = arg1, arg2 self.kwarg1, self.kwarg2 = kwarg1, kwarg2 def deconstruct(self): kwargs = {} if self.kwarg1 is not None: kwargs["kwarg1"] = self.kwarg1 if self.kwarg2 is not None: kwargs["kwarg2"] = self.kwarg2 return ( self.__class__.__name__, [self.arg1, self.arg2], kwargs, ) class ArgsAndKeywordOnlyArgsOperation(ArgsKwargsOperation): def __init__(self, arg1, arg2, *, kwarg1, kwarg2): super().__init__(arg1, arg2, kwarg1=kwarg1, kwarg2=kwarg2) class ExpandArgsOperation(TestOperation): serialization_expand_args = ["arg"] def __init__(self, arg): self.arg = arg def deconstruct(self): return (self.__class__.__name__, [self.arg], {})
import sqlite3 import unittest from django.core.management.color import no_style from django.db import connection, models from django.test import TestCase from ..models import Person, Tag @unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests.") class SQLiteOperationsTests(TestCase): def test_sql_flush(self): self.assertEqual( connection.ops.sql_flush( no_style(), [Person._meta.db_table, Tag._meta.db_table], ), [ 'DELETE FROM "backends_person";', 'DELETE FROM "backends_tag";', ], ) def test_sql_flush_allow_cascade(self): statements = connection.ops.sql_flush( no_style(), [Person._meta.db_table, Tag._meta.db_table], allow_cascade=True, ) self.assertEqual( # The tables are processed in an unordered set. sorted(statements), [ 'DELETE FROM "backends_person";', 'DELETE FROM "backends_tag";', 'DELETE FROM "backends_verylongmodelnamezzzzzzzzzzzzzzzzzzzzzz' "zzzzzzzzzzzzzzzzzzzz_m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzz" 'zzzzzzzzzzzzzzzzzzzzzzz";', ], ) def test_sql_flush_sequences(self): self.assertEqual( connection.ops.sql_flush( no_style(), [Person._meta.db_table, Tag._meta.db_table], reset_sequences=True, ), [ 'DELETE FROM "backends_person";', 'DELETE FROM "backends_tag";', 'UPDATE "sqlite_sequence" SET "seq" = 0 WHERE "name" IN ' "('backends_person', 'backends_tag');", ], ) def test_sql_flush_sequences_allow_cascade(self): statements = connection.ops.sql_flush( no_style(), [Person._meta.db_table, Tag._meta.db_table], reset_sequences=True, allow_cascade=True, ) self.assertEqual( # The tables are processed in an unordered set. sorted(statements[:-1]), [ 'DELETE FROM "backends_person";', 'DELETE FROM "backends_tag";', 'DELETE FROM "backends_verylongmodelnamezzzzzzzzzzzzzzzzzzzzzz' "zzzzzzzzzzzzzzzzzzzz_m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzz" 'zzzzzzzzzzzzzzzzzzzzzzz";', ], ) self.assertIs( statements[-1].startswith( 'UPDATE "sqlite_sequence" SET "seq" = 0 WHERE "name" IN (' ), True, ) self.assertIn("'backends_person'", statements[-1]) self.assertIn("'backends_tag'", statements[-1]) self.assertIn( "'backends_verylongmodelnamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" "zzzz_m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" "zzz'", statements[-1], ) def test_bulk_batch_size(self): self.assertEqual(connection.ops.bulk_batch_size([], [Person()]), 1) first_name_field = Person._meta.get_field("first_name") last_name_field = Person._meta.get_field("last_name") self.assertEqual( connection.ops.bulk_batch_size([first_name_field], [Person()]), connection.features.max_query_params, ) self.assertEqual( connection.ops.bulk_batch_size( [first_name_field, last_name_field], [Person()] ), connection.features.max_query_params // 2, ) composite_pk = models.CompositePrimaryKey("first_name", "last_name") composite_pk.fields = [first_name_field, last_name_field] self.assertEqual( connection.ops.bulk_batch_size( [composite_pk, first_name_field], [Person()] ), connection.features.max_query_params // 3, ) def test_bulk_batch_size_respects_variable_limit(self): first_name_field = Person._meta.get_field("first_name") last_name_field = Person._meta.get_field("last_name") limit_name = sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER current_limit = connection.features.max_query_params self.assertEqual( connection.ops.bulk_batch_size( [first_name_field, last_name_field], [Person()] ), current_limit // 2, ) new_limit = min(42, current_limit) try: connection.connection.setlimit(limit_name, new_limit) self.assertEqual( connection.ops.bulk_batch_size( [first_name_field, last_name_field], [Person()] ), new_limit // 2, ) finally: connection.connection.setlimit(limit_name, current_limit) self.assertEqual( connection.ops.bulk_batch_size( [first_name_field, last_name_field], [Person()] ), current_limit // 2, )
django
python
import multiprocessing import os import shutil import sqlite3 import sys from pathlib import Path from django.db import NotSupportedError from django.db.backends.base.creation import BaseDatabaseCreation class DatabaseCreation(BaseDatabaseCreation): @staticmethod def is_in_memory_db(database_name): return not isinstance(database_name, Path) and ( database_name == ":memory:" or "mode=memory" in database_name ) def _get_test_db_name(self): test_database_name = self.connection.settings_dict["TEST"]["NAME"] or ":memory:" if test_database_name == ":memory:": return "file:memorydb_%s?mode=memory&cache=shared" % self.connection.alias return test_database_name def _create_test_db(self, verbosity, autoclobber, keepdb=False): test_database_name = self._get_test_db_name() if keepdb: return test_database_name if not self.is_in_memory_db(test_database_name): # Erase the old test database if verbosity >= 1: self.log( "Destroying old test database for alias %s..." % (self._get_database_display_str(verbosity, test_database_name),) ) if os.access(test_database_name, os.F_OK): if not autoclobber: confirm = input( "Type 'yes' if you would like to try deleting the test " "database '%s', or 'no' to cancel: " % test_database_name ) if autoclobber or confirm == "yes": try: os.remove(test_database_name) except Exception as e: self.log("Got an error deleting the old test database: %s" % e) sys.exit(2) else: self.log("Tests cancelled.") sys.exit(1) return test_database_name def get_test_db_clone_settings(self, suffix): orig_settings_dict = self.connection.settings_dict source_database_name = orig_settings_dict["NAME"] or ":memory:" if not self.is_in_memory_db(source_database_name): root, ext = os.path.splitext(source_database_name) return {**orig_settings_dict, "NAME": f"{root}_{suffix}{ext}"} start_method = multiprocessing.get_start_method() if start_method == "fork": return orig_settings_dict if start_method in {"forkserver", "spawn"}: return { **orig_settings_dict, "NAME": f"{self.connection.alias}_{suffix}.sqlite3", } raise NotSupportedError( f"Cloning with start method {start_method!r} is not supported." ) def _clone_test_db(self, suffix, verbosity, keepdb=False): source_database_name = self.connection.settings_dict["NAME"] target_database_name = self.get_test_db_clone_settings(suffix)["NAME"] if not self.is_in_memory_db(source_database_name): # Erase the old test database if os.access(target_database_name, os.F_OK): if keepdb: return if verbosity >= 1: self.log( "Destroying old test database for alias %s..." % ( self._get_database_display_str( verbosity, target_database_name ), ) ) try: os.remove(target_database_name) except Exception as e: self.log("Got an error deleting the old test database: %s" % e) sys.exit(2) try: shutil.copy(source_database_name, target_database_name) except Exception as e: self.log("Got an error cloning the test database: %s" % e) sys.exit(2) # Forking automatically makes a copy of an in-memory database. # Forkserver and spawn require migrating to disk which will be # re-opened in setup_worker_connection. elif multiprocessing.get_start_method() in {"forkserver", "spawn"}: ondisk_db = sqlite3.connect(target_database_name, uri=True) self.connection.connection.backup(ondisk_db) ondisk_db.close() def _destroy_test_db(self, test_database_name, verbosity): if test_database_name and not self.is_in_memory_db(test_database_name): # Remove the SQLite database file os.remove(test_database_name) def test_db_signature(self): """ Return a tuple that uniquely identifies a test database. This takes into account the special cases of ":memory:" and "" for SQLite since the databases will be distinct despite having the same TEST NAME. See https://www.sqlite.org/inmemorydb.html """ test_database_name = self._get_test_db_name() sig = [self.connection.settings_dict["NAME"]] if self.is_in_memory_db(test_database_name): sig.append(self.connection.alias) else: sig.append(test_database_name) return tuple(sig) def setup_worker_connection(self, _worker_id): settings_dict = self.get_test_db_clone_settings(_worker_id) # connection.settings_dict must be updated in place for changes to be # reflected in django.db.connections. Otherwise new threads would # connect to the default database instead of the appropriate clone. start_method = multiprocessing.get_start_method() if start_method == "fork": # Update settings_dict in place. self.connection.settings_dict.update(settings_dict) self.connection.close() elif start_method in {"forkserver", "spawn"}: alias = self.connection.alias connection_str = ( f"file:memorydb_{alias}_{_worker_id}?mode=memory&cache=shared" ) source_db = self.connection.Database.connect( f"file:{alias}_{_worker_id}.sqlite3?mode=ro", uri=True ) target_db = sqlite3.connect(connection_str, uri=True) source_db.backup(target_db) source_db.close() # Update settings_dict in place. self.connection.settings_dict.update(settings_dict) self.connection.settings_dict["NAME"] = connection_str # Re-open connection to in-memory database before closing copy # connection. self.connection.connect() target_db.close()
import copy import multiprocessing import unittest from unittest import mock from django.db import DEFAULT_DB_ALIAS, NotSupportedError, connection, connections from django.test import SimpleTestCase @unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests") class TestDbSignatureTests(SimpleTestCase): def test_custom_test_name(self): test_connection = copy.copy(connections[DEFAULT_DB_ALIAS]) test_connection.settings_dict = copy.deepcopy( connections[DEFAULT_DB_ALIAS].settings_dict ) test_connection.settings_dict["NAME"] = None test_connection.settings_dict["TEST"]["NAME"] = "custom.sqlite.db" signature = test_connection.creation_class(test_connection).test_db_signature() self.assertEqual(signature, (None, "custom.sqlite.db")) def test_get_test_db_clone_settings_name(self): test_connection = copy.copy(connections[DEFAULT_DB_ALIAS]) test_connection.settings_dict = copy.deepcopy( connections[DEFAULT_DB_ALIAS].settings_dict, ) tests = [ ("test.sqlite3", "test_1.sqlite3"), ("test", "test_1"), ] for test_db_name, expected_clone_name in tests: with self.subTest(test_db_name=test_db_name): test_connection.settings_dict["NAME"] = test_db_name test_connection.settings_dict["TEST"]["NAME"] = test_db_name creation_class = test_connection.creation_class(test_connection) clone_settings_dict = creation_class.get_test_db_clone_settings("1") self.assertEqual(clone_settings_dict["NAME"], expected_clone_name) @mock.patch.object(multiprocessing, "get_start_method", return_value="unsupported") def test_get_test_db_clone_settings_not_supported(self, *mocked_objects): msg = "Cloning with start method 'unsupported' is not supported." with self.assertRaisesMessage(NotSupportedError, msg): connection.creation.get_test_db_clone_settings(1)
django
python
import operator import sqlite3 from django.db import transaction from django.db.backends.base.features import BaseDatabaseFeatures from django.db.utils import OperationalError from django.utils.functional import cached_property from .base import Database class DatabaseFeatures(BaseDatabaseFeatures): minimum_database_version = (3, 37) test_db_allows_multiple_connections = False supports_unspecified_pk = True supports_timezones = False supports_transactions = True atomic_transactions = False can_rollback_ddl = True can_create_inline_fk = False requires_literal_defaults = True can_clone_databases = True supports_temporal_subtraction = True ignores_table_name_case = True supports_cast_with_precision = False time_cast_precision = 3 can_release_savepoints = True has_case_insensitive_like = True supports_parentheses_in_compound = False can_defer_constraint_checks = True supports_over_clause = True supports_frame_range_fixed_distance = True supports_frame_exclusion = True supports_aggregate_filter_clause = True supports_aggregate_order_by_clause = Database.sqlite_version_info >= (3, 44, 0) supports_aggregate_distinct_multiple_argument = False supports_any_value = True order_by_nulls_first = True supports_json_field_contains = False supports_update_conflicts = True supports_update_conflicts_with_target = True supports_stored_generated_columns = True supports_virtual_generated_columns = True test_collations = { "ci": "nocase", "cs": "binary", "non_default": "nocase", "virtual": "nocase", } django_test_expected_failures = { # The django_format_dtdelta() function doesn't properly handle mixed # Date/DateTime fields and timedeltas. "expressions.tests.FTimeDeltaTests.test_mixed_comparisons1", } insert_test_table_with_defaults = 'INSERT INTO {} ("null") VALUES (1)' supports_default_keyword_in_insert = False supports_unlimited_charfield = True supports_no_precision_decimalfield = True can_return_columns_from_insert = True can_return_rows_from_bulk_insert = True can_return_rows_from_update = True @cached_property def django_test_skips(self): skips = { "SQLite stores values rounded to 15 significant digits.": { "model_fields.test_decimalfield.DecimalFieldTests." "test_fetch_from_db_without_float_rounding", }, "SQLite naively remakes the table on field alteration.": { "schema.tests.SchemaTests.test_unique_no_unnecessary_fk_drops", "schema.tests.SchemaTests.test_unique_and_reverse_m2m", "schema.tests.SchemaTests." "test_alter_field_default_doesnt_perform_queries", "schema.tests.SchemaTests." "test_rename_column_renames_deferred_sql_references", }, "SQLite doesn't support negative precision for ROUND().": { "db_functions.math.test_round.RoundTests." "test_null_with_negative_precision", "db_functions.math.test_round.RoundTests." "test_decimal_with_negative_precision", "db_functions.math.test_round.RoundTests." "test_float_with_negative_precision", "db_functions.math.test_round.RoundTests." "test_integer_with_negative_precision", }, "The actual query cannot be determined on SQLite": { "backends.base.test_base.ExecuteWrapperTests.test_wrapper_debug", }, } if self.connection.is_in_memory_db(): skips.update( { "the sqlite backend's close() method is a no-op when using an " "in-memory database": { "servers.test_liveserverthread.LiveServerThreadTest." "test_closes_connections", "servers.tests.LiveServerTestCloseConnectionTest." "test_closes_connections", }, "For SQLite in-memory tests, closing the connection destroys " "the database.": { "test_utils.tests.AssertNumQueriesUponConnectionTests." "test_ignores_connection_configuration_queries", }, } ) else: skips.update( { "Only connections to in-memory SQLite databases are passed to the " "server thread.": { "servers.tests.LiveServerInMemoryDatabaseLockTest." "test_in_memory_database_lock", }, "multiprocessing's start method is checked only for in-memory " "SQLite databases": { "backends.sqlite.test_creation.TestDbSignatureTests." "test_get_test_db_clone_settings_not_supported", }, } ) if Database.sqlite_version_info < (3, 47): skips.update( { "SQLite does not parse escaped double quotes in the JSON path " "notation": { "model_fields.test_jsonfield.TestQuerying." "test_lookups_special_chars_double_quotes", }, } ) return skips @cached_property def introspected_field_types(self): return { **super().introspected_field_types, "BigAutoField": "AutoField", "DurationField": "BigIntegerField", "GenericIPAddressField": "CharField", "SmallAutoField": "AutoField", } @property def max_query_params(self): """ SQLite has a variable limit per query. The limit can be changed using the SQLITE_MAX_VARIABLE_NUMBER compile-time option (which defaults to 32766) or lowered per connection at run-time with setlimit(SQLITE_LIMIT_VARIABLE_NUMBER, N). """ return self.connection.connection.getlimit(sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER) @cached_property def supports_json_field(self): with self.connection.cursor() as cursor: try: with transaction.atomic(self.connection.alias): cursor.execute('SELECT JSON(\'{"a": "b"}\')') except OperationalError: return False return True can_introspect_json_field = property(operator.attrgetter("supports_json_field")) has_json_object_function = property(operator.attrgetter("supports_json_field"))
import sqlite3 from unittest import mock, skipUnless from django.db import OperationalError, connection from django.test import TestCase @skipUnless(connection.vendor == "sqlite", "SQLite tests.") class FeaturesTests(TestCase): def test_supports_json_field_operational_error(self): if hasattr(connection.features, "supports_json_field"): del connection.features.supports_json_field msg = "unable to open database file" with mock.patch.object( connection, "cursor", side_effect=OperationalError(msg), ): with self.assertRaisesMessage(OperationalError, msg): connection.features.supports_json_field def test_max_query_params_respects_variable_limit(self): limit_name = sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER current_limit = connection.features.max_query_params new_limit = min(42, current_limit) try: connection.connection.setlimit(limit_name, new_limit) self.assertEqual(connection.features.max_query_params, new_limit) finally: connection.connection.setlimit(limit_name, current_limit) self.assertEqual(connection.features.max_query_params, current_limit)
django
python
from collections import namedtuple import sqlparse from django.db import DatabaseError from django.db.backends.base.introspection import BaseDatabaseIntrospection from django.db.backends.base.introspection import FieldInfo as BaseFieldInfo from django.db.backends.base.introspection import TableInfo from django.db.models import Index from django.utils.regex_helper import _lazy_re_compile FieldInfo = namedtuple( "FieldInfo", [*BaseFieldInfo._fields, "pk", "has_json_constraint"] ) field_size_re = _lazy_re_compile(r"^\s*(?:var)?char\s*\(\s*(\d+)\s*\)\s*$") def get_field_size(name): """Extract the size number from a "varchar(11)" type name""" m = field_size_re.search(name) return int(m[1]) if m else None # This light wrapper "fakes" a dictionary interface, because some SQLite data # types include variables in them -- e.g. "varchar(30)" -- and can't be matched # as a simple dictionary lookup. class FlexibleFieldLookupDict: # Maps SQL types to Django Field types. Some of the SQL types have multiple # entries here because SQLite allows for anything and doesn't normalize the # field type; it uses whatever was given. base_data_types_reverse = { "bool": "BooleanField", "boolean": "BooleanField", "smallint": "SmallIntegerField", "smallint unsigned": "PositiveSmallIntegerField", "smallinteger": "SmallIntegerField", "int": "IntegerField", "integer": "IntegerField", "bigint": "BigIntegerField", "integer unsigned": "PositiveIntegerField", "bigint unsigned": "PositiveBigIntegerField", "decimal": "DecimalField", "real": "FloatField", "text": "TextField", "char": "CharField", "varchar": "CharField", "blob": "BinaryField", "date": "DateField", "datetime": "DateTimeField", "time": "TimeField", } def __getitem__(self, key): key = key.lower().split("(", 1)[0].strip() return self.base_data_types_reverse[key] class DatabaseIntrospection(BaseDatabaseIntrospection): data_types_reverse = FlexibleFieldLookupDict() def get_field_type(self, data_type, description): field_type = super().get_field_type(data_type, description) if description.pk and field_type in { "BigIntegerField", "IntegerField", "SmallIntegerField", }: # No support for BigAutoField or SmallAutoField as SQLite treats # all integer primary keys as signed 64-bit integers. return "AutoField" if description.has_json_constraint: return "JSONField" return field_type def get_table_list(self, cursor): """Return a list of table and view names in the current database.""" # Skip the sqlite_sequence system table used for autoincrement key # generation. cursor.execute( """ SELECT name, type FROM sqlite_master WHERE type in ('table', 'view') AND NOT name='sqlite_sequence' ORDER BY name""" ) return [TableInfo(row[0], row[1][0]) for row in cursor.fetchall()] def get_table_description(self, cursor, table_name): """ Return a description of the table with the DB-API cursor.description interface. """ cursor.execute( "PRAGMA table_xinfo(%s)" % self.connection.ops.quote_name(table_name) ) table_info = cursor.fetchall() if not table_info: raise DatabaseError(f"Table {table_name} does not exist (empty pragma).") collations = self._get_column_collations(cursor, table_name) json_columns = set() if self.connection.features.can_introspect_json_field: for line in table_info: column = line[1] json_constraint_sql = '%%json_valid("%s")%%' % column has_json_constraint = cursor.execute( """ SELECT sql FROM sqlite_master WHERE type = 'table' AND name = %s AND sql LIKE %s """, [table_name, json_constraint_sql], ).fetchone() if has_json_constraint: json_columns.add(column) table_description = [ FieldInfo( name, data_type, get_field_size(data_type), None, None, None, not notnull, default, collations.get(name), bool(pk), name in json_columns, ) for cid, name, data_type, notnull, default, pk, hidden in table_info if hidden in [ 0, # Normal column. 2, # Virtual generated column. 3, # Stored generated column. ] ] # If the primary key is composed of multiple columns they should not # be individually marked as pk. primary_key = [ index for index, field_info in enumerate(table_description) if field_info.pk ] if len(primary_key) > 1: for index in primary_key: table_description[index] = table_description[index]._replace(pk=False) return table_description def get_sequences(self, cursor, table_name, table_fields=()): pk_col = self.get_primary_key_column(cursor, table_name) return [{"table": table_name, "column": pk_col}] def get_relations(self, cursor, table_name): """ Return a dictionary of {column_name: (ref_column_name, ref_table_name, db_on_delete)} representing all foreign keys in the given table. """ cursor.execute( "PRAGMA foreign_key_list(%s)" % self.connection.ops.quote_name(table_name) ) return { column_name: ( ref_column_name, ref_table_name, self.on_delete_types.get(on_delete), ) for ( _, _, ref_table_name, column_name, ref_column_name, _, on_delete, *_, ) in cursor.fetchall() } def get_primary_key_columns(self, cursor, table_name): cursor.execute( "PRAGMA table_info(%s)" % self.connection.ops.quote_name(table_name) ) return [name for _, name, *_, pk in cursor.fetchall() if pk] def _parse_column_or_constraint_definition(self, tokens, columns): token = None is_constraint_definition = None field_name = None constraint_name = None unique = False unique_columns = [] check = False check_columns = [] braces_deep = 0 for token in tokens: if token.match(sqlparse.tokens.Punctuation, "("): braces_deep += 1 elif token.match(sqlparse.tokens.Punctuation, ")"): braces_deep -= 1 if braces_deep < 0: # End of columns and constraints for table definition. break elif braces_deep == 0 and token.match(sqlparse.tokens.Punctuation, ","): # End of current column or constraint definition. break # Detect column or constraint definition by first token. if is_constraint_definition is None: is_constraint_definition = token.match( sqlparse.tokens.Keyword, "CONSTRAINT" ) if is_constraint_definition: continue if is_constraint_definition: # Detect constraint name by second token. if constraint_name is None: if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): constraint_name = token.value elif token.ttype == sqlparse.tokens.Literal.String.Symbol: constraint_name = token.value[1:-1] # Start constraint columns parsing after UNIQUE keyword. if token.match(sqlparse.tokens.Keyword, "UNIQUE"): unique = True unique_braces_deep = braces_deep elif unique: if unique_braces_deep == braces_deep: if unique_columns: # Stop constraint parsing. unique = False continue if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): unique_columns.append(token.value) elif token.ttype == sqlparse.tokens.Literal.String.Symbol: unique_columns.append(token.value[1:-1]) else: # Detect field name by first token. if field_name is None: if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): field_name = token.value elif token.ttype == sqlparse.tokens.Literal.String.Symbol: field_name = token.value[1:-1] if token.match(sqlparse.tokens.Keyword, "UNIQUE"): unique_columns = [field_name] # Start constraint columns parsing after CHECK keyword. if token.match(sqlparse.tokens.Keyword, "CHECK"): check = True check_braces_deep = braces_deep elif check: if check_braces_deep == braces_deep: if check_columns: # Stop constraint parsing. check = False continue if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): if token.value in columns: check_columns.append(token.value) elif token.ttype == sqlparse.tokens.Literal.String.Symbol: if token.value[1:-1] in columns: check_columns.append(token.value[1:-1]) unique_constraint = ( { "unique": True, "columns": unique_columns, "primary_key": False, "foreign_key": None, "check": False, "index": False, } if unique_columns else None ) check_constraint = ( { "check": True, "columns": check_columns, "primary_key": False, "unique": False, "foreign_key": None, "index": False, } if check_columns else None ) return constraint_name, unique_constraint, check_constraint, token def _parse_table_constraints(self, sql, columns): # Check constraint parsing is based of SQLite syntax diagram. # https://www.sqlite.org/syntaxdiagrams.html#table-constraint statement = sqlparse.parse(sql)[0] constraints = {} unnamed_constrains_index = 0 tokens = (token for token in statement.flatten() if not token.is_whitespace) # Go to columns and constraint definition for token in tokens: if token.match(sqlparse.tokens.Punctuation, "("): break # Parse columns and constraint definition while True: ( constraint_name, unique, check, end_token, ) = self._parse_column_or_constraint_definition(tokens, columns) if unique: if constraint_name: constraints[constraint_name] = unique else: unnamed_constrains_index += 1 constraints[ "__unnamed_constraint_%s__" % unnamed_constrains_index ] = unique if check: if constraint_name: constraints[constraint_name] = check else: unnamed_constrains_index += 1 constraints[ "__unnamed_constraint_%s__" % unnamed_constrains_index ] = check if end_token.match(sqlparse.tokens.Punctuation, ")"): break return constraints def get_constraints(self, cursor, table_name): """ Retrieve any constraints or keys (unique, pk, fk, check, index) across one or more columns. """ constraints = {} # Find inline check constraints. try: table_schema = cursor.execute( "SELECT sql FROM sqlite_master WHERE type='table' and name=%s", [table_name], ).fetchone()[0] except TypeError: # table_name is a view. pass else: columns = { info.name for info in self.get_table_description(cursor, table_name) } constraints.update(self._parse_table_constraints(table_schema, columns)) # Get the index info cursor.execute( "PRAGMA index_list(%s)" % self.connection.ops.quote_name(table_name) ) for row in cursor.fetchall(): # Discard last 2 columns. number, index, unique = row[:3] cursor.execute( "SELECT sql FROM sqlite_master WHERE type='index' AND name=%s", [index], ) # There's at most one row. (sql,) = cursor.fetchone() or (None,) # Inline constraints are already detected in # _parse_table_constraints(). The reasons to avoid fetching inline # constraints from `PRAGMA index_list` are: # - Inline constraints can have a different name and information # than what `PRAGMA index_list` gives. # - Not all inline constraints may appear in `PRAGMA index_list`. if not sql: # An inline constraint continue # Get the index info for that index cursor.execute( "PRAGMA index_info(%s)" % self.connection.ops.quote_name(index) ) for index_rank, column_rank, column in cursor.fetchall(): if index not in constraints: constraints[index] = { "columns": [], "primary_key": False, "unique": bool(unique), "foreign_key": None, "check": False, "index": True, } constraints[index]["columns"].append(column) # Add type and column orders for indexes if constraints[index]["index"]: # SQLite doesn't support any index type other than b-tree constraints[index]["type"] = Index.suffix orders = self._get_index_columns_orders(sql) if orders is not None: constraints[index]["orders"] = orders # Get the PK pk_columns = self.get_primary_key_columns(cursor, table_name) if pk_columns: # SQLite doesn't actually give a name to the PK constraint, # so we invent one. This is fine, as the SQLite backend never # deletes PK constraints by name, as you can't delete constraints # in SQLite; we remake the table with a new PK instead. constraints["__primary__"] = { "columns": pk_columns, "primary_key": True, "unique": False, # It's not actually a unique constraint. "foreign_key": None, "check": False, "index": False, } relations = enumerate(self.get_relations(cursor, table_name).items()) constraints.update( { f"fk_{index}": { "columns": [column_name], "primary_key": False, "unique": False, "foreign_key": (ref_table_name, ref_column_name), "check": False, "index": False, } for index, ( column_name, (ref_column_name, ref_table_name, _), ) in relations } ) return constraints def _get_index_columns_orders(self, sql): tokens = sqlparse.parse(sql)[0] for token in tokens: if isinstance(token, sqlparse.sql.Parenthesis): columns = str(token).strip("()").split(", ") return ["DESC" if info.endswith("DESC") else "ASC" for info in columns] return None def _get_column_collations(self, cursor, table_name): row = cursor.execute( """ SELECT sql FROM sqlite_master WHERE type = 'table' AND name = %s """, [table_name], ).fetchone() if not row: return {} sql = row[0] columns = str(sqlparse.parse(sql)[0][-1]).strip("()").split(", ") collations = {} for column in columns: tokens = column[1:].split() column_name = tokens[0].strip('"') for index, token in enumerate(tokens): if token == "COLLATE": collation = tokens[index + 1] break else: collation = None collations[column_name] = collation return collations
import unittest import sqlparse from django.db import connection from django.test import TestCase @unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests") class IntrospectionTests(TestCase): def test_get_primary_key_column(self): """ Get the primary key column regardless of whether or not it has quotation. """ testable_column_strings = ( ("id", "id"), ("[id]", "id"), ("`id`", "id"), ('"id"', "id"), ("[id col]", "id col"), ("`id col`", "id col"), ('"id col"', "id col"), ) with connection.cursor() as cursor: for column, expected_string in testable_column_strings: sql = "CREATE TABLE test_primary (%s int PRIMARY KEY NOT NULL)" % column with self.subTest(column=column): try: cursor.execute(sql) field = connection.introspection.get_primary_key_column( cursor, "test_primary" ) self.assertEqual(field, expected_string) finally: cursor.execute("DROP TABLE test_primary") def test_get_primary_key_column_pk_constraint(self): sql = """ CREATE TABLE test_primary( id INTEGER NOT NULL, created DATE, PRIMARY KEY(id) ) """ with connection.cursor() as cursor: try: cursor.execute(sql) field = connection.introspection.get_primary_key_column( cursor, "test_primary", ) self.assertEqual(field, "id") finally: cursor.execute("DROP TABLE test_primary") @unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests") class ParsingTests(TestCase): def parse_definition(self, sql, columns): """Parse a column or constraint definition.""" statement = sqlparse.parse(sql)[0] tokens = (token for token in statement.flatten() if not token.is_whitespace) with connection.cursor(): return connection.introspection._parse_column_or_constraint_definition( tokens, set(columns) ) def assertConstraint(self, constraint_details, cols, unique=False, check=False): self.assertEqual( constraint_details, { "unique": unique, "columns": cols, "primary_key": False, "foreign_key": None, "check": check, "index": False, }, ) def test_unique_column(self): tests = ( ('"ref" integer UNIQUE,', ["ref"]), ("ref integer UNIQUE,", ["ref"]), ('"customname" integer UNIQUE,', ["customname"]), ("customname integer UNIQUE,", ["customname"]), ) for sql, columns in tests: with self.subTest(sql=sql): constraint, details, check, _ = self.parse_definition(sql, columns) self.assertIsNone(constraint) self.assertConstraint(details, columns, unique=True) self.assertIsNone(check) def test_unique_constraint(self): tests = ( ('CONSTRAINT "ref" UNIQUE ("ref"),', "ref", ["ref"]), ("CONSTRAINT ref UNIQUE (ref),", "ref", ["ref"]), ( 'CONSTRAINT "customname1" UNIQUE ("customname2"),', "customname1", ["customname2"], ), ( "CONSTRAINT customname1 UNIQUE (customname2),", "customname1", ["customname2"], ), ) for sql, constraint_name, columns in tests: with self.subTest(sql=sql): constraint, details, check, _ = self.parse_definition(sql, columns) self.assertEqual(constraint, constraint_name) self.assertConstraint(details, columns, unique=True) self.assertIsNone(check) def test_unique_constraint_multicolumn(self): tests = ( ( 'CONSTRAINT "ref" UNIQUE ("ref", "customname"),', "ref", ["ref", "customname"], ), ("CONSTRAINT ref UNIQUE (ref, customname),", "ref", ["ref", "customname"]), ) for sql, constraint_name, columns in tests: with self.subTest(sql=sql): constraint, details, check, _ = self.parse_definition(sql, columns) self.assertEqual(constraint, constraint_name) self.assertConstraint(details, columns, unique=True) self.assertIsNone(check) def test_check_column(self): tests = ( ('"ref" varchar(255) CHECK ("ref" != \'test\'),', ["ref"]), ("ref varchar(255) CHECK (ref != 'test'),", ["ref"]), ( '"customname1" varchar(255) CHECK ("customname2" != \'test\'),', ["customname2"], ), ( "customname1 varchar(255) CHECK (customname2 != 'test'),", ["customname2"], ), ) for sql, columns in tests: with self.subTest(sql=sql): constraint, details, check, _ = self.parse_definition(sql, columns) self.assertIsNone(constraint) self.assertIsNone(details) self.assertConstraint(check, columns, check=True) def test_check_constraint(self): tests = ( ('CONSTRAINT "ref" CHECK ("ref" != \'test\'),', "ref", ["ref"]), ("CONSTRAINT ref CHECK (ref != 'test'),", "ref", ["ref"]), ( 'CONSTRAINT "customname1" CHECK ("customname2" != \'test\'),', "customname1", ["customname2"], ), ( "CONSTRAINT customname1 CHECK (customname2 != 'test'),", "customname1", ["customname2"], ), ) for sql, constraint_name, columns in tests: with self.subTest(sql=sql): constraint, details, check, _ = self.parse_definition(sql, columns) self.assertEqual(constraint, constraint_name) self.assertIsNone(details) self.assertConstraint(check, columns, check=True) def test_check_column_with_operators_and_functions(self): tests = ( ('"ref" integer CHECK ("ref" BETWEEN 1 AND 10),', ["ref"]), ('"ref" varchar(255) CHECK ("ref" LIKE \'test%\'),', ["ref"]), ( '"ref" varchar(255) CHECK (LENGTH(ref) > "max_length"),', ["ref", "max_length"], ), ) for sql, columns in tests: with self.subTest(sql=sql): constraint, details, check, _ = self.parse_definition(sql, columns) self.assertIsNone(constraint) self.assertIsNone(details) self.assertConstraint(check, columns, check=True) def test_check_and_unique_column(self): tests = ( ('"ref" varchar(255) CHECK ("ref" != \'test\') UNIQUE,', ["ref"]), ("ref varchar(255) UNIQUE CHECK (ref != 'test'),", ["ref"]), ) for sql, columns in tests: with self.subTest(sql=sql): constraint, details, check, _ = self.parse_definition(sql, columns) self.assertIsNone(constraint) self.assertConstraint(details, columns, unique=True) self.assertConstraint(check, columns, check=True)
django
python
from django.db.migrations.operations.base import Operation class TestOperation(Operation): def __init__(self): pass def deconstruct(self): return (self.__class__.__name__, [], {}) @property def reversible(self): return True def state_forwards(self, app_label, state): pass def database_forwards(self, app_label, schema_editor, from_state, to_state): pass def state_backwards(self, app_label, state): pass def database_backwards(self, app_label, schema_editor, from_state, to_state): pass class CreateModel(TestOperation): pass class ArgsOperation(TestOperation): def __init__(self, arg1, arg2): self.arg1, self.arg2 = arg1, arg2 def deconstruct(self): return (self.__class__.__name__, [self.arg1, self.arg2], {}) class KwargsOperation(TestOperation): def __init__(self, kwarg1=None, kwarg2=None): self.kwarg1, self.kwarg2 = kwarg1, kwarg2 def deconstruct(self): kwargs = {} if self.kwarg1 is not None: kwargs["kwarg1"] = self.kwarg1 if self.kwarg2 is not None: kwargs["kwarg2"] = self.kwarg2 return (self.__class__.__name__, [], kwargs) class ArgsKwargsOperation(TestOperation): def __init__(self, arg1, arg2, kwarg1=None, kwarg2=None): self.arg1, self.arg2 = arg1, arg2 self.kwarg1, self.kwarg2 = kwarg1, kwarg2 def deconstruct(self): kwargs = {} if self.kwarg1 is not None: kwargs["kwarg1"] = self.kwarg1 if self.kwarg2 is not None: kwargs["kwarg2"] = self.kwarg2 return ( self.__class__.__name__, [self.arg1, self.arg2], kwargs, ) class ArgsAndKeywordOnlyArgsOperation(ArgsKwargsOperation): def __init__(self, arg1, arg2, *, kwarg1, kwarg2): super().__init__(arg1, arg2, kwarg1=kwarg1, kwarg2=kwarg2) class ExpandArgsOperation(TestOperation): serialization_expand_args = ["arg"] def __init__(self, arg): self.arg = arg def deconstruct(self): return (self.__class__.__name__, [self.arg], {})
import unittest from django.core.management.color import no_style from django.db import connection, models from django.test import TransactionTestCase from ..models import Person, Tag @unittest.skipUnless(connection.vendor == "oracle", "Oracle tests") class OperationsTests(TransactionTestCase): available_apps = ["backends"] def test_sequence_name_truncation(self): seq_name = connection.ops._get_no_autofield_sequence_name( "schema_authorwithevenlongee869" ) self.assertEqual(seq_name, "SCHEMA_AUTHORWITHEVENLOB0B8_SQ") def test_bulk_batch_size(self): # Oracle restricts the number of parameters in a query. objects = range(2**16) self.assertEqual(connection.ops.bulk_batch_size([], objects), len(objects)) # Each field is a parameter for each object. first_name_field = Person._meta.get_field("first_name") last_name_field = Person._meta.get_field("last_name") self.assertEqual( connection.ops.bulk_batch_size([first_name_field], objects), connection.features.max_query_params, ) self.assertEqual( connection.ops.bulk_batch_size( [first_name_field, last_name_field], objects, ), connection.features.max_query_params // 2, ) composite_pk = models.CompositePrimaryKey("first_name", "last_name") composite_pk.fields = [first_name_field, last_name_field] self.assertEqual( connection.ops.bulk_batch_size([composite_pk, first_name_field], objects), connection.features.max_query_params // 3, ) def test_sql_flush(self): statements = connection.ops.sql_flush( no_style(), [Person._meta.db_table, Tag._meta.db_table], ) # The tables and constraints are processed in an unordered set. self.assertEqual( statements[0], 'ALTER TABLE "BACKENDS_TAG" DISABLE CONSTRAINT ' '"BACKENDS__CONTENT_T_FD9D7A85_F" KEEP INDEX;', ) self.assertEqual( sorted(statements[1:-1]), [ 'TRUNCATE TABLE "BACKENDS_PERSON";', 'TRUNCATE TABLE "BACKENDS_TAG";', ], ) self.assertEqual( statements[-1], 'ALTER TABLE "BACKENDS_TAG" ENABLE CONSTRAINT ' '"BACKENDS__CONTENT_T_FD9D7A85_F";', ) def test_sql_flush_allow_cascade(self): statements = connection.ops.sql_flush( no_style(), [Person._meta.db_table, Tag._meta.db_table], allow_cascade=True, ) # The tables and constraints are processed in an unordered set. self.assertEqual( statements[0], 'ALTER TABLE "BACKENDS_VERYLONGMODELNAME540F" DISABLE CONSTRAINT ' '"BACKENDS__PERSON_ID_1DD5E829_F" KEEP INDEX;', ) self.assertEqual( sorted(statements[1:-1]), [ 'TRUNCATE TABLE "BACKENDS_PERSON";', 'TRUNCATE TABLE "BACKENDS_TAG";', 'TRUNCATE TABLE "BACKENDS_VERYLONGMODELNAME540F";', ], ) self.assertEqual( statements[-1], 'ALTER TABLE "BACKENDS_VERYLONGMODELNAME540F" ENABLE CONSTRAINT ' '"BACKENDS__PERSON_ID_1DD5E829_F";', ) def test_sql_flush_sequences(self): statements = connection.ops.sql_flush( no_style(), [Person._meta.db_table, Tag._meta.db_table], reset_sequences=True, ) # The tables and constraints are processed in an unordered set. self.assertEqual( statements[0], 'ALTER TABLE "BACKENDS_TAG" DISABLE CONSTRAINT ' '"BACKENDS__CONTENT_T_FD9D7A85_F" KEEP INDEX;', ) self.assertEqual( sorted(statements[1:3]), [ 'TRUNCATE TABLE "BACKENDS_PERSON";', 'TRUNCATE TABLE "BACKENDS_TAG";', ], ) self.assertEqual( statements[3], 'ALTER TABLE "BACKENDS_TAG" ENABLE CONSTRAINT ' '"BACKENDS__CONTENT_T_FD9D7A85_F";', ) # Sequences. self.assertEqual(len(statements[4:]), 2) self.assertIn("BACKENDS_PERSON_SQ", statements[4]) self.assertIn("BACKENDS_TAG_SQ", statements[5]) def test_sql_flush_sequences_allow_cascade(self): statements = connection.ops.sql_flush( no_style(), [Person._meta.db_table, Tag._meta.db_table], reset_sequences=True, allow_cascade=True, ) # The tables and constraints are processed in an unordered set. self.assertEqual( statements[0], 'ALTER TABLE "BACKENDS_VERYLONGMODELNAME540F" DISABLE CONSTRAINT ' '"BACKENDS__PERSON_ID_1DD5E829_F" KEEP INDEX;', ) self.assertEqual( sorted(statements[1:4]), [ 'TRUNCATE TABLE "BACKENDS_PERSON";', 'TRUNCATE TABLE "BACKENDS_TAG";', 'TRUNCATE TABLE "BACKENDS_VERYLONGMODELNAME540F";', ], ) self.assertEqual( statements[4], 'ALTER TABLE "BACKENDS_VERYLONGMODELNAME540F" ENABLE CONSTRAINT ' '"BACKENDS__PERSON_ID_1DD5E829_F";', ) # Sequences. self.assertEqual(len(statements[5:]), 3) self.assertIn("BACKENDS_PERSON_SQ", statements[5]) self.assertIn("BACKENDS_VERYLONGMODELN7BE2_SQ", statements[6]) self.assertIn("BACKENDS_TAG_SQ", statements[7])
django
python
import multiprocessing import os import shutil import sqlite3 import sys from pathlib import Path from django.db import NotSupportedError from django.db.backends.base.creation import BaseDatabaseCreation class DatabaseCreation(BaseDatabaseCreation): @staticmethod def is_in_memory_db(database_name): return not isinstance(database_name, Path) and ( database_name == ":memory:" or "mode=memory" in database_name ) def _get_test_db_name(self): test_database_name = self.connection.settings_dict["TEST"]["NAME"] or ":memory:" if test_database_name == ":memory:": return "file:memorydb_%s?mode=memory&cache=shared" % self.connection.alias return test_database_name def _create_test_db(self, verbosity, autoclobber, keepdb=False): test_database_name = self._get_test_db_name() if keepdb: return test_database_name if not self.is_in_memory_db(test_database_name): # Erase the old test database if verbosity >= 1: self.log( "Destroying old test database for alias %s..." % (self._get_database_display_str(verbosity, test_database_name),) ) if os.access(test_database_name, os.F_OK): if not autoclobber: confirm = input( "Type 'yes' if you would like to try deleting the test " "database '%s', or 'no' to cancel: " % test_database_name ) if autoclobber or confirm == "yes": try: os.remove(test_database_name) except Exception as e: self.log("Got an error deleting the old test database: %s" % e) sys.exit(2) else: self.log("Tests cancelled.") sys.exit(1) return test_database_name def get_test_db_clone_settings(self, suffix): orig_settings_dict = self.connection.settings_dict source_database_name = orig_settings_dict["NAME"] or ":memory:" if not self.is_in_memory_db(source_database_name): root, ext = os.path.splitext(source_database_name) return {**orig_settings_dict, "NAME": f"{root}_{suffix}{ext}"} start_method = multiprocessing.get_start_method() if start_method == "fork": return orig_settings_dict if start_method in {"forkserver", "spawn"}: return { **orig_settings_dict, "NAME": f"{self.connection.alias}_{suffix}.sqlite3", } raise NotSupportedError( f"Cloning with start method {start_method!r} is not supported." ) def _clone_test_db(self, suffix, verbosity, keepdb=False): source_database_name = self.connection.settings_dict["NAME"] target_database_name = self.get_test_db_clone_settings(suffix)["NAME"] if not self.is_in_memory_db(source_database_name): # Erase the old test database if os.access(target_database_name, os.F_OK): if keepdb: return if verbosity >= 1: self.log( "Destroying old test database for alias %s..." % ( self._get_database_display_str( verbosity, target_database_name ), ) ) try: os.remove(target_database_name) except Exception as e: self.log("Got an error deleting the old test database: %s" % e) sys.exit(2) try: shutil.copy(source_database_name, target_database_name) except Exception as e: self.log("Got an error cloning the test database: %s" % e) sys.exit(2) # Forking automatically makes a copy of an in-memory database. # Forkserver and spawn require migrating to disk which will be # re-opened in setup_worker_connection. elif multiprocessing.get_start_method() in {"forkserver", "spawn"}: ondisk_db = sqlite3.connect(target_database_name, uri=True) self.connection.connection.backup(ondisk_db) ondisk_db.close() def _destroy_test_db(self, test_database_name, verbosity): if test_database_name and not self.is_in_memory_db(test_database_name): # Remove the SQLite database file os.remove(test_database_name) def test_db_signature(self): """ Return a tuple that uniquely identifies a test database. This takes into account the special cases of ":memory:" and "" for SQLite since the databases will be distinct despite having the same TEST NAME. See https://www.sqlite.org/inmemorydb.html """ test_database_name = self._get_test_db_name() sig = [self.connection.settings_dict["NAME"]] if self.is_in_memory_db(test_database_name): sig.append(self.connection.alias) else: sig.append(test_database_name) return tuple(sig) def setup_worker_connection(self, _worker_id): settings_dict = self.get_test_db_clone_settings(_worker_id) # connection.settings_dict must be updated in place for changes to be # reflected in django.db.connections. Otherwise new threads would # connect to the default database instead of the appropriate clone. start_method = multiprocessing.get_start_method() if start_method == "fork": # Update settings_dict in place. self.connection.settings_dict.update(settings_dict) self.connection.close() elif start_method in {"forkserver", "spawn"}: alias = self.connection.alias connection_str = ( f"file:memorydb_{alias}_{_worker_id}?mode=memory&cache=shared" ) source_db = self.connection.Database.connect( f"file:{alias}_{_worker_id}.sqlite3?mode=ro", uri=True ) target_db = sqlite3.connect(connection_str, uri=True) source_db.backup(target_db) source_db.close() # Update settings_dict in place. self.connection.settings_dict.update(settings_dict) self.connection.settings_dict["NAME"] = connection_str # Re-open connection to in-memory database before closing copy # connection. self.connection.connect() target_db.close()
import unittest from io import StringIO from unittest import mock from django.db import DatabaseError, connection from django.db.backends.oracle.creation import DatabaseCreation from django.test import TestCase @unittest.skipUnless(connection.vendor == "oracle", "Oracle tests") @mock.patch.object(DatabaseCreation, "_maindb_connection", return_value=connection) @mock.patch("sys.stdout", new_callable=StringIO) @mock.patch("sys.stderr", new_callable=StringIO) class DatabaseCreationTests(TestCase): def _execute_raise_user_already_exists( self, cursor, statements, parameters, verbosity, allow_quiet_fail=False ): # Raise "user already exists" only in test user creation if statements and statements[0].startswith("CREATE USER"): raise DatabaseError( "ORA-01920: user name 'string' conflicts with another user or role name" ) def _execute_raise_tablespace_already_exists( self, cursor, statements, parameters, verbosity, allow_quiet_fail=False ): raise DatabaseError("ORA-01543: tablespace 'string' already exists") def _execute_raise_insufficient_privileges( self, cursor, statements, parameters, verbosity, allow_quiet_fail=False ): raise DatabaseError("ORA-01031: insufficient privileges") def _test_database_passwd(self): # Mocked to avoid test user password changed return connection.settings_dict["SAVED_PASSWORD"] def patch_execute_statements(self, execute_statements): return mock.patch.object( DatabaseCreation, "_execute_statements", execute_statements ) @mock.patch.object(DatabaseCreation, "_test_user_create", return_value=False) def test_create_test_db(self, *mocked_objects): creation = DatabaseCreation(connection) # Simulate test database creation raising "tablespace already exists" with self.patch_execute_statements( self._execute_raise_tablespace_already_exists ): with mock.patch("builtins.input", return_value="no"): with self.assertRaises(SystemExit): # SystemExit is raised if the user answers "no" to the # prompt asking if it's okay to delete the test tablespace. creation._create_test_db(verbosity=0, keepdb=False) # "Tablespace already exists" error is ignored when keepdb is on creation._create_test_db(verbosity=0, keepdb=True) # Simulate test database creation raising unexpected error with self.patch_execute_statements(self._execute_raise_insufficient_privileges): with self.assertRaises(SystemExit): creation._create_test_db(verbosity=0, keepdb=False) with self.assertRaises(SystemExit): creation._create_test_db(verbosity=0, keepdb=True) @mock.patch.object(DatabaseCreation, "_test_database_create", return_value=False) def test_create_test_user(self, *mocked_objects): creation = DatabaseCreation(connection) with mock.patch.object( DatabaseCreation, "_test_database_passwd", self._test_database_passwd ): # Simulate test user creation raising "user already exists" with self.patch_execute_statements(self._execute_raise_user_already_exists): with mock.patch("builtins.input", return_value="no"): with self.assertRaises(SystemExit): # SystemExit is raised if the user answers "no" to the # prompt asking if it's okay to delete the test user. creation._create_test_db(verbosity=0, keepdb=False) # "User already exists" error is ignored when keepdb is on creation._create_test_db(verbosity=0, keepdb=True) # Simulate test user creation raising unexpected error with self.patch_execute_statements( self._execute_raise_insufficient_privileges ): with self.assertRaises(SystemExit): creation._create_test_db(verbosity=0, keepdb=False) with self.assertRaises(SystemExit): creation._create_test_db(verbosity=0, keepdb=True) def test_oracle_managed_files(self, *mocked_objects): def _execute_capture_statements( self, cursor, statements, parameters, verbosity, allow_quiet_fail=False ): self.tblspace_sqls = statements creation = DatabaseCreation(connection) # Simulate test database creation with Oracle Managed File (OMF) # tablespaces. with mock.patch.object( DatabaseCreation, "_test_database_oracle_managed_files", return_value=True ): with self.patch_execute_statements(_execute_capture_statements): with connection.cursor() as cursor: creation._execute_test_db_creation( cursor, creation._get_test_db_params(), verbosity=0 ) tblspace_sql, tblspace_tmp_sql = creation.tblspace_sqls # Datafile names shouldn't appear. self.assertIn("DATAFILE SIZE", tblspace_sql) self.assertIn("TEMPFILE SIZE", tblspace_tmp_sql) # REUSE cannot be used with OMF. self.assertNotIn("REUSE", tblspace_sql) self.assertNotIn("REUSE", tblspace_tmp_sql)
django
python
from collections import namedtuple import sqlparse from django.db import DatabaseError from django.db.backends.base.introspection import BaseDatabaseIntrospection from django.db.backends.base.introspection import FieldInfo as BaseFieldInfo from django.db.backends.base.introspection import TableInfo from django.db.models import Index from django.utils.regex_helper import _lazy_re_compile FieldInfo = namedtuple( "FieldInfo", [*BaseFieldInfo._fields, "pk", "has_json_constraint"] ) field_size_re = _lazy_re_compile(r"^\s*(?:var)?char\s*\(\s*(\d+)\s*\)\s*$") def get_field_size(name): """Extract the size number from a "varchar(11)" type name""" m = field_size_re.search(name) return int(m[1]) if m else None # This light wrapper "fakes" a dictionary interface, because some SQLite data # types include variables in them -- e.g. "varchar(30)" -- and can't be matched # as a simple dictionary lookup. class FlexibleFieldLookupDict: # Maps SQL types to Django Field types. Some of the SQL types have multiple # entries here because SQLite allows for anything and doesn't normalize the # field type; it uses whatever was given. base_data_types_reverse = { "bool": "BooleanField", "boolean": "BooleanField", "smallint": "SmallIntegerField", "smallint unsigned": "PositiveSmallIntegerField", "smallinteger": "SmallIntegerField", "int": "IntegerField", "integer": "IntegerField", "bigint": "BigIntegerField", "integer unsigned": "PositiveIntegerField", "bigint unsigned": "PositiveBigIntegerField", "decimal": "DecimalField", "real": "FloatField", "text": "TextField", "char": "CharField", "varchar": "CharField", "blob": "BinaryField", "date": "DateField", "datetime": "DateTimeField", "time": "TimeField", } def __getitem__(self, key): key = key.lower().split("(", 1)[0].strip() return self.base_data_types_reverse[key] class DatabaseIntrospection(BaseDatabaseIntrospection): data_types_reverse = FlexibleFieldLookupDict() def get_field_type(self, data_type, description): field_type = super().get_field_type(data_type, description) if description.pk and field_type in { "BigIntegerField", "IntegerField", "SmallIntegerField", }: # No support for BigAutoField or SmallAutoField as SQLite treats # all integer primary keys as signed 64-bit integers. return "AutoField" if description.has_json_constraint: return "JSONField" return field_type def get_table_list(self, cursor): """Return a list of table and view names in the current database.""" # Skip the sqlite_sequence system table used for autoincrement key # generation. cursor.execute( """ SELECT name, type FROM sqlite_master WHERE type in ('table', 'view') AND NOT name='sqlite_sequence' ORDER BY name""" ) return [TableInfo(row[0], row[1][0]) for row in cursor.fetchall()] def get_table_description(self, cursor, table_name): """ Return a description of the table with the DB-API cursor.description interface. """ cursor.execute( "PRAGMA table_xinfo(%s)" % self.connection.ops.quote_name(table_name) ) table_info = cursor.fetchall() if not table_info: raise DatabaseError(f"Table {table_name} does not exist (empty pragma).") collations = self._get_column_collations(cursor, table_name) json_columns = set() if self.connection.features.can_introspect_json_field: for line in table_info: column = line[1] json_constraint_sql = '%%json_valid("%s")%%' % column has_json_constraint = cursor.execute( """ SELECT sql FROM sqlite_master WHERE type = 'table' AND name = %s AND sql LIKE %s """, [table_name, json_constraint_sql], ).fetchone() if has_json_constraint: json_columns.add(column) table_description = [ FieldInfo( name, data_type, get_field_size(data_type), None, None, None, not notnull, default, collations.get(name), bool(pk), name in json_columns, ) for cid, name, data_type, notnull, default, pk, hidden in table_info if hidden in [ 0, # Normal column. 2, # Virtual generated column. 3, # Stored generated column. ] ] # If the primary key is composed of multiple columns they should not # be individually marked as pk. primary_key = [ index for index, field_info in enumerate(table_description) if field_info.pk ] if len(primary_key) > 1: for index in primary_key: table_description[index] = table_description[index]._replace(pk=False) return table_description def get_sequences(self, cursor, table_name, table_fields=()): pk_col = self.get_primary_key_column(cursor, table_name) return [{"table": table_name, "column": pk_col}] def get_relations(self, cursor, table_name): """ Return a dictionary of {column_name: (ref_column_name, ref_table_name, db_on_delete)} representing all foreign keys in the given table. """ cursor.execute( "PRAGMA foreign_key_list(%s)" % self.connection.ops.quote_name(table_name) ) return { column_name: ( ref_column_name, ref_table_name, self.on_delete_types.get(on_delete), ) for ( _, _, ref_table_name, column_name, ref_column_name, _, on_delete, *_, ) in cursor.fetchall() } def get_primary_key_columns(self, cursor, table_name): cursor.execute( "PRAGMA table_info(%s)" % self.connection.ops.quote_name(table_name) ) return [name for _, name, *_, pk in cursor.fetchall() if pk] def _parse_column_or_constraint_definition(self, tokens, columns): token = None is_constraint_definition = None field_name = None constraint_name = None unique = False unique_columns = [] check = False check_columns = [] braces_deep = 0 for token in tokens: if token.match(sqlparse.tokens.Punctuation, "("): braces_deep += 1 elif token.match(sqlparse.tokens.Punctuation, ")"): braces_deep -= 1 if braces_deep < 0: # End of columns and constraints for table definition. break elif braces_deep == 0 and token.match(sqlparse.tokens.Punctuation, ","): # End of current column or constraint definition. break # Detect column or constraint definition by first token. if is_constraint_definition is None: is_constraint_definition = token.match( sqlparse.tokens.Keyword, "CONSTRAINT" ) if is_constraint_definition: continue if is_constraint_definition: # Detect constraint name by second token. if constraint_name is None: if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): constraint_name = token.value elif token.ttype == sqlparse.tokens.Literal.String.Symbol: constraint_name = token.value[1:-1] # Start constraint columns parsing after UNIQUE keyword. if token.match(sqlparse.tokens.Keyword, "UNIQUE"): unique = True unique_braces_deep = braces_deep elif unique: if unique_braces_deep == braces_deep: if unique_columns: # Stop constraint parsing. unique = False continue if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): unique_columns.append(token.value) elif token.ttype == sqlparse.tokens.Literal.String.Symbol: unique_columns.append(token.value[1:-1]) else: # Detect field name by first token. if field_name is None: if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): field_name = token.value elif token.ttype == sqlparse.tokens.Literal.String.Symbol: field_name = token.value[1:-1] if token.match(sqlparse.tokens.Keyword, "UNIQUE"): unique_columns = [field_name] # Start constraint columns parsing after CHECK keyword. if token.match(sqlparse.tokens.Keyword, "CHECK"): check = True check_braces_deep = braces_deep elif check: if check_braces_deep == braces_deep: if check_columns: # Stop constraint parsing. check = False continue if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): if token.value in columns: check_columns.append(token.value) elif token.ttype == sqlparse.tokens.Literal.String.Symbol: if token.value[1:-1] in columns: check_columns.append(token.value[1:-1]) unique_constraint = ( { "unique": True, "columns": unique_columns, "primary_key": False, "foreign_key": None, "check": False, "index": False, } if unique_columns else None ) check_constraint = ( { "check": True, "columns": check_columns, "primary_key": False, "unique": False, "foreign_key": None, "index": False, } if check_columns else None ) return constraint_name, unique_constraint, check_constraint, token def _parse_table_constraints(self, sql, columns): # Check constraint parsing is based of SQLite syntax diagram. # https://www.sqlite.org/syntaxdiagrams.html#table-constraint statement = sqlparse.parse(sql)[0] constraints = {} unnamed_constrains_index = 0 tokens = (token for token in statement.flatten() if not token.is_whitespace) # Go to columns and constraint definition for token in tokens: if token.match(sqlparse.tokens.Punctuation, "("): break # Parse columns and constraint definition while True: ( constraint_name, unique, check, end_token, ) = self._parse_column_or_constraint_definition(tokens, columns) if unique: if constraint_name: constraints[constraint_name] = unique else: unnamed_constrains_index += 1 constraints[ "__unnamed_constraint_%s__" % unnamed_constrains_index ] = unique if check: if constraint_name: constraints[constraint_name] = check else: unnamed_constrains_index += 1 constraints[ "__unnamed_constraint_%s__" % unnamed_constrains_index ] = check if end_token.match(sqlparse.tokens.Punctuation, ")"): break return constraints def get_constraints(self, cursor, table_name): """ Retrieve any constraints or keys (unique, pk, fk, check, index) across one or more columns. """ constraints = {} # Find inline check constraints. try: table_schema = cursor.execute( "SELECT sql FROM sqlite_master WHERE type='table' and name=%s", [table_name], ).fetchone()[0] except TypeError: # table_name is a view. pass else: columns = { info.name for info in self.get_table_description(cursor, table_name) } constraints.update(self._parse_table_constraints(table_schema, columns)) # Get the index info cursor.execute( "PRAGMA index_list(%s)" % self.connection.ops.quote_name(table_name) ) for row in cursor.fetchall(): # Discard last 2 columns. number, index, unique = row[:3] cursor.execute( "SELECT sql FROM sqlite_master WHERE type='index' AND name=%s", [index], ) # There's at most one row. (sql,) = cursor.fetchone() or (None,) # Inline constraints are already detected in # _parse_table_constraints(). The reasons to avoid fetching inline # constraints from `PRAGMA index_list` are: # - Inline constraints can have a different name and information # than what `PRAGMA index_list` gives. # - Not all inline constraints may appear in `PRAGMA index_list`. if not sql: # An inline constraint continue # Get the index info for that index cursor.execute( "PRAGMA index_info(%s)" % self.connection.ops.quote_name(index) ) for index_rank, column_rank, column in cursor.fetchall(): if index not in constraints: constraints[index] = { "columns": [], "primary_key": False, "unique": bool(unique), "foreign_key": None, "check": False, "index": True, } constraints[index]["columns"].append(column) # Add type and column orders for indexes if constraints[index]["index"]: # SQLite doesn't support any index type other than b-tree constraints[index]["type"] = Index.suffix orders = self._get_index_columns_orders(sql) if orders is not None: constraints[index]["orders"] = orders # Get the PK pk_columns = self.get_primary_key_columns(cursor, table_name) if pk_columns: # SQLite doesn't actually give a name to the PK constraint, # so we invent one. This is fine, as the SQLite backend never # deletes PK constraints by name, as you can't delete constraints # in SQLite; we remake the table with a new PK instead. constraints["__primary__"] = { "columns": pk_columns, "primary_key": True, "unique": False, # It's not actually a unique constraint. "foreign_key": None, "check": False, "index": False, } relations = enumerate(self.get_relations(cursor, table_name).items()) constraints.update( { f"fk_{index}": { "columns": [column_name], "primary_key": False, "unique": False, "foreign_key": (ref_table_name, ref_column_name), "check": False, "index": False, } for index, ( column_name, (ref_column_name, ref_table_name, _), ) in relations } ) return constraints def _get_index_columns_orders(self, sql): tokens = sqlparse.parse(sql)[0] for token in tokens: if isinstance(token, sqlparse.sql.Parenthesis): columns = str(token).strip("()").split(", ") return ["DESC" if info.endswith("DESC") else "ASC" for info in columns] return None def _get_column_collations(self, cursor, table_name): row = cursor.execute( """ SELECT sql FROM sqlite_master WHERE type = 'table' AND name = %s """, [table_name], ).fetchone() if not row: return {} sql = row[0] columns = str(sqlparse.parse(sql)[0][-1]).strip("()").split(", ") collations = {} for column in columns: tokens = column[1:].split() column_name = tokens[0].strip('"') for index, token in enumerate(tokens): if token == "COLLATE": collation = tokens[index + 1] break else: collation = None collations[column_name] = collation return collations
import unittest from django.db import connection from django.test import TransactionTestCase, skipUnlessDBFeature from ..models import Person, Square @unittest.skipUnless(connection.vendor == "oracle", "Oracle tests") class DatabaseSequenceTests(TransactionTestCase): available_apps = [] def test_get_sequences(self): with connection.cursor() as cursor: seqs = connection.introspection.get_sequences( cursor, Square._meta.db_table, Square._meta.local_fields ) self.assertEqual(len(seqs), 1) self.assertIsNotNone(seqs[0]["name"]) self.assertEqual(seqs[0]["table"], Square._meta.db_table) self.assertEqual(seqs[0]["column"], "id") def test_get_sequences_manually_created_index(self): with connection.cursor() as cursor: with connection.schema_editor() as editor: editor._drop_identity(Square._meta.db_table, "id") seqs = connection.introspection.get_sequences( cursor, Square._meta.db_table, Square._meta.local_fields ) self.assertEqual( seqs, [{"table": Square._meta.db_table, "column": "id"}] ) # Recreate model, because adding identity is impossible. editor.delete_model(Square) editor.create_model(Square) @skipUnlessDBFeature("supports_collation_on_charfield") def test_get_table_description_view_default_collation(self): person_table = connection.introspection.identifier_converter( Person._meta.db_table ) first_name_column = connection.ops.quote_name( Person._meta.get_field("first_name").column ) person_view = connection.introspection.identifier_converter("TEST_PERSON_VIEW") with connection.cursor() as cursor: cursor.execute( f"CREATE VIEW {person_view} " f"AS SELECT {first_name_column} FROM {person_table}" ) try: columns = connection.introspection.get_table_description( cursor, person_view ) self.assertEqual(len(columns), 1) self.assertIsNone(columns[0].collation) finally: cursor.execute(f"DROP VIEW {person_view}") @skipUnlessDBFeature("supports_collation_on_charfield") def test_get_table_description_materialized_view_non_default_collation(self): person_table = connection.introspection.identifier_converter( Person._meta.db_table ) first_name_column = connection.ops.quote_name( Person._meta.get_field("first_name").column ) person_mview = connection.introspection.identifier_converter( "TEST_PERSON_MVIEW" ) collation = connection.features.test_collations.get("ci") with connection.cursor() as cursor: cursor.execute( f"CREATE MATERIALIZED VIEW {person_mview} " f"DEFAULT COLLATION {collation} " f"AS SELECT {first_name_column} FROM {person_table}" ) try: columns = connection.introspection.get_table_description( cursor, person_mview ) self.assertEqual(len(columns), 1) self.assertIsNotNone(columns[0].collation) self.assertNotEqual(columns[0].collation, collation) finally: cursor.execute(f"DROP MATERIALIZED VIEW {person_mview}")
django
python
from django.db.migrations.operations.base import Operation class TestOperation(Operation): def __init__(self): pass def deconstruct(self): return (self.__class__.__name__, [], {}) @property def reversible(self): return True def state_forwards(self, app_label, state): pass def database_forwards(self, app_label, schema_editor, from_state, to_state): pass def state_backwards(self, app_label, state): pass def database_backwards(self, app_label, schema_editor, from_state, to_state): pass class CreateModel(TestOperation): pass class ArgsOperation(TestOperation): def __init__(self, arg1, arg2): self.arg1, self.arg2 = arg1, arg2 def deconstruct(self): return (self.__class__.__name__, [self.arg1, self.arg2], {}) class KwargsOperation(TestOperation): def __init__(self, kwarg1=None, kwarg2=None): self.kwarg1, self.kwarg2 = kwarg1, kwarg2 def deconstruct(self): kwargs = {} if self.kwarg1 is not None: kwargs["kwarg1"] = self.kwarg1 if self.kwarg2 is not None: kwargs["kwarg2"] = self.kwarg2 return (self.__class__.__name__, [], kwargs) class ArgsKwargsOperation(TestOperation): def __init__(self, arg1, arg2, kwarg1=None, kwarg2=None): self.arg1, self.arg2 = arg1, arg2 self.kwarg1, self.kwarg2 = kwarg1, kwarg2 def deconstruct(self): kwargs = {} if self.kwarg1 is not None: kwargs["kwarg1"] = self.kwarg1 if self.kwarg2 is not None: kwargs["kwarg2"] = self.kwarg2 return ( self.__class__.__name__, [self.arg1, self.arg2], kwargs, ) class ArgsAndKeywordOnlyArgsOperation(ArgsKwargsOperation): def __init__(self, arg1, arg2, *, kwarg1, kwarg2): super().__init__(arg1, arg2, kwarg1=kwarg1, kwarg2=kwarg2) class ExpandArgsOperation(TestOperation): serialization_expand_args = ["arg"] def __init__(self, arg): self.arg = arg def deconstruct(self): return (self.__class__.__name__, [self.arg], {})
import unittest from django.core.management.color import no_style from django.db import connection from django.db.models.expressions import Col from django.db.models.functions import Cast from django.test import SimpleTestCase from ..models import Author, Book, Person, Tag @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL tests.") class PostgreSQLOperationsTests(SimpleTestCase): def test_sql_flush(self): self.assertEqual( connection.ops.sql_flush( no_style(), [Person._meta.db_table, Tag._meta.db_table], ), ['TRUNCATE "backends_person", "backends_tag";'], ) def test_sql_flush_allow_cascade(self): self.assertEqual( connection.ops.sql_flush( no_style(), [Person._meta.db_table, Tag._meta.db_table], allow_cascade=True, ), ['TRUNCATE "backends_person", "backends_tag" CASCADE;'], ) def test_sql_flush_sequences(self): self.assertEqual( connection.ops.sql_flush( no_style(), [Person._meta.db_table, Tag._meta.db_table], reset_sequences=True, ), ['TRUNCATE "backends_person", "backends_tag" RESTART IDENTITY;'], ) def test_sql_flush_sequences_allow_cascade(self): self.assertEqual( connection.ops.sql_flush( no_style(), [Person._meta.db_table, Tag._meta.db_table], reset_sequences=True, allow_cascade=True, ), ['TRUNCATE "backends_person", "backends_tag" RESTART IDENTITY CASCADE;'], ) def test_prepare_join_on_clause_same_type(self): author_table = Author._meta.db_table author_id_field = Author._meta.get_field("id") lhs_expr, rhs_expr = connection.ops.prepare_join_on_clause( author_table, author_id_field, author_table, author_id_field, ) self.assertEqual(lhs_expr, Col(author_table, author_id_field)) self.assertEqual(rhs_expr, Col(author_table, author_id_field)) def test_prepare_join_on_clause_different_types(self): author_table = Author._meta.db_table author_id_field = Author._meta.get_field("id") book_table = Book._meta.db_table book_fk_field = Book._meta.get_field("author") lhs_expr, rhs_expr = connection.ops.prepare_join_on_clause( author_table, author_id_field, book_table, book_fk_field, ) self.assertEqual(lhs_expr, Col(author_table, author_id_field)) self.assertEqual( rhs_expr, Cast(Col(book_table, book_fk_field), author_id_field) )
django
python
import multiprocessing import os import shutil import sqlite3 import sys from pathlib import Path from django.db import NotSupportedError from django.db.backends.base.creation import BaseDatabaseCreation class DatabaseCreation(BaseDatabaseCreation): @staticmethod def is_in_memory_db(database_name): return not isinstance(database_name, Path) and ( database_name == ":memory:" or "mode=memory" in database_name ) def _get_test_db_name(self): test_database_name = self.connection.settings_dict["TEST"]["NAME"] or ":memory:" if test_database_name == ":memory:": return "file:memorydb_%s?mode=memory&cache=shared" % self.connection.alias return test_database_name def _create_test_db(self, verbosity, autoclobber, keepdb=False): test_database_name = self._get_test_db_name() if keepdb: return test_database_name if not self.is_in_memory_db(test_database_name): # Erase the old test database if verbosity >= 1: self.log( "Destroying old test database for alias %s..." % (self._get_database_display_str(verbosity, test_database_name),) ) if os.access(test_database_name, os.F_OK): if not autoclobber: confirm = input( "Type 'yes' if you would like to try deleting the test " "database '%s', or 'no' to cancel: " % test_database_name ) if autoclobber or confirm == "yes": try: os.remove(test_database_name) except Exception as e: self.log("Got an error deleting the old test database: %s" % e) sys.exit(2) else: self.log("Tests cancelled.") sys.exit(1) return test_database_name def get_test_db_clone_settings(self, suffix): orig_settings_dict = self.connection.settings_dict source_database_name = orig_settings_dict["NAME"] or ":memory:" if not self.is_in_memory_db(source_database_name): root, ext = os.path.splitext(source_database_name) return {**orig_settings_dict, "NAME": f"{root}_{suffix}{ext}"} start_method = multiprocessing.get_start_method() if start_method == "fork": return orig_settings_dict if start_method in {"forkserver", "spawn"}: return { **orig_settings_dict, "NAME": f"{self.connection.alias}_{suffix}.sqlite3", } raise NotSupportedError( f"Cloning with start method {start_method!r} is not supported." ) def _clone_test_db(self, suffix, verbosity, keepdb=False): source_database_name = self.connection.settings_dict["NAME"] target_database_name = self.get_test_db_clone_settings(suffix)["NAME"] if not self.is_in_memory_db(source_database_name): # Erase the old test database if os.access(target_database_name, os.F_OK): if keepdb: return if verbosity >= 1: self.log( "Destroying old test database for alias %s..." % ( self._get_database_display_str( verbosity, target_database_name ), ) ) try: os.remove(target_database_name) except Exception as e: self.log("Got an error deleting the old test database: %s" % e) sys.exit(2) try: shutil.copy(source_database_name, target_database_name) except Exception as e: self.log("Got an error cloning the test database: %s" % e) sys.exit(2) # Forking automatically makes a copy of an in-memory database. # Forkserver and spawn require migrating to disk which will be # re-opened in setup_worker_connection. elif multiprocessing.get_start_method() in {"forkserver", "spawn"}: ondisk_db = sqlite3.connect(target_database_name, uri=True) self.connection.connection.backup(ondisk_db) ondisk_db.close() def _destroy_test_db(self, test_database_name, verbosity): if test_database_name and not self.is_in_memory_db(test_database_name): # Remove the SQLite database file os.remove(test_database_name) def test_db_signature(self): """ Return a tuple that uniquely identifies a test database. This takes into account the special cases of ":memory:" and "" for SQLite since the databases will be distinct despite having the same TEST NAME. See https://www.sqlite.org/inmemorydb.html """ test_database_name = self._get_test_db_name() sig = [self.connection.settings_dict["NAME"]] if self.is_in_memory_db(test_database_name): sig.append(self.connection.alias) else: sig.append(test_database_name) return tuple(sig) def setup_worker_connection(self, _worker_id): settings_dict = self.get_test_db_clone_settings(_worker_id) # connection.settings_dict must be updated in place for changes to be # reflected in django.db.connections. Otherwise new threads would # connect to the default database instead of the appropriate clone. start_method = multiprocessing.get_start_method() if start_method == "fork": # Update settings_dict in place. self.connection.settings_dict.update(settings_dict) self.connection.close() elif start_method in {"forkserver", "spawn"}: alias = self.connection.alias connection_str = ( f"file:memorydb_{alias}_{_worker_id}?mode=memory&cache=shared" ) source_db = self.connection.Database.connect( f"file:{alias}_{_worker_id}.sqlite3?mode=ro", uri=True ) target_db = sqlite3.connect(connection_str, uri=True) source_db.backup(target_db) source_db.close() # Update settings_dict in place. self.connection.settings_dict.update(settings_dict) self.connection.settings_dict["NAME"] = connection_str # Re-open connection to in-memory database before closing copy # connection. self.connection.connect() target_db.close()
import unittest from contextlib import contextmanager from io import StringIO from unittest import mock from django.core.exceptions import ImproperlyConfigured from django.db import DatabaseError, connection from django.db.backends.base.creation import BaseDatabaseCreation from django.test import SimpleTestCase try: from django.db.backends.postgresql.psycopg_any import errors except ImportError: pass else: from django.db.backends.postgresql.creation import DatabaseCreation @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL tests") class DatabaseCreationTests(SimpleTestCase): @contextmanager def changed_test_settings(self, **kwargs): settings = connection.settings_dict["TEST"] saved_values = {} for name in kwargs: if name in settings: saved_values[name] = settings[name] for name, value in kwargs.items(): settings[name] = value try: yield finally: for name in kwargs: if name in saved_values: settings[name] = saved_values[name] else: del settings[name] def check_sql_table_creation_suffix(self, settings, expected): with self.changed_test_settings(**settings): creation = DatabaseCreation(connection) suffix = creation.sql_table_creation_suffix() self.assertEqual(suffix, expected) def test_sql_table_creation_suffix_with_none_settings(self): settings = {"CHARSET": None, "TEMPLATE": None} self.check_sql_table_creation_suffix(settings, "") def test_sql_table_creation_suffix_with_encoding(self): settings = {"CHARSET": "UTF8"} self.check_sql_table_creation_suffix(settings, "WITH ENCODING 'UTF8'") def test_sql_table_creation_suffix_with_template(self): settings = {"TEMPLATE": "template0"} self.check_sql_table_creation_suffix(settings, 'WITH TEMPLATE "template0"') def test_sql_table_creation_suffix_with_encoding_and_template(self): settings = {"CHARSET": "UTF8", "TEMPLATE": "template0"} self.check_sql_table_creation_suffix( settings, '''WITH ENCODING 'UTF8' TEMPLATE "template0"''' ) def test_sql_table_creation_raises_with_collation(self): settings = {"COLLATION": "test"} msg = ( "PostgreSQL does not support collation setting at database " "creation time." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): self.check_sql_table_creation_suffix(settings, None) def _execute_raise_database_already_exists(self, cursor, parameters, keepdb=False): error = errors.DuplicateDatabase( "database %s already exists" % parameters["dbname"] ) raise DatabaseError() from error def _execute_raise_permission_denied(self, cursor, parameters, keepdb=False): error = errors.InsufficientPrivilege("permission denied to create database") raise DatabaseError() from error def patch_test_db_creation(self, execute_create_test_db): return mock.patch.object( BaseDatabaseCreation, "_execute_create_test_db", execute_create_test_db ) @mock.patch("sys.stdout", new_callable=StringIO) @mock.patch("sys.stderr", new_callable=StringIO) def test_create_test_db(self, *mocked_objects): creation = DatabaseCreation(connection) # Simulate test database creation raising "database already exists" with self.patch_test_db_creation(self._execute_raise_database_already_exists): with mock.patch("builtins.input", return_value="no"): with self.assertRaises(SystemExit): # SystemExit is raised if the user answers "no" to the # prompt asking if it's okay to delete the test database. creation._create_test_db( verbosity=0, autoclobber=False, keepdb=False ) # "Database already exists" error is ignored when keepdb is on creation._create_test_db(verbosity=0, autoclobber=False, keepdb=True) # Simulate test database creation raising unexpected error with self.patch_test_db_creation(self._execute_raise_permission_denied): with mock.patch.object( DatabaseCreation, "_database_exists", return_value=False ): with self.assertRaises(SystemExit): creation._create_test_db( verbosity=0, autoclobber=False, keepdb=False ) with self.assertRaises(SystemExit): creation._create_test_db( verbosity=0, autoclobber=False, keepdb=True ) # Simulate test database creation raising "insufficient privileges". # An error shouldn't appear when keepdb is on and the database already # exists. with self.patch_test_db_creation(self._execute_raise_permission_denied): with mock.patch.object( DatabaseCreation, "_database_exists", return_value=True ): creation._create_test_db(verbosity=0, autoclobber=False, keepdb=True)
django
python
from collections import namedtuple import sqlparse from django.db import DatabaseError from django.db.backends.base.introspection import BaseDatabaseIntrospection from django.db.backends.base.introspection import FieldInfo as BaseFieldInfo from django.db.backends.base.introspection import TableInfo from django.db.models import Index from django.utils.regex_helper import _lazy_re_compile FieldInfo = namedtuple( "FieldInfo", [*BaseFieldInfo._fields, "pk", "has_json_constraint"] ) field_size_re = _lazy_re_compile(r"^\s*(?:var)?char\s*\(\s*(\d+)\s*\)\s*$") def get_field_size(name): """Extract the size number from a "varchar(11)" type name""" m = field_size_re.search(name) return int(m[1]) if m else None # This light wrapper "fakes" a dictionary interface, because some SQLite data # types include variables in them -- e.g. "varchar(30)" -- and can't be matched # as a simple dictionary lookup. class FlexibleFieldLookupDict: # Maps SQL types to Django Field types. Some of the SQL types have multiple # entries here because SQLite allows for anything and doesn't normalize the # field type; it uses whatever was given. base_data_types_reverse = { "bool": "BooleanField", "boolean": "BooleanField", "smallint": "SmallIntegerField", "smallint unsigned": "PositiveSmallIntegerField", "smallinteger": "SmallIntegerField", "int": "IntegerField", "integer": "IntegerField", "bigint": "BigIntegerField", "integer unsigned": "PositiveIntegerField", "bigint unsigned": "PositiveBigIntegerField", "decimal": "DecimalField", "real": "FloatField", "text": "TextField", "char": "CharField", "varchar": "CharField", "blob": "BinaryField", "date": "DateField", "datetime": "DateTimeField", "time": "TimeField", } def __getitem__(self, key): key = key.lower().split("(", 1)[0].strip() return self.base_data_types_reverse[key] class DatabaseIntrospection(BaseDatabaseIntrospection): data_types_reverse = FlexibleFieldLookupDict() def get_field_type(self, data_type, description): field_type = super().get_field_type(data_type, description) if description.pk and field_type in { "BigIntegerField", "IntegerField", "SmallIntegerField", }: # No support for BigAutoField or SmallAutoField as SQLite treats # all integer primary keys as signed 64-bit integers. return "AutoField" if description.has_json_constraint: return "JSONField" return field_type def get_table_list(self, cursor): """Return a list of table and view names in the current database.""" # Skip the sqlite_sequence system table used for autoincrement key # generation. cursor.execute( """ SELECT name, type FROM sqlite_master WHERE type in ('table', 'view') AND NOT name='sqlite_sequence' ORDER BY name""" ) return [TableInfo(row[0], row[1][0]) for row in cursor.fetchall()] def get_table_description(self, cursor, table_name): """ Return a description of the table with the DB-API cursor.description interface. """ cursor.execute( "PRAGMA table_xinfo(%s)" % self.connection.ops.quote_name(table_name) ) table_info = cursor.fetchall() if not table_info: raise DatabaseError(f"Table {table_name} does not exist (empty pragma).") collations = self._get_column_collations(cursor, table_name) json_columns = set() if self.connection.features.can_introspect_json_field: for line in table_info: column = line[1] json_constraint_sql = '%%json_valid("%s")%%' % column has_json_constraint = cursor.execute( """ SELECT sql FROM sqlite_master WHERE type = 'table' AND name = %s AND sql LIKE %s """, [table_name, json_constraint_sql], ).fetchone() if has_json_constraint: json_columns.add(column) table_description = [ FieldInfo( name, data_type, get_field_size(data_type), None, None, None, not notnull, default, collations.get(name), bool(pk), name in json_columns, ) for cid, name, data_type, notnull, default, pk, hidden in table_info if hidden in [ 0, # Normal column. 2, # Virtual generated column. 3, # Stored generated column. ] ] # If the primary key is composed of multiple columns they should not # be individually marked as pk. primary_key = [ index for index, field_info in enumerate(table_description) if field_info.pk ] if len(primary_key) > 1: for index in primary_key: table_description[index] = table_description[index]._replace(pk=False) return table_description def get_sequences(self, cursor, table_name, table_fields=()): pk_col = self.get_primary_key_column(cursor, table_name) return [{"table": table_name, "column": pk_col}] def get_relations(self, cursor, table_name): """ Return a dictionary of {column_name: (ref_column_name, ref_table_name, db_on_delete)} representing all foreign keys in the given table. """ cursor.execute( "PRAGMA foreign_key_list(%s)" % self.connection.ops.quote_name(table_name) ) return { column_name: ( ref_column_name, ref_table_name, self.on_delete_types.get(on_delete), ) for ( _, _, ref_table_name, column_name, ref_column_name, _, on_delete, *_, ) in cursor.fetchall() } def get_primary_key_columns(self, cursor, table_name): cursor.execute( "PRAGMA table_info(%s)" % self.connection.ops.quote_name(table_name) ) return [name for _, name, *_, pk in cursor.fetchall() if pk] def _parse_column_or_constraint_definition(self, tokens, columns): token = None is_constraint_definition = None field_name = None constraint_name = None unique = False unique_columns = [] check = False check_columns = [] braces_deep = 0 for token in tokens: if token.match(sqlparse.tokens.Punctuation, "("): braces_deep += 1 elif token.match(sqlparse.tokens.Punctuation, ")"): braces_deep -= 1 if braces_deep < 0: # End of columns and constraints for table definition. break elif braces_deep == 0 and token.match(sqlparse.tokens.Punctuation, ","): # End of current column or constraint definition. break # Detect column or constraint definition by first token. if is_constraint_definition is None: is_constraint_definition = token.match( sqlparse.tokens.Keyword, "CONSTRAINT" ) if is_constraint_definition: continue if is_constraint_definition: # Detect constraint name by second token. if constraint_name is None: if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): constraint_name = token.value elif token.ttype == sqlparse.tokens.Literal.String.Symbol: constraint_name = token.value[1:-1] # Start constraint columns parsing after UNIQUE keyword. if token.match(sqlparse.tokens.Keyword, "UNIQUE"): unique = True unique_braces_deep = braces_deep elif unique: if unique_braces_deep == braces_deep: if unique_columns: # Stop constraint parsing. unique = False continue if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): unique_columns.append(token.value) elif token.ttype == sqlparse.tokens.Literal.String.Symbol: unique_columns.append(token.value[1:-1]) else: # Detect field name by first token. if field_name is None: if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): field_name = token.value elif token.ttype == sqlparse.tokens.Literal.String.Symbol: field_name = token.value[1:-1] if token.match(sqlparse.tokens.Keyword, "UNIQUE"): unique_columns = [field_name] # Start constraint columns parsing after CHECK keyword. if token.match(sqlparse.tokens.Keyword, "CHECK"): check = True check_braces_deep = braces_deep elif check: if check_braces_deep == braces_deep: if check_columns: # Stop constraint parsing. check = False continue if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): if token.value in columns: check_columns.append(token.value) elif token.ttype == sqlparse.tokens.Literal.String.Symbol: if token.value[1:-1] in columns: check_columns.append(token.value[1:-1]) unique_constraint = ( { "unique": True, "columns": unique_columns, "primary_key": False, "foreign_key": None, "check": False, "index": False, } if unique_columns else None ) check_constraint = ( { "check": True, "columns": check_columns, "primary_key": False, "unique": False, "foreign_key": None, "index": False, } if check_columns else None ) return constraint_name, unique_constraint, check_constraint, token def _parse_table_constraints(self, sql, columns): # Check constraint parsing is based of SQLite syntax diagram. # https://www.sqlite.org/syntaxdiagrams.html#table-constraint statement = sqlparse.parse(sql)[0] constraints = {} unnamed_constrains_index = 0 tokens = (token for token in statement.flatten() if not token.is_whitespace) # Go to columns and constraint definition for token in tokens: if token.match(sqlparse.tokens.Punctuation, "("): break # Parse columns and constraint definition while True: ( constraint_name, unique, check, end_token, ) = self._parse_column_or_constraint_definition(tokens, columns) if unique: if constraint_name: constraints[constraint_name] = unique else: unnamed_constrains_index += 1 constraints[ "__unnamed_constraint_%s__" % unnamed_constrains_index ] = unique if check: if constraint_name: constraints[constraint_name] = check else: unnamed_constrains_index += 1 constraints[ "__unnamed_constraint_%s__" % unnamed_constrains_index ] = check if end_token.match(sqlparse.tokens.Punctuation, ")"): break return constraints def get_constraints(self, cursor, table_name): """ Retrieve any constraints or keys (unique, pk, fk, check, index) across one or more columns. """ constraints = {} # Find inline check constraints. try: table_schema = cursor.execute( "SELECT sql FROM sqlite_master WHERE type='table' and name=%s", [table_name], ).fetchone()[0] except TypeError: # table_name is a view. pass else: columns = { info.name for info in self.get_table_description(cursor, table_name) } constraints.update(self._parse_table_constraints(table_schema, columns)) # Get the index info cursor.execute( "PRAGMA index_list(%s)" % self.connection.ops.quote_name(table_name) ) for row in cursor.fetchall(): # Discard last 2 columns. number, index, unique = row[:3] cursor.execute( "SELECT sql FROM sqlite_master WHERE type='index' AND name=%s", [index], ) # There's at most one row. (sql,) = cursor.fetchone() or (None,) # Inline constraints are already detected in # _parse_table_constraints(). The reasons to avoid fetching inline # constraints from `PRAGMA index_list` are: # - Inline constraints can have a different name and information # than what `PRAGMA index_list` gives. # - Not all inline constraints may appear in `PRAGMA index_list`. if not sql: # An inline constraint continue # Get the index info for that index cursor.execute( "PRAGMA index_info(%s)" % self.connection.ops.quote_name(index) ) for index_rank, column_rank, column in cursor.fetchall(): if index not in constraints: constraints[index] = { "columns": [], "primary_key": False, "unique": bool(unique), "foreign_key": None, "check": False, "index": True, } constraints[index]["columns"].append(column) # Add type and column orders for indexes if constraints[index]["index"]: # SQLite doesn't support any index type other than b-tree constraints[index]["type"] = Index.suffix orders = self._get_index_columns_orders(sql) if orders is not None: constraints[index]["orders"] = orders # Get the PK pk_columns = self.get_primary_key_columns(cursor, table_name) if pk_columns: # SQLite doesn't actually give a name to the PK constraint, # so we invent one. This is fine, as the SQLite backend never # deletes PK constraints by name, as you can't delete constraints # in SQLite; we remake the table with a new PK instead. constraints["__primary__"] = { "columns": pk_columns, "primary_key": True, "unique": False, # It's not actually a unique constraint. "foreign_key": None, "check": False, "index": False, } relations = enumerate(self.get_relations(cursor, table_name).items()) constraints.update( { f"fk_{index}": { "columns": [column_name], "primary_key": False, "unique": False, "foreign_key": (ref_table_name, ref_column_name), "check": False, "index": False, } for index, ( column_name, (ref_column_name, ref_table_name, _), ) in relations } ) return constraints def _get_index_columns_orders(self, sql): tokens = sqlparse.parse(sql)[0] for token in tokens: if isinstance(token, sqlparse.sql.Parenthesis): columns = str(token).strip("()").split(", ") return ["DESC" if info.endswith("DESC") else "ASC" for info in columns] return None def _get_column_collations(self, cursor, table_name): row = cursor.execute( """ SELECT sql FROM sqlite_master WHERE type = 'table' AND name = %s """, [table_name], ).fetchone() if not row: return {} sql = row[0] columns = str(sqlparse.parse(sql)[0][-1]).strip("()").split(", ") collations = {} for column in columns: tokens = column[1:].split() column_name = tokens[0].strip('"') for index, token in enumerate(tokens): if token == "COLLATE": collation = tokens[index + 1] break else: collation = None collations[column_name] = collation return collations
import unittest from django.db import connection from django.test import TestCase from ..models import Person @unittest.skipUnless(connection.vendor == "postgresql", "Test only for PostgreSQL") class DatabaseSequenceTests(TestCase): def test_get_sequences(self): with connection.cursor() as cursor: seqs = connection.introspection.get_sequences(cursor, Person._meta.db_table) self.assertEqual( seqs, [ { "table": Person._meta.db_table, "column": "id", "name": "backends_person_id_seq", } ], ) cursor.execute("ALTER SEQUENCE backends_person_id_seq RENAME TO pers_seq") seqs = connection.introspection.get_sequences(cursor, Person._meta.db_table) self.assertEqual( seqs, [{"table": Person._meta.db_table, "column": "id", "name": "pers_seq"}], ) def test_get_sequences_old_serial(self): with connection.cursor() as cursor: cursor.execute("CREATE TABLE testing (serial_field SERIAL);") seqs = connection.introspection.get_sequences(cursor, "testing") self.assertEqual( seqs, [ { "table": "testing", "column": "serial_field", "name": "testing_serial_field_seq", } ], )
django
python
from django.core.cache.backends.locmem import LocMemCache class CacheClass(LocMemCache): def set(self, *args, **kwargs): raise Exception("Faked exception saving to cache") async def aset(self, *args, **kwargs): raise Exception("Faked exception saving to cache")
from unittest import mock from asgiref.sync import iscoroutinefunction from django.http import HttpRequest, HttpResponse from django.test import SimpleTestCase from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_control, cache_page, never_cache class HttpRequestProxy: def __init__(self, request): self._request = request def __getattr__(self, attr): """Proxy to the underlying HttpRequest object.""" return getattr(self._request, attr) class CacheControlDecoratorTest(SimpleTestCase): def test_wrapped_sync_function_is_not_coroutine_function(self): def sync_view(request): return HttpResponse() wrapped_view = cache_control()(sync_view) self.assertIs(iscoroutinefunction(wrapped_view), False) def test_wrapped_async_function_is_coroutine_function(self): async def async_view(request): return HttpResponse() wrapped_view = cache_control()(async_view) self.assertIs(iscoroutinefunction(wrapped_view), True) def test_cache_control_decorator_http_request(self): class MyClass: @cache_control(a="b") def a_view(self, request): return HttpResponse() msg = ( "cache_control didn't receive an HttpRequest. If you are " "decorating a classmethod, be sure to use @method_decorator." ) request = HttpRequest() with self.assertRaisesMessage(TypeError, msg): MyClass().a_view(request) with self.assertRaisesMessage(TypeError, msg): MyClass().a_view(HttpRequestProxy(request)) async def test_cache_control_decorator_http_request_async_view(self): class MyClass: @cache_control(a="b") async def async_view(self, request): return HttpResponse() msg = ( "cache_control didn't receive an HttpRequest. If you are decorating a " "classmethod, be sure to use @method_decorator." ) request = HttpRequest() with self.assertRaisesMessage(TypeError, msg): await MyClass().async_view(request) with self.assertRaisesMessage(TypeError, msg): await MyClass().async_view(HttpRequestProxy(request)) def test_cache_control_decorator_http_request_proxy(self): class MyClass: @method_decorator(cache_control(a="b")) def a_view(self, request): return HttpResponse() request = HttpRequest() response = MyClass().a_view(HttpRequestProxy(request)) self.assertEqual(response.headers["Cache-Control"], "a=b") def test_cache_control_empty_decorator(self): @cache_control() def a_view(request): return HttpResponse() response = a_view(HttpRequest()) self.assertEqual(response.get("Cache-Control"), "") async def test_cache_control_empty_decorator_async_view(self): @cache_control() async def async_view(request): return HttpResponse() response = await async_view(HttpRequest()) self.assertEqual(response.get("Cache-Control"), "") def test_cache_control_full_decorator(self): @cache_control(max_age=123, private=True, public=True, custom=456) def a_view(request): return HttpResponse() response = a_view(HttpRequest()) cache_control_items = response.get("Cache-Control").split(", ") self.assertEqual( set(cache_control_items), {"max-age=123", "private", "public", "custom=456"} ) async def test_cache_control_full_decorator_async_view(self): @cache_control(max_age=123, private=True, public=True, custom=456) async def async_view(request): return HttpResponse() response = await async_view(HttpRequest()) cache_control_items = response.get("Cache-Control").split(", ") self.assertEqual( set(cache_control_items), {"max-age=123", "private", "public", "custom=456"} ) class CachePageDecoratorTest(SimpleTestCase): def test_cache_page(self): def my_view(request): return "response" my_view_cached = cache_page(123)(my_view) self.assertEqual(my_view_cached(HttpRequest()), "response") my_view_cached2 = cache_page(123, key_prefix="test")(my_view) self.assertEqual(my_view_cached2(HttpRequest()), "response") class NeverCacheDecoratorTest(SimpleTestCase): def test_wrapped_sync_function_is_not_coroutine_function(self): def sync_view(request): return HttpResponse() wrapped_view = never_cache(sync_view) self.assertIs(iscoroutinefunction(wrapped_view), False) def test_wrapped_async_function_is_coroutine_function(self): async def async_view(request): return HttpResponse() wrapped_view = never_cache(async_view) self.assertIs(iscoroutinefunction(wrapped_view), True) @mock.patch("time.time") def test_never_cache_decorator_headers(self, mocked_time): @never_cache def a_view(request): return HttpResponse() mocked_time.return_value = 1167616461.0 response = a_view(HttpRequest()) self.assertEqual( response.headers["Expires"], "Mon, 01 Jan 2007 01:54:21 GMT", ) self.assertEqual( response.headers["Cache-Control"], "max-age=0, no-cache, no-store, must-revalidate, private", ) @mock.patch("time.time") async def test_never_cache_decorator_headers_async_view(self, mocked_time): @never_cache async def async_view(request): return HttpResponse() mocked_time.return_value = 1167616461.0 response = await async_view(HttpRequest()) self.assertEqual(response.headers["Expires"], "Mon, 01 Jan 2007 01:54:21 GMT") self.assertEqual( response.headers["Cache-Control"], "max-age=0, no-cache, no-store, must-revalidate, private", ) def test_never_cache_decorator_expires_not_overridden(self): @never_cache def a_view(request): return HttpResponse(headers={"Expires": "tomorrow"}) response = a_view(HttpRequest()) self.assertEqual(response.headers["Expires"], "tomorrow") async def test_never_cache_decorator_expires_not_overridden_async_view(self): @never_cache async def async_view(request): return HttpResponse(headers={"Expires": "tomorrow"}) response = await async_view(HttpRequest()) self.assertEqual(response.headers["Expires"], "tomorrow") def test_never_cache_decorator_http_request(self): class MyClass: @never_cache def a_view(self, request): return HttpResponse() request = HttpRequest() msg = ( "never_cache didn't receive an HttpRequest. If you are decorating " "a classmethod, be sure to use @method_decorator." ) with self.assertRaisesMessage(TypeError, msg): MyClass().a_view(request) with self.assertRaisesMessage(TypeError, msg): MyClass().a_view(HttpRequestProxy(request)) async def test_never_cache_decorator_http_request_async_view(self): class MyClass: @never_cache async def async_view(self, request): return HttpResponse() request = HttpRequest() msg = ( "never_cache didn't receive an HttpRequest. If you are decorating " "a classmethod, be sure to use @method_decorator." ) with self.assertRaisesMessage(TypeError, msg): await MyClass().async_view(request) with self.assertRaisesMessage(TypeError, msg): await MyClass().async_view(HttpRequestProxy(request)) def test_never_cache_decorator_http_request_proxy(self): class MyClass: @method_decorator(never_cache) def a_view(self, request): return HttpResponse() request = HttpRequest() response = MyClass().a_view(HttpRequestProxy(request)) self.assertIn("Cache-Control", response.headers) self.assertIn("Expires", response.headers)
django
python
""" Creates the default Site object. """ from django.apps import apps as global_apps from django.conf import settings from django.core.management.color import no_style from django.db import DEFAULT_DB_ALIAS, connections, router def create_default_site( app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, apps=global_apps, **kwargs, ): try: Site = apps.get_model("sites", "Site") except LookupError: return if not router.allow_migrate_model(using, Site): return if not Site.objects.using(using).exists(): # The default settings set SITE_ID = 1, and some tests in Django's test # suite rely on this value. However, if database sequences are reused # (e.g. in the test suite after flush/syncdb), it isn't guaranteed that # the next id will be 1, so we coerce it. See #15573 and #16353. This # can also crop up outside of tests - see #15346. if verbosity >= 2: print("Creating example.com Site object") Site( pk=getattr(settings, "SITE_ID", 1), domain="example.com", name="example.com" ).save(using=using) # We set an explicit pk instead of relying on auto-incrementation, # so we need to reset the database sequence. See #17415. sequence_sql = connections[using].ops.sequence_reset_sql(no_style(), [Site]) if sequence_sql: if verbosity >= 2: print("Resetting sequence") with connections[using].cursor() as cursor: for command in sequence_sql: cursor.execute(command)
import builtins import getpass import os import sys from datetime import date from io import StringIO from unittest import mock from django.apps import apps from django.conf import settings from django.contrib.auth import get_permission_codename, management from django.contrib.auth.management import ( RenamePermission, create_permissions, get_default_username, ) from django.contrib.auth.management.commands import changepassword, createsuperuser from django.contrib.auth.models import Group, Permission, User from django.contrib.contenttypes.models import ContentType from django.core.management import call_command from django.core.management.base import CommandError from django.db import migrations, models from django.test import TestCase, override_settings from django.test.testcases import TransactionTestCase from django.utils.translation import gettext_lazy as _ from .models import ( CustomUser, CustomUserNonUniqueUsername, CustomUserWithFK, CustomUserWithM2M, CustomUserWithUniqueConstraint, Email, Organization, UserProxy, ) MOCK_INPUT_KEY_TO_PROMPTS = { # @mock_inputs dict key: [expected prompt messages], "bypass": ["Bypass password validation and create user anyway? [y/N]: "], "email": ["Email address: "], "date_of_birth": ["Date of birth: "], "first_name": ["First name: "], "username": [ "Username: ", lambda: "Username (leave blank to use '%s'): " % get_default_username(), ], } def mock_inputs(inputs): """ Decorator to temporarily replace input/getpass to allow interactive createsuperuser. """ def inner(test_func): def wrapper(*args): class mock_getpass: @staticmethod def getpass(prompt=b"Password: ", stream=None): if callable(inputs["password"]): return inputs["password"]() return inputs["password"] def mock_input(prompt): assert "__proxy__" not in prompt response = None for key, val in inputs.items(): if val == "KeyboardInterrupt": raise KeyboardInterrupt # get() fallback because sometimes 'key' is the actual # prompt rather than a shortcut name. prompt_msgs = MOCK_INPUT_KEY_TO_PROMPTS.get(key, key) if isinstance(prompt_msgs, list): prompt_msgs = [ msg() if callable(msg) else msg for msg in prompt_msgs ] if prompt in prompt_msgs: if callable(val): response = val() else: response = val break if response is None: raise ValueError("Mock input for %r not found." % prompt) return response old_getpass = createsuperuser.getpass old_input = builtins.input createsuperuser.getpass = mock_getpass builtins.input = mock_input try: test_func(*args) finally: createsuperuser.getpass = old_getpass builtins.input = old_input return wrapper return inner class MockTTY: """ A fake stdin object that pretends to be a TTY to be used in conjunction with mock_inputs. """ def isatty(self): return True class MockInputTests(TestCase): @mock_inputs({"username": "alice"}) def test_input_not_found(self): with self.assertRaisesMessage( ValueError, "Mock input for 'Email address: ' not found." ): call_command("createsuperuser", stdin=MockTTY()) class GetDefaultUsernameTestCase(TestCase): databases = {"default", "other"} def setUp(self): self.old_get_system_username = management.get_system_username def tearDown(self): management.get_system_username = self.old_get_system_username def test_actual_implementation(self): self.assertIsInstance(management.get_system_username(), str) def test_getuser_raises_exception(self): # TODO: Drop ImportError and KeyError when dropping support for PY312. for exc in (ImportError, KeyError, OSError): with self.subTest(exc=str(exc)): with mock.patch("getpass.getuser", side_effect=exc): self.assertEqual(management.get_system_username(), "") def test_simple(self): management.get_system_username = lambda: "joe" self.assertEqual(management.get_default_username(), "joe") def test_existing(self): User.objects.create(username="joe") management.get_system_username = lambda: "joe" self.assertEqual(management.get_default_username(), "") self.assertEqual(management.get_default_username(check_db=False), "joe") def test_i18n(self): # 'Julia' with accented 'u': management.get_system_username = lambda: "J\xfalia" self.assertEqual(management.get_default_username(), "julia") def test_with_database(self): User.objects.create(username="joe") management.get_system_username = lambda: "joe" self.assertEqual(management.get_default_username(), "") self.assertEqual(management.get_default_username(database="other"), "joe") User.objects.using("other").create(username="joe") self.assertEqual(management.get_default_username(database="other"), "") @override_settings( AUTH_PASSWORD_VALIDATORS=[ {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"}, ] ) class ChangepasswordManagementCommandTestCase(TestCase): @classmethod def setUpTestData(cls): cls.user = User.objects.create_user(username="joe", password="qwerty") def setUp(self): self.stdout = StringIO() self.addCleanup(self.stdout.close) self.stderr = StringIO() self.addCleanup(self.stderr.close) @mock.patch.object(getpass, "getpass", return_value="password") def test_get_pass(self, mock_get_pass): call_command("changepassword", username="joe", stdout=self.stdout) self.assertIs(User.objects.get(username="joe").check_password("password"), True) @mock.patch.object(getpass, "getpass", return_value="") def test_get_pass_no_input(self, mock_get_pass): with self.assertRaisesMessage(CommandError, "aborted"): call_command("changepassword", username="joe", stdout=self.stdout) @mock.patch.object(changepassword.Command, "_get_pass", return_value="new_password") def test_system_username(self, mock_get_pass): """The system username is used if --username isn't provided.""" username = getpass.getuser() User.objects.create_user(username=username, password="qwerty") call_command("changepassword", stdout=self.stdout) self.assertIs( User.objects.get(username=username).check_password("new_password"), True ) def test_nonexistent_username(self): with self.assertRaisesMessage(CommandError, "user 'test' does not exist"): call_command("changepassword", username="test", stdout=self.stdout) @mock.patch.object(changepassword.Command, "_get_pass", return_value="not qwerty") def test_that_changepassword_command_changes_joes_password(self, mock_get_pass): """ Executing the changepassword management command should change joe's password """ self.assertTrue(self.user.check_password("qwerty")) call_command("changepassword", username="joe", stdout=self.stdout) command_output = self.stdout.getvalue().strip() self.assertEqual( command_output, "Changing password for user 'joe'\n" "Password changed successfully for user 'joe'", ) self.assertTrue(User.objects.get(username="joe").check_password("not qwerty")) @mock.patch.object( changepassword.Command, "_get_pass", side_effect=lambda *args: str(args) ) def test_that_max_tries_exits_1(self, mock_get_pass): """ A CommandError should be thrown by handle() if the user enters in mismatched passwords three times. """ msg = "Aborting password change for user 'joe' after 3 attempts" with self.assertRaisesMessage(CommandError, msg): call_command( "changepassword", username="joe", stdout=self.stdout, stderr=self.stderr ) @mock.patch.object(changepassword.Command, "_get_pass", return_value="1234567890") def test_password_validation(self, mock_get_pass): """ A CommandError should be raised if the user enters in passwords which fail validation three times. """ abort_msg = "Aborting password change for user 'joe' after 3 attempts" with self.assertRaisesMessage(CommandError, abort_msg): call_command( "changepassword", username="joe", stdout=self.stdout, stderr=self.stderr ) self.assertIn("This password is entirely numeric.", self.stderr.getvalue()) @mock.patch.object(changepassword.Command, "_get_pass", return_value="not qwerty") def test_that_changepassword_command_works_with_nonascii_output( self, mock_get_pass ): """ #21627 -- Executing the changepassword management command should allow non-ASCII characters from the User object representation. """ # 'Julia' with accented 'u': User.objects.create_user(username="J\xfalia", password="qwerty") call_command("changepassword", username="J\xfalia", stdout=self.stdout) class MultiDBChangepasswordManagementCommandTestCase(TestCase): databases = {"default", "other"} @mock.patch.object(changepassword.Command, "_get_pass", return_value="not qwerty") def test_that_changepassword_command_with_database_option_uses_given_db( self, mock_get_pass ): """ changepassword --database should operate on the specified DB. """ user = User.objects.db_manager("other").create_user( username="joe", password="qwerty" ) self.assertTrue(user.check_password("qwerty")) out = StringIO() call_command("changepassword", username="joe", database="other", stdout=out) command_output = out.getvalue().strip() self.assertEqual( command_output, "Changing password for user 'joe'\n" "Password changed successfully for user 'joe'", ) self.assertTrue( User.objects.using("other").get(username="joe").check_password("not qwerty") ) @override_settings( SILENCED_SYSTEM_CHECKS=["fields.W342"], # ForeignKey(unique=True) AUTH_PASSWORD_VALIDATORS=[ {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"} ], ) class CreatesuperuserManagementCommandTestCase(TestCase): def test_no_email_argument(self): new_io = StringIO() with self.assertRaisesMessage( CommandError, "You must use --email with --noinput." ): call_command( "createsuperuser", interactive=False, username="joe", stdout=new_io ) def test_basic_usage(self): "Check the operation of the createsuperuser management command" # We can use the management command to create a superuser new_io = StringIO() call_command( "createsuperuser", interactive=False, username="joe", email="[email protected]", stdout=new_io, ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, "Superuser created successfully.") u = User.objects.get(username="joe") self.assertEqual(u.email, "[email protected]") # created password should be unusable self.assertFalse(u.has_usable_password()) def test_validate_username(self): msg = ( "Enter a valid username. This value may contain only letters, numbers, " "and @/./+/-/_ characters." ) with self.assertRaisesMessage(CommandError, msg): call_command( "createsuperuser", interactive=False, username="🤠", email="[email protected]", ) def test_non_ascii_verbose_name(self): @mock_inputs( { "password": "nopasswd", "Uživatel (leave blank to use '%s'): " % get_default_username(): "foo", # username (cz) "email": "[email protected]", } ) def test(self): username_field = User._meta.get_field("username") old_verbose_name = username_field.verbose_name username_field.verbose_name = _("u\u017eivatel") new_io = StringIO() try: call_command( "createsuperuser", interactive=True, stdout=new_io, stdin=MockTTY(), ) finally: username_field.verbose_name = old_verbose_name command_output = new_io.getvalue().strip() self.assertEqual(command_output, "Superuser created successfully.") test(self) def test_verbosity_zero(self): # We can suppress output on the management command new_io = StringIO() call_command( "createsuperuser", interactive=False, username="joe2", email="[email protected]", verbosity=0, stdout=new_io, ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, "") u = User.objects.get(username="joe2") self.assertEqual(u.email, "[email protected]") self.assertFalse(u.has_usable_password()) def test_email_in_username(self): call_command( "createsuperuser", interactive=False, username="[email protected]", email="[email protected]", verbosity=0, ) u = User._default_manager.get(username="[email protected]") self.assertEqual(u.email, "[email protected]") self.assertFalse(u.has_usable_password()) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUser") def test_swappable_user(self): "A superuser can be created when a custom user model is in use" # We can use the management command to create a superuser # We skip validation because the temporary substitution of the # swappable User model messes with validation. new_io = StringIO() call_command( "createsuperuser", interactive=False, email="[email protected]", date_of_birth="1976-04-01", first_name="Joe", stdout=new_io, ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, "Superuser created successfully.") u = CustomUser._default_manager.get(email="[email protected]") self.assertEqual(u.date_of_birth, date(1976, 4, 1)) # created password should be unusable self.assertFalse(u.has_usable_password()) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUser") def test_swappable_user_missing_required_field(self): """ A Custom superuser won't be created when a required field isn't provided """ # We can use the management command to create a superuser # We skip validation because the temporary substitution of the # swappable User model messes with validation. new_io = StringIO() with self.assertRaisesMessage( CommandError, "You must use --email with --noinput." ): call_command( "createsuperuser", interactive=False, stdout=new_io, stderr=new_io, ) self.assertEqual(CustomUser._default_manager.count(), 0) @override_settings( AUTH_USER_MODEL="auth_tests.CustomUserNonUniqueUsername", AUTHENTICATION_BACKENDS=["my.custom.backend"], ) def test_swappable_user_username_non_unique(self): @mock_inputs( { "username": "joe", "password": "nopasswd", } ) def createsuperuser(): new_io = StringIO() call_command( "createsuperuser", interactive=True, email="[email protected]", stdout=new_io, stdin=MockTTY(), ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, "Superuser created successfully.") for i in range(2): createsuperuser() users = CustomUserNonUniqueUsername.objects.filter(username="joe") self.assertEqual(users.count(), 2) def test_skip_if_not_in_TTY(self): """ If the command is not called from a TTY, it should be skipped and a message should be displayed (#7423). """ class FakeStdin: """A fake stdin object that has isatty() return False.""" def isatty(self): return False out = StringIO() call_command( "createsuperuser", stdin=FakeStdin(), stdout=out, interactive=True, ) self.assertEqual(User._default_manager.count(), 0) self.assertIn("Superuser creation skipped", out.getvalue()) def test_passing_stdin(self): """ You can pass a stdin object as an option and it should be available on self.stdin. If no such option is passed, it defaults to sys.stdin. """ sentinel = object() command = createsuperuser.Command() call_command( command, stdin=sentinel, interactive=False, verbosity=0, username="janet", email="[email protected]", ) self.assertIs(command.stdin, sentinel) command = createsuperuser.Command() call_command( command, interactive=False, verbosity=0, username="joe", email="[email protected]", ) self.assertIs(command.stdin, sys.stdin) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithFK") def test_fields_with_fk(self): new_io = StringIO() group = Group.objects.create(name="mygroup") email = Email.objects.create(email="[email protected]") call_command( "createsuperuser", interactive=False, username=email.pk, email=email.email, group=group.pk, stdout=new_io, ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, "Superuser created successfully.") u = CustomUserWithFK._default_manager.get(email=email) self.assertEqual(u.username, email) self.assertEqual(u.group, group) non_existent_email = "[email protected]" msg = "email instance with email %r is not a valid choice." % non_existent_email with self.assertRaisesMessage(CommandError, msg): call_command( "createsuperuser", interactive=False, username=email.pk, email=non_existent_email, stdout=new_io, ) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithFK") def test_fields_with_fk_interactive(self): new_io = StringIO() group = Group.objects.create(name="mygroup") email = Email.objects.create(email="[email protected]") @mock_inputs( { "password": "nopasswd", "Username (Email.id): ": email.pk, "Email (Email.email): ": email.email, "Group (Group.id): ": group.pk, } ) def test(self): call_command( "createsuperuser", interactive=True, stdout=new_io, stdin=MockTTY(), ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, "Superuser created successfully.") u = CustomUserWithFK._default_manager.get(email=email) self.assertEqual(u.username, email) self.assertEqual(u.group, group) test(self) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithFK") def test_fields_with_fk_via_option_interactive(self): new_io = StringIO() group = Group.objects.create(name="mygroup") email = Email.objects.create(email="[email protected]") @mock_inputs({"password": "nopasswd"}) def test(self): call_command( "createsuperuser", interactive=True, username=email.pk, email=email.email, group=group.pk, stdout=new_io, stdin=MockTTY(), ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, "Superuser created successfully.") u = CustomUserWithFK._default_manager.get(email=email) self.assertEqual(u.username, email) self.assertEqual(u.group, group) test(self) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithFK") def test_validate_fk(self): email = Email.objects.create(email="[email protected]") Group.objects.all().delete() nonexistent_group_id = 1 msg = f"group instance with id {nonexistent_group_id} is not a valid choice." with self.assertRaisesMessage(CommandError, msg): call_command( "createsuperuser", interactive=False, username=email.pk, email=email.email, group=nonexistent_group_id, verbosity=0, ) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithFK") def test_validate_fk_environment_variable(self): email = Email.objects.create(email="[email protected]") Group.objects.all().delete() nonexistent_group_id = 1 msg = f"group instance with id {nonexistent_group_id} is not a valid choice." with mock.patch.dict( os.environ, {"DJANGO_SUPERUSER_GROUP": str(nonexistent_group_id)}, ): with self.assertRaisesMessage(CommandError, msg): call_command( "createsuperuser", interactive=False, username=email.pk, email=email.email, verbosity=0, ) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithFK") def test_validate_fk_via_option_interactive(self): email = Email.objects.create(email="[email protected]") Group.objects.all().delete() nonexistent_group_id = 1 msg = f"group instance with id {nonexistent_group_id} is not a valid choice." @mock_inputs( { "password": "nopasswd", "Username (Email.id): ": email.pk, "Email (Email.email): ": email.email, } ) def test(self): with self.assertRaisesMessage(CommandError, msg): call_command( "createsuperuser", group=nonexistent_group_id, stdin=MockTTY(), verbosity=0, ) test(self) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithM2m") def test_fields_with_m2m(self): new_io = StringIO() org_id_1 = Organization.objects.create(name="Organization 1").pk org_id_2 = Organization.objects.create(name="Organization 2").pk call_command( "createsuperuser", interactive=False, username="joe", orgs=[org_id_1, org_id_2], stdout=new_io, ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, "Superuser created successfully.") user = CustomUserWithM2M._default_manager.get(username="joe") self.assertEqual(user.orgs.count(), 2) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithM2M") def test_fields_with_m2m_interactive(self): new_io = StringIO() org_id_1 = Organization.objects.create(name="Organization 1").pk org_id_2 = Organization.objects.create(name="Organization 2").pk @mock_inputs( { "password": "nopasswd", "Username: ": "joe", "Orgs (Organization.id): ": "%s, %s" % (org_id_1, org_id_2), } ) def test(self): call_command( "createsuperuser", interactive=True, stdout=new_io, stdin=MockTTY(), ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, "Superuser created successfully.") user = CustomUserWithM2M._default_manager.get(username="joe") self.assertEqual(user.orgs.count(), 2) test(self) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithM2M") def test_fields_with_m2m_interactive_blank(self): new_io = StringIO() org_id = Organization.objects.create(name="Organization").pk entered_orgs = [str(org_id), " "] def return_orgs(): return entered_orgs.pop() @mock_inputs( { "password": "nopasswd", "Username: ": "joe", "Orgs (Organization.id): ": return_orgs, } ) def test(self): call_command( "createsuperuser", interactive=True, stdout=new_io, stderr=new_io, stdin=MockTTY(), ) self.assertEqual( new_io.getvalue().strip(), "Error: This field cannot be blank.\n" "Superuser created successfully.", ) test(self) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithM2MThrough") def test_fields_with_m2m_and_through(self): msg = ( "Required field 'orgs' specifies a many-to-many relation through " "model, which is not supported." ) with self.assertRaisesMessage(CommandError, msg): call_command("createsuperuser") def test_default_username(self): """createsuperuser uses a default username when one isn't provided.""" # Get the default username before creating a user. default_username = get_default_username() new_io = StringIO() entered_passwords = ["password", "password"] def return_passwords(): return entered_passwords.pop(0) @mock_inputs({"password": return_passwords, "username": "", "email": ""}) def test(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "Superuser created successfully." ) self.assertTrue(User.objects.filter(username=default_username).exists()) test(self) def test_password_validation(self): """ Creation should fail if the password fails validation. """ new_io = StringIO() entered_passwords = ["1234567890", "1234567890", "password", "password"] def bad_then_good_password(): return entered_passwords.pop(0) @mock_inputs( { "password": bad_then_good_password, "username": "joe1234567890", "email": "", "bypass": "n", } ) def test(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "This password is entirely numeric.\n" "Superuser created successfully.", ) test(self) @override_settings( AUTH_PASSWORD_VALIDATORS=[ { "NAME": ( "django.contrib.auth.password_validation." "UserAttributeSimilarityValidator" ) }, ] ) def test_validate_password_against_username(self): new_io = StringIO() username = "supremelycomplex" entered_passwords = [ username, username, "superduperunguessablepassword", "superduperunguessablepassword", ] def bad_then_good_password(): return entered_passwords.pop(0) @mock_inputs( { "password": bad_then_good_password, "username": username, "email": "", "bypass": "n", } ) def test(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "The password is too similar to the username.\n" "Superuser created successfully.", ) test(self) @override_settings( AUTH_USER_MODEL="auth_tests.CustomUser", AUTH_PASSWORD_VALIDATORS=[ { "NAME": ( "django.contrib.auth.password_validation." "UserAttributeSimilarityValidator" ) }, ], ) def test_validate_password_against_required_fields(self): new_io = StringIO() first_name = "josephine" entered_passwords = [ first_name, first_name, "superduperunguessablepassword", "superduperunguessablepassword", ] def bad_then_good_password(): return entered_passwords.pop(0) @mock_inputs( { "password": bad_then_good_password, "username": "whatever", "first_name": first_name, "date_of_birth": "1970-01-01", "email": "[email protected]", "bypass": "n", } ) def test(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "The password is too similar to the first name.\n" "Superuser created successfully.", ) test(self) @override_settings( AUTH_USER_MODEL="auth_tests.CustomUser", AUTH_PASSWORD_VALIDATORS=[ { "NAME": ( "django.contrib.auth.password_validation." "UserAttributeSimilarityValidator" ) }, ], ) def test_validate_password_against_required_fields_via_option(self): new_io = StringIO() first_name = "josephine" entered_passwords = [ first_name, first_name, "superduperunguessablepassword", "superduperunguessablepassword", ] def bad_then_good_password(): return entered_passwords.pop(0) @mock_inputs( { "password": bad_then_good_password, "bypass": "n", } ) def test(self): call_command( "createsuperuser", interactive=True, first_name=first_name, date_of_birth="1970-01-01", email="[email protected]", stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "The password is too similar to the first name.\n" "Superuser created successfully.", ) test(self) def test_blank_username(self): """Creation fails if --username is blank.""" new_io = StringIO() with self.assertRaisesMessage(CommandError, "Username cannot be blank."): call_command( "createsuperuser", username="", stdin=MockTTY(), stdout=new_io, stderr=new_io, ) def test_blank_username_non_interactive(self): new_io = StringIO() with self.assertRaisesMessage(CommandError, "Username cannot be blank."): call_command( "createsuperuser", username="", interactive=False, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) def test_blank_email_allowed_non_interactive(self): new_io = StringIO() call_command( "createsuperuser", email="", username="joe", interactive=False, stdout=new_io, stderr=new_io, ) self.assertEqual(new_io.getvalue().strip(), "Superuser created successfully.") u = User.objects.get(username="joe") self.assertEqual(u.email, "") @mock.patch.dict(os.environ, {"DJANGO_SUPERUSER_EMAIL": ""}) def test_blank_email_allowed_non_interactive_environment_variable(self): new_io = StringIO() call_command( "createsuperuser", username="joe", interactive=False, stdout=new_io, stderr=new_io, ) self.assertEqual(new_io.getvalue().strip(), "Superuser created successfully.") u = User.objects.get(username="joe") self.assertEqual(u.email, "") def test_password_validation_bypass(self): """ Password validation can be bypassed by entering 'y' at the prompt. """ new_io = StringIO() @mock_inputs( { "password": "1234567890", "username": "joe1234567890", "email": "", "bypass": "y", } ) def test(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "This password is entirely numeric.\n" "Superuser created successfully.", ) test(self) def test_invalid_username(self): """Creation fails if the username fails validation.""" user_field = User._meta.get_field(User.USERNAME_FIELD) new_io = StringIO() entered_passwords = ["password", "password"] # Enter an invalid (too long) username first and then a valid one. invalid_username = ("x" * user_field.max_length) + "y" entered_usernames = [invalid_username, "janet"] def return_passwords(): return entered_passwords.pop(0) def return_usernames(): return entered_usernames.pop(0) @mock_inputs( {"password": return_passwords, "username": return_usernames, "email": ""} ) def test(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "Error: Ensure this value has at most %s characters (it has %s).\n" "Superuser created successfully." % (user_field.max_length, len(invalid_username)), ) test(self) @mock_inputs({"username": "KeyboardInterrupt"}) def test_keyboard_interrupt(self): new_io = StringIO() with self.assertRaises(SystemExit): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual(new_io.getvalue(), "\nOperation cancelled.\n") def test_existing_username(self): """Creation fails if the username already exists.""" user = User.objects.create(username="janet") new_io = StringIO() entered_passwords = ["password", "password"] # Enter the existing username first and then a new one. entered_usernames = [user.username, "joe"] def return_passwords(): return entered_passwords.pop(0) def return_usernames(): return entered_usernames.pop(0) @mock_inputs( {"password": return_passwords, "username": return_usernames, "email": ""} ) def test(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "Error: That username is already taken.\n" "Superuser created successfully.", ) test(self) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithUniqueConstraint") def test_existing_username_meta_unique_constraint(self): """ Creation fails if the username already exists and a custom user model has UniqueConstraint. """ user = CustomUserWithUniqueConstraint.objects.create(username="janet") new_io = StringIO() entered_passwords = ["password", "password"] # Enter the existing username first and then a new one. entered_usernames = [user.username, "joe"] def return_passwords(): return entered_passwords.pop(0) def return_usernames(): return entered_usernames.pop(0) @mock_inputs({"password": return_passwords, "username": return_usernames}) def test(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "Error: That username is already taken.\n" "Superuser created successfully.", ) test(self) def test_existing_username_non_interactive(self): """Creation fails if the username already exists.""" User.objects.create(username="janet") new_io = StringIO() with self.assertRaisesMessage( CommandError, "Error: That username is already taken." ): call_command( "createsuperuser", username="janet", email="", interactive=False, stdout=new_io, ) def test_existing_username_provided_via_option_and_interactive(self): """call_command() gets username='janet' and interactive=True.""" new_io = StringIO() entered_passwords = ["password", "password"] User.objects.create(username="janet") def return_passwords(): return entered_passwords.pop(0) @mock_inputs( { "password": return_passwords, "username": "janet1", "email": "[email protected]", } ) def test(self): call_command( "createsuperuser", username="janet", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) msg = ( "Error: That username is already taken.\n" "Superuser created successfully." ) self.assertEqual(new_io.getvalue().strip(), msg) test(self) def test_validation_mismatched_passwords(self): """ Creation should fail if the user enters mismatched passwords. """ new_io = StringIO() # The first two passwords do not match, but the second two do match and # are valid. entered_passwords = ["password", "not password", "password2", "password2"] def mismatched_passwords_then_matched(): return entered_passwords.pop(0) @mock_inputs( { "password": mismatched_passwords_then_matched, "username": "joe1234567890", "email": "", } ) def test(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "Error: Your passwords didn't match.\n" "Superuser created successfully.", ) test(self) def test_validation_blank_password_entered(self): """ Creation should fail if the user enters blank passwords. """ new_io = StringIO() # The first two passwords are empty strings, but the second two are # valid. entered_passwords = ["", "", "password2", "password2"] def blank_passwords_then_valid(): return entered_passwords.pop(0) @mock_inputs( { "password": blank_passwords_then_valid, "username": "joe1234567890", "email": "", } ) def test(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "Error: Blank passwords aren't allowed.\n" "Superuser created successfully.", ) test(self) @override_settings(AUTH_USER_MODEL="auth_tests.NoPasswordUser") def test_usermodel_without_password(self): new_io = StringIO() call_command( "createsuperuser", interactive=False, stdin=MockTTY(), stdout=new_io, stderr=new_io, username="username", ) self.assertEqual(new_io.getvalue().strip(), "Superuser created successfully.") @override_settings(AUTH_USER_MODEL="auth_tests.NoPasswordUser") def test_usermodel_without_password_interactive(self): new_io = StringIO() @mock_inputs({"username": "username"}) def test(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "Superuser created successfully." ) test(self) @mock.patch.dict( os.environ, { "DJANGO_SUPERUSER_PASSWORD": "test_password", "DJANGO_SUPERUSER_USERNAME": "test_superuser", "DJANGO_SUPERUSER_EMAIL": "[email protected]", "DJANGO_SUPERUSER_FIRST_NAME": "ignored_first_name", }, ) def test_environment_variable_non_interactive(self): call_command("createsuperuser", interactive=False, verbosity=0) user = User.objects.get(username="test_superuser") self.assertEqual(user.email, "[email protected]") self.assertTrue(user.check_password("test_password")) # Environment variables are ignored for non-required fields. self.assertEqual(user.first_name, "") @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithM2m") def test_environment_variable_m2m_non_interactive(self): new_io = StringIO() org_id_1 = Organization.objects.create(name="Organization 1").pk org_id_2 = Organization.objects.create(name="Organization 2").pk with mock.patch.dict( os.environ, { "DJANGO_SUPERUSER_ORGS": f"{org_id_1},{org_id_2}", }, ): call_command( "createsuperuser", interactive=False, username="joe", stdout=new_io, ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, "Superuser created successfully.") user = CustomUserWithM2M._default_manager.get(username="joe") self.assertEqual(user.orgs.count(), 2) @mock.patch.dict( os.environ, { "DJANGO_SUPERUSER_USERNAME": "test_superuser", "DJANGO_SUPERUSER_EMAIL": "[email protected]", }, ) def test_ignore_environment_variable_non_interactive(self): # Environment variables are ignored in non-interactive mode, if # provided by a command line arguments. call_command( "createsuperuser", interactive=False, username="cmd_superuser", email="[email protected]", verbosity=0, ) user = User.objects.get(username="cmd_superuser") self.assertEqual(user.email, "[email protected]") self.assertFalse(user.has_usable_password()) @mock.patch.dict( os.environ, { "DJANGO_SUPERUSER_PASSWORD": "test_password", "DJANGO_SUPERUSER_USERNAME": "test_superuser", "DJANGO_SUPERUSER_EMAIL": "[email protected]", }, ) def test_ignore_environment_variable_interactive(self): # Environment variables are ignored in interactive mode. @mock_inputs({"password": "cmd_password"}) def test(self): call_command( "createsuperuser", interactive=True, username="cmd_superuser", email="[email protected]", stdin=MockTTY(), verbosity=0, ) user = User.objects.get(username="cmd_superuser") self.assertEqual(user.email, "[email protected]") self.assertTrue(user.check_password("cmd_password")) test(self) class MultiDBCreatesuperuserTestCase(TestCase): databases = {"default", "other"} def test_createsuperuser_command_with_database_option(self): """ createsuperuser --database should operate on the specified DB. """ new_io = StringIO() call_command( "createsuperuser", interactive=False, username="joe", email="[email protected]", database="other", stdout=new_io, ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, "Superuser created successfully.") user = User.objects.using("other").get(username="joe") self.assertEqual(user.email, "[email protected]") def test_createsuperuser_command_suggested_username_with_database_option(self): default_username = get_default_username(database="other") qs = User.objects.using("other") @mock_inputs({"password": "nopasswd", "username": "", "email": ""}) def test_other_create_with_suggested_username(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), verbosity=0, database="other", ) self.assertIs(qs.filter(username=default_username).exists(), True) test_other_create_with_suggested_username(self) @mock_inputs({"password": "nopasswd", "Username: ": "other", "email": ""}) def test_other_no_suggestion(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), verbosity=0, database="other", ) self.assertIs(qs.filter(username="other").exists(), True) test_other_no_suggestion(self) class CreatePermissionsTests(TestCase): def setUp(self): self._original_permissions = Permission._meta.permissions[:] self._original_default_permissions = Permission._meta.default_permissions self.app_config = apps.get_app_config("auth") def tearDown(self): Permission._meta.permissions = self._original_permissions Permission._meta.default_permissions = self._original_default_permissions ContentType.objects.clear_cache() def test_default_permissions(self): permission_content_type = ContentType.objects.get_by_natural_key( "auth", "permission" ) Permission._meta.permissions = [ ("my_custom_permission", "Some permission"), ] create_permissions(self.app_config, verbosity=0) # view/add/change/delete permission by default + custom permission self.assertEqual( Permission.objects.filter( content_type=permission_content_type, ).count(), 5, ) Permission.objects.filter(content_type=permission_content_type).delete() Permission._meta.default_permissions = [] create_permissions(self.app_config, verbosity=0) # custom permission only since default permissions is empty self.assertEqual( Permission.objects.filter( content_type=permission_content_type, ).count(), 1, ) def test_unavailable_models(self): """ #24075 - Permissions shouldn't be created or deleted if the ContentType or Permission models aren't available. """ state = migrations.state.ProjectState() # Unavailable contenttypes.ContentType with self.assertNumQueries(0): create_permissions(self.app_config, verbosity=0, apps=state.apps) # Unavailable auth.Permission state = migrations.state.ProjectState(real_apps={"contenttypes"}) with self.assertNumQueries(0): create_permissions(self.app_config, verbosity=0, apps=state.apps) def test_create_permissions_checks_contenttypes_created(self): """ `post_migrate` handler ordering isn't guaranteed. Simulate a case where create_permissions() is called before create_contenttypes(). """ # Warm the manager cache. ContentType.objects.get_for_model(Group) # Apply a deletion as if e.g. a database 'flush' had been executed. ContentType.objects.filter(app_label="auth", model="group").delete() # This fails with a foreign key constraint without the fix. create_permissions(apps.get_app_config("auth"), interactive=False, verbosity=0) def test_permission_with_proxy_content_type_created(self): """ A proxy model's permissions use its own content type rather than the content type of the concrete model. """ opts = UserProxy._meta codename = get_permission_codename("add", opts) self.assertTrue( Permission.objects.filter( content_type__model=opts.model_name, content_type__app_label=opts.app_label, codename=codename, ).exists() ) @override_settings( MIGRATION_MODULES=dict( settings.MIGRATION_MODULES, auth_tests="auth_tests.operations_migrations", ), ) class PermissionRenameOperationsTests(TransactionTestCase): available_apps = [ "django.contrib.contenttypes", "django.contrib.auth", "auth_tests", ] databases = {"default", "other"} def setUp(self): app_config = apps.get_app_config("auth_tests") models.signals.post_migrate.connect( self.assertOperationsInjected, sender=app_config ) self.addCleanup( models.signals.post_migrate.disconnect, self.assertOperationsInjected, sender=app_config, ) def assertOperationsInjected(self, plan, **kwargs): for migration, _backward in plan: operations = iter(migration.operations) for operation in operations: if isinstance(operation, migrations.RenameModel): next_operation = next(operations) self.assertIsInstance(next_operation, RenamePermission) self.assertEqual(next_operation.app_label, migration.app_label) self.assertEqual(next_operation.old_model, operation.old_name) self.assertEqual(next_operation.new_model, operation.new_name) def test_permission_rename(self): ct = ContentType.objects.create(app_label="auth_tests", model="oldmodel") actions = ["add", "change", "delete", "view"] for action in actions: Permission.objects.create( codename=f"{action}_oldmodel", name=f"Can {action} old model", content_type=ct, ) call_command("migrate", "auth_tests", verbosity=0) for action in actions: self.assertFalse( Permission.objects.filter(codename=f"{action}_oldmodel").exists() ) self.assertTrue( Permission.objects.filter(codename=f"{action}_newmodel").exists() ) call_command( "migrate", "auth_tests", "zero", database="default", interactive=False, verbosity=0, ) for action in actions: self.assertTrue( Permission.objects.filter(codename=f"{action}_oldmodel").exists() ) self.assertFalse( Permission.objects.filter(codename=f"{action}_newmodel").exists() ) def test_permission_rename_other_db(self): ct = ContentType.objects.using("default").create( app_label="auth_tests", model="oldmodel" ) permission = Permission.objects.using("default").create( codename="add_oldmodel", name="Can add old model", content_type=ct, ) # RenamePermission respects the database. call_command("migrate", "auth_tests", verbosity=0, database="other") permission.refresh_from_db() self.assertEqual(permission.codename, "add_oldmodel") self.assertFalse( Permission.objects.using("other").filter(codename="add_oldmodel").exists() ) self.assertTrue( Permission.objects.using("other").filter(codename="add_newmodel").exists() ) @mock.patch( "django.db.router.allow_migrate_model", return_value=False, ) def test_rename_skipped_if_router_disallows(self, _): ct = ContentType.objects.create(app_label="auth_tests", model="oldmodel") Permission.objects.create( codename="change_oldmodel", name="Can change old model", content_type=ct, ) # The rename operation should not be there when disallowed by router. app_config = apps.get_app_config("auth_tests") models.signals.post_migrate.disconnect( self.assertOperationsInjected, sender=app_config ) call_command( "migrate", "auth_tests", database="default", interactive=False, verbosity=0, ) self.assertTrue(Permission.objects.filter(codename="change_oldmodel").exists()) self.assertFalse(Permission.objects.filter(codename="change_newmodel").exists()) call_command( "migrate", "auth_tests", "zero", database="default", interactive=False, verbosity=0, ) def test_rename_backward_does_nothing_if_no_permissions(self): Permission.objects.filter(content_type__app_label="auth_tests").delete() call_command( "migrate", "auth_tests", "zero", database="default", interactive=False, verbosity=0, ) self.assertFalse( Permission.objects.filter( codename__in=["change_oldmodel", "change_newmodel"] ).exists() ) def test_rename_permission_conflict(self): ct = ContentType.objects.create(app_label="auth_tests", model="oldmodel") Permission.objects.create( codename="change_newmodel", name="Can change new model", content_type=ct, ) Permission.objects.create( codename="change_oldmodel", name="Can change old model", content_type=ct, ) call_command( "migrate", "auth_tests", database="default", interactive=False, verbosity=0, ) self.assertTrue( Permission.objects.filter( codename="change_oldmodel", name="Can change old model", ).exists() ) self.assertEqual( Permission.objects.filter( codename="change_newmodel", name="Can change new model", ).count(), 1, ) call_command( "migrate", "auth_tests", "zero", database="default", interactive=False, verbosity=0, ) class DefaultDBRouter: """Route all writes to default.""" def db_for_write(self, model, **hints): return "default" @override_settings(DATABASE_ROUTERS=[DefaultDBRouter()]) class CreatePermissionsMultipleDatabasesTests(TestCase): databases = {"default", "other"} def test_set_permissions_fk_to_using_parameter(self): Permission.objects.using("other").delete() with self.assertNumQueries(4, using="other") as captured_queries: create_permissions(apps.get_app_config("auth"), verbosity=0, using="other") self.assertIn("INSERT INTO", captured_queries[-1]["sql"].upper()) self.assertGreater(Permission.objects.using("other").count(), 0)
django
python
import datetime import decimal import logging import sys from pathlib import Path from django.core.exceptions import BadRequest, PermissionDenied, SuspiciousOperation from django.http import Http404, HttpResponse, JsonResponse from django.shortcuts import render from django.template import Context, Template, TemplateDoesNotExist from django.urls import get_resolver from django.views import View from django.views.debug import ( ExceptionReporter, SafeExceptionReporterFilter, technical_500_response, ) from django.views.decorators.debug import sensitive_post_parameters, sensitive_variables TEMPLATES_PATH = Path(__file__).resolve().parent / "templates" def index_page(request): """Dummy index page""" return HttpResponse("<html><body>Dummy page</body></html>") def with_parameter(request, parameter): return HttpResponse("ok") def raises(request): # Make sure that a callable that raises an exception in the stack frame's # local vars won't hijack the technical 500 response (#15025). def callable(): raise Exception try: raise Exception except Exception: return technical_500_response(request, *sys.exc_info()) def raises500(request): # We need to inspect the HTML generated by the fancy 500 debug view but # the test client ignores it, so we send it explicitly. try: raise Exception except Exception: return technical_500_response(request, *sys.exc_info()) class Raises500View(View): def get(self, request): try: raise Exception except Exception: return technical_500_response(request, *sys.exc_info()) def raises400(request): raise SuspiciousOperation def raises400_bad_request(request): raise BadRequest("Malformed request syntax") def raises403(request): raise PermissionDenied("Insufficient Permissions") def raises404(request): resolver = get_resolver(None) resolver.resolve("/not-in-urls") def technical404(request): raise Http404("Testing technical 404.") class Http404View(View): def get(self, request): raise Http404("Testing class-based technical 404.") def template_exception(request): return render(request, "debug/template_exception.html") def safestring_in_template_exception(request): """ Trigger an exception in the template machinery which causes a SafeString to be inserted as args[0] of the Exception. """ template = Template('{% extends "<script>alert(1);</script>" %}') try: template.render(Context()) except Exception: return technical_500_response(request, *sys.exc_info()) def jsi18n(request): return render(request, "jsi18n.html") def jsi18n_multi_catalogs(request): return render(request, "jsi18n-multi-catalogs.html") def raises_template_does_not_exist(request, path="i_dont_exist.html"): # We need to inspect the HTML generated by the fancy 500 debug view but # the test client ignores it, so we send it explicitly. try: return render(request, path) except TemplateDoesNotExist: return technical_500_response(request, *sys.exc_info()) def render_no_template(request): # If we do not specify a template, we need to make sure the debug # view doesn't blow up. return render(request, [], {}) def send_log(request, exc_info): logger = logging.getLogger("django") # The default logging config has a logging filter to ensure admin emails # are only sent with DEBUG=False, but since someone might choose to remove # that filter, we still want to be able to test the behavior of error # emails with DEBUG=True. So we need to remove the filter temporarily. admin_email_handler = [ h for h in logger.handlers if h.__class__.__name__ == "AdminEmailHandler" ][0] orig_filters = admin_email_handler.filters admin_email_handler.filters = [] admin_email_handler.include_html = True logger.error( "Internal Server Error: %s", request.path, exc_info=exc_info, extra={"status_code": 500, "request": request}, ) admin_email_handler.filters = orig_filters def non_sensitive_view(request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables("sauce") @sensitive_post_parameters("bacon-key", "sausage-key") def sensitive_view(request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables("sauce") @sensitive_post_parameters("bacon-key", "sausage-key") async def async_sensitive_view(request): # Do not just use plain strings for the variables' values in the code so # that the tests don't return false positives when the function's source is # displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables("sauce") @sensitive_post_parameters("bacon-key", "sausage-key") async def async_sensitive_function(request): # Do not just use plain strings for the variables' values in the code so # that the tests don't return false positives when the function's source is # displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) raise Exception async def async_sensitive_view_nested(request): try: await async_sensitive_function(request) except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables() @sensitive_post_parameters() def paranoid_view(request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) def sensitive_args_function_caller(request): try: sensitive_args_function( "".join( ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) ) except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables("sauce") def sensitive_args_function(sauce): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA raise Exception def sensitive_kwargs_function_caller(request): try: sensitive_kwargs_function( "".join( ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) ) except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables("sauce") def sensitive_kwargs_function(sauce=None): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA raise Exception class UnsafeExceptionReporterFilter(SafeExceptionReporterFilter): """ Ignores all the filtering done by its parent class. """ def get_post_parameters(self, request): return request.POST def get_traceback_frame_variables(self, request, tb_frame): return tb_frame.f_locals.items() @sensitive_variables() @sensitive_post_parameters() def custom_exception_reporter_filter_view(request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) request.exception_reporter_filter = UnsafeExceptionReporterFilter() try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) class CustomExceptionReporter(ExceptionReporter): custom_traceback_text = "custom traceback text" def get_traceback_html(self): return self.custom_traceback_text class TemplateOverrideExceptionReporter(ExceptionReporter): html_template_path = TEMPLATES_PATH / "my_technical_500.html" text_template_path = TEMPLATES_PATH / "my_technical_500.txt" def custom_reporter_class_view(request): request.exception_reporter_class = CustomExceptionReporter try: raise Exception except Exception: exc_info = sys.exc_info() return technical_500_response(request, *exc_info) class Klass: @sensitive_variables("sauce") def method(self, request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's # source is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables("sauce") async def async_method(self, request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's # source is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables("sauce") async def _async_method_inner(self, request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's # source is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) raise Exception async def async_method_nested(self, request): try: await self._async_method_inner(request) except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) def sensitive_method_view(request): return Klass().method(request) async def async_sensitive_method_view(request): return await Klass().async_method(request) async def async_sensitive_method_view_nested(request): return await Klass().async_method_nested(request) @sensitive_variables("sauce") @sensitive_post_parameters("bacon-key", "sausage-key") def multivalue_dict_key_error(request): cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: request.POST["bar"] except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) def json_response_view(request): return JsonResponse( { "a": [1, 2, 3], "foo": {"bar": "baz"}, # Make sure datetime and Decimal objects would be serialized # properly "timestamp": datetime.datetime(2013, 5, 19, 20), "value": decimal.Decimal("3.14"), } )
import datetime import itertools import re from importlib import import_module from unittest import mock from urllib.parse import quote, urljoin from django.apps import apps from django.conf import settings from django.contrib.admin.models import LogEntry from django.contrib.auth import BACKEND_SESSION_KEY, REDIRECT_FIELD_NAME, SESSION_KEY from django.contrib.auth.forms import ( AuthenticationForm, PasswordChangeForm, SetPasswordForm, ) from django.contrib.auth.models import Permission, User from django.contrib.auth.views import ( INTERNAL_RESET_SESSION_TOKEN, LoginView, RedirectURLMixin, logout_then_login, redirect_to_login, ) from django.contrib.contenttypes.models import ContentType from django.contrib.messages import Message from django.contrib.messages.test import MessagesTestMixin from django.contrib.sessions.middleware import SessionMiddleware from django.contrib.sites.requests import RequestSite from django.core import mail from django.core.exceptions import ImproperlyConfigured from django.db import connection from django.http import HttpRequest, HttpResponse from django.middleware.csrf import CsrfViewMiddleware, get_token from django.test import Client, TestCase, modify_settings, override_settings from django.test.client import RedirectCycleError from django.urls import NoReverseMatch, reverse, reverse_lazy from django.utils.http import urlsafe_base64_encode from .client import PasswordResetConfirmClient from .models import CustomUser, CustomUserCompositePrimaryKey, UUIDUser from .settings import AUTH_TEMPLATES class RedirectURLMixinTests(TestCase): @override_settings(ROOT_URLCONF="auth_tests.urls") def test_get_default_redirect_url_next_page(self): class RedirectURLView(RedirectURLMixin): next_page = "/custom/" self.assertEqual(RedirectURLView().get_default_redirect_url(), "/custom/") def test_get_default_redirect_url_no_next_page(self): msg = "No URL to redirect to. Provide a next_page." with self.assertRaisesMessage(ImproperlyConfigured, msg): RedirectURLMixin().get_default_redirect_url() @override_settings( LANGUAGES=[("en", "English")], LANGUAGE_CODE="en", TEMPLATES=AUTH_TEMPLATES, ROOT_URLCONF="auth_tests.urls", ) class AuthViewsTestCase(TestCase): """ Helper base class for the test classes that follow. """ @classmethod def setUpTestData(cls): cls.u1 = User.objects.create_user( username="testclient", password="password", email="[email protected]" ) cls.u3 = User.objects.create_user( username="staff", password="password", email="[email protected]" ) def login(self, username="testclient", password="password", url="/login/"): response = self.client.post( url, { "username": username, "password": password, }, ) self.assertIn(SESSION_KEY, self.client.session) return response def logout(self): response = self.client.post("/admin/logout/") self.assertEqual(response.status_code, 200) self.assertNotIn(SESSION_KEY, self.client.session) def assertFormError(self, response, error): """Assert that error is found in response.context['form'] errors""" form_errors = list(itertools.chain(*response.context["form"].errors.values())) self.assertIn(str(error), form_errors) @override_settings(ROOT_URLCONF="django.contrib.auth.urls") class AuthViewNamedURLTests(AuthViewsTestCase): def test_named_urls(self): "Named URLs should be reversible" expected_named_urls = [ ("login", [], {}), ("logout", [], {}), ("password_change", [], {}), ("password_change_done", [], {}), ("password_reset", [], {}), ("password_reset_done", [], {}), ( "password_reset_confirm", [], { "uidb64": "aaaaaaa", "token": "1111-aaaaa", }, ), ("password_reset_complete", [], {}), ] for name, args, kwargs in expected_named_urls: with self.subTest(name=name): try: reverse(name, args=args, kwargs=kwargs) except NoReverseMatch: self.fail( "Reversal of url named '%s' failed with NoReverseMatch" % name ) class PasswordResetTest(AuthViewsTestCase): def setUp(self): self.client = PasswordResetConfirmClient() def test_email_not_found(self): """If the provided email is not registered, don't raise any error but also don't send any email.""" response = self.client.get("/password_reset/") self.assertEqual(response.status_code, 200) response = self.client.post( "/password_reset/", {"email": "[email protected]"} ) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 0) def test_email_found(self): "Email is sent if a valid email address is provided for password reset" response = self.client.post( "/password_reset/", {"email": "[email protected]"} ) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) self.assertIn("http://", mail.outbox[0].body) self.assertEqual(settings.DEFAULT_FROM_EMAIL, mail.outbox[0].from_email) # optional multipart text/html email has been added. Make sure # original, default functionality is 100% the same self.assertFalse(mail.outbox[0].message().is_multipart()) def test_extra_email_context(self): """ extra_email_context should be available in the email template context. """ response = self.client.post( "/password_reset_extra_email_context/", {"email": "[email protected]"}, ) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) self.assertIn('Email email context: "Hello!"', mail.outbox[0].body) self.assertIn("http://custom.example.com/reset/", mail.outbox[0].body) def test_html_mail_template(self): """ A multipart email with text/plain and text/html is sent if the html_email_template parameter is passed to the view """ response = self.client.post( "/password_reset/html_email_template/", {"email": "[email protected]"} ) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) message = mail.outbox[0].message() self.assertEqual(len(message.get_payload()), 2) self.assertTrue(message.is_multipart()) self.assertEqual(message.get_payload(0).get_content_type(), "text/plain") self.assertEqual(message.get_payload(1).get_content_type(), "text/html") self.assertNotIn("<html>", message.get_payload(0).get_payload()) self.assertIn("<html>", message.get_payload(1).get_payload()) def test_email_found_custom_from(self): """ Email is sent if a valid email address is provided for password reset when a custom from_email is provided. """ response = self.client.post( "/password_reset_from_email/", {"email": "[email protected]"} ) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) self.assertEqual("[email protected]", mail.outbox[0].from_email) # Skip any 500 handler action (like sending more mail...) @override_settings(DEBUG_PROPAGATE_EXCEPTIONS=True) def test_poisoned_http_host(self): "Poisoned HTTP_HOST headers can't be used for reset emails" # This attack is based on the way browsers handle URLs. The colon # should be used to separate the port, but if the URL contains an @, # the colon is interpreted as part of a username for login purposes, # making 'evil.com' the request domain. Since HTTP_HOST is used to # produce a meaningful reset URL, we need to be certain that the # HTTP_HOST header isn't poisoned. This is done as a check when # get_host() is invoked, but we check here as a practical consequence. with self.assertLogs("django.security.DisallowedHost", "ERROR"): response = self.client.post( "/password_reset/", {"email": "[email protected]"}, headers={"host": "www.example:[email protected]"}, ) self.assertEqual(response.status_code, 400) self.assertEqual(len(mail.outbox), 0) # Skip any 500 handler action (like sending more mail...) @override_settings(DEBUG_PROPAGATE_EXCEPTIONS=True) def test_poisoned_http_host_admin_site(self): """ Poisoned HTTP_HOST headers can't be used for reset emails on admin views """ with self.assertLogs("django.security.DisallowedHost", "ERROR"): response = self.client.post( "/admin_password_reset/", {"email": "[email protected]"}, headers={"host": "www.example:[email protected]"}, ) self.assertEqual(response.status_code, 400) self.assertEqual(len(mail.outbox), 0) def _test_confirm_start(self): # Start by creating the email self.client.post("/password_reset/", {"email": "[email protected]"}) self.assertEqual(len(mail.outbox), 1) return self._read_signup_email(mail.outbox[0]) def _read_signup_email(self, email): urlmatch = re.search(r"https?://[^/]*(/.*reset/\S*)", email.body) self.assertIsNotNone(urlmatch, "No URL found in sent email") return urlmatch[0], urlmatch[1] def test_confirm_valid(self): url, path = self._test_confirm_start() response = self.client.get(path) # redirect to a 'complete' page: self.assertContains(response, "Please enter your new password") def test_confirm_invalid(self): url, path = self._test_confirm_start() # Let's munge the token in the path, but keep the same length, # in case the URLconf will reject a different length. path = path[:-5] + ("0" * 4) + path[-1] response = self.client.get(path) self.assertContains(response, "The password reset link was invalid") def test_confirm_invalid_user(self): # A nonexistent user returns a 200 response, not a 404. response = self.client.get("/reset/123456/1-1/") self.assertContains(response, "The password reset link was invalid") def test_confirm_overflow_user(self): # A base36 user id that overflows int returns a 200 response. response = self.client.get("/reset/zzzzzzzzzzzzz/1-1/") self.assertContains(response, "The password reset link was invalid") def test_confirm_invalid_post(self): # Same as test_confirm_invalid, but trying to do a POST instead. url, path = self._test_confirm_start() path = path[:-5] + ("0" * 4) + path[-1] self.client.post( path, { "new_password1": "anewpassword", "new_password2": " anewpassword", }, ) # Check the password has not been changed u = User.objects.get(email="[email protected]") self.assertTrue(not u.check_password("anewpassword")) def test_confirm_invalid_hash(self): """A POST with an invalid token is rejected.""" u = User.objects.get(email="[email protected]") original_password = u.password url, path = self._test_confirm_start() path_parts = path.split("-") path_parts[-1] = ("0") * 20 + "/" path = "-".join(path_parts) response = self.client.post( path, { "new_password1": "anewpassword", "new_password2": "anewpassword", }, ) self.assertIs(response.context["validlink"], False) u.refresh_from_db() self.assertEqual(original_password, u.password) # password hasn't changed def test_confirm_complete(self): url, path = self._test_confirm_start() response = self.client.post( path, {"new_password1": "anewpassword", "new_password2": "anewpassword"} ) # Check the password has been changed u = User.objects.get(email="[email protected]") self.assertTrue(u.check_password("anewpassword")) # The reset token is deleted from the session. self.assertNotIn(INTERNAL_RESET_SESSION_TOKEN, self.client.session) # Check we can't use the link again response = self.client.get(path) self.assertContains(response, "The password reset link was invalid") def test_confirm_different_passwords(self): url, path = self._test_confirm_start() response = self.client.post( path, {"new_password1": "anewpassword", "new_password2": "x"} ) self.assertFormError( response, SetPasswordForm.error_messages["password_mismatch"] ) def test_reset_redirect_default(self): response = self.client.post( "/password_reset/", {"email": "[email protected]"} ) self.assertRedirects( response, "/password_reset/done/", fetch_redirect_response=False ) def test_reset_custom_redirect(self): response = self.client.post( "/password_reset/custom_redirect/", {"email": "[email protected]"} ) self.assertRedirects(response, "/custom/", fetch_redirect_response=False) def test_reset_custom_redirect_named(self): response = self.client.post( "/password_reset/custom_redirect/named/", {"email": "[email protected]"}, ) self.assertRedirects( response, "/password_reset/", fetch_redirect_response=False ) def test_confirm_redirect_default(self): url, path = self._test_confirm_start() response = self.client.post( path, {"new_password1": "anewpassword", "new_password2": "anewpassword"} ) self.assertRedirects(response, "/reset/done/", fetch_redirect_response=False) def test_confirm_redirect_custom(self): url, path = self._test_confirm_start() path = path.replace("/reset/", "/reset/custom/") response = self.client.post( path, {"new_password1": "anewpassword", "new_password2": "anewpassword"} ) self.assertRedirects(response, "/custom/", fetch_redirect_response=False) def test_confirm_redirect_custom_named(self): url, path = self._test_confirm_start() path = path.replace("/reset/", "/reset/custom/named/") response = self.client.post( path, {"new_password1": "anewpassword", "new_password2": "anewpassword"} ) self.assertRedirects( response, "/password_reset/", fetch_redirect_response=False ) def test_confirm_custom_reset_url_token(self): url, path = self._test_confirm_start() path = path.replace("/reset/", "/reset/custom/token/") self.client.reset_url_token = "set-passwordcustom" response = self.client.post( path, {"new_password1": "anewpassword", "new_password2": "anewpassword"}, ) self.assertRedirects(response, "/reset/done/", fetch_redirect_response=False) def test_confirm_login_post_reset(self): url, path = self._test_confirm_start() path = path.replace("/reset/", "/reset/post_reset_login/") response = self.client.post( path, {"new_password1": "anewpassword", "new_password2": "anewpassword"} ) self.assertRedirects(response, "/reset/done/", fetch_redirect_response=False) self.assertIn(SESSION_KEY, self.client.session) @override_settings( AUTHENTICATION_BACKENDS=[ "django.contrib.auth.backends.ModelBackend", "django.contrib.auth.backends.AllowAllUsersModelBackend", ] ) def test_confirm_login_post_reset_custom_backend(self): # This backend is specified in the URL pattern. backend = "django.contrib.auth.backends.AllowAllUsersModelBackend" url, path = self._test_confirm_start() path = path.replace("/reset/", "/reset/post_reset_login_custom_backend/") response = self.client.post( path, {"new_password1": "anewpassword", "new_password2": "anewpassword"} ) self.assertRedirects(response, "/reset/done/", fetch_redirect_response=False) self.assertIn(SESSION_KEY, self.client.session) self.assertEqual(self.client.session[BACKEND_SESSION_KEY], backend) def test_confirm_login_post_reset_already_logged_in(self): url, path = self._test_confirm_start() path = path.replace("/reset/", "/reset/post_reset_login/") self.login() response = self.client.post( path, {"new_password1": "anewpassword", "new_password2": "anewpassword"} ) self.assertRedirects(response, "/reset/done/", fetch_redirect_response=False) self.assertIn(SESSION_KEY, self.client.session) def test_confirm_display_user_from_form(self): url, path = self._test_confirm_start() response = self.client.get(path) # The password_reset_confirm() view passes the user object to the # SetPasswordForm``, even on GET requests (#16919). For this test, # {{ form.user }}`` is rendered in the template # registration/password_reset_confirm.html. username = User.objects.get(email="[email protected]").username self.assertContains(response, "Hello, %s." % username) # However, the view should NOT pass any user object on a form if the # password reset link was invalid. response = self.client.get("/reset/zzzzzzzzzzzzz/1-1/") self.assertContains(response, "Hello, .") def test_confirm_link_redirects_to_set_password_page(self): url, path = self._test_confirm_start() # Don't use PasswordResetConfirmClient (self.client) here which # automatically fetches the redirect page. client = Client() response = client.get(path) token = response.resolver_match.kwargs["token"] uuidb64 = response.resolver_match.kwargs["uidb64"] self.assertRedirects(response, "/reset/%s/set-password/" % uuidb64) self.assertEqual(client.session["_password_reset_token"], token) def test_confirm_custom_reset_url_token_link_redirects_to_set_password_page(self): url, path = self._test_confirm_start() path = path.replace("/reset/", "/reset/custom/token/") client = Client() response = client.get(path) token = response.resolver_match.kwargs["token"] uuidb64 = response.resolver_match.kwargs["uidb64"] self.assertRedirects( response, "/reset/custom/token/%s/set-passwordcustom/" % uuidb64 ) self.assertEqual(client.session["_password_reset_token"], token) def test_invalid_link_if_going_directly_to_the_final_reset_password_url(self): url, path = self._test_confirm_start() _, uuidb64, _ = path.strip("/").split("/") response = Client().get("/reset/%s/set-password/" % uuidb64) self.assertContains(response, "The password reset link was invalid") def test_missing_kwargs(self): msg = "The URL path must contain 'uidb64' and 'token' parameters." with self.assertRaisesMessage(ImproperlyConfigured, msg): self.client.get("/reset/missing_parameters/") @modify_settings( MIDDLEWARE={"append": "django.contrib.auth.middleware.LoginRequiredMiddleware"} ) def test_access_under_login_required_middleware(self): reset_urls = [ reverse("password_reset"), reverse("password_reset_done"), reverse("password_reset_confirm", kwargs={"uidb64": "abc", "token": "def"}), reverse("password_reset_complete"), ] for url in reset_urls: with self.subTest(url=url): response = self.client.get(url) self.assertEqual(response.status_code, 200) response = self.client.post( "/password_reset/", {"email": "[email protected]"} ) self.assertRedirects( response, "/password_reset/done/", fetch_redirect_response=False ) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUser") class CustomUserPasswordResetTest(AuthViewsTestCase): user_email = "[email protected]" @classmethod def setUpTestData(cls): cls.u1 = CustomUser.custom_objects.create( email="[email protected]", date_of_birth=datetime.date(1976, 11, 8), ) cls.u1.set_password("password") cls.u1.save() def setUp(self): self.client = PasswordResetConfirmClient() def _test_confirm_start(self): # Start by creating the email response = self.client.post("/password_reset/", {"email": self.user_email}) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) return self._read_signup_email(mail.outbox[0]) def _read_signup_email(self, email): urlmatch = re.search(r"https?://[^/]*(/.*reset/\S*)", email.body) self.assertIsNotNone(urlmatch, "No URL found in sent email") return urlmatch[0], urlmatch[1] def test_confirm_valid_custom_user(self): url, path = self._test_confirm_start() response = self.client.get(path) # redirect to a 'complete' page: self.assertContains(response, "Please enter your new password") # then submit a new password response = self.client.post( path, { "new_password1": "anewpassword", "new_password2": "anewpassword", }, ) self.assertRedirects(response, "/reset/done/") @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserCompositePrimaryKey") class CustomUserCompositePrimaryKeyPasswordResetTest(CustomUserPasswordResetTest): @classmethod def setUpTestData(cls): cls.u1 = CustomUserCompositePrimaryKey.custom_objects.create( email="[email protected]", date_of_birth=datetime.date(1976, 11, 8), ) cls.u1.set_password("password") cls.u1.save() @override_settings(AUTH_USER_MODEL="auth_tests.UUIDUser") class UUIDUserPasswordResetTest(CustomUserPasswordResetTest): def _test_confirm_start(self): # instead of fixture UUIDUser.objects.create_user( email=self.user_email, username="foo", password="foo", ) return super()._test_confirm_start() def test_confirm_invalid_uuid(self): """A uidb64 that decodes to a non-UUID doesn't crash.""" _, path = self._test_confirm_start() invalid_uidb64 = urlsafe_base64_encode(b"INVALID_UUID") first, _uuidb64_, second = path.strip("/").split("/") response = self.client.get( "/" + "/".join((first, invalid_uidb64, second)) + "/" ) self.assertContains(response, "The password reset link was invalid") class ChangePasswordTest(AuthViewsTestCase): def fail_login(self): response = self.client.post( "/login/", { "username": "testclient", "password": "password", }, ) self.assertFormError( response, AuthenticationForm.error_messages["invalid_login"] % {"username": User._meta.get_field("username").verbose_name}, ) def logout(self): self.client.post("/logout/") def test_password_change_fails_with_invalid_old_password(self): self.login() response = self.client.post( "/password_change/", { "old_password": "donuts", "new_password1": "password1", "new_password2": "password1", }, ) self.assertFormError( response, PasswordChangeForm.error_messages["password_incorrect"] ) def test_password_change_fails_with_mismatched_passwords(self): self.login() response = self.client.post( "/password_change/", { "old_password": "password", "new_password1": "password1", "new_password2": "donuts", }, ) self.assertFormError( response, SetPasswordForm.error_messages["password_mismatch"] ) def test_password_change_succeeds(self): self.login() self.client.post( "/password_change/", { "old_password": "password", "new_password1": "password1", "new_password2": "password1", }, ) self.fail_login() self.login(password="password1") def test_password_change_done_succeeds(self): self.login() response = self.client.post( "/password_change/", { "old_password": "password", "new_password1": "password1", "new_password2": "password1", }, ) self.assertRedirects( response, "/password_change/done/", fetch_redirect_response=False ) @override_settings(LOGIN_URL="/login/") def test_password_change_done_fails(self): response = self.client.get("/password_change/done/") self.assertRedirects( response, "/login/?next=/password_change/done/", fetch_redirect_response=False, ) def test_password_change_redirect_default(self): self.login() response = self.client.post( "/password_change/", { "old_password": "password", "new_password1": "password1", "new_password2": "password1", }, ) self.assertRedirects( response, "/password_change/done/", fetch_redirect_response=False ) def test_password_change_redirect_custom(self): self.login() response = self.client.post( "/password_change/custom/", { "old_password": "password", "new_password1": "password1", "new_password2": "password1", }, ) self.assertRedirects(response, "/custom/", fetch_redirect_response=False) def test_password_change_redirect_custom_named(self): self.login() response = self.client.post( "/password_change/custom/named/", { "old_password": "password", "new_password1": "password1", "new_password2": "password1", }, ) self.assertRedirects( response, "/password_reset/", fetch_redirect_response=False ) @modify_settings( MIDDLEWARE={"append": "django.contrib.auth.middleware.LoginRequiredMiddleware"} ) def test_access_under_login_required_middleware(self): response = self.client.post( "/password_change/", { "old_password": "password", "new_password1": "password1", "new_password2": "password1", }, ) self.assertRedirects( response, settings.LOGIN_URL + "?next=/password_change/", fetch_redirect_response=False, ) self.login() response = self.client.post( "/password_change/", { "old_password": "password", "new_password1": "password1", "new_password2": "password1", }, ) self.assertRedirects( response, "/password_change/done/", fetch_redirect_response=False ) class SessionAuthenticationTests(AuthViewsTestCase): def test_user_password_change_updates_session(self): """ #21649 - Ensure contrib.auth.views.password_change updates the user's session auth hash after a password change so the session isn't logged out. """ self.login() original_session_key = self.client.session.session_key response = self.client.post( "/password_change/", { "old_password": "password", "new_password1": "password1", "new_password2": "password1", }, ) # if the hash isn't updated, retrieving the redirection page will fail. self.assertRedirects(response, "/password_change/done/") # The session key is rotated. self.assertNotEqual(original_session_key, self.client.session.session_key) class LoginTest(AuthViewsTestCase): def test_current_site_in_context_after_login(self): response = self.client.get(reverse("login")) self.assertEqual(response.status_code, 200) if apps.is_installed("django.contrib.sites"): Site = apps.get_model("sites.Site") site = Site.objects.get_current() self.assertEqual(response.context["site"], site) self.assertEqual(response.context["site_name"], site.name) else: self.assertIsInstance(response.context["site"], RequestSite) self.assertIsInstance(response.context["form"], AuthenticationForm) def test_security_check(self): login_url = reverse("login") # These URLs should not pass the security check. bad_urls = ( "http://example.com", "http:///example.com", "https://example.com", "ftp://example.com", "///example.com", "//example.com", 'javascript:alert("XSS")', ) for bad_url in bad_urls: with self.subTest(bad_url=bad_url): nasty_url = "%(url)s?%(next)s=%(bad_url)s" % { "url": login_url, "next": REDIRECT_FIELD_NAME, "bad_url": quote(bad_url), } response = self.client.post( nasty_url, { "username": "testclient", "password": "password", }, ) self.assertEqual(response.status_code, 302) self.assertNotIn( bad_url, response.url, "%s should be blocked" % bad_url ) # These URLs should pass the security check. good_urls = ( "/view/?param=http://example.com", "/view/?param=https://example.com", "/view?param=ftp://example.com", "view/?param=//example.com", "https://testserver/", "HTTPS://testserver/", "//testserver/", "/url%20with%20spaces/", ) for good_url in good_urls: with self.subTest(good_url=good_url): safe_url = "%(url)s?%(next)s=%(good_url)s" % { "url": login_url, "next": REDIRECT_FIELD_NAME, "good_url": quote(good_url), } response = self.client.post( safe_url, { "username": "testclient", "password": "password", }, ) self.assertEqual(response.status_code, 302) self.assertIn(good_url, response.url, "%s should be allowed" % good_url) def test_security_check_https(self): login_url = reverse("login") non_https_next_url = "http://testserver/path" not_secured_url = "%(url)s?%(next)s=%(next_url)s" % { "url": login_url, "next": REDIRECT_FIELD_NAME, "next_url": quote(non_https_next_url), } post_data = { "username": "testclient", "password": "password", } response = self.client.post(not_secured_url, post_data, secure=True) self.assertEqual(response.status_code, 302) self.assertNotEqual(response.url, non_https_next_url) self.assertEqual(response.url, settings.LOGIN_REDIRECT_URL) def test_login_form_contains_request(self): # The custom authentication form for this login requires a request to # initialize it. response = self.client.post( "/custom_request_auth_login/", { "username": "testclient", "password": "password", }, ) # The login was successful. self.assertRedirects( response, settings.LOGIN_REDIRECT_URL, fetch_redirect_response=False ) def test_login_csrf_rotate(self): """ Makes sure that a login rotates the currently-used CSRF token. """ def get_response(request): return HttpResponse() # Do a GET to establish a CSRF token # The test client isn't used here as it's a test for middleware. req = HttpRequest() CsrfViewMiddleware(get_response).process_view(req, LoginView.as_view(), (), {}) # get_token() triggers CSRF token inclusion in the response get_token(req) resp = CsrfViewMiddleware(LoginView.as_view())(req) csrf_cookie = resp.cookies.get(settings.CSRF_COOKIE_NAME, None) token1 = csrf_cookie.coded_value # Prepare the POST request req = HttpRequest() req.COOKIES[settings.CSRF_COOKIE_NAME] = token1 req.method = "POST" req.POST = { "username": "testclient", "password": "password", "csrfmiddlewaretoken": token1, } # Use POST request to log in SessionMiddleware(get_response).process_request(req) CsrfViewMiddleware(get_response).process_view(req, LoginView.as_view(), (), {}) req.META["SERVER_NAME"] = ( "testserver" # Required to have redirect work in login view ) req.META["SERVER_PORT"] = 80 resp = CsrfViewMiddleware(LoginView.as_view())(req) csrf_cookie = resp.cookies.get(settings.CSRF_COOKIE_NAME, None) token2 = csrf_cookie.coded_value # Check the CSRF token switched self.assertNotEqual(token1, token2) def test_session_key_flushed_on_login(self): """ To avoid reusing another user's session, ensure a new, empty session is created if the existing session corresponds to a different authenticated user. """ self.login() original_session_key = self.client.session.session_key self.login(username="staff") self.assertNotEqual(original_session_key, self.client.session.session_key) def test_session_key_flushed_on_login_after_password_change(self): """ As above, but same user logging in after a password change. """ self.login() original_session_key = self.client.session.session_key # If no password change, session key should not be flushed. self.login() self.assertEqual(original_session_key, self.client.session.session_key) user = User.objects.get(username="testclient") user.set_password("foobar") user.save() self.login(password="foobar") self.assertNotEqual(original_session_key, self.client.session.session_key) def test_login_session_without_hash_session_key(self): """ Session without django.contrib.auth.HASH_SESSION_KEY should login without an exception. """ user = User.objects.get(username="testclient") engine = import_module(settings.SESSION_ENGINE) session = engine.SessionStore() session[SESSION_KEY] = user.id session.save() original_session_key = session.session_key self.client.cookies[settings.SESSION_COOKIE_NAME] = original_session_key self.login() self.assertNotEqual(original_session_key, self.client.session.session_key) def test_login_get_default_redirect_url(self): response = self.login(url="/login/get_default_redirect_url/") self.assertRedirects(response, "/custom/", fetch_redirect_response=False) def test_login_next_page(self): response = self.login(url="/login/next_page/") self.assertRedirects(response, "/somewhere/", fetch_redirect_response=False) def test_login_named_next_page_named(self): response = self.login(url="/login/next_page/named/") self.assertRedirects( response, "/password_reset/", fetch_redirect_response=False ) @override_settings(LOGIN_REDIRECT_URL="/custom/") def test_login_next_page_overrides_login_redirect_url_setting(self): response = self.login(url="/login/next_page/") self.assertRedirects(response, "/somewhere/", fetch_redirect_response=False) def test_login_redirect_url_overrides_next_page(self): response = self.login(url="/login/next_page/?next=/test/") self.assertRedirects(response, "/test/", fetch_redirect_response=False) def test_login_redirect_url_overrides_get_default_redirect_url(self): response = self.login(url="/login/get_default_redirect_url/?next=/test/") self.assertRedirects(response, "/test/", fetch_redirect_response=False) @modify_settings( MIDDLEWARE={"append": "django.contrib.auth.middleware.LoginRequiredMiddleware"} ) def test_access_under_login_required_middleware(self): response = self.client.get(reverse("login")) self.assertEqual(response.status_code, 200) class LoginURLSettings(AuthViewsTestCase): """Tests for settings.LOGIN_URL.""" def assertLoginURLEquals(self, url): response = self.client.get("/login_required/") self.assertRedirects(response, url, fetch_redirect_response=False) @override_settings(LOGIN_URL="/login/") def test_standard_login_url(self): self.assertLoginURLEquals("/login/?next=/login_required/") @override_settings(LOGIN_URL="login") def test_named_login_url(self): self.assertLoginURLEquals("/login/?next=/login_required/") @override_settings(LOGIN_URL="http://remote.example.com/login") def test_remote_login_url(self): quoted_next = quote("http://testserver/login_required/") expected = "http://remote.example.com/login?next=%s" % quoted_next self.assertLoginURLEquals(expected) @override_settings(LOGIN_URL="https:///login/") def test_https_login_url(self): quoted_next = quote("http://testserver/login_required/") expected = "https:///login/?next=%s" % quoted_next self.assertLoginURLEquals(expected) @override_settings(LOGIN_URL="/login/?pretty=1") def test_login_url_with_querystring(self): self.assertLoginURLEquals("/login/?pretty=1&next=/login_required/") @override_settings(LOGIN_URL="http://remote.example.com/login/?next=/default/") def test_remote_login_url_with_next_querystring(self): quoted_next = quote("http://testserver/login_required/") expected = "http://remote.example.com/login/?next=%s" % quoted_next self.assertLoginURLEquals(expected) @override_settings(LOGIN_URL=reverse_lazy("login")) def test_lazy_login_url(self): self.assertLoginURLEquals("/login/?next=/login_required/") class LoginRedirectUrlTest(AuthViewsTestCase): """Tests for settings.LOGIN_REDIRECT_URL.""" def assertLoginRedirectURLEqual(self, url): response = self.login() self.assertRedirects(response, url, fetch_redirect_response=False) def test_default(self): self.assertLoginRedirectURLEqual("/accounts/profile/") @override_settings(LOGIN_REDIRECT_URL="/custom/") def test_custom(self): self.assertLoginRedirectURLEqual("/custom/") @override_settings(LOGIN_REDIRECT_URL="password_reset") def test_named(self): self.assertLoginRedirectURLEqual("/password_reset/") @override_settings(LOGIN_REDIRECT_URL="http://remote.example.com/welcome/") def test_remote(self): self.assertLoginRedirectURLEqual("http://remote.example.com/welcome/") class RedirectToLoginTests(AuthViewsTestCase): """Tests for the redirect_to_login view""" @override_settings(LOGIN_URL=reverse_lazy("login")) def test_redirect_to_login_with_lazy(self): login_redirect_response = redirect_to_login(next="/else/where/") expected = "/login/?next=/else/where/" self.assertEqual(expected, login_redirect_response.url) @override_settings(LOGIN_URL=reverse_lazy("login")) def test_redirect_to_login_with_lazy_and_unicode(self): login_redirect_response = redirect_to_login(next="/else/where/झ/") expected = "/login/?next=/else/where/%E0%A4%9D/" self.assertEqual(expected, login_redirect_response.url) class LogoutThenLoginTests(AuthViewsTestCase): """Tests for the logout_then_login view""" def confirm_logged_out(self): self.assertNotIn(SESSION_KEY, self.client.session) @override_settings(LOGIN_URL="/login/") def test_default_logout_then_login(self): self.login() req = HttpRequest() req.method = "POST" csrf_token = get_token(req) req.COOKIES[settings.CSRF_COOKIE_NAME] = csrf_token req.POST = {"csrfmiddlewaretoken": csrf_token} req.META["SERVER_NAME"] = "testserver" req.META["SERVER_PORT"] = 80 req.session = self.client.session response = logout_then_login(req) self.confirm_logged_out() self.assertRedirects(response, "/login/", fetch_redirect_response=False) def test_logout_then_login_with_custom_login(self): self.login() req = HttpRequest() req.method = "POST" csrf_token = get_token(req) req.COOKIES[settings.CSRF_COOKIE_NAME] = csrf_token req.POST = {"csrfmiddlewaretoken": csrf_token} req.META["SERVER_NAME"] = "testserver" req.META["SERVER_PORT"] = 80 req.session = self.client.session response = logout_then_login(req, login_url="/custom/") self.confirm_logged_out() self.assertRedirects(response, "/custom/", fetch_redirect_response=False) @override_settings(LOGIN_URL="/login/") def test_default_logout_then_login_get(self): self.login() req = HttpRequest() req.method = "GET" req.META["SERVER_NAME"] = "testserver" req.META["SERVER_PORT"] = 80 req.session = self.client.session response = logout_then_login(req) self.assertEqual(response.status_code, 405) class LoginRedirectAuthenticatedUser(AuthViewsTestCase): dont_redirect_url = "/login/redirect_authenticated_user_default/" do_redirect_url = "/login/redirect_authenticated_user/" def test_default(self): """Stay on the login page by default.""" self.login() response = self.client.get(self.dont_redirect_url) self.assertEqual(response.status_code, 200) self.assertEqual(response.context["next"], "") def test_guest(self): """If not logged in, stay on the same page.""" response = self.client.get(self.do_redirect_url) self.assertEqual(response.status_code, 200) def test_redirect(self): """If logged in, go to default redirected URL.""" self.login() response = self.client.get(self.do_redirect_url) self.assertRedirects( response, "/accounts/profile/", fetch_redirect_response=False ) @override_settings(LOGIN_REDIRECT_URL="/custom/") def test_redirect_url(self): """If logged in, go to custom redirected URL.""" self.login() response = self.client.get(self.do_redirect_url) self.assertRedirects(response, "/custom/", fetch_redirect_response=False) def test_redirect_param(self): """If next is specified as a GET parameter, go there.""" self.login() url = self.do_redirect_url + "?next=/custom_next/" response = self.client.get(url) self.assertRedirects(response, "/custom_next/", fetch_redirect_response=False) def test_redirect_loop(self): """ Detect a redirect loop if LOGIN_REDIRECT_URL is not correctly set, with and without custom parameters. """ self.login() msg = ( "Redirection loop for authenticated user detected. Check that " "your LOGIN_REDIRECT_URL doesn't point to a login page." ) with self.settings(LOGIN_REDIRECT_URL=self.do_redirect_url): with self.assertRaisesMessage(ValueError, msg): self.client.get(self.do_redirect_url) url = self.do_redirect_url + "?bla=2" with self.assertRaisesMessage(ValueError, msg): self.client.get(url) def test_permission_required_not_logged_in(self): # Not logged in ... with self.settings(LOGIN_URL=self.do_redirect_url): # redirected to login. response = self.client.get("/permission_required_redirect/", follow=True) self.assertEqual(response.status_code, 200) # exception raised. response = self.client.get("/permission_required_exception/", follow=True) self.assertEqual(response.status_code, 403) # redirected to login. response = self.client.get( "/login_and_permission_required_exception/", follow=True ) self.assertEqual(response.status_code, 200) def test_permission_required_logged_in(self): self.login() # Already logged in... with self.settings(LOGIN_URL=self.do_redirect_url): # redirect loop encountered. with self.assertRaisesMessage( RedirectCycleError, "Redirect loop detected." ): self.client.get("/permission_required_redirect/", follow=True) # exception raised. response = self.client.get("/permission_required_exception/", follow=True) self.assertEqual(response.status_code, 403) # exception raised. response = self.client.get( "/login_and_permission_required_exception/", follow=True ) self.assertEqual(response.status_code, 403) class LoginSuccessURLAllowedHostsTest(AuthViewsTestCase): def test_success_url_allowed_hosts_same_host(self): response = self.client.post( "/login/allowed_hosts/", { "username": "testclient", "password": "password", "next": "https://testserver/home", }, ) self.assertIn(SESSION_KEY, self.client.session) self.assertRedirects( response, "https://testserver/home", fetch_redirect_response=False ) def test_success_url_allowed_hosts_safe_host(self): response = self.client.post( "/login/allowed_hosts/", { "username": "testclient", "password": "password", "next": "https://otherserver/home", }, ) self.assertIn(SESSION_KEY, self.client.session) self.assertRedirects( response, "https://otherserver/home", fetch_redirect_response=False ) def test_success_url_allowed_hosts_unsafe_host(self): response = self.client.post( "/login/allowed_hosts/", { "username": "testclient", "password": "password", "next": "https://evil/home", }, ) self.assertIn(SESSION_KEY, self.client.session) self.assertRedirects( response, "/accounts/profile/", fetch_redirect_response=False ) class LogoutTest(AuthViewsTestCase): def confirm_logged_out(self): self.assertNotIn(SESSION_KEY, self.client.session) def test_logout_default(self): "Logout without next_page option renders the default template" self.login() response = self.client.post("/logout/") self.assertContains(response, "Logged out") self.confirm_logged_out() def test_logout_with_post(self): self.login() response = self.client.post("/logout/") self.assertContains(response, "Logged out") self.confirm_logged_out() def test_14377(self): # Bug 14377 self.login() response = self.client.post("/logout/") self.assertIn("site", response.context) def test_logout_doesnt_cache(self): """ The logout() view should send "no-cache" headers for reasons described in #25490. """ response = self.client.post("/logout/") self.assertIn("no-store", response.headers["Cache-Control"]) def test_logout_with_overridden_redirect_url(self): # Bug 11223 self.login() response = self.client.post("/logout/next_page/") self.assertRedirects(response, "/somewhere/", fetch_redirect_response=False) response = self.client.post("/logout/next_page/?next=/login/") self.assertRedirects(response, "/login/", fetch_redirect_response=False) self.confirm_logged_out() def test_logout_with_next_page_specified(self): "Logout with next_page option given redirects to specified resource" self.login() response = self.client.post("/logout/next_page/") self.assertRedirects(response, "/somewhere/", fetch_redirect_response=False) self.confirm_logged_out() def test_logout_with_redirect_argument(self): "Logout with query string redirects to specified resource" self.login() response = self.client.post("/logout/?next=/login/") self.assertRedirects(response, "/login/", fetch_redirect_response=False) self.confirm_logged_out() def test_logout_with_custom_redirect_argument(self): "Logout with custom query string redirects to specified resource" self.login() response = self.client.post("/logout/custom_query/?follow=/somewhere/") self.assertRedirects(response, "/somewhere/", fetch_redirect_response=False) self.confirm_logged_out() def test_logout_with_named_redirect(self): "Logout resolves names or URLs passed as next_page." self.login() response = self.client.post("/logout/next_page/named/") self.assertRedirects( response, "/password_reset/", fetch_redirect_response=False ) self.confirm_logged_out() def test_success_url_allowed_hosts_same_host(self): self.login() response = self.client.post("/logout/allowed_hosts/?next=https://testserver/") self.assertRedirects( response, "https://testserver/", fetch_redirect_response=False ) self.confirm_logged_out() def test_success_url_allowed_hosts_safe_host(self): self.login() response = self.client.post("/logout/allowed_hosts/?next=https://otherserver/") self.assertRedirects( response, "https://otherserver/", fetch_redirect_response=False ) self.confirm_logged_out() def test_success_url_allowed_hosts_unsafe_host(self): self.login() response = self.client.post("/logout/allowed_hosts/?next=https://evil/") self.assertRedirects( response, "/logout/allowed_hosts/", fetch_redirect_response=False ) self.confirm_logged_out() def test_security_check(self): logout_url = reverse("logout") # These URLs should not pass the security check. bad_urls = ( "http://example.com", "http:///example.com", "https://example.com", "ftp://example.com", "///example.com", "//example.com", 'javascript:alert("XSS")', ) for bad_url in bad_urls: with self.subTest(bad_url=bad_url): nasty_url = "%(url)s?%(next)s=%(bad_url)s" % { "url": logout_url, "next": REDIRECT_FIELD_NAME, "bad_url": quote(bad_url), } self.login() response = self.client.post(nasty_url) self.assertEqual(response.status_code, 302) self.assertNotIn( bad_url, response.url, "%s should be blocked" % bad_url ) self.confirm_logged_out() # These URLs should pass the security check. good_urls = ( "/view/?param=http://example.com", "/view/?param=https://example.com", "/view?param=ftp://example.com", "view/?param=//example.com", "https://testserver/", "HTTPS://testserver/", "//testserver/", "/url%20with%20spaces/", ) for good_url in good_urls: with self.subTest(good_url=good_url): safe_url = "%(url)s?%(next)s=%(good_url)s" % { "url": logout_url, "next": REDIRECT_FIELD_NAME, "good_url": quote(good_url), } self.login() response = self.client.post(safe_url) self.assertEqual(response.status_code, 302) self.assertIn(good_url, response.url, "%s should be allowed" % good_url) self.confirm_logged_out() def test_security_check_https(self): logout_url = reverse("logout") non_https_next_url = "http://testserver/" url = "%(url)s?%(next)s=%(next_url)s" % { "url": logout_url, "next": REDIRECT_FIELD_NAME, "next_url": quote(non_https_next_url), } self.login() response = self.client.post(url, secure=True) self.assertRedirects(response, logout_url, fetch_redirect_response=False) self.confirm_logged_out() def test_logout_preserve_language(self): """Language is preserved after logout.""" self.login() self.client.post("/setlang/", {"language": "pl"}) self.assertEqual(self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, "pl") self.client.post("/logout/") self.assertEqual(self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, "pl") @override_settings(LOGOUT_REDIRECT_URL="/custom/") def test_logout_redirect_url_setting(self): self.login() response = self.client.post("/logout/") self.assertRedirects(response, "/custom/", fetch_redirect_response=False) @override_settings(LOGOUT_REDIRECT_URL="/custom/") def test_logout_redirect_url_setting_allowed_hosts_unsafe_host(self): self.login() response = self.client.post("/logout/allowed_hosts/?next=https://evil/") self.assertRedirects(response, "/custom/", fetch_redirect_response=False) @override_settings(LOGOUT_REDIRECT_URL="logout") def test_logout_redirect_url_named_setting(self): self.login() response = self.client.post("/logout/") self.assertContains(response, "Logged out") self.confirm_logged_out() @modify_settings( MIDDLEWARE={"append": "django.contrib.auth.middleware.LoginRequiredMiddleware"} ) def test_access_under_login_required_middleware(self): response = self.client.post("/logout/") self.assertRedirects( response, settings.LOGIN_URL + "?next=/logout/", fetch_redirect_response=False, ) self.login() response = self.client.post("/logout/") self.assertEqual(response.status_code, 200) def get_perm(Model, perm): ct = ContentType.objects.get_for_model(Model) return Permission.objects.get(content_type=ct, codename=perm) # Redirect in test_user_change_password will fail if session auth hash # isn't updated after password change (#21649) @override_settings( ROOT_URLCONF="auth_tests.urls_admin", PASSWORD_HASHERS=["django.contrib.auth.hashers.MD5PasswordHasher"], ) class ChangelistTests(MessagesTestMixin, AuthViewsTestCase): @classmethod def setUpTestData(cls): super().setUpTestData() # Make me a superuser before logging in. User.objects.filter(username="testclient").update( is_staff=True, is_superuser=True ) def setUp(self): self.login() # Get the latest last_login value. self.admin = User.objects.get(pk=self.u1.pk) def get_user_data(self, user): return { "username": user.username, "password": user.password, "email": user.email, "is_active": user.is_active, "is_staff": user.is_staff, "is_superuser": user.is_superuser, "last_login_0": user.last_login.strftime("%Y-%m-%d"), "last_login_1": user.last_login.strftime("%H:%M:%S"), "initial-last_login_0": user.last_login.strftime("%Y-%m-%d"), "initial-last_login_1": user.last_login.strftime("%H:%M:%S"), "date_joined_0": user.date_joined.strftime("%Y-%m-%d"), "date_joined_1": user.date_joined.strftime("%H:%M:%S"), "initial-date_joined_0": user.date_joined.strftime("%Y-%m-%d"), "initial-date_joined_1": user.date_joined.strftime("%H:%M:%S"), "first_name": user.first_name, "last_name": user.last_name, } # #20078 - users shouldn't be allowed to guess password hashes via # repeated password__startswith queries. def test_changelist_disallows_password_lookups(self): # A lookup that tries to filter on password isn't OK with self.assertLogs("django.security.DisallowedModelAdminLookup", "ERROR"): response = self.client.get( reverse("auth_test_admin:auth_user_changelist") + "?password__startswith=sha1$" ) self.assertEqual(response.status_code, 400) def test_user_change_email(self): data = self.get_user_data(self.admin) data["email"] = "new_" + data["email"] response = self.client.post( reverse("auth_test_admin:auth_user_change", args=(self.admin.pk,)), data ) self.assertRedirects(response, reverse("auth_test_admin:auth_user_changelist")) row = LogEntry.objects.latest("id") self.assertEqual(row.get_change_message(), "Changed Email address.") def test_user_not_change(self): response = self.client.post( reverse("auth_test_admin:auth_user_change", args=(self.admin.pk,)), self.get_user_data(self.admin), ) self.assertRedirects(response, reverse("auth_test_admin:auth_user_changelist")) row = LogEntry.objects.latest("id") self.assertEqual(row.get_change_message(), "No fields changed.") def test_user_with_usable_password_change_password(self): user_change_url = reverse( "auth_test_admin:auth_user_change", args=(self.admin.pk,) ) password_change_url = reverse( "auth_test_admin:auth_user_password_change", args=(self.admin.pk,) ) response = self.client.get(user_change_url) # Test the link inside password field help_text. rel_link = re.search( r'<a role="button" class="button" href="([^"]*)">Reset password</a>', response.text, )[1] self.assertEqual(urljoin(user_change_url, rel_link), password_change_url) response = self.client.get(password_change_url) # Test the form title with original (usable) password self.assertContains( response, f"<h1>Change password: {self.admin.username}</h1>" ) # Breadcrumb. self.assertContains( response, f'{self.admin.username}</a></li>\n<li aria-current="page">' "Change password</li>", ) # Usable password field. self.assertContains( response, '<fieldset class="flex-container">' "<legend>Password-based authentication:</legend>", ) # Submit buttons self.assertContains(response, '<input type="submit" name="set-password"') self.assertContains(response, '<input type="submit" name="unset-password"') # Password change. response = self.client.post( password_change_url, { "password1": "password1", "password2": "password1", }, ) self.assertRedirects(response, user_change_url) self.assertMessages( response, [Message(level=25, message="Password changed successfully.")] ) row = LogEntry.objects.latest("id") self.assertEqual(row.get_change_message(), "Changed password.") self.logout() self.login(password="password1") # Disable password-based authentication without proper submit button. response = self.client.post( password_change_url, { "password1": "password1", "password2": "password1", "usable_password": "false", }, ) self.assertRedirects(response, password_change_url) self.assertMessages( response, [ Message( level=40, message="Conflicting form data submitted. Please try again.", ) ], ) # No password change yet. self.login(password="password1") # Disable password-based authentication with proper submit button. response = self.client.post( password_change_url, { "password1": "password1", "password2": "password1", "usable_password": "false", "unset-password": 1, }, ) self.assertRedirects(response, user_change_url) self.assertMessages( response, [Message(level=25, message="Password-based authentication was disabled.")], ) row = LogEntry.objects.latest("id") self.assertEqual(row.get_change_message(), "Changed password.") self.logout() # Password-based authentication was disabled. with self.assertRaises(AssertionError): self.login(password="password1") self.admin.refresh_from_db() self.assertIs(self.admin.has_usable_password(), False) def test_user_with_unusable_password_change_password(self): # Test for title with unusable password with a test user test_user = User.objects.get(email="[email protected]") test_user.set_unusable_password() test_user.save() user_change_url = reverse( "auth_test_admin:auth_user_change", args=(test_user.pk,) ) password_change_url = reverse( "auth_test_admin:auth_user_password_change", args=(test_user.pk,) ) response = self.client.get(user_change_url) # Test the link inside password field help_text. rel_link = re.search( r'<a role="button" class="button" href="([^"]*)">Set password</a>', response.text, )[1] self.assertEqual(urljoin(user_change_url, rel_link), password_change_url) response = self.client.get(password_change_url) # Test the form title with original (usable) password self.assertContains(response, f"<h1>Set password: {test_user.username}</h1>") # Breadcrumb. self.assertContains( response, f'{test_user.username}</a></li>\n<li aria-current="page">' "Set password</li>", ) # Submit buttons self.assertContains(response, '<input type="submit" name="set-password"') self.assertNotContains(response, '<input type="submit" name="unset-password"') response = self.client.post( password_change_url, { "password1": "password1", "password2": "password1", }, ) self.assertRedirects(response, user_change_url) self.assertMessages( response, [Message(level=25, message="Password changed successfully.")] ) row = LogEntry.objects.latest("id") self.assertEqual(row.get_change_message(), "Changed password.") def test_user_change_different_user_password(self): u = User.objects.get(email="[email protected]") response = self.client.post( reverse("auth_test_admin:auth_user_password_change", args=(u.pk,)), { "password1": "password1", "password2": "password1", }, ) self.assertRedirects( response, reverse("auth_test_admin:auth_user_change", args=(u.pk,)) ) row = LogEntry.objects.latest("id") self.assertEqual(row.user_id, self.admin.pk) self.assertEqual(row.object_id, str(u.pk)) self.assertEqual(row.get_change_message(), "Changed password.") def test_password_change_bad_url(self): response = self.client.get( reverse("auth_test_admin:auth_user_password_change", args=("foobar",)) ) self.assertEqual(response.status_code, 404) @mock.patch("django.contrib.auth.admin.UserAdmin.has_change_permission") def test_user_change_password_passes_user_to_has_change_permission( self, has_change_permission ): url = reverse( "auth_test_admin:auth_user_password_change", args=(self.admin.pk,) ) self.client.post(url, {"password1": "password1", "password2": "password1"}) (_request, user), _kwargs = has_change_permission.call_args self.assertEqual(user.pk, self.admin.pk) def test_view_user_password_is_readonly(self): u = User.objects.get(username="testclient") u.is_superuser = False u.save() original_password = u.password u.user_permissions.add(get_perm(User, "view_user")) response = self.client.get( reverse("auth_test_admin:auth_user_change", args=(u.pk,)), ) algo, salt, hash_string = u.password.split("$") self.assertContains(response, '<div class="readonly">testclient</div>') # The password value is hashed. self.assertContains( response, "<strong>algorithm</strong>: <bdi>%s</bdi>\n\n" "<strong>salt</strong>: <bdi>%s********************</bdi>\n\n" "<strong>hash</strong>: <bdi>%s**************************</bdi>\n\n" % ( algo, salt[:2], hash_string[:6], ), html=True, ) self.assertNotContains( response, '<a role="button" class="button" href="../password/">Reset password</a>', ) # Value in POST data is ignored. data = self.get_user_data(u) data["password"] = "shouldnotchange" change_url = reverse("auth_test_admin:auth_user_change", args=(u.pk,)) response = self.client.post(change_url, data) self.assertEqual(response.status_code, 403) u.refresh_from_db() self.assertEqual(u.password, original_password) @override_settings( AUTH_USER_MODEL="auth_tests.UUIDUser", ROOT_URLCONF="auth_tests.urls_custom_user_admin", ) class UUIDUserTests(TestCase): def test_admin_password_change(self): u = UUIDUser.objects.create_superuser( username="uuid", email="[email protected]", password="test" ) self.assertTrue(self.client.login(username="uuid", password="test")) user_change_url = reverse( "custom_user_admin:auth_tests_uuiduser_change", args=(u.pk,) ) response = self.client.get(user_change_url) self.assertEqual(response.status_code, 200) password_change_url = reverse( "custom_user_admin:auth_user_password_change", args=(u.pk,) ) response = self.client.get(password_change_url) # The action attribute is omitted. self.assertContains(response, '<form method="post" id="uuiduser_form">') # A LogEntry is created with pk=1 which breaks a FK constraint on MySQL with connection.constraint_checks_disabled(): response = self.client.post( password_change_url, { "password1": "password1", "password2": "password1", }, ) self.assertRedirects(response, user_change_url) row = LogEntry.objects.latest("id") self.assertEqual(row.user_id, 1) # hardcoded in CustomUserAdmin.log_change() self.assertEqual(row.object_id, str(u.pk)) self.assertEqual(row.get_change_message(), "Changed password.") # The LogEntry.user column isn't altered to a UUID type so it's set to # an integer manually in CustomUserAdmin to avoid an error. To avoid a # constraint error, delete the entry before constraints are checked # after the test. row.delete()
django
python
def special(request): return {"path": request.special_path}
from django.contrib.auth import authenticate from django.contrib.auth.context_processors import PermLookupDict, PermWrapper from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.models import ContentType from django.db.models import Q from django.test import SimpleTestCase, TestCase, override_settings from .settings import AUTH_MIDDLEWARE, AUTH_TEMPLATES class MockUser: def __repr__(self): return "MockUser()" def has_module_perms(self, perm): return perm == "mockapp" def has_perm(self, perm, obj=None): return perm == "mockapp.someperm" class PermWrapperTests(SimpleTestCase): """ Test some details of the PermWrapper implementation. """ class EQLimiterObject: """ This object makes sure __eq__ will not be called endlessly. """ def __init__(self): self.eq_calls = 0 def __eq__(self, other): if self.eq_calls > 0: return True self.eq_calls += 1 return False def test_repr(self): perms = PermWrapper(MockUser()) self.assertEqual(repr(perms), "PermWrapper(MockUser())") def test_permwrapper_in(self): """ 'something' in PermWrapper works as expected. """ perms = PermWrapper(MockUser()) # Works for modules and full permissions. self.assertIn("mockapp", perms) self.assertNotIn("nonexistent", perms) self.assertIn("mockapp.someperm", perms) self.assertNotIn("mockapp.nonexistent", perms) def test_permlookupdict_in(self): """ No endless loops if accessed with 'in' - refs #18979. """ pldict = PermLookupDict(MockUser(), "mockapp") with self.assertRaises(TypeError): self.EQLimiterObject() in pldict def test_iter(self): with self.assertRaisesMessage(TypeError, "PermWrapper is not iterable."): iter(PermWrapper(MockUser())) @override_settings(ROOT_URLCONF="auth_tests.urls", TEMPLATES=AUTH_TEMPLATES) class AuthContextProcessorTests(TestCase): """ Tests for the ``django.contrib.auth.context_processors.auth`` processor """ @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) @override_settings(MIDDLEWARE=AUTH_MIDDLEWARE) def test_session_not_accessed(self): """ The session is not accessed simply by including the auth context processor """ response = self.client.get("/auth_processor_no_attr_access/") self.assertContains(response, "Session not accessed") @override_settings(MIDDLEWARE=AUTH_MIDDLEWARE) def test_session_is_accessed(self): """ The session is accessed if the auth context processor is used and relevant attributes accessed. """ response = self.client.get("/auth_processor_attr_access/") self.assertContains(response, "Session accessed") def test_perms_attrs(self): u = User.objects.create_user(username="normal", password="secret") u.user_permissions.add( Permission.objects.get( content_type=ContentType.objects.get_for_model(Permission), codename="add_permission", ) ) self.client.force_login(u) response = self.client.get("/auth_processor_perms/") self.assertContains(response, "Has auth permissions") self.assertContains(response, "Has auth.add_permission permissions") self.assertNotContains(response, "nonexistent") def test_perm_in_perms_attrs(self): u = User.objects.create_user(username="normal", password="secret") u.user_permissions.add( Permission.objects.get( content_type=ContentType.objects.get_for_model(Permission), codename="add_permission", ) ) self.client.login(username="normal", password="secret") response = self.client.get("/auth_processor_perm_in_perms/") self.assertContains(response, "Has auth permissions") self.assertContains(response, "Has auth.add_permission permissions") self.assertNotContains(response, "nonexistent") def test_message_attrs(self): self.client.force_login(self.superuser) response = self.client.get("/auth_processor_messages/") self.assertContains(response, "Message 1") def test_user_attrs(self): """ The lazy objects returned behave just like the wrapped objects. """ # These are 'functional' level tests for common use cases. Direct # testing of the implementation (SimpleLazyObject) is in the 'utils' # tests. self.client.login(username="super", password="secret") user = authenticate(username="super", password="secret") response = self.client.get("/auth_processor_user/") self.assertContains(response, "unicode: super") self.assertContains(response, "id: %d" % self.superuser.pk) self.assertContains(response, "username: super") # bug #12037 is tested by the {% url %} in the template: self.assertContains(response, "url: /userpage/super/") # A Q() comparing a user and with another Q() (in an AND or OR # fashion). Q(user=response.context["user"]) & Q(someflag=True) # Tests for user equality. This is hard because User defines # equality in a non-duck-typing way # See bug #12060 self.assertEqual(response.context["user"], user) self.assertEqual(user, response.context["user"])
django
python
import re from django.core import validators from django.utils.deconstruct import deconstructible from django.utils.translation import gettext_lazy as _ @deconstructible class ASCIIUsernameValidator(validators.RegexValidator): regex = r"^[\w.@+-]+\Z" message = _( "Enter a valid username. This value may contain only unaccented lowercase a-z " "and uppercase A-Z letters, numbers, and @/./+/-/_ characters." ) flags = re.ASCII @deconstructible class UnicodeUsernameValidator(validators.RegexValidator): regex = r"^[\w.@+-]+\Z" message = _( "Enter a valid username. This value may contain only letters, " "numbers, and @/./+/-/_ characters." ) flags = 0
import os from unittest import mock from django.contrib.auth import validators from django.contrib.auth.models import User from django.contrib.auth.password_validation import ( CommonPasswordValidator, MinimumLengthValidator, NumericPasswordValidator, UserAttributeSimilarityValidator, get_default_password_validators, get_password_validators, password_changed, password_validators_help_text_html, password_validators_help_texts, validate_password, ) from django.core.exceptions import ImproperlyConfigured, ValidationError from django.db import models from django.test import SimpleTestCase, TestCase, override_settings from django.test.utils import isolate_apps from django.utils.html import conditional_escape @override_settings( AUTH_PASSWORD_VALIDATORS=[ {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"}, { "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", "OPTIONS": { "min_length": 12, }, }, ] ) class PasswordValidationTest(SimpleTestCase): def test_get_default_password_validators(self): validators = get_default_password_validators() self.assertEqual(len(validators), 2) self.assertEqual(validators[0].__class__.__name__, "CommonPasswordValidator") self.assertEqual(validators[1].__class__.__name__, "MinimumLengthValidator") self.assertEqual(validators[1].min_length, 12) def test_get_password_validators_custom(self): validator_config = [ {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"} ] validators = get_password_validators(validator_config) self.assertEqual(len(validators), 1) self.assertEqual(validators[0].__class__.__name__, "CommonPasswordValidator") self.assertEqual(get_password_validators([]), []) def test_get_password_validators_custom_invalid(self): validator_config = [{"NAME": "json.tool"}] msg = ( "The module in NAME could not be imported: json.tool. " "Check your AUTH_PASSWORD_VALIDATORS setting." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): get_password_validators(validator_config) def test_validate_password(self): self.assertIsNone(validate_password("sufficiently-long")) msg_too_short = ( "This password is too short. It must contain at least 12 characters." ) with self.assertRaises(ValidationError) as cm: validate_password("django4242") self.assertEqual(cm.exception.messages, [msg_too_short]) self.assertEqual(cm.exception.error_list[0].code, "password_too_short") with self.assertRaises(ValidationError) as cm: validate_password("password") self.assertEqual( cm.exception.messages, ["This password is too common.", msg_too_short] ) self.assertEqual(cm.exception.error_list[0].code, "password_too_common") self.assertIsNone(validate_password("password", password_validators=[])) def test_password_changed(self): self.assertIsNone(password_changed("password")) def test_password_changed_with_custom_validator(self): class Validator: def password_changed(self, password, user): self.password = password self.user = user user = object() validator = Validator() password_changed("password", user=user, password_validators=(validator,)) self.assertIs(validator.user, user) self.assertEqual(validator.password, "password") def test_password_validators_help_texts(self): help_texts = password_validators_help_texts() self.assertEqual(len(help_texts), 2) self.assertIn("12 characters", help_texts[1]) self.assertEqual(password_validators_help_texts(password_validators=[]), []) def test_password_validators_help_text_html(self): help_text = password_validators_help_text_html() self.assertEqual(help_text.count("<li>"), 2) self.assertIn("12 characters", help_text) def test_password_validators_help_text_html_escaping(self): class AmpersandValidator: def get_help_text(self): return "Must contain &" help_text = password_validators_help_text_html([AmpersandValidator()]) self.assertEqual(help_text, "<ul><li>Must contain &amp;</li></ul>") # help_text is marked safe and therefore unchanged by # conditional_escape(). self.assertEqual(help_text, conditional_escape(help_text)) @override_settings(AUTH_PASSWORD_VALIDATORS=[]) def test_empty_password_validator_help_text_html(self): self.assertEqual(password_validators_help_text_html(), "") class MinimumLengthValidatorTest(SimpleTestCase): def test_validate(self): expected_error = ( "This password is too short. It must contain at least %d characters." ) self.assertIsNone(MinimumLengthValidator().validate("12345678")) self.assertIsNone(MinimumLengthValidator(min_length=3).validate("123")) with self.assertRaises(ValidationError) as cm: MinimumLengthValidator().validate("1234567") self.assertEqual(cm.exception.messages, [expected_error % 8]) error = cm.exception.error_list[0] self.assertEqual(error.code, "password_too_short") self.assertEqual(error.params, {"min_length": 8}) with self.assertRaises(ValidationError) as cm: MinimumLengthValidator(min_length=3).validate("12") self.assertEqual(cm.exception.messages, [expected_error % 3]) error = cm.exception.error_list[0] self.assertEqual(error.code, "password_too_short") self.assertEqual(error.params, {"min_length": 3}) def test_help_text(self): self.assertEqual( MinimumLengthValidator().get_help_text(), "Your password must contain at least 8 characters.", ) @mock.patch("django.contrib.auth.password_validation.ngettext") def test_l10n(self, mock_ngettext): with self.subTest("get_error_message"): MinimumLengthValidator().get_error_message() mock_ngettext.assert_called_with( "This password is too short. It must contain at least %d character.", "This password is too short. It must contain at least %d characters.", 8, ) mock_ngettext.reset() with self.subTest("get_help_text"): MinimumLengthValidator().get_help_text() mock_ngettext.assert_called_with( "Your password must contain at least %(min_length)d " "character.", "Your password must contain at least %(min_length)d " "characters.", 8, ) def test_custom_error(self): class CustomMinimumLengthValidator(MinimumLengthValidator): def get_error_message(self): return "Your password must be %d characters long" % self.min_length expected_error = "Your password must be %d characters long" with self.assertRaisesMessage(ValidationError, expected_error % 8) as cm: CustomMinimumLengthValidator().validate("1234567") self.assertEqual(cm.exception.error_list[0].code, "password_too_short") with self.assertRaisesMessage(ValidationError, expected_error % 3) as cm: CustomMinimumLengthValidator(min_length=3).validate("12") class UserAttributeSimilarityValidatorTest(TestCase): def test_validate(self): user = User.objects.create_user( username="testclient", password="password", email="[email protected]", first_name="Test", last_name="Client", ) expected_error = "The password is too similar to the %s." self.assertIsNone(UserAttributeSimilarityValidator().validate("testclient")) with self.assertRaises(ValidationError) as cm: UserAttributeSimilarityValidator().validate("testclient", user=user) self.assertEqual(cm.exception.messages, [expected_error % "username"]) self.assertEqual(cm.exception.error_list[0].code, "password_too_similar") msg = expected_error % "email address" with self.assertRaisesMessage(ValidationError, msg): UserAttributeSimilarityValidator().validate("example.com", user=user) msg = expected_error % "first name" with self.assertRaisesMessage(ValidationError, msg): UserAttributeSimilarityValidator( user_attributes=["first_name"], max_similarity=0.3, ).validate("testclient", user=user) # max_similarity=1 doesn't allow passwords that are identical to the # attribute's value. msg = expected_error % "first name" with self.assertRaisesMessage(ValidationError, msg): UserAttributeSimilarityValidator( user_attributes=["first_name"], max_similarity=1, ).validate(user.first_name, user=user) # Very low max_similarity is rejected. msg = "max_similarity must be at least 0.1" with self.assertRaisesMessage(ValueError, msg): UserAttributeSimilarityValidator(max_similarity=0.09) # Passes validation. self.assertIsNone( UserAttributeSimilarityValidator(user_attributes=["first_name"]).validate( "testclient", user=user ) ) @isolate_apps("auth_tests") def test_validate_property(self): class TestUser(models.Model): pass @property def username(self): return "foobar" msg = "The password is too similar to the username." with self.assertRaisesMessage(ValidationError, msg): UserAttributeSimilarityValidator().validate("foobar", user=TestUser()) def test_help_text(self): self.assertEqual( UserAttributeSimilarityValidator().get_help_text(), "Your password can’t be too similar to your other personal information.", ) def test_custom_error(self): class CustomUserAttributeSimilarityValidator(UserAttributeSimilarityValidator): def get_error_message(self): return "The password is too close to the %(verbose_name)s." user = User.objects.create_user( username="testclient", password="password", email="[email protected]", first_name="Test", last_name="Client", ) expected_error = "The password is too close to the %s." with self.assertRaisesMessage(ValidationError, expected_error % "username"): CustomUserAttributeSimilarityValidator().validate("testclient", user=user) def test_custom_error_verbose_name_not_used(self): class CustomUserAttributeSimilarityValidator(UserAttributeSimilarityValidator): def get_error_message(self): return "The password is too close to a user attribute." user = User.objects.create_user( username="testclient", password="password", email="[email protected]", first_name="Test", last_name="Client", ) expected_error = "The password is too close to a user attribute." with self.assertRaisesMessage(ValidationError, expected_error): CustomUserAttributeSimilarityValidator().validate("testclient", user=user) class CommonPasswordValidatorTest(SimpleTestCase): def test_validate(self): expected_error = "This password is too common." self.assertIsNone(CommonPasswordValidator().validate("a-safe-password")) with self.assertRaisesMessage(ValidationError, expected_error): CommonPasswordValidator().validate("godzilla") def test_common_hexed_codes(self): expected_error = "This password is too common." common_hexed_passwords = ["asdfjkl:", "&#2336:"] for password in common_hexed_passwords: with self.subTest(password=password): with self.assertRaisesMessage(ValidationError, expected_error): CommonPasswordValidator().validate(password) def test_validate_custom_list(self): path = os.path.join( os.path.dirname(os.path.realpath(__file__)), "common-passwords-custom.txt" ) validator = CommonPasswordValidator(password_list_path=path) expected_error = "This password is too common." self.assertIsNone(validator.validate("a-safe-password")) with self.assertRaises(ValidationError) as cm: validator.validate("from-my-custom-list") self.assertEqual(cm.exception.messages, [expected_error]) self.assertEqual(cm.exception.error_list[0].code, "password_too_common") def test_validate_django_supplied_file(self): validator = CommonPasswordValidator() for password in validator.passwords: self.assertEqual(password, password.lower()) def test_help_text(self): self.assertEqual( CommonPasswordValidator().get_help_text(), "Your password can’t be a commonly used password.", ) def test_custom_error(self): class CustomCommonPasswordValidator(CommonPasswordValidator): def get_error_message(self): return "This password has been used too much." expected_error = "This password has been used too much." with self.assertRaisesMessage(ValidationError, expected_error): CustomCommonPasswordValidator().validate("godzilla") class NumericPasswordValidatorTest(SimpleTestCase): def test_validate(self): expected_error = "This password is entirely numeric." self.assertIsNone(NumericPasswordValidator().validate("a-safe-password")) with self.assertRaises(ValidationError) as cm: NumericPasswordValidator().validate("42424242") self.assertEqual(cm.exception.messages, [expected_error]) self.assertEqual(cm.exception.error_list[0].code, "password_entirely_numeric") def test_help_text(self): self.assertEqual( NumericPasswordValidator().get_help_text(), "Your password can’t be entirely numeric.", ) def test_custom_error(self): class CustomNumericPasswordValidator(NumericPasswordValidator): def get_error_message(self): return "This password is all digits." expected_error = "This password is all digits." with self.assertRaisesMessage(ValidationError, expected_error): CustomNumericPasswordValidator().validate("42424242") class UsernameValidatorsTests(SimpleTestCase): def test_unicode_validator(self): valid_usernames = ["joe", "René", "ᴮᴵᴳᴮᴵᴿᴰ", "أحمد"] invalid_usernames = [ "o'connell", "عبد ال", "zerowidth\u200bspace", "nonbreaking\u00a0space", "en\u2013dash", "trailingnewline\u000a", ] v = validators.UnicodeUsernameValidator() for valid in valid_usernames: with self.subTest(valid=valid): v(valid) for invalid in invalid_usernames: with self.subTest(invalid=invalid): with self.assertRaises(ValidationError): v(invalid) def test_ascii_validator(self): valid_usernames = ["glenn", "GLEnN", "jean-marc"] invalid_usernames = [ "o'connell", "Éric", "jean marc", "أحمد", "trailingnewline\n", ] v = validators.ASCIIUsernameValidator() for valid in valid_usernames: with self.subTest(valid=valid): v(valid) for invalid in invalid_usernames: with self.subTest(invalid=invalid): with self.assertRaises(ValidationError): v(invalid)
django
python
import base64 import binascii import functools import hashlib import importlib import math import warnings from asgiref.sync import sync_to_async from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.signals import setting_changed from django.dispatch import receiver from django.utils.crypto import ( RANDOM_STRING_CHARS, constant_time_compare, get_random_string, pbkdf2, ) from django.utils.encoding import force_bytes, force_str from django.utils.module_loading import import_string from django.utils.translation import gettext_noop as _ UNUSABLE_PASSWORD_PREFIX = "!" # This will never be a valid encoded hash UNUSABLE_PASSWORD_SUFFIX_LENGTH = ( 40 # number of random chars to add after UNUSABLE_PASSWORD_PREFIX ) def is_password_usable(encoded): """ Return True if this password wasn't generated by User.set_unusable_password(), i.e. make_password(None). """ return encoded is None or not encoded.startswith(UNUSABLE_PASSWORD_PREFIX) def verify_password(password, encoded, preferred="default"): """ Return two booleans. The first is whether the raw password matches the three part encoded digest, and the second whether to regenerate the password. """ fake_runtime = password is None or not is_password_usable(encoded) preferred = get_hasher(preferred) try: hasher = identify_hasher(encoded) except ValueError: # encoded is gibberish or uses a hasher that's no longer installed. fake_runtime = True if fake_runtime: # Run the default password hasher once to reduce the timing difference # between an existing user with an unusable password and a nonexistent # user or missing hasher (similar to #20760). make_password(get_random_string(UNUSABLE_PASSWORD_SUFFIX_LENGTH)) return False, False hasher_changed = hasher.algorithm != preferred.algorithm must_update = hasher_changed or preferred.must_update(encoded) is_correct = hasher.verify(password, encoded) # If the hasher didn't change (we don't protect against enumeration if it # does) and the password should get updated, try to close the timing gap # between the work factor of the current encoded password and the default # work factor. if not is_correct and not hasher_changed and must_update: hasher.harden_runtime(password, encoded) return is_correct, must_update def check_password(password, encoded, setter=None, preferred="default"): """ Return a boolean of whether the raw password matches the three part encoded digest. If setter is specified, it'll be called when you need to regenerate the password. """ is_correct, must_update = verify_password(password, encoded, preferred=preferred) if setter and is_correct and must_update: setter(password) return is_correct async def acheck_password(password, encoded, setter=None, preferred="default"): """See check_password().""" is_correct, must_update = await sync_to_async( verify_password, thread_sensitive=False, )(password, encoded, preferred=preferred) if setter and is_correct and must_update: await setter(password) return is_correct def make_password(password, salt=None, hasher="default"): """ Turn a plain-text password into a hash for database storage Same as encode() but generate a new random salt. If password is None then return a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string, which disallows logins. Additional random string reduces chances of gaining access to staff or superuser accounts. See ticket #20079 for more info. """ if password is None: return UNUSABLE_PASSWORD_PREFIX + get_random_string( UNUSABLE_PASSWORD_SUFFIX_LENGTH ) if not isinstance(password, (bytes, str)): raise TypeError( "Password must be a string or bytes, got %s." % type(password).__qualname__ ) hasher = get_hasher(hasher) salt = salt or hasher.salt() return hasher.encode(password, salt) @functools.lru_cache def get_hashers(): hashers = [] for hasher_path in settings.PASSWORD_HASHERS: hasher_cls = import_string(hasher_path) hasher = hasher_cls() if not getattr(hasher, "algorithm"): raise ImproperlyConfigured( "hasher doesn't specify an algorithm name: %s" % hasher_path ) hashers.append(hasher) return hashers @functools.lru_cache def get_hashers_by_algorithm(): return {hasher.algorithm: hasher for hasher in get_hashers()} @receiver(setting_changed) def reset_hashers(*, setting, **kwargs): if setting == "PASSWORD_HASHERS": get_hashers.cache_clear() get_hashers_by_algorithm.cache_clear() def get_hasher(algorithm="default"): """ Return an instance of a loaded password hasher. If algorithm is 'default', return the default hasher. Lazily import hashers specified in the project's settings file if needed. """ if hasattr(algorithm, "algorithm"): return algorithm elif algorithm == "default": return get_hashers()[0] else: hashers = get_hashers_by_algorithm() try: return hashers[algorithm] except KeyError: raise ValueError( "Unknown password hashing algorithm '%s'. " "Did you specify it in the PASSWORD_HASHERS " "setting?" % algorithm ) def identify_hasher(encoded): """ Return an instance of a loaded password hasher. Identify hasher algorithm by examining encoded hash, and call get_hasher() to return hasher. Raise ValueError if algorithm cannot be identified, or if hasher is not loaded. """ # Ancient versions of Django created plain MD5 passwords and accepted # MD5 passwords with an empty salt. if (len(encoded) == 32 and "$" not in encoded) or ( len(encoded) == 37 and encoded.startswith("md5$$") ): algorithm = "unsalted_md5" # Ancient versions of Django accepted SHA1 passwords with an empty salt. elif len(encoded) == 46 and encoded.startswith("sha1$$"): algorithm = "unsalted_sha1" else: algorithm = encoded.split("$", 1)[0] return get_hasher(algorithm) def mask_hash(hash, show=6, char="*"): """ Return the given hash, with only the first ``show`` number shown. The rest are masked with ``char`` for security reasons. """ masked = hash[:show] masked += char * len(hash[show:]) return masked def must_update_salt(salt, expected_entropy): # Each character in the salt provides log_2(len(alphabet)) bits of entropy. return len(salt) * math.log2(len(RANDOM_STRING_CHARS)) < expected_entropy class BasePasswordHasher: """ Abstract base class for password hashers When creating your own hasher, you need to override algorithm, verify(), encode() and safe_summary(). PasswordHasher objects are immutable. """ algorithm = None library = None salt_entropy = 128 def _load_library(self): if self.library is not None: if isinstance(self.library, (tuple, list)): name, mod_path = self.library else: mod_path = self.library try: module = importlib.import_module(mod_path) except ImportError as e: raise ValueError( "Couldn't load %r algorithm library: %s" % (self.__class__.__name__, e) ) return module raise ValueError( "Hasher %r doesn't specify a library attribute" % self.__class__.__name__ ) def salt(self): """ Generate a cryptographically secure nonce salt in ASCII with an entropy of at least `salt_entropy` bits. """ # Each character in the salt provides # log_2(len(alphabet)) bits of entropy. char_count = math.ceil(self.salt_entropy / math.log2(len(RANDOM_STRING_CHARS))) return get_random_string(char_count, allowed_chars=RANDOM_STRING_CHARS) def verify(self, password, encoded): """Check if the given password is correct.""" raise NotImplementedError( "subclasses of BasePasswordHasher must provide a verify() method" ) def _check_encode_args(self, password, salt): if password is None: raise TypeError("password must be provided.") if not salt or "$" in force_str(salt): # salt can be str or bytes. raise ValueError("salt must be provided and cannot contain $.") def encode(self, password, salt): """ Create an encoded database value. The result is normally formatted as "algorithm$salt$hash" and must be fewer than 128 characters. """ raise NotImplementedError( "subclasses of BasePasswordHasher must provide an encode() method" ) def decode(self, encoded): """ Return a decoded database value. The result is a dictionary and should contain `algorithm`, `hash`, and `salt`. Extra keys can be algorithm specific like `iterations` or `work_factor`. """ raise NotImplementedError( "subclasses of BasePasswordHasher must provide a decode() method." ) def safe_summary(self, encoded): """ Return a summary of safe values. The result is a dictionary and will be used where the password field must be displayed to construct a safe representation of the password. """ raise NotImplementedError( "subclasses of BasePasswordHasher must provide a safe_summary() method" ) def must_update(self, encoded): return False def harden_runtime(self, password, encoded): """ Bridge the runtime gap between the work factor supplied in `encoded` and the work factor suggested by this hasher. Taking PBKDF2 as an example, if `encoded` contains 20000 iterations and `self.iterations` is 30000, this method should run password through another 10000 iterations of PBKDF2. Similar approaches should exist for any hasher that has a work factor. If not, this method should be defined as a no-op to silence the warning. """ warnings.warn( "subclasses of BasePasswordHasher should provide a harden_runtime() method" ) class PBKDF2PasswordHasher(BasePasswordHasher): """ Secure password hashing using the PBKDF2 algorithm (recommended) Configured to use PBKDF2 + HMAC + SHA256. The result is a 64 byte binary string. Iterations may be changed safely but you must rename the algorithm if you change SHA256. """ algorithm = "pbkdf2_sha256" iterations = 1_500_000 digest = hashlib.sha256 def encode(self, password, salt, iterations=None): self._check_encode_args(password, salt) iterations = iterations or self.iterations password = force_str(password) salt = force_str(salt) hash = pbkdf2(password, salt, iterations, digest=self.digest) hash = base64.b64encode(hash).decode("ascii").strip() return "%s$%d$%s$%s" % (self.algorithm, iterations, salt, hash) def decode(self, encoded): algorithm, iterations, salt, hash = encoded.split("$", 3) assert algorithm == self.algorithm return { "algorithm": algorithm, "hash": hash, "iterations": int(iterations), "salt": salt, } def verify(self, password, encoded): decoded = self.decode(encoded) encoded_2 = self.encode(password, decoded["salt"], decoded["iterations"]) return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): decoded = self.decode(encoded) return { _("algorithm"): decoded["algorithm"], _("iterations"): decoded["iterations"], _("salt"): mask_hash(decoded["salt"]), _("hash"): mask_hash(decoded["hash"]), } def must_update(self, encoded): decoded = self.decode(encoded) update_salt = must_update_salt(decoded["salt"], self.salt_entropy) return (decoded["iterations"] != self.iterations) or update_salt def harden_runtime(self, password, encoded): decoded = self.decode(encoded) extra_iterations = self.iterations - decoded["iterations"] if extra_iterations > 0: self.encode(password, decoded["salt"], extra_iterations) class PBKDF2SHA1PasswordHasher(PBKDF2PasswordHasher): """ Alternate PBKDF2 hasher which uses SHA1, the default PRF recommended by PKCS #5. This is compatible with other implementations of PBKDF2, such as openssl's PKCS5_PBKDF2_HMAC_SHA1(). """ algorithm = "pbkdf2_sha1" digest = hashlib.sha1 class Argon2PasswordHasher(BasePasswordHasher): """ Secure password hashing using the argon2 algorithm. This is the winner of the Password Hashing Competition 2013-2015 (https://password-hashing.net). It requires the argon2-cffi library which depends on native C code and might cause portability issues. """ algorithm = "argon2" library = "argon2" time_cost = 2 memory_cost = 102400 parallelism = 8 def encode(self, password, salt): argon2 = self._load_library() params = self.params() data = argon2.low_level.hash_secret( force_bytes(password), force_bytes(salt), time_cost=params.time_cost, memory_cost=params.memory_cost, parallelism=params.parallelism, hash_len=params.hash_len, type=params.type, ) return self.algorithm + data.decode("ascii") def decode(self, encoded): argon2 = self._load_library() algorithm, rest = encoded.split("$", 1) assert algorithm == self.algorithm params = argon2.extract_parameters("$" + rest) variety, *_, b64salt, hash = rest.split("$") # Add padding. b64salt += "=" * (-len(b64salt) % 4) salt = base64.b64decode(b64salt).decode("latin1") return { "algorithm": algorithm, "hash": hash, "memory_cost": params.memory_cost, "parallelism": params.parallelism, "salt": salt, "time_cost": params.time_cost, "variety": variety, "version": params.version, "params": params, } def verify(self, password, encoded): argon2 = self._load_library() algorithm, rest = encoded.split("$", 1) assert algorithm == self.algorithm try: return argon2.PasswordHasher().verify("$" + rest, password) except argon2.exceptions.VerificationError: return False def safe_summary(self, encoded): decoded = self.decode(encoded) return { _("algorithm"): decoded["algorithm"], _("variety"): decoded["variety"], _("version"): decoded["version"], _("memory cost"): decoded["memory_cost"], _("time cost"): decoded["time_cost"], _("parallelism"): decoded["parallelism"], _("salt"): mask_hash(decoded["salt"]), _("hash"): mask_hash(decoded["hash"]), } def must_update(self, encoded): decoded = self.decode(encoded) current_params = decoded["params"] new_params = self.params() # Set salt_len to the salt_len of the current parameters because salt # is explicitly passed to argon2. new_params.salt_len = current_params.salt_len update_salt = must_update_salt(decoded["salt"], self.salt_entropy) return (current_params != new_params) or update_salt def harden_runtime(self, password, encoded): # The runtime for Argon2 is too complicated to implement a sensible # hardening algorithm. pass def params(self): argon2 = self._load_library() # salt_len is a noop, because we provide our own salt. return argon2.Parameters( type=argon2.low_level.Type.ID, version=argon2.low_level.ARGON2_VERSION, salt_len=argon2.DEFAULT_RANDOM_SALT_LENGTH, hash_len=argon2.DEFAULT_HASH_LENGTH, time_cost=self.time_cost, memory_cost=self.memory_cost, parallelism=self.parallelism, ) class BCryptSHA256PasswordHasher(BasePasswordHasher): """ Secure password hashing using the bcrypt algorithm (recommended) This is considered by many to be the most secure algorithm but you must first install the bcrypt library. Please be warned that this library depends on native C code and might cause portability issues. """ algorithm = "bcrypt_sha256" digest = hashlib.sha256 library = ("bcrypt", "bcrypt") rounds = 12 def salt(self): bcrypt = self._load_library() return bcrypt.gensalt(self.rounds) def encode(self, password, salt): bcrypt = self._load_library() password = force_bytes(password) salt = force_bytes(salt) # Hash the password prior to using bcrypt to prevent password # truncation as described in #20138. if self.digest is not None: # Use binascii.hexlify() because a hex encoded bytestring is str. password = binascii.hexlify(self.digest(password).digest()) data = bcrypt.hashpw(password, salt) return "%s$%s" % (self.algorithm, data.decode("ascii")) def decode(self, encoded): algorithm, empty, algostr, work_factor, data = encoded.split("$", 4) assert algorithm == self.algorithm return { "algorithm": algorithm, "algostr": algostr, "checksum": data[22:], "salt": data[:22], "work_factor": int(work_factor), } def verify(self, password, encoded): algorithm, data = encoded.split("$", 1) assert algorithm == self.algorithm encoded_2 = self.encode(password, data.encode("ascii")) return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): decoded = self.decode(encoded) return { _("algorithm"): decoded["algorithm"], _("work factor"): decoded["work_factor"], _("salt"): mask_hash(decoded["salt"]), _("checksum"): mask_hash(decoded["checksum"]), } def must_update(self, encoded): decoded = self.decode(encoded) return decoded["work_factor"] != self.rounds def harden_runtime(self, password, encoded): _, data = encoded.split("$", 1) salt = data[:29] # Length of the salt in bcrypt. rounds = data.split("$")[2] # work factor is logarithmic, adding one doubles the load. diff = 2 ** (self.rounds - int(rounds)) - 1 while diff > 0: self.encode(password, salt.encode("ascii")) diff -= 1 class BCryptPasswordHasher(BCryptSHA256PasswordHasher): """ Secure password hashing using the bcrypt algorithm This is considered by many to be the most secure algorithm but you must first install the bcrypt library. Please be warned that this library depends on native C code and might cause portability issues. This hasher does not first hash the password which means it is subject to bcrypt's 72 bytes password truncation. Most use cases should prefer the BCryptSHA256PasswordHasher. """ algorithm = "bcrypt" digest = None class ScryptPasswordHasher(BasePasswordHasher): """ Secure password hashing using the Scrypt algorithm. """ algorithm = "scrypt" block_size = 8 maxmem = 0 parallelism = 5 work_factor = 2**14 def encode(self, password, salt, n=None, r=None, p=None): self._check_encode_args(password, salt) n = n or self.work_factor r = r or self.block_size p = p or self.parallelism hash_ = hashlib.scrypt( password=force_bytes(password), salt=force_bytes(salt), n=n, r=r, p=p, maxmem=self.maxmem, dklen=64, ) hash_ = base64.b64encode(hash_).decode("ascii").strip() return "%s$%d$%s$%d$%d$%s" % (self.algorithm, n, force_str(salt), r, p, hash_) def decode(self, encoded): algorithm, work_factor, salt, block_size, parallelism, hash_ = encoded.split( "$", 6 ) assert algorithm == self.algorithm return { "algorithm": algorithm, "work_factor": int(work_factor), "salt": salt, "block_size": int(block_size), "parallelism": int(parallelism), "hash": hash_, } def verify(self, password, encoded): decoded = self.decode(encoded) encoded_2 = self.encode( password, decoded["salt"], decoded["work_factor"], decoded["block_size"], decoded["parallelism"], ) return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): decoded = self.decode(encoded) return { _("algorithm"): decoded["algorithm"], _("work factor"): decoded["work_factor"], _("block size"): decoded["block_size"], _("parallelism"): decoded["parallelism"], _("salt"): mask_hash(decoded["salt"]), _("hash"): mask_hash(decoded["hash"]), } def must_update(self, encoded): decoded = self.decode(encoded) return ( decoded["work_factor"] != self.work_factor or decoded["block_size"] != self.block_size or decoded["parallelism"] != self.parallelism ) def harden_runtime(self, password, encoded): # The runtime for Scrypt is too complicated to implement a sensible # hardening algorithm. pass class MD5PasswordHasher(BasePasswordHasher): """ The Salted MD5 password hashing algorithm (not recommended) """ algorithm = "md5" def encode(self, password, salt): self._check_encode_args(password, salt) password = force_str(password) salt = force_str(salt) hash = hashlib.md5((salt + password).encode()).hexdigest() return "%s$%s$%s" % (self.algorithm, salt, hash) def decode(self, encoded): algorithm, salt, hash = encoded.split("$", 2) assert algorithm == self.algorithm return { "algorithm": algorithm, "hash": hash, "salt": salt, } def verify(self, password, encoded): decoded = self.decode(encoded) encoded_2 = self.encode(password, decoded["salt"]) return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): decoded = self.decode(encoded) return { _("algorithm"): decoded["algorithm"], _("salt"): mask_hash(decoded["salt"], show=2), _("hash"): mask_hash(decoded["hash"]), } def must_update(self, encoded): decoded = self.decode(encoded) return must_update_salt(decoded["salt"], self.salt_entropy) def harden_runtime(self, password, encoded): pass
from contextlib import contextmanager from unittest import mock, skipUnless from django.conf.global_settings import PASSWORD_HASHERS from django.contrib.auth.hashers import ( UNUSABLE_PASSWORD_PREFIX, UNUSABLE_PASSWORD_SUFFIX_LENGTH, Argon2PasswordHasher, BasePasswordHasher, BCryptPasswordHasher, BCryptSHA256PasswordHasher, MD5PasswordHasher, PBKDF2PasswordHasher, PBKDF2SHA1PasswordHasher, ScryptPasswordHasher, acheck_password, check_password, get_hasher, identify_hasher, is_password_usable, make_password, ) from django.test import SimpleTestCase from django.test.utils import override_settings try: import bcrypt except ImportError: bcrypt = None try: import argon2 except ImportError: argon2 = None # scrypt requires OpenSSL 1.1+ try: import hashlib scrypt = hashlib.scrypt except ImportError: scrypt = None class PBKDF2SingleIterationHasher(PBKDF2PasswordHasher): iterations = 1 @override_settings(PASSWORD_HASHERS=PASSWORD_HASHERS) class TestUtilsHashPass(SimpleTestCase): def test_simple(self): encoded = make_password("lètmein") self.assertTrue(encoded.startswith("pbkdf2_sha256$")) self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) # Blank passwords blank_encoded = make_password("") self.assertTrue(blank_encoded.startswith("pbkdf2_sha256$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) async def test_acheck_password(self): encoded = make_password("lètmein") self.assertIs(await acheck_password("lètmein", encoded), True) self.assertIs(await acheck_password("lètmeinz", encoded), False) # Blank passwords. blank_encoded = make_password("") self.assertIs(await acheck_password("", blank_encoded), True) self.assertIs(await acheck_password(" ", blank_encoded), False) def test_bytes(self): encoded = make_password(b"bytes_password") self.assertTrue(encoded.startswith("pbkdf2_sha256$")) self.assertIs(is_password_usable(encoded), True) self.assertIs(check_password(b"bytes_password", encoded), True) def test_invalid_password(self): msg = "Password must be a string or bytes, got int." with self.assertRaisesMessage(TypeError, msg): make_password(1) def test_pbkdf2(self): encoded = make_password("lètmein", "seasalt", "pbkdf2_sha256") self.assertEqual( encoded, "pbkdf2_sha256$1500000$" "seasalt$P4UiMPVduVWIL/oS1GzH+IofsccjJNM5hUTikBvi5to=", ) self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "pbkdf2_sha256") # Blank passwords blank_encoded = make_password("", "seasalt", "pbkdf2_sha256") self.assertTrue(blank_encoded.startswith("pbkdf2_sha256$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) # Salt entropy check. hasher = get_hasher("pbkdf2_sha256") encoded_weak_salt = make_password("lètmein", "iodizedsalt", "pbkdf2_sha256") encoded_strong_salt = make_password("lètmein", hasher.salt(), "pbkdf2_sha256") self.assertIs(hasher.must_update(encoded_weak_salt), True) self.assertIs(hasher.must_update(encoded_strong_salt), False) @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.MD5PasswordHasher"] ) def test_md5(self): encoded = make_password("lètmein", "seasalt", "md5") self.assertEqual(encoded, "md5$seasalt$3f86d0d3d465b7b458c231bf3555c0e3") self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "md5") # Blank passwords blank_encoded = make_password("", "seasalt", "md5") self.assertTrue(blank_encoded.startswith("md5$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) # Salt entropy check. hasher = get_hasher("md5") encoded_weak_salt = make_password("lètmein", "iodizedsalt", "md5") encoded_strong_salt = make_password("lètmein", hasher.salt(), "md5") self.assertIs(hasher.must_update(encoded_weak_salt), True) self.assertIs(hasher.must_update(encoded_strong_salt), False) @skipUnless(bcrypt, "bcrypt not installed") def test_bcrypt_sha256(self): encoded = make_password("lètmein", hasher="bcrypt_sha256") self.assertTrue(is_password_usable(encoded)) self.assertTrue(encoded.startswith("bcrypt_sha256$")) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "bcrypt_sha256") # password truncation no longer works password = ( "VSK0UYV6FFQVZ0KG88DYN9WADAADZO1CTSIVDJUNZSUML6IBX7LN7ZS3R5" "JGB3RGZ7VI7G7DJQ9NI8BQFSRPTG6UWTTVESA5ZPUN" ) encoded = make_password(password, hasher="bcrypt_sha256") self.assertTrue(check_password(password, encoded)) self.assertFalse(check_password(password[:72], encoded)) # Blank passwords blank_encoded = make_password("", hasher="bcrypt_sha256") self.assertTrue(blank_encoded.startswith("bcrypt_sha256$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) @skipUnless(bcrypt, "bcrypt not installed") @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.BCryptPasswordHasher"] ) def test_bcrypt(self): encoded = make_password("lètmein", hasher="bcrypt") self.assertTrue(is_password_usable(encoded)) self.assertTrue(encoded.startswith("bcrypt$")) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "bcrypt") # Blank passwords blank_encoded = make_password("", hasher="bcrypt") self.assertTrue(blank_encoded.startswith("bcrypt$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) @skipUnless(bcrypt, "bcrypt not installed") @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.BCryptPasswordHasher"] ) def test_bcrypt_upgrade(self): hasher = get_hasher("bcrypt") self.assertEqual("bcrypt", hasher.algorithm) self.assertNotEqual(hasher.rounds, 4) old_rounds = hasher.rounds try: # Generate a password with 4 rounds. hasher.rounds = 4 encoded = make_password("letmein", hasher="bcrypt") rounds = hasher.safe_summary(encoded)["work factor"] self.assertEqual(rounds, 4) state = {"upgraded": False} def setter(password): state["upgraded"] = True # No upgrade is triggered. self.assertTrue(check_password("letmein", encoded, setter, "bcrypt")) self.assertFalse(state["upgraded"]) # Revert to the old rounds count and ... hasher.rounds = old_rounds # ... check if the password would get updated to the new count. self.assertTrue(check_password("letmein", encoded, setter, "bcrypt")) self.assertTrue(state["upgraded"]) finally: hasher.rounds = old_rounds @skipUnless(bcrypt, "bcrypt not installed") @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.BCryptPasswordHasher"] ) def test_bcrypt_harden_runtime(self): hasher = get_hasher("bcrypt") self.assertEqual("bcrypt", hasher.algorithm) with mock.patch.object(hasher, "rounds", 4): encoded = make_password("letmein", hasher="bcrypt") with ( mock.patch.object(hasher, "rounds", 6), mock.patch.object(hasher, "encode", side_effect=hasher.encode), ): hasher.harden_runtime("wrong_password", encoded) # Increasing rounds from 4 to 6 means an increase of 4 in workload, # therefore hardening should run 3 times to make the timing the # same (the original encode() call already ran once). self.assertEqual(hasher.encode.call_count, 3) # Get the original salt (includes the original workload factor) algorithm, data = encoded.split("$", 1) expected_call = (("wrong_password", data[:29].encode()),) self.assertEqual(hasher.encode.call_args_list, [expected_call] * 3) def test_unusable(self): encoded = make_password(None) self.assertEqual( len(encoded), len(UNUSABLE_PASSWORD_PREFIX) + UNUSABLE_PASSWORD_SUFFIX_LENGTH, ) self.assertFalse(is_password_usable(encoded)) self.assertFalse(check_password(None, encoded)) self.assertFalse(check_password(encoded, encoded)) self.assertFalse(check_password(UNUSABLE_PASSWORD_PREFIX, encoded)) self.assertFalse(check_password("", encoded)) self.assertFalse(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) with self.assertRaisesMessage(ValueError, "Unknown password hashing algorithm"): identify_hasher(encoded) # Assert that the unusable passwords actually contain a random part. # This might fail one day due to a hash collision. self.assertNotEqual(encoded, make_password(None), "Random password collision?") def test_unspecified_password(self): """ Makes sure specifying no plain password with a valid encoded password returns `False`. """ self.assertFalse(check_password(None, make_password("lètmein"))) def test_bad_algorithm(self): msg = ( "Unknown password hashing algorithm '%s'. Did you specify it in " "the PASSWORD_HASHERS setting?" ) with self.assertRaisesMessage(ValueError, msg % "lolcat"): make_password("lètmein", hasher="lolcat") with self.assertRaisesMessage(ValueError, msg % "lolcat"): identify_hasher("lolcat$salt$hash") def test_is_password_usable(self): passwords = ("lètmein_badencoded", "", None) for password in passwords: with self.subTest(password=password): self.assertIs(is_password_usable(password), True) def test_low_level_pbkdf2(self): hasher = PBKDF2PasswordHasher() encoded = hasher.encode("lètmein", "seasalt2") self.assertEqual( encoded, "pbkdf2_sha256$1500000$" "seasalt2$xWKIh704updzhxL+vMfPbhVsHljK62FyE988AtcoHU4=", ) self.assertTrue(hasher.verify("lètmein", encoded)) def test_low_level_pbkdf2_sha1(self): hasher = PBKDF2SHA1PasswordHasher() encoded = hasher.encode("lètmein", "seasalt2") self.assertEqual( encoded, "pbkdf2_sha1$1500000$seasalt2$ep4Ou2hnt2mlvMRsIjUln0Z5MYY=" ) self.assertTrue(hasher.verify("lètmein", encoded)) @skipUnless(bcrypt, "bcrypt not installed") def test_bcrypt_salt_check(self): hasher = BCryptPasswordHasher() encoded = hasher.encode("lètmein", hasher.salt()) self.assertIs(hasher.must_update(encoded), False) @skipUnless(bcrypt, "bcrypt not installed") def test_bcryptsha256_salt_check(self): hasher = BCryptSHA256PasswordHasher() encoded = hasher.encode("lètmein", hasher.salt()) self.assertIs(hasher.must_update(encoded), False) @override_settings( PASSWORD_HASHERS=[ "django.contrib.auth.hashers.PBKDF2PasswordHasher", "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher", "django.contrib.auth.hashers.MD5PasswordHasher", ], ) def test_upgrade(self): self.assertEqual("pbkdf2_sha256", get_hasher("default").algorithm) for algo in ("pbkdf2_sha1", "md5"): with self.subTest(algo=algo): encoded = make_password("lètmein", hasher=algo) state = {"upgraded": False} def setter(password): state["upgraded"] = True self.assertTrue(check_password("lètmein", encoded, setter)) self.assertTrue(state["upgraded"]) def test_no_upgrade(self): encoded = make_password("lètmein") state = {"upgraded": False} def setter(): state["upgraded"] = True self.assertFalse(check_password("WRONG", encoded, setter)) self.assertFalse(state["upgraded"]) @override_settings( PASSWORD_HASHERS=[ "django.contrib.auth.hashers.PBKDF2PasswordHasher", "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher", "django.contrib.auth.hashers.MD5PasswordHasher", ], ) def test_no_upgrade_on_incorrect_pass(self): self.assertEqual("pbkdf2_sha256", get_hasher("default").algorithm) for algo in ("pbkdf2_sha1", "md5"): with self.subTest(algo=algo): encoded = make_password("lètmein", hasher=algo) state = {"upgraded": False} def setter(): state["upgraded"] = True self.assertFalse(check_password("WRONG", encoded, setter)) self.assertFalse(state["upgraded"]) def test_pbkdf2_upgrade(self): hasher = get_hasher("default") self.assertEqual("pbkdf2_sha256", hasher.algorithm) self.assertNotEqual(hasher.iterations, 1) old_iterations = hasher.iterations try: # Generate a password with 1 iteration. hasher.iterations = 1 encoded = make_password("letmein") algo, iterations, salt, hash = encoded.split("$", 3) self.assertEqual(iterations, "1") state = {"upgraded": False} def setter(password): state["upgraded"] = True # No upgrade is triggered self.assertTrue(check_password("letmein", encoded, setter)) self.assertFalse(state["upgraded"]) # Revert to the old iteration count and ... hasher.iterations = old_iterations # ... check if the password would get updated to the new iteration # count. self.assertTrue(check_password("letmein", encoded, setter)) self.assertTrue(state["upgraded"]) finally: hasher.iterations = old_iterations def test_pbkdf2_harden_runtime(self): hasher = get_hasher("default") self.assertEqual("pbkdf2_sha256", hasher.algorithm) with mock.patch.object(hasher, "iterations", 1): encoded = make_password("letmein") with ( mock.patch.object(hasher, "iterations", 6), mock.patch.object(hasher, "encode", side_effect=hasher.encode), ): hasher.harden_runtime("wrong_password", encoded) # Encode should get called once ... self.assertEqual(hasher.encode.call_count, 1) # ... with the original salt and 5 iterations. algorithm, iterations, salt, hash = encoded.split("$", 3) expected_call = (("wrong_password", salt, 5),) self.assertEqual(hasher.encode.call_args, expected_call) def test_pbkdf2_upgrade_new_hasher(self): hasher = get_hasher("default") self.assertEqual("pbkdf2_sha256", hasher.algorithm) self.assertNotEqual(hasher.iterations, 1) state = {"upgraded": False} def setter(password): state["upgraded"] = True with self.settings( PASSWORD_HASHERS=["auth_tests.test_hashers.PBKDF2SingleIterationHasher"] ): encoded = make_password("letmein") algo, iterations, salt, hash = encoded.split("$", 3) self.assertEqual(iterations, "1") # No upgrade is triggered self.assertTrue(check_password("letmein", encoded, setter)) self.assertFalse(state["upgraded"]) # Revert to the old iteration count and check if the password would get # updated to the new iteration count. with self.settings( PASSWORD_HASHERS=[ "django.contrib.auth.hashers.PBKDF2PasswordHasher", "auth_tests.test_hashers.PBKDF2SingleIterationHasher", ] ): self.assertTrue(check_password("letmein", encoded, setter)) self.assertTrue(state["upgraded"]) def test_check_password_calls_harden_runtime(self): hasher = get_hasher("default") encoded = make_password("letmein") with ( mock.patch.object(hasher, "harden_runtime"), mock.patch.object(hasher, "must_update", return_value=True), ): # Correct password supplied, no hardening needed check_password("letmein", encoded) self.assertEqual(hasher.harden_runtime.call_count, 0) # Wrong password supplied, hardening needed check_password("wrong_password", encoded) self.assertEqual(hasher.harden_runtime.call_count, 1) @contextmanager def assertMakePasswordCalled(self, password, encoded, hasher_side_effect): hasher = get_hasher("default") with ( mock.patch( "django.contrib.auth.hashers.identify_hasher", side_effect=hasher_side_effect, ) as mock_identify_hasher, mock.patch( "django.contrib.auth.hashers.make_password" ) as mock_make_password, mock.patch( "django.contrib.auth.hashers.get_random_string", side_effect=lambda size: "x" * size, ), mock.patch.object(hasher, "verify"), ): # Ensure make_password is called to standardize timing. yield self.assertEqual(hasher.verify.call_count, 0) self.assertEqual(mock_identify_hasher.mock_calls, [mock.call(encoded)]) self.assertEqual( mock_make_password.mock_calls, [mock.call("x" * UNUSABLE_PASSWORD_SUFFIX_LENGTH)], ) def test_check_password_calls_make_password_to_fake_runtime(self): cases = [ (None, None, None), # no plain text password provided ("foo", make_password(password=None), None), # unusable encoded ("letmein", make_password(password="letmein"), ValueError), # valid encoded ] for password, encoded, hasher_side_effect in cases: with ( self.subTest(encoded=encoded), self.assertMakePasswordCalled(password, encoded, hasher_side_effect), ): check_password(password, encoded) async def test_acheck_password_calls_make_password_to_fake_runtime(self): cases = [ (None, None, None), # no plain text password provided ("foo", make_password(password=None), None), # unusable encoded ("letmein", make_password(password="letmein"), ValueError), # valid encoded ] for password, encoded, hasher_side_effect in cases: with ( self.subTest(encoded=encoded), self.assertMakePasswordCalled(password, encoded, hasher_side_effect), ): await acheck_password(password, encoded) def test_encode_invalid_salt(self): hasher_classes = [ MD5PasswordHasher, PBKDF2PasswordHasher, PBKDF2SHA1PasswordHasher, ScryptPasswordHasher, ] msg = "salt must be provided and cannot contain $." for hasher_class in hasher_classes: hasher = hasher_class() for salt in [None, "", "sea$salt"]: with self.subTest(hasher_class.__name__, salt=salt): with self.assertRaisesMessage(ValueError, msg): hasher.encode("password", salt) def test_password_and_salt_in_str_and_bytes(self): hasher_classes = [ MD5PasswordHasher, PBKDF2PasswordHasher, PBKDF2SHA1PasswordHasher, ScryptPasswordHasher, ] for hasher_class in hasher_classes: hasher = hasher_class() with self.subTest(hasher_class.__name__): passwords = ["password", b"password"] for password in passwords: for salt in [hasher.salt(), hasher.salt().encode()]: encoded = hasher.encode(password, salt) for password_to_verify in passwords: self.assertIs( hasher.verify(password_to_verify, encoded), True ) @skipUnless(argon2, "argon2-cffi not installed") def test_password_and_salt_in_str_and_bytes_argon2(self): hasher = Argon2PasswordHasher() passwords = ["password", b"password"] for password in passwords: for salt in [hasher.salt(), hasher.salt().encode()]: encoded = hasher.encode(password, salt) for password_to_verify in passwords: self.assertIs(hasher.verify(password_to_verify, encoded), True) @skipUnless(bcrypt, "bcrypt not installed") def test_password_and_salt_in_str_and_bytes_bcrypt(self): hasher_classes = [ BCryptPasswordHasher, BCryptSHA256PasswordHasher, ] for hasher_class in hasher_classes: hasher = hasher_class() with self.subTest(hasher_class.__name__): passwords = ["password", b"password"] for password in passwords: salts = [hasher.salt().decode(), hasher.salt()] for salt in salts: encoded = hasher.encode(password, salt) for password_to_verify in passwords: self.assertIs( hasher.verify(password_to_verify, encoded), True ) def test_encode_password_required(self): hasher_classes = [ MD5PasswordHasher, PBKDF2PasswordHasher, PBKDF2SHA1PasswordHasher, ScryptPasswordHasher, ] msg = "password must be provided." for hasher_class in hasher_classes: hasher = hasher_class() with self.subTest(hasher_class.__name__): with self.assertRaisesMessage(TypeError, msg): hasher.encode(None, "seasalt") class BasePasswordHasherTests(SimpleTestCase): not_implemented_msg = "subclasses of BasePasswordHasher must provide %s() method" def setUp(self): self.hasher = BasePasswordHasher() def test_load_library_no_algorithm(self): msg = "Hasher 'BasePasswordHasher' doesn't specify a library attribute" with self.assertRaisesMessage(ValueError, msg): self.hasher._load_library() def test_load_library_importerror(self): PlainHasher = type( "PlainHasher", (BasePasswordHasher,), {"algorithm": "plain", "library": "plain"}, ) msg = "Couldn't load 'PlainHasher' algorithm library: No module named 'plain'" with self.assertRaisesMessage(ValueError, msg): PlainHasher()._load_library() def test_attributes(self): self.assertIsNone(self.hasher.algorithm) self.assertIsNone(self.hasher.library) def test_encode(self): msg = self.not_implemented_msg % "an encode" with self.assertRaisesMessage(NotImplementedError, msg): self.hasher.encode("password", "salt") def test_decode(self): msg = self.not_implemented_msg % "a decode" with self.assertRaisesMessage(NotImplementedError, msg): self.hasher.decode("encoded") def test_harden_runtime(self): msg = ( "subclasses of BasePasswordHasher should provide a harden_runtime() method" ) with self.assertWarnsMessage(Warning, msg): self.hasher.harden_runtime("password", "encoded") def test_must_update(self): self.assertIs(self.hasher.must_update("encoded"), False) def test_safe_summary(self): msg = self.not_implemented_msg % "a safe_summary" with self.assertRaisesMessage(NotImplementedError, msg): self.hasher.safe_summary("encoded") def test_verify(self): msg = self.not_implemented_msg % "a verify" with self.assertRaisesMessage(NotImplementedError, msg): self.hasher.verify("password", "encoded") @skipUnless(argon2, "argon2-cffi not installed") @override_settings(PASSWORD_HASHERS=PASSWORD_HASHERS) class TestUtilsHashPassArgon2(SimpleTestCase): def test_argon2(self): encoded = make_password("lètmein", hasher="argon2") self.assertTrue(is_password_usable(encoded)) self.assertTrue(encoded.startswith("argon2$argon2id$")) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "argon2") # Blank passwords blank_encoded = make_password("", hasher="argon2") self.assertTrue(blank_encoded.startswith("argon2$argon2id$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) # Old hashes without version attribute encoded = ( "argon2$argon2i$m=8,t=1,p=1$c29tZXNhbHQ$gwQOXSNhxiOxPOA0+PY10P9QFO" "4NAYysnqRt1GSQLE55m+2GYDt9FEjPMHhP2Cuf0nOEXXMocVrsJAtNSsKyfg" ) self.assertTrue(check_password("secret", encoded)) self.assertFalse(check_password("wrong", encoded)) # Old hashes with version attribute. encoded = "argon2$argon2i$v=19$m=8,t=1,p=1$c2FsdHNhbHQ$YC9+jJCrQhs5R6db7LlN8Q" self.assertIs(check_password("secret", encoded), True) self.assertIs(check_password("wrong", encoded), False) # Salt entropy check. hasher = get_hasher("argon2") encoded_weak_salt = make_password("lètmein", "iodizedsalt", "argon2") encoded_strong_salt = make_password("lètmein", hasher.salt(), "argon2") self.assertIs(hasher.must_update(encoded_weak_salt), True) self.assertIs(hasher.must_update(encoded_strong_salt), False) def test_argon2_decode(self): salt = "abcdefghijk" encoded = make_password("lètmein", salt=salt, hasher="argon2") hasher = get_hasher("argon2") decoded = hasher.decode(encoded) self.assertEqual(decoded["memory_cost"], hasher.memory_cost) self.assertEqual(decoded["parallelism"], hasher.parallelism) self.assertEqual(decoded["salt"], salt) self.assertEqual(decoded["time_cost"], hasher.time_cost) def test_argon2_upgrade(self): self._test_argon2_upgrade("time_cost", "time cost", 1) self._test_argon2_upgrade("memory_cost", "memory cost", 64) self._test_argon2_upgrade("parallelism", "parallelism", 1) def test_argon2_version_upgrade(self): hasher = get_hasher("argon2") state = {"upgraded": False} encoded = ( "argon2$argon2id$v=19$m=102400,t=2,p=8$Y041dExhNkljRUUy$TMa6A8fPJh" "CAUXRhJXCXdw" ) def setter(password): state["upgraded"] = True old_m = hasher.memory_cost old_t = hasher.time_cost old_p = hasher.parallelism try: hasher.memory_cost = 8 hasher.time_cost = 1 hasher.parallelism = 1 self.assertTrue(check_password("secret", encoded, setter, "argon2")) self.assertTrue(state["upgraded"]) finally: hasher.memory_cost = old_m hasher.time_cost = old_t hasher.parallelism = old_p def _test_argon2_upgrade(self, attr, summary_key, new_value): hasher = get_hasher("argon2") self.assertEqual("argon2", hasher.algorithm) self.assertNotEqual(getattr(hasher, attr), new_value) old_value = getattr(hasher, attr) try: # Generate hash with attr set to 1 setattr(hasher, attr, new_value) encoded = make_password("letmein", hasher="argon2") attr_value = hasher.safe_summary(encoded)[summary_key] self.assertEqual(attr_value, new_value) state = {"upgraded": False} def setter(password): state["upgraded"] = True # No upgrade is triggered. self.assertTrue(check_password("letmein", encoded, setter, "argon2")) self.assertFalse(state["upgraded"]) # Revert to the old rounds count and ... setattr(hasher, attr, old_value) # ... check if the password would get updated to the new count. self.assertTrue(check_password("letmein", encoded, setter, "argon2")) self.assertTrue(state["upgraded"]) finally: setattr(hasher, attr, old_value) @skipUnless(scrypt, "scrypt not available") @override_settings(PASSWORD_HASHERS=PASSWORD_HASHERS) class TestUtilsHashPassScrypt(SimpleTestCase): def test_scrypt(self): encoded = make_password("lètmein", "seasalt", "scrypt") self.assertEqual( encoded, "scrypt$16384$seasalt$8$5$ECMIUp+LMxMSK8xB/IVyba+KYGTI7FTnet025q/1f" "/vBAVnnP3hdYqJuRi+mJn6ji6ze3Fbb7JEFPKGpuEf5vw==", ) self.assertIs(is_password_usable(encoded), True) self.assertIs(check_password("lètmein", encoded), True) self.assertIs(check_password("lètmeinz", encoded), False) self.assertEqual(identify_hasher(encoded).algorithm, "scrypt") # Blank passwords. blank_encoded = make_password("", "seasalt", "scrypt") self.assertIs(blank_encoded.startswith("scrypt$"), True) self.assertIs(is_password_usable(blank_encoded), True) self.assertIs(check_password("", blank_encoded), True) self.assertIs(check_password(" ", blank_encoded), False) def test_scrypt_decode(self): encoded = make_password("lètmein", "seasalt", "scrypt") hasher = get_hasher("scrypt") decoded = hasher.decode(encoded) tests = [ ("block_size", hasher.block_size), ("parallelism", hasher.parallelism), ("salt", "seasalt"), ("work_factor", hasher.work_factor), ] for key, excepted in tests: with self.subTest(key=key): self.assertEqual(decoded[key], excepted) def _test_scrypt_upgrade(self, attr, summary_key, new_value): hasher = get_hasher("scrypt") self.assertEqual(hasher.algorithm, "scrypt") self.assertNotEqual(getattr(hasher, attr), new_value) old_value = getattr(hasher, attr) try: # Generate hash with attr set to the new value. setattr(hasher, attr, new_value) encoded = make_password("lètmein", "seasalt", "scrypt") attr_value = hasher.safe_summary(encoded)[summary_key] self.assertEqual(attr_value, new_value) state = {"upgraded": False} def setter(password): state["upgraded"] = True # No update is triggered. self.assertIs(check_password("lètmein", encoded, setter, "scrypt"), True) self.assertIs(state["upgraded"], False) # Revert to the old value. setattr(hasher, attr, old_value) # Password is updated. self.assertIs(check_password("lètmein", encoded, setter, "scrypt"), True) self.assertIs(state["upgraded"], True) finally: setattr(hasher, attr, old_value) def test_scrypt_upgrade(self): tests = [ ("work_factor", "work factor", 2**11), ("block_size", "block size", 10), ("parallelism", "parallelism", 2), ] for attr, summary_key, new_value in tests: with self.subTest(attr=attr): self._test_scrypt_upgrade(attr, summary_key, new_value)
django
python
from django.contrib.auth.backends import ModelBackend from .models import CustomUser class CustomUserBackend(ModelBackend): def authenticate(self, request, username=None, password=None): try: user = CustomUser.custom_objects.get_by_natural_key(username) if user.check_password(password): return user except CustomUser.DoesNotExist: return None def get_user(self, user_id): try: return CustomUser.custom_objects.get(pk=user_id) except CustomUser.DoesNotExist: return None
import sys from datetime import date from unittest import mock from unittest.mock import patch from asgiref.sync import sync_to_async from django.contrib.auth import ( BACKEND_SESSION_KEY, SESSION_KEY, _clean_credentials, aauthenticate, authenticate, get_user, signals, ) from django.contrib.auth.backends import BaseBackend, ModelBackend from django.contrib.auth.forms import PasswordChangeForm, SetPasswordForm from django.contrib.auth.hashers import MD5PasswordHasher from django.contrib.auth.models import AnonymousUser, Group, Permission, User from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ImproperlyConfigured, PermissionDenied from django.http import HttpRequest from django.test import ( Client, RequestFactory, SimpleTestCase, TestCase, modify_settings, override_settings, ) from django.urls import reverse from django.views.debug import ExceptionReporter, technical_500_response from django.views.decorators.debug import sensitive_variables from .models import ( CustomPermissionsUser, CustomUser, CustomUserWithoutIsActiveField, ExtensionUser, UUIDUser, ) class FilteredExceptionReporter(ExceptionReporter): def get_traceback_frames(self): frames = super().get_traceback_frames() return [ frame for frame in frames if not isinstance(dict(frame["vars"]).get("self"), Client) ] class SimpleBackend(BaseBackend): def get_user_permissions(self, user_obj, obj=None): return ["user_perm"] def get_group_permissions(self, user_obj, obj=None): return ["group_perm"] @override_settings( AUTHENTICATION_BACKENDS=["auth_tests.test_auth_backends.SimpleBackend"] ) class BaseBackendTest(TestCase): @classmethod def setUpTestData(cls): cls.user = User.objects.create_user("test", "[email protected]", "test") def test_get_user_permissions(self): self.assertEqual(self.user.get_user_permissions(), {"user_perm"}) async def test_aget_user_permissions(self): self.assertEqual(await self.user.aget_user_permissions(), {"user_perm"}) def test_get_group_permissions(self): self.assertEqual(self.user.get_group_permissions(), {"group_perm"}) async def test_aget_group_permissions(self): self.assertEqual(await self.user.aget_group_permissions(), {"group_perm"}) def test_get_all_permissions(self): self.assertEqual(self.user.get_all_permissions(), {"user_perm", "group_perm"}) async def test_aget_all_permissions(self): self.assertEqual( await self.user.aget_all_permissions(), {"user_perm", "group_perm"} ) def test_has_perm(self): self.assertIs(self.user.has_perm("user_perm"), True) self.assertIs(self.user.has_perm("group_perm"), True) self.assertIs(self.user.has_perm("other_perm", TestObj()), False) async def test_ahas_perm(self): self.assertIs(await self.user.ahas_perm("user_perm"), True) self.assertIs(await self.user.ahas_perm("group_perm"), True) self.assertIs(await self.user.ahas_perm("other_perm", TestObj()), False) def test_has_perms_perm_list_invalid(self): msg = "perm_list must be an iterable of permissions." with self.assertRaisesMessage(ValueError, msg): self.user.has_perms("user_perm") with self.assertRaisesMessage(ValueError, msg): self.user.has_perms(object()) async def test_ahas_perms_perm_list_invalid(self): msg = "perm_list must be an iterable of permissions." with self.assertRaisesMessage(ValueError, msg): await self.user.ahas_perms("user_perm") with self.assertRaisesMessage(ValueError, msg): await self.user.ahas_perms(object()) class CountingMD5PasswordHasher(MD5PasswordHasher): """Hasher that counts how many times it computes a hash.""" calls = 0 def encode(self, *args, **kwargs): type(self).calls += 1 return super().encode(*args, **kwargs) class BaseModelBackendTest: """ A base class for tests that need to validate the ModelBackend with different User models. Subclasses should define a class level UserModel attribute, and a create_users() method to construct two users for test purposes. """ backend = "django.contrib.auth.backends.ModelBackend" @classmethod def setUpClass(cls): cls.enterClassContext( modify_settings(AUTHENTICATION_BACKENDS={"append": cls.backend}) ) super().setUpClass() def setUp(self): # The custom_perms test messes with ContentTypes, which will be cached. # Flush the cache to ensure there are no side effects. self.addCleanup(ContentType.objects.clear_cache) self.create_users() def test_has_perm(self): user = self.UserModel._default_manager.get(pk=self.user.pk) self.assertIs(user.has_perm("auth.test"), False) user.is_staff = True user.save() self.assertIs(user.has_perm("auth.test"), False) user.is_superuser = True user.save() self.assertIs(user.has_perm("auth.test"), True) user.is_staff = True user.is_superuser = True user.is_active = False user.save() self.assertIs(user.has_perm("auth.test"), False) async def test_ahas_perm(self): user = await self.UserModel._default_manager.aget(pk=self.user.pk) self.assertIs(await user.ahas_perm("auth.test"), False) user.is_staff = True await user.asave() self.assertIs(await user.ahas_perm("auth.test"), False) user.is_superuser = True await user.asave() self.assertIs(await user.ahas_perm("auth.test"), True) self.assertIs(await user.ahas_module_perms("auth"), True) user.is_staff = True user.is_superuser = True user.is_active = False await user.asave() self.assertIs(await user.ahas_perm("auth.test"), False) def test_custom_perms(self): user = self.UserModel._default_manager.get(pk=self.user.pk) content_type = ContentType.objects.get_for_model(Group) perm = Permission.objects.create( name="test", content_type=content_type, codename="test" ) user.user_permissions.add(perm) # reloading user to purge the _perm_cache user = self.UserModel._default_manager.get(pk=self.user.pk) self.assertEqual(user.get_all_permissions(), {"auth.test"}) self.assertEqual(user.get_user_permissions(), {"auth.test"}) self.assertEqual(user.get_group_permissions(), set()) self.assertIs(user.has_module_perms("Group"), False) self.assertIs(user.has_module_perms("auth"), True) perm = Permission.objects.create( name="test2", content_type=content_type, codename="test2" ) user.user_permissions.add(perm) perm = Permission.objects.create( name="test3", content_type=content_type, codename="test3" ) user.user_permissions.add(perm) user = self.UserModel._default_manager.get(pk=self.user.pk) expected_user_perms = {"auth.test2", "auth.test", "auth.test3"} self.assertEqual(user.get_all_permissions(), expected_user_perms) self.assertIs(user.has_perm("test"), False) self.assertIs(user.has_perm("auth.test"), True) self.assertIs(user.has_perms(["auth.test2", "auth.test3"]), True) perm = Permission.objects.create( name="test_group", content_type=content_type, codename="test_group" ) group = Group.objects.create(name="test_group") group.permissions.add(perm) user.groups.add(group) user = self.UserModel._default_manager.get(pk=self.user.pk) self.assertEqual( user.get_all_permissions(), {*expected_user_perms, "auth.test_group"} ) self.assertEqual(user.get_user_permissions(), expected_user_perms) self.assertEqual(user.get_group_permissions(), {"auth.test_group"}) self.assertIs(user.has_perms(["auth.test3", "auth.test_group"]), True) user = AnonymousUser() self.assertIs(user.has_perm("test"), False) self.assertIs(user.has_perms(["auth.test2", "auth.test3"]), False) async def test_acustom_perms(self): user = await self.UserModel._default_manager.aget(pk=self.user.pk) content_type = await sync_to_async(ContentType.objects.get_for_model)(Group) perm = await Permission.objects.acreate( name="test", content_type=content_type, codename="test" ) await user.user_permissions.aadd(perm) # Reloading user to purge the _perm_cache. user = await self.UserModel._default_manager.aget(pk=self.user.pk) self.assertEqual(await user.aget_all_permissions(), {"auth.test"}) self.assertEqual(await user.aget_user_permissions(), {"auth.test"}) self.assertEqual(await user.aget_group_permissions(), set()) self.assertIs(await user.ahas_module_perms("Group"), False) self.assertIs(await user.ahas_module_perms("auth"), True) perm = await Permission.objects.acreate( name="test2", content_type=content_type, codename="test2" ) await user.user_permissions.aadd(perm) perm = await Permission.objects.acreate( name="test3", content_type=content_type, codename="test3" ) await user.user_permissions.aadd(perm) user = await self.UserModel._default_manager.aget(pk=self.user.pk) expected_user_perms = {"auth.test2", "auth.test", "auth.test3"} self.assertEqual(await user.aget_all_permissions(), expected_user_perms) self.assertIs(await user.ahas_perm("test"), False) self.assertIs(await user.ahas_perm("auth.test"), True) self.assertIs(await user.ahas_perms(["auth.test2", "auth.test3"]), True) perm = await Permission.objects.acreate( name="test_group", content_type=content_type, codename="test_group" ) group = await Group.objects.acreate(name="test_group") await group.permissions.aadd(perm) await user.groups.aadd(group) user = await self.UserModel._default_manager.aget(pk=self.user.pk) self.assertEqual( await user.aget_all_permissions(), {*expected_user_perms, "auth.test_group"} ) self.assertEqual(await user.aget_user_permissions(), expected_user_perms) self.assertEqual(await user.aget_group_permissions(), {"auth.test_group"}) self.assertIs(await user.ahas_perms(["auth.test3", "auth.test_group"]), True) user = AnonymousUser() self.assertIs(await user.ahas_perm("test"), False) self.assertIs(await user.ahas_perms(["auth.test2", "auth.test3"]), False) def test_has_no_object_perm(self): """Regressiontest for #12462""" user = self.UserModel._default_manager.get(pk=self.user.pk) content_type = ContentType.objects.get_for_model(Group) perm = Permission.objects.create( name="test", content_type=content_type, codename="test" ) user.user_permissions.add(perm) self.assertIs(user.has_perm("auth.test", "object"), False) self.assertEqual(user.get_all_permissions("object"), set()) self.assertIs(user.has_perm("auth.test"), True) self.assertEqual(user.get_all_permissions(), {"auth.test"}) async def test_ahas_no_object_perm(self): """See test_has_no_object_perm()""" user = await self.UserModel._default_manager.aget(pk=self.user.pk) content_type = await sync_to_async(ContentType.objects.get_for_model)(Group) perm = await Permission.objects.acreate( name="test", content_type=content_type, codename="test" ) await user.user_permissions.aadd(perm) self.assertIs(await user.ahas_perm("auth.test", "object"), False) self.assertEqual(await user.aget_all_permissions("object"), set()) self.assertIs(await user.ahas_perm("auth.test"), True) self.assertEqual(await user.aget_all_permissions(), {"auth.test"}) def test_anonymous_has_no_permissions(self): """ #17903 -- Anonymous users shouldn't have permissions in ModelBackend.get_(all|user|group)_permissions(). """ backend = ModelBackend() user = self.UserModel._default_manager.get(pk=self.user.pk) content_type = ContentType.objects.get_for_model(Group) user_perm = Permission.objects.create( name="test", content_type=content_type, codename="test_user" ) group_perm = Permission.objects.create( name="test2", content_type=content_type, codename="test_group" ) user.user_permissions.add(user_perm) group = Group.objects.create(name="test_group") user.groups.add(group) group.permissions.add(group_perm) self.assertEqual( backend.get_all_permissions(user), {"auth.test_user", "auth.test_group"} ) self.assertEqual(backend.get_user_permissions(user), {"auth.test_user"}) self.assertEqual(backend.get_group_permissions(user), {"auth.test_group"}) with mock.patch.object(self.UserModel, "is_anonymous", True): self.assertEqual(backend.get_all_permissions(user), set()) self.assertEqual(backend.get_user_permissions(user), set()) self.assertEqual(backend.get_group_permissions(user), set()) async def test_aanonymous_has_no_permissions(self): """See test_anonymous_has_no_permissions()""" backend = ModelBackend() user = await self.UserModel._default_manager.aget(pk=self.user.pk) content_type = await sync_to_async(ContentType.objects.get_for_model)(Group) user_perm = await Permission.objects.acreate( name="test", content_type=content_type, codename="test_user" ) group_perm = await Permission.objects.acreate( name="test2", content_type=content_type, codename="test_group" ) await user.user_permissions.aadd(user_perm) group = await Group.objects.acreate(name="test_group") await user.groups.aadd(group) await group.permissions.aadd(group_perm) self.assertEqual( await backend.aget_all_permissions(user), {"auth.test_user", "auth.test_group"}, ) self.assertEqual(await backend.aget_user_permissions(user), {"auth.test_user"}) self.assertEqual( await backend.aget_group_permissions(user), {"auth.test_group"} ) with mock.patch.object(self.UserModel, "is_anonymous", True): self.assertEqual(await backend.aget_all_permissions(user), set()) self.assertEqual(await backend.aget_user_permissions(user), set()) self.assertEqual(await backend.aget_group_permissions(user), set()) def test_inactive_has_no_permissions(self): """ #17903 -- Inactive users shouldn't have permissions in ModelBackend.get_(all|user|group)_permissions(). """ backend = ModelBackend() user = self.UserModel._default_manager.get(pk=self.user.pk) content_type = ContentType.objects.get_for_model(Group) user_perm = Permission.objects.create( name="test", content_type=content_type, codename="test_user" ) group_perm = Permission.objects.create( name="test2", content_type=content_type, codename="test_group" ) user.user_permissions.add(user_perm) group = Group.objects.create(name="test_group") user.groups.add(group) group.permissions.add(group_perm) self.assertEqual( backend.get_all_permissions(user), {"auth.test_user", "auth.test_group"} ) self.assertEqual(backend.get_user_permissions(user), {"auth.test_user"}) self.assertEqual(backend.get_group_permissions(user), {"auth.test_group"}) user.is_active = False user.save() self.assertEqual(backend.get_all_permissions(user), set()) self.assertEqual(backend.get_user_permissions(user), set()) self.assertEqual(backend.get_group_permissions(user), set()) async def test_ainactive_has_no_permissions(self): """See test_inactive_has_no_permissions()""" backend = ModelBackend() user = await self.UserModel._default_manager.aget(pk=self.user.pk) content_type = await sync_to_async(ContentType.objects.get_for_model)(Group) user_perm = await Permission.objects.acreate( name="test", content_type=content_type, codename="test_user" ) group_perm = await Permission.objects.acreate( name="test2", content_type=content_type, codename="test_group" ) await user.user_permissions.aadd(user_perm) group = await Group.objects.acreate(name="test_group") await user.groups.aadd(group) await group.permissions.aadd(group_perm) self.assertEqual( await backend.aget_all_permissions(user), {"auth.test_user", "auth.test_group"}, ) self.assertEqual(await backend.aget_user_permissions(user), {"auth.test_user"}) self.assertEqual( await backend.aget_group_permissions(user), {"auth.test_group"} ) user.is_active = False await user.asave() self.assertEqual(await backend.aget_all_permissions(user), set()) self.assertEqual(await backend.aget_user_permissions(user), set()) self.assertEqual(await backend.aget_group_permissions(user), set()) def test_get_all_superuser_permissions(self): """A superuser has all permissions. Refs #14795.""" user = self.UserModel._default_manager.get(pk=self.superuser.pk) self.assertEqual(len(user.get_all_permissions()), len(Permission.objects.all())) async def test_aget_all_superuser_permissions(self): """See test_get_all_superuser_permissions()""" user = await self.UserModel._default_manager.aget(pk=self.superuser.pk) self.assertEqual( len(await user.aget_all_permissions()), await Permission.objects.acount() ) @override_settings( PASSWORD_HASHERS=["auth_tests.test_auth_backends.CountingMD5PasswordHasher"] ) def test_authentication_timing(self): """ Hasher is run once regardless of whether the user exists. Refs #20760. """ # Re-set the password, because this tests overrides PASSWORD_HASHERS self.user.set_password("test") self.user.save() CountingMD5PasswordHasher.calls = 0 username = getattr(self.user, self.UserModel.USERNAME_FIELD) authenticate(username=username, password="test") self.assertEqual(CountingMD5PasswordHasher.calls, 1) CountingMD5PasswordHasher.calls = 0 authenticate(username="no_such_user", password="test") self.assertEqual(CountingMD5PasswordHasher.calls, 1) @override_settings( PASSWORD_HASHERS=["auth_tests.test_auth_backends.CountingMD5PasswordHasher"] ) async def test_aauthentication_timing(self): """See test_authentication_timing()""" # Re-set the password, because this tests overrides PASSWORD_HASHERS. self.user.set_password("test") await self.user.asave() CountingMD5PasswordHasher.calls = 0 username = getattr(self.user, self.UserModel.USERNAME_FIELD) await aauthenticate(username=username, password="test") self.assertEqual(CountingMD5PasswordHasher.calls, 1) CountingMD5PasswordHasher.calls = 0 await aauthenticate(username="no_such_user", password="test") self.assertEqual(CountingMD5PasswordHasher.calls, 1) @override_settings( PASSWORD_HASHERS=["auth_tests.test_auth_backends.CountingMD5PasswordHasher"] ) def test_authentication_without_credentials(self): CountingMD5PasswordHasher.calls = 0 for credentials in ( {}, {"username": getattr(self.user, self.UserModel.USERNAME_FIELD)}, {"password": "test"}, ): with self.subTest(credentials=credentials): with self.assertNumQueries(0): authenticate(**credentials) self.assertEqual(CountingMD5PasswordHasher.calls, 0) class ModelBackendTest(BaseModelBackendTest, TestCase): """ Tests for the ModelBackend using the default User model. """ UserModel = User user_credentials = {"username": "test", "password": "test"} def create_users(self): self.user = User.objects.create_user( email="[email protected]", **self.user_credentials ) self.superuser = User.objects.create_superuser( username="test2", email="[email protected]", password="test", ) def test_authenticate_inactive(self): """ An inactive user can't authenticate. """ self.assertEqual(authenticate(**self.user_credentials), self.user) self.user.is_active = False self.user.save() self.assertIsNone(authenticate(**self.user_credentials)) async def test_aauthenticate_inactive(self): """ An inactive user can't authenticate. """ self.assertEqual(await aauthenticate(**self.user_credentials), self.user) self.user.is_active = False await self.user.asave() self.assertIsNone(await aauthenticate(**self.user_credentials)) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithoutIsActiveField") def test_authenticate_user_without_is_active_field(self): """ A custom user without an `is_active` field is allowed to authenticate. """ user = CustomUserWithoutIsActiveField.objects._create_user( username="test", email="[email protected]", password="test", ) self.assertEqual(authenticate(username="test", password="test"), user) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithoutIsActiveField") async def test_aauthenticate_user_without_is_active_field(self): """ A custom user without an `is_active` field is allowed to authenticate. """ user = await CustomUserWithoutIsActiveField.objects._acreate_user( username="test", email="[email protected]", password="test", ) self.assertEqual(await aauthenticate(username="test", password="test"), user) @override_settings(AUTH_USER_MODEL="auth_tests.ExtensionUser") class ExtensionUserModelBackendTest(BaseModelBackendTest, TestCase): """ Tests for the ModelBackend using the custom ExtensionUser model. This isn't a perfect test, because both the User and ExtensionUser are synchronized to the database, which wouldn't ordinary happen in production. As a result, it doesn't catch errors caused by the non- existence of the User table. The specific problem is queries on .filter(groups__user) et al, which makes an implicit assumption that the user model is called 'User'. In production, the auth.User table won't exist, so the requested join won't exist either; in testing, the auth.User *does* exist, and so does the join. However, the join table won't contain any useful data; for testing, we check that the data we expect actually does exist. """ UserModel = ExtensionUser def create_users(self): self.user = ExtensionUser._default_manager.create_user( username="test", email="[email protected]", password="test", date_of_birth=date(2006, 4, 25), ) self.superuser = ExtensionUser._default_manager.create_superuser( username="test2", email="[email protected]", password="test", date_of_birth=date(1976, 11, 8), ) @override_settings(AUTH_USER_MODEL="auth_tests.CustomPermissionsUser") class CustomPermissionsUserModelBackendTest(BaseModelBackendTest, TestCase): """ Tests for the ModelBackend using the CustomPermissionsUser model. As with the ExtensionUser test, this isn't a perfect test, because both the User and CustomPermissionsUser are synchronized to the database, which wouldn't ordinary happen in production. """ UserModel = CustomPermissionsUser def create_users(self): self.user = CustomPermissionsUser._default_manager.create_user( email="[email protected]", password="test", date_of_birth=date(2006, 4, 25) ) self.superuser = CustomPermissionsUser._default_manager.create_superuser( email="[email protected]", password="test", date_of_birth=date(1976, 11, 8) ) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUser") class CustomUserModelBackendAuthenticateTest(TestCase): """ The model backend can accept a credentials kwarg labeled with custom user model's USERNAME_FIELD. """ def test_authenticate(self): test_user = CustomUser._default_manager.create_user( email="[email protected]", password="test", date_of_birth=date(2006, 4, 25) ) authenticated_user = authenticate(email="[email protected]", password="test") self.assertEqual(test_user, authenticated_user) async def test_aauthenticate(self): test_user = await CustomUser._default_manager.acreate_user( email="[email protected]", password="test", date_of_birth=date(2006, 4, 25) ) authenticated_user = await aauthenticate( email="[email protected]", password="test" ) self.assertEqual(test_user, authenticated_user) @override_settings(AUTH_USER_MODEL="auth_tests.UUIDUser") class UUIDUserTests(TestCase): def test_login(self): """ A custom user with a UUID primary key should be able to login. """ user = UUIDUser.objects.create_user(username="uuid", password="test") self.assertTrue(self.client.login(username="uuid", password="test")) self.assertEqual( UUIDUser.objects.get(pk=self.client.session[SESSION_KEY]), user ) async def test_alogin(self): """See test_login()""" user = await UUIDUser.objects.acreate_user(username="uuid", password="test") self.assertTrue(await self.client.alogin(username="uuid", password="test")) session_key = await self.client.session.aget(SESSION_KEY) self.assertEqual(await UUIDUser.objects.aget(pk=session_key), user) class TestObj: pass class SimpleRowlevelBackend: def has_perm(self, user, perm, obj=None): if not obj: return # We only support row level perms if isinstance(obj, TestObj): if user.username == "test2": return True elif user.is_anonymous and perm == "anon": return True elif not user.is_active and perm == "inactive": return True return False async def ahas_perm(self, user, perm, obj=None): return self.has_perm(user, perm, obj) def has_module_perms(self, user, app_label): return (user.is_anonymous or user.is_active) and app_label == "app1" async def ahas_module_perms(self, user, app_label): return self.has_module_perms(user, app_label) def get_all_permissions(self, user, obj=None): if not obj: return [] # We only support row level perms if not isinstance(obj, TestObj): return ["none"] if user.is_anonymous: return ["anon"] if user.username == "test2": return ["simple", "advanced"] else: return ["simple"] async def aget_all_permissions(self, user, obj=None): return self.get_all_permissions(user, obj) def get_group_permissions(self, user, obj=None): if not obj: return # We only support row level perms if not isinstance(obj, TestObj): return ["none"] if "test_group" in [group.name for group in user.groups.all()]: return ["group_perm"] else: return ["none"] @modify_settings( AUTHENTICATION_BACKENDS={ "append": "auth_tests.test_auth_backends.SimpleRowlevelBackend", } ) class RowlevelBackendTest(TestCase): """ Tests for auth backend that supports object level permissions """ @classmethod def setUpTestData(cls): cls.user1 = User.objects.create_user("test", "[email protected]", "test") cls.user2 = User.objects.create_user("test2", "[email protected]", "test") cls.user3 = User.objects.create_user("test3", "[email protected]", "test") def tearDown(self): # The get_group_permissions test messes with ContentTypes, which will # be cached; flush the cache to ensure there are no side effects # Refs #14975, #14925 ContentType.objects.clear_cache() def test_has_perm(self): self.assertIs(self.user1.has_perm("perm", TestObj()), False) self.assertIs(self.user2.has_perm("perm", TestObj()), True) self.assertIs(self.user2.has_perm("perm"), False) self.assertIs(self.user2.has_perms(["simple", "advanced"], TestObj()), True) self.assertIs(self.user3.has_perm("perm", TestObj()), False) self.assertIs(self.user3.has_perm("anon", TestObj()), False) self.assertIs(self.user3.has_perms(["simple", "advanced"], TestObj()), False) def test_get_all_permissions(self): self.assertEqual(self.user1.get_all_permissions(TestObj()), {"simple"}) self.assertEqual( self.user2.get_all_permissions(TestObj()), {"simple", "advanced"} ) self.assertEqual(self.user2.get_all_permissions(), set()) def test_get_group_permissions(self): group = Group.objects.create(name="test_group") self.user3.groups.add(group) self.assertEqual(self.user3.get_group_permissions(TestObj()), {"group_perm"}) @override_settings( AUTHENTICATION_BACKENDS=["auth_tests.test_auth_backends.SimpleRowlevelBackend"], ) class AnonymousUserBackendTest(SimpleTestCase): """ Tests for AnonymousUser delegating to backend. """ def setUp(self): self.user1 = AnonymousUser() def test_has_perm(self): self.assertIs(self.user1.has_perm("perm", TestObj()), False) self.assertIs(self.user1.has_perm("anon", TestObj()), True) async def test_ahas_perm(self): self.assertIs(await self.user1.ahas_perm("perm", TestObj()), False) self.assertIs(await self.user1.ahas_perm("anon", TestObj()), True) def test_has_perms(self): self.assertIs(self.user1.has_perms(["anon"], TestObj()), True) self.assertIs(self.user1.has_perms(["anon", "perm"], TestObj()), False) async def test_ahas_perms(self): self.assertIs(await self.user1.ahas_perms(["anon"], TestObj()), True) self.assertIs(await self.user1.ahas_perms(["anon", "perm"], TestObj()), False) def test_has_perms_perm_list_invalid(self): msg = "perm_list must be an iterable of permissions." with self.assertRaisesMessage(ValueError, msg): self.user1.has_perms("perm") with self.assertRaisesMessage(ValueError, msg): self.user1.has_perms(object()) async def test_ahas_perms_perm_list_invalid(self): msg = "perm_list must be an iterable of permissions." with self.assertRaisesMessage(ValueError, msg): await self.user1.ahas_perms("perm") with self.assertRaisesMessage(ValueError, msg): await self.user1.ahas_perms(object()) def test_has_module_perms(self): self.assertIs(self.user1.has_module_perms("app1"), True) self.assertIs(self.user1.has_module_perms("app2"), False) async def test_ahas_module_perms(self): self.assertIs(await self.user1.ahas_module_perms("app1"), True) self.assertIs(await self.user1.ahas_module_perms("app2"), False) def test_get_all_permissions(self): self.assertEqual(self.user1.get_all_permissions(TestObj()), {"anon"}) async def test_aget_all_permissions(self): self.assertEqual(await self.user1.aget_all_permissions(TestObj()), {"anon"}) @override_settings(AUTHENTICATION_BACKENDS=[]) class NoBackendsTest(TestCase): """ An appropriate error is raised if no auth backends are provided. """ @classmethod def setUpTestData(cls): cls.user = User.objects.create_user("test", "[email protected]", "test") def test_raises_exception(self): msg = ( "No authentication backends have been defined. " "Does AUTHENTICATION_BACKENDS contain anything?" ) with self.assertRaisesMessage(ImproperlyConfigured, msg): self.user.has_perm(("perm", TestObj())) async def test_araises_exception(self): msg = ( "No authentication backends have been defined. " "Does AUTHENTICATION_BACKENDS contain anything?" ) with self.assertRaisesMessage(ImproperlyConfigured, msg): await self.user.ahas_perm(("perm", TestObj())) @override_settings( AUTHENTICATION_BACKENDS=["auth_tests.test_auth_backends.SimpleRowlevelBackend"] ) class InActiveUserBackendTest(TestCase): """ Tests for an inactive user """ @classmethod def setUpTestData(cls): cls.user1 = User.objects.create_user("test", "[email protected]", "test") cls.user1.is_active = False cls.user1.save() def test_has_perm(self): self.assertIs(self.user1.has_perm("perm", TestObj()), False) self.assertIs(self.user1.has_perm("inactive", TestObj()), True) def test_has_module_perms(self): self.assertIs(self.user1.has_module_perms("app1"), False) self.assertIs(self.user1.has_module_perms("app2"), False) class PermissionDeniedBackend: """ Always raises PermissionDenied in `authenticate`, `has_perm` and `has_module_perms`. """ def authenticate(self, request, username=None, password=None): raise PermissionDenied async def aauthenticate(self, request, username=None, password=None): raise PermissionDenied def has_perm(self, user_obj, perm, obj=None): raise PermissionDenied async def ahas_perm(self, user_obj, perm, obj=None): raise PermissionDenied def has_module_perms(self, user_obj, app_label): raise PermissionDenied async def ahas_module_perms(self, user_obj, app_label): raise PermissionDenied class PermissionDeniedBackendTest(TestCase): """ Other backends are not checked once a backend raises PermissionDenied """ backend = "auth_tests.test_auth_backends.PermissionDeniedBackend" @classmethod def setUpTestData(cls): cls.user1 = User.objects.create_user("test", "[email protected]", "test") def setUp(self): self.user_login_failed = [] signals.user_login_failed.connect(self.user_login_failed_listener) self.addCleanup( signals.user_login_failed.disconnect, self.user_login_failed_listener ) def user_login_failed_listener(self, sender, credentials, **kwargs): self.user_login_failed.append(credentials) @modify_settings(AUTHENTICATION_BACKENDS={"prepend": backend}) def test_permission_denied(self): """ user is not authenticated after a backend raises permission denied #2550 """ self.assertIsNone(authenticate(username="test", password="test")) # user_login_failed signal is sent. self.assertEqual( self.user_login_failed, [{"password": "********************", "username": "test"}], ) @modify_settings(AUTHENTICATION_BACKENDS={"prepend": backend}) async def test_aauthenticate_permission_denied(self): self.assertIsNone(await aauthenticate(username="test", password="test")) # user_login_failed signal is sent. self.assertEqual( self.user_login_failed, [{"password": "********************", "username": "test"}], ) @modify_settings(AUTHENTICATION_BACKENDS={"append": backend}) def test_authenticates(self): self.assertEqual(authenticate(username="test", password="test"), self.user1) @modify_settings(AUTHENTICATION_BACKENDS={"append": backend}) async def test_aauthenticate(self): self.assertEqual( await aauthenticate(username="test", password="test"), self.user1 ) @modify_settings(AUTHENTICATION_BACKENDS={"prepend": backend}) def test_has_perm_denied(self): content_type = ContentType.objects.get_for_model(Group) perm = Permission.objects.create( name="test", content_type=content_type, codename="test" ) self.user1.user_permissions.add(perm) self.assertIs(self.user1.has_perm("auth.test"), False) self.assertIs(self.user1.has_module_perms("auth"), False) @modify_settings(AUTHENTICATION_BACKENDS={"prepend": backend}) async def test_ahas_perm_denied(self): content_type = await sync_to_async(ContentType.objects.get_for_model)(Group) perm = await Permission.objects.acreate( name="test", content_type=content_type, codename="test" ) await self.user1.user_permissions.aadd(perm) self.assertIs(await self.user1.ahas_perm("auth.test"), False) self.assertIs(await self.user1.ahas_module_perms("auth"), False) @modify_settings(AUTHENTICATION_BACKENDS={"append": backend}) def test_has_perm(self): content_type = ContentType.objects.get_for_model(Group) perm = Permission.objects.create( name="test", content_type=content_type, codename="test" ) self.user1.user_permissions.add(perm) self.assertIs(self.user1.has_perm("auth.test"), True) self.assertIs(self.user1.has_module_perms("auth"), True) @modify_settings(AUTHENTICATION_BACKENDS={"append": backend}) async def test_ahas_perm(self): content_type = await sync_to_async(ContentType.objects.get_for_model)(Group) perm = await Permission.objects.acreate( name="test", content_type=content_type, codename="test" ) await self.user1.user_permissions.aadd(perm) self.assertIs(await self.user1.ahas_perm("auth.test"), True) self.assertIs(await self.user1.ahas_module_perms("auth"), True) class NewModelBackend(ModelBackend): pass class ChangedBackendSettingsTest(TestCase): """ Tests for changes in the settings.AUTHENTICATION_BACKENDS """ backend = "auth_tests.test_auth_backends.NewModelBackend" TEST_USERNAME = "test_user" TEST_PASSWORD = "test_password" TEST_EMAIL = "[email protected]" @classmethod def setUpTestData(cls): User.objects.create_user(cls.TEST_USERNAME, cls.TEST_EMAIL, cls.TEST_PASSWORD) @override_settings(AUTHENTICATION_BACKENDS=[backend]) def test_changed_backend_settings(self): """ Removing a backend configured in AUTHENTICATION_BACKENDS makes already logged-in users disconnect. """ # Get a session for the test user self.assertTrue( self.client.login( username=self.TEST_USERNAME, password=self.TEST_PASSWORD, ) ) # Prepare a request object request = HttpRequest() request.session = self.client.session # Remove NewModelBackend with self.settings( AUTHENTICATION_BACKENDS=["django.contrib.auth.backends.ModelBackend"] ): # Get the user from the request user = get_user(request) # Assert that the user retrieval is successful and the user is # anonymous as the backend is not longer available. self.assertIsNotNone(user) self.assertTrue(user.is_anonymous) class TypeErrorBackend: """ Always raises TypeError. """ @sensitive_variables("password") def authenticate(self, request, username=None, password=None): raise TypeError @sensitive_variables("password") async def aauthenticate(self, request, username=None, password=None): raise TypeError class TypeErrorValidator: """ Always raises a TypeError. """ def validate(self, password=None, user=None): raise TypeError class SkippedBackend: def authenticate(self): # Doesn't accept any credentials so is skipped by authenticate(). pass class SkippedBackendWithDecoratedMethod: @sensitive_variables() def authenticate(self): pass class AuthenticateTests(TestCase): @classmethod def setUpTestData(cls): cls.user1 = User.objects.create_user("test", "[email protected]", "test") def setUp(self): self.sensitive_password = "mypassword" @override_settings( AUTHENTICATION_BACKENDS=["auth_tests.test_auth_backends.TypeErrorBackend"] ) def test_type_error_raised(self): """A TypeError within a backend is propagated properly (#18171).""" with self.assertRaises(TypeError): authenticate(username="test", password="test") @override_settings( AUTHENTICATION_BACKENDS=["auth_tests.test_auth_backends.TypeErrorBackend"] ) def test_authenticate_sensitive_variables(self): try: authenticate(username="testusername", password=self.sensitive_password) except TypeError: exc_info = sys.exc_info() rf = RequestFactory() response = technical_500_response(rf.get("/"), *exc_info) self.assertNotContains(response, self.sensitive_password, status_code=500) self.assertContains(response, "TypeErrorBackend", status_code=500) self.assertContains( response, '<tr><td>credentials</td><td class="code">' "<pre>&#39;********************&#39;</pre></td></tr>", html=True, status_code=500, ) @override_settings( AUTHENTICATION_BACKENDS=["auth_tests.test_auth_backends.TypeErrorBackend"] ) async def test_aauthenticate_sensitive_variables(self): try: await aauthenticate( username="testusername", password=self.sensitive_password ) except TypeError: exc_info = sys.exc_info() rf = RequestFactory() response = technical_500_response(rf.get("/"), *exc_info) self.assertNotContains(response, self.sensitive_password, status_code=500) self.assertContains(response, "TypeErrorBackend", status_code=500) self.assertContains( response, '<tr><td>credentials</td><td class="code">' "<pre>&#39;********************&#39;</pre></td></tr>", html=True, status_code=500, ) def test_clean_credentials_sensitive_variables(self): try: # Passing in a list to cause an exception _clean_credentials([1, self.sensitive_password]) except TypeError: exc_info = sys.exc_info() rf = RequestFactory() response = technical_500_response(rf.get("/"), *exc_info) self.assertNotContains(response, self.sensitive_password, status_code=500) self.assertContains( response, '<tr><td>credentials</td><td class="code">' "<pre>&#39;********************&#39;</pre></td></tr>", html=True, status_code=500, ) @override_settings( ROOT_URLCONF="django.contrib.auth.urls", AUTHENTICATION_BACKENDS=["auth_tests.test_auth_backends.TypeErrorBackend"], ) def test_login_process_sensitive_variables(self): try: self.client.post( reverse("login"), dict(username="testusername", password=self.sensitive_password), ) except TypeError: exc_info = sys.exc_info() rf = RequestFactory() with patch("django.views.debug.ExceptionReporter", FilteredExceptionReporter): response = technical_500_response(rf.get("/"), *exc_info) self.assertNotContains(response, self.sensitive_password, status_code=500) self.assertContains(response, "TypeErrorBackend", status_code=500) # AuthenticationForm.clean(). self.assertContains( response, '<tr><td>password</td><td class="code">' "<pre>&#39;********************&#39;</pre></td></tr>", html=True, status_code=500, ) def test_setpasswordform_validate_passwords_sensitive_variables(self): password_form = SetPasswordForm(AnonymousUser()) password_form.cleaned_data = { "password1": self.sensitive_password, "password2": self.sensitive_password + "2", } try: password_form.validate_passwords() except ValueError: exc_info = sys.exc_info() rf = RequestFactory() response = technical_500_response(rf.get("/"), *exc_info) self.assertNotContains(response, self.sensitive_password, status_code=500) self.assertNotContains(response, self.sensitive_password + "2", status_code=500) self.assertContains( response, '<tr><td>password1</td><td class="code">' "<pre>&#x27;********************&#x27;</pre></td></tr>", html=True, status_code=500, ) self.assertContains( response, '<tr><td>password2</td><td class="code">' "<pre>&#x27;********************&#x27;</pre></td></tr>", html=True, status_code=500, ) @override_settings( AUTH_PASSWORD_VALIDATORS=[ {"NAME": __name__ + ".TypeErrorValidator"}, ] ) def test_setpasswordform_validate_password_for_user_sensitive_variables(self): password_form = SetPasswordForm(AnonymousUser()) password_form.cleaned_data = {"password2": self.sensitive_password} try: password_form.validate_password_for_user(AnonymousUser()) except TypeError: exc_info = sys.exc_info() rf = RequestFactory() response = technical_500_response(rf.get("/"), *exc_info) self.assertNotContains(response, self.sensitive_password, status_code=500) self.assertContains( response, '<tr><td>password</td><td class="code">' "<pre>&#x27;********************&#x27;</pre></td></tr>", html=True, status_code=500, ) def test_passwordchangeform_clean_old_password_sensitive_variables(self): password_form = PasswordChangeForm(User()) password_form.cleaned_data = {"old_password": self.sensitive_password} password_form.error_messages = None try: password_form.clean_old_password() except TypeError: exc_info = sys.exc_info() rf = RequestFactory() response = technical_500_response(rf.get("/"), *exc_info) self.assertNotContains(response, self.sensitive_password, status_code=500) self.assertContains( response, '<tr><td>old_password</td><td class="code">' "<pre>&#x27;********************&#x27;</pre></td></tr>", html=True, status_code=500, ) @override_settings( AUTHENTICATION_BACKENDS=( "auth_tests.test_auth_backends.SkippedBackend", "django.contrib.auth.backends.ModelBackend", ) ) def test_skips_backends_without_arguments(self): """ A backend (SkippedBackend) is ignored if it doesn't accept the credentials as arguments. """ self.assertEqual(authenticate(username="test", password="test"), self.user1) @override_settings( AUTHENTICATION_BACKENDS=( "auth_tests.test_auth_backends.SkippedBackendWithDecoratedMethod", "django.contrib.auth.backends.ModelBackend", ) ) def test_skips_backends_with_decorated_method(self): self.assertEqual(authenticate(username="test", password="test"), self.user1) class ImproperlyConfiguredUserModelTest(TestCase): """ An exception from within get_user_model() is propagated and doesn't raise an UnboundLocalError (#21439). """ @classmethod def setUpTestData(cls): cls.user1 = User.objects.create_user("test", "[email protected]", "test") def setUp(self): self.client.login(username="test", password="test") @override_settings(AUTH_USER_MODEL="thismodel.doesntexist") def test_does_not_shadow_exception(self): # Prepare a request object request = HttpRequest() request.session = self.client.session msg = ( "AUTH_USER_MODEL refers to model 'thismodel.doesntexist' " "that has not been installed" ) with self.assertRaisesMessage(ImproperlyConfigured, msg): get_user(request) class ImportedModelBackend(ModelBackend): pass class CustomModelBackend(ModelBackend): pass class OtherModelBackend(ModelBackend): pass class ImportedBackendTests(TestCase): """ #23925 - The backend path added to the session should be the same as the one defined in AUTHENTICATION_BACKENDS setting. """ backend = "auth_tests.backend_alias.ImportedModelBackend" @override_settings(AUTHENTICATION_BACKENDS=[backend]) def test_backend_path(self): username = "username" password = "password" User.objects.create_user(username, "email", password) self.assertTrue(self.client.login(username=username, password=password)) request = HttpRequest() request.session = self.client.session self.assertEqual(request.session[BACKEND_SESSION_KEY], self.backend) class SelectingBackendTests(TestCase): backend = "auth_tests.test_auth_backends.CustomModelBackend" other_backend = "auth_tests.test_auth_backends.OtherModelBackend" username = "username" password = "password" def assertBackendInSession(self, backend): request = HttpRequest() request.session = self.client.session self.assertEqual(request.session[BACKEND_SESSION_KEY], backend) @override_settings(AUTHENTICATION_BACKENDS=[backend]) def test_backend_path_login_without_authenticate_single_backend(self): user = User.objects.create_user(self.username, "email", self.password) self.client._login(user) self.assertBackendInSession(self.backend) @override_settings(AUTHENTICATION_BACKENDS=[backend, other_backend]) def test_backend_path_login_without_authenticate_multiple_backends(self): user = User.objects.create_user(self.username, "email", self.password) expected_message = ( "You have multiple authentication backends configured and " "therefore must provide the `backend` argument or set the " "`backend` attribute on the user." ) with self.assertRaisesMessage(ValueError, expected_message): self.client._login(user) def test_non_string_backend(self): user = User.objects.create_user(self.username, "email", self.password) expected_message = ( "backend must be a dotted import path string (got " "<class 'django.contrib.auth.backends.ModelBackend'>)." ) with self.assertRaisesMessage(TypeError, expected_message): self.client._login(user, backend=ModelBackend) @override_settings(AUTHENTICATION_BACKENDS=[backend, other_backend]) def test_backend_path_login_with_explicit_backends(self): user = User.objects.create_user(self.username, "email", self.password) self.client._login(user, self.other_backend) self.assertBackendInSession(self.other_backend) @override_settings( AUTHENTICATION_BACKENDS=["django.contrib.auth.backends.AllowAllUsersModelBackend"] ) class AllowAllUsersModelBackendTest(TestCase): """ Inactive users may authenticate with the AllowAllUsersModelBackend. """ user_credentials = {"username": "test", "password": "test"} @classmethod def setUpTestData(cls): cls.user = User.objects.create_user( email="[email protected]", is_active=False, **cls.user_credentials ) def test_authenticate(self): self.assertFalse(self.user.is_active) self.assertEqual(authenticate(**self.user_credentials), self.user) def test_get_user(self): self.client.force_login(self.user) request = HttpRequest() request.session = self.client.session user = get_user(request) self.assertEqual(user, self.user)
django