Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
test_credential_skip_validate
(hass)
Test credential can skip validate.
Test credential can skip validate.
async def test_credential_skip_validate(hass): """Test credential can skip validate.""" with async_patch("aiobotocore.AioSession", new=MockAioSession): await async_setup_component( hass, "aws", { "aws": { "credentials": [ { "name": "key", "aws_access_key_id": "not-valid", "aws_secret_access_key": "dont-care", "validate": False, } ] } }, ) await hass.async_block_till_done() sessions = hass.data[aws.DATA_SESSIONS] assert sessions is not None assert len(sessions) == 1 session = sessions.get("key") assert isinstance(session, MockAioSession) session.get_user.assert_not_awaited()
[ "async", "def", "test_credential_skip_validate", "(", "hass", ")", ":", "with", "async_patch", "(", "\"aiobotocore.AioSession\"", ",", "new", "=", "MockAioSession", ")", ":", "await", "async_setup_component", "(", "hass", ",", "\"aws\"", ",", "{", "\"aws\"", ":", "{", "\"credentials\"", ":", "[", "{", "\"name\"", ":", "\"key\"", ",", "\"aws_access_key_id\"", ":", "\"not-valid\"", ",", "\"aws_secret_access_key\"", ":", "\"dont-care\"", ",", "\"validate\"", ":", "False", ",", "}", "]", "}", "}", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "sessions", "=", "hass", ".", "data", "[", "aws", ".", "DATA_SESSIONS", "]", "assert", "sessions", "is", "not", "None", "assert", "len", "(", "sessions", ")", "==", "1", "session", "=", "sessions", ".", "get", "(", "\"key\"", ")", "assert", "isinstance", "(", "session", ",", "MockAioSession", ")", "session", ".", "get_user", ".", "assert_not_awaited", "(", ")" ]
[ 229, 0 ]
[ 255, 41 ]
python
en
['en', 'en', 'en']
True
MockAioSession.__init__
(self, *args, **kwargs)
Init a mock session.
Init a mock session.
def __init__(self, *args, **kwargs): """Init a mock session.""" self.get_user = AsyncMock() self.invoke = AsyncMock() self.publish = AsyncMock() self.send_message = AsyncMock()
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "get_user", "=", "AsyncMock", "(", ")", "self", ".", "invoke", "=", "AsyncMock", "(", ")", "self", ".", "publish", "=", "AsyncMock", "(", ")", "self", ".", "send_message", "=", "AsyncMock", "(", ")" ]
[ 10, 4 ]
[ 15, 39 ]
python
en
['en', 'bg', 'en']
True
MockAioSession.create_client
(self, *args, **kwargs)
Create a mocked client.
Create a mocked client.
def create_client(self, *args, **kwargs): # pylint: disable=no-self-use """Create a mocked client.""" return MagicMock( __aenter__=AsyncMock( return_value=AsyncMock( get_user=self.get_user, # iam invoke=self.invoke, # lambda publish=self.publish, # sns send_message=self.send_message, # sqs ) ), __aexit__=AsyncMock(), )
[ "def", "create_client", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=no-self-use", "return", "MagicMock", "(", "__aenter__", "=", "AsyncMock", "(", "return_value", "=", "AsyncMock", "(", "get_user", "=", "self", ".", "get_user", ",", "# iam", "invoke", "=", "self", ".", "invoke", ",", "# lambda", "publish", "=", "self", ".", "publish", ",", "# sns", "send_message", "=", "self", ".", "send_message", ",", "# sqs", ")", ")", ",", "__aexit__", "=", "AsyncMock", "(", ")", ",", ")" ]
[ 17, 4 ]
[ 29, 9 ]
python
en
['en', 'en', 'en']
True
mock_request
()
Mock a request.
Mock a request.
def mock_request(): """Mock a request.""" return Mock(app={"hass": Mock(is_stopping=False)}, match_info={})
[ "def", "mock_request", "(", ")", ":", "return", "Mock", "(", "app", "=", "{", "\"hass\"", ":", "Mock", "(", "is_stopping", "=", "False", ")", "}", ",", "match_info", "=", "{", "}", ")" ]
[ 19, 0 ]
[ 21, 69 ]
python
en
['en', 'en', 'en']
True
mock_request_with_stopping
()
Mock a request.
Mock a request.
def mock_request_with_stopping(): """Mock a request.""" return Mock(app={"hass": Mock(is_stopping=True)}, match_info={})
[ "def", "mock_request_with_stopping", "(", ")", ":", "return", "Mock", "(", "app", "=", "{", "\"hass\"", ":", "Mock", "(", "is_stopping", "=", "True", ")", "}", ",", "match_info", "=", "{", "}", ")" ]
[ 25, 0 ]
[ 27, 68 ]
python
en
['en', 'en', 'en']
True
test_invalid_json
(caplog)
Test trying to return invalid JSON.
Test trying to return invalid JSON.
async def test_invalid_json(caplog): """Test trying to return invalid JSON.""" view = HomeAssistantView() with pytest.raises(HTTPInternalServerError): view.json(float("NaN")) assert str(float("NaN")) in caplog.text
[ "async", "def", "test_invalid_json", "(", "caplog", ")", ":", "view", "=", "HomeAssistantView", "(", ")", "with", "pytest", ".", "raises", "(", "HTTPInternalServerError", ")", ":", "view", ".", "json", "(", "float", "(", "\"NaN\"", ")", ")", "assert", "str", "(", "float", "(", "\"NaN\"", ")", ")", "in", "caplog", ".", "text" ]
[ 30, 0 ]
[ 37, 43 ]
python
en
['en', 'en', 'en']
True
test_handling_unauthorized
(mock_request)
Test handling unauth exceptions.
Test handling unauth exceptions.
async def test_handling_unauthorized(mock_request): """Test handling unauth exceptions.""" with pytest.raises(HTTPUnauthorized): await request_handler_factory( Mock(requires_auth=False), AsyncMock(side_effect=Unauthorized) )(mock_request)
[ "async", "def", "test_handling_unauthorized", "(", "mock_request", ")", ":", "with", "pytest", ".", "raises", "(", "HTTPUnauthorized", ")", ":", "await", "request_handler_factory", "(", "Mock", "(", "requires_auth", "=", "False", ")", ",", "AsyncMock", "(", "side_effect", "=", "Unauthorized", ")", ")", "(", "mock_request", ")" ]
[ 40, 0 ]
[ 45, 23 ]
python
en
['en', 'en', 'it']
True
test_handling_invalid_data
(mock_request)
Test handling unauth exceptions.
Test handling unauth exceptions.
async def test_handling_invalid_data(mock_request): """Test handling unauth exceptions.""" with pytest.raises(HTTPBadRequest): await request_handler_factory( Mock(requires_auth=False), AsyncMock(side_effect=vol.Invalid("yo")) )(mock_request)
[ "async", "def", "test_handling_invalid_data", "(", "mock_request", ")", ":", "with", "pytest", ".", "raises", "(", "HTTPBadRequest", ")", ":", "await", "request_handler_factory", "(", "Mock", "(", "requires_auth", "=", "False", ")", ",", "AsyncMock", "(", "side_effect", "=", "vol", ".", "Invalid", "(", "\"yo\"", ")", ")", ")", "(", "mock_request", ")" ]
[ 48, 0 ]
[ 53, 23 ]
python
en
['en', 'en', 'it']
True
test_handling_service_not_found
(mock_request)
Test handling unauth exceptions.
Test handling unauth exceptions.
async def test_handling_service_not_found(mock_request): """Test handling unauth exceptions.""" with pytest.raises(HTTPInternalServerError): await request_handler_factory( Mock(requires_auth=False), AsyncMock(side_effect=ServiceNotFound("test", "test")), )(mock_request)
[ "async", "def", "test_handling_service_not_found", "(", "mock_request", ")", ":", "with", "pytest", ".", "raises", "(", "HTTPInternalServerError", ")", ":", "await", "request_handler_factory", "(", "Mock", "(", "requires_auth", "=", "False", ")", ",", "AsyncMock", "(", "side_effect", "=", "ServiceNotFound", "(", "\"test\"", ",", "\"test\"", ")", ")", ",", ")", "(", "mock_request", ")" ]
[ 56, 0 ]
[ 62, 23 ]
python
en
['en', 'en', 'it']
True
test_not_running
(mock_request_with_stopping)
Test we get a 503 when not running.
Test we get a 503 when not running.
async def test_not_running(mock_request_with_stopping): """Test we get a 503 when not running.""" response = await request_handler_factory( Mock(requires_auth=False), AsyncMock(side_effect=Unauthorized) )(mock_request_with_stopping) assert response.status == 503
[ "async", "def", "test_not_running", "(", "mock_request_with_stopping", ")", ":", "response", "=", "await", "request_handler_factory", "(", "Mock", "(", "requires_auth", "=", "False", ")", ",", "AsyncMock", "(", "side_effect", "=", "Unauthorized", ")", ")", "(", "mock_request_with_stopping", ")", "assert", "response", ".", "status", "==", "503" ]
[ 65, 0 ]
[ 70, 33 ]
python
en
['en', 'lb', 'en']
True
conv2d
(x_input, w_matrix)
conv2d returns a 2d convolution layer with full stride.
conv2d returns a 2d convolution layer with full stride.
def conv2d(x_input, w_matrix): """conv2d returns a 2d convolution layer with full stride.""" return tf.nn.conv2d(x_input, w_matrix, strides=[1, 1, 1, 1], padding='SAME')
[ "def", "conv2d", "(", "x_input", ",", "w_matrix", ")", ":", "return", "tf", ".", "nn", ".", "conv2d", "(", "x_input", ",", "w_matrix", ",", "strides", "=", "[", "1", ",", "1", ",", "1", ",", "1", "]", ",", "padding", "=", "'SAME'", ")" ]
[ 135, 0 ]
[ 137, 80 ]
python
en
['en', 'en', 'en']
True
max_pool
(x_input, pool_size)
max_pool downsamples a feature map by 2X.
max_pool downsamples a feature map by 2X.
def max_pool(x_input, pool_size): """max_pool downsamples a feature map by 2X.""" return tf.nn.max_pool(x_input, ksize=[1, pool_size, pool_size, 1], strides=[1, pool_size, pool_size, 1], padding='SAME')
[ "def", "max_pool", "(", "x_input", ",", "pool_size", ")", ":", "return", "tf", ".", "nn", ".", "max_pool", "(", "x_input", ",", "ksize", "=", "[", "1", ",", "pool_size", ",", "pool_size", ",", "1", "]", ",", "strides", "=", "[", "1", ",", "pool_size", ",", "pool_size", ",", "1", "]", ",", "padding", "=", "'SAME'", ")" ]
[ 140, 0 ]
[ 143, 79 ]
python
en
['en', 'en', 'en']
True
weight_variable
(shape)
weight_variable generates a weight variable of a given shape.
weight_variable generates a weight variable of a given shape.
def weight_variable(shape): """weight_variable generates a weight variable of a given shape.""" initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial)
[ "def", "weight_variable", "(", "shape", ")", ":", "initial", "=", "tf", ".", "truncated_normal", "(", "shape", ",", "stddev", "=", "0.1", ")", "return", "tf", ".", "Variable", "(", "initial", ")" ]
[ 151, 0 ]
[ 154, 31 ]
python
en
['en', 'en', 'en']
True
bias_variable
(shape)
bias_variable generates a bias variable of a given shape.
bias_variable generates a bias variable of a given shape.
def bias_variable(shape): """bias_variable generates a bias variable of a given shape.""" initial = tf.constant(0.1, shape=shape) return tf.Variable(initial)
[ "def", "bias_variable", "(", "shape", ")", ":", "initial", "=", "tf", ".", "constant", "(", "0.1", ",", "shape", "=", "shape", ")", "return", "tf", ".", "Variable", "(", "initial", ")" ]
[ 157, 0 ]
[ 160, 31 ]
python
en
['en', 'en', 'en']
True
download_mnist_retry
(data_dir, max_num_retries=20)
Try to download mnist dataset and avoid errors
Try to download mnist dataset and avoid errors
def download_mnist_retry(data_dir, max_num_retries=20): """Try to download mnist dataset and avoid errors""" for _ in range(max_num_retries): try: return input_data.read_data_sets(data_dir, one_hot=True) except tf.errors.AlreadyExistsError: time.sleep(1) raise Exception("Failed to download MNIST.")
[ "def", "download_mnist_retry", "(", "data_dir", ",", "max_num_retries", "=", "20", ")", ":", "for", "_", "in", "range", "(", "max_num_retries", ")", ":", "try", ":", "return", "input_data", ".", "read_data_sets", "(", "data_dir", ",", "one_hot", "=", "True", ")", "except", "tf", ".", "errors", ".", "AlreadyExistsError", ":", "time", ".", "sleep", "(", "1", ")", "raise", "Exception", "(", "\"Failed to download MNIST.\"", ")" ]
[ 162, 0 ]
[ 169, 48 ]
python
en
['en', 'en', 'en']
True
main
(params)
Main function, build mnist network, run and send result to NNI.
Main function, build mnist network, run and send result to NNI.
def main(params): ''' Main function, build mnist network, run and send result to NNI. ''' # Import data mnist = download_mnist_retry(params['data_dir']) print('Mnist download data done.') logger.debug('Mnist download data done.') # Create the model # Build the graph for the deep net mnist_network = MnistNetwork(channel_1_num=params['channel_1_num'], channel_2_num=params['channel_2_num'], pool_size=params['pool_size']) mnist_network.build_network() logger.debug('Mnist build network done.') # Write log graph_location = tempfile.mkdtemp() logger.debug('Saving graph to: %s', graph_location) train_writer = tf.summary.FileWriter(graph_location) train_writer.add_graph(tf.get_default_graph()) test_acc = 0.0 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) batch_num = nni.choice(50, 250, 500, name='batch_num') for i in range(batch_num): batch = mnist.train.next_batch(batch_num) dropout_rate = nni.choice(1, 5, name='dropout_rate') mnist_network.train_step.run(feed_dict={mnist_network.images: batch[0], mnist_network.labels: batch[1], mnist_network.keep_prob: dropout_rate} ) if i % 100 == 0: test_acc = mnist_network.accuracy.eval( feed_dict={mnist_network.images: mnist.test.images, mnist_network.labels: mnist.test.labels, mnist_network.keep_prob: 1.0}) nni.report_intermediate_result(test_acc) logger.debug('test accuracy %g', test_acc) logger.debug('Pipe send intermediate result done.') test_acc = mnist_network.accuracy.eval( feed_dict={mnist_network.images: mnist.test.images, mnist_network.labels: mnist.test.labels, mnist_network.keep_prob: 1.0}) nni.report_final_result(test_acc) logger.debug('Final result is %g', test_acc) logger.debug('Send final result done.')
[ "def", "main", "(", "params", ")", ":", "# Import data", "mnist", "=", "download_mnist_retry", "(", "params", "[", "'data_dir'", "]", ")", "print", "(", "'Mnist download data done.'", ")", "logger", ".", "debug", "(", "'Mnist download data done.'", ")", "# Create the model", "# Build the graph for the deep net", "mnist_network", "=", "MnistNetwork", "(", "channel_1_num", "=", "params", "[", "'channel_1_num'", "]", ",", "channel_2_num", "=", "params", "[", "'channel_2_num'", "]", ",", "pool_size", "=", "params", "[", "'pool_size'", "]", ")", "mnist_network", ".", "build_network", "(", ")", "logger", ".", "debug", "(", "'Mnist build network done.'", ")", "# Write log", "graph_location", "=", "tempfile", ".", "mkdtemp", "(", ")", "logger", ".", "debug", "(", "'Saving graph to: %s'", ",", "graph_location", ")", "train_writer", "=", "tf", ".", "summary", ".", "FileWriter", "(", "graph_location", ")", "train_writer", ".", "add_graph", "(", "tf", ".", "get_default_graph", "(", ")", ")", "test_acc", "=", "0.0", "with", "tf", ".", "Session", "(", ")", "as", "sess", ":", "sess", ".", "run", "(", "tf", ".", "global_variables_initializer", "(", ")", ")", "batch_num", "=", "nni", ".", "choice", "(", "50", ",", "250", ",", "500", ",", "name", "=", "'batch_num'", ")", "for", "i", "in", "range", "(", "batch_num", ")", ":", "batch", "=", "mnist", ".", "train", ".", "next_batch", "(", "batch_num", ")", "dropout_rate", "=", "nni", ".", "choice", "(", "1", ",", "5", ",", "name", "=", "'dropout_rate'", ")", "mnist_network", ".", "train_step", ".", "run", "(", "feed_dict", "=", "{", "mnist_network", ".", "images", ":", "batch", "[", "0", "]", ",", "mnist_network", ".", "labels", ":", "batch", "[", "1", "]", ",", "mnist_network", ".", "keep_prob", ":", "dropout_rate", "}", ")", "if", "i", "%", "100", "==", "0", ":", "test_acc", "=", "mnist_network", ".", "accuracy", ".", "eval", "(", "feed_dict", "=", "{", "mnist_network", ".", "images", ":", "mnist", ".", "test", ".", "images", ",", "mnist_network", ".", "labels", ":", "mnist", ".", "test", ".", "labels", ",", "mnist_network", ".", "keep_prob", ":", "1.0", "}", ")", "nni", ".", "report_intermediate_result", "(", "test_acc", ")", "logger", ".", "debug", "(", "'test accuracy %g'", ",", "test_acc", ")", "logger", ".", "debug", "(", "'Pipe send intermediate result done.'", ")", "test_acc", "=", "mnist_network", ".", "accuracy", ".", "eval", "(", "feed_dict", "=", "{", "mnist_network", ".", "images", ":", "mnist", ".", "test", ".", "images", ",", "mnist_network", ".", "labels", ":", "mnist", ".", "test", ".", "labels", ",", "mnist_network", ".", "keep_prob", ":", "1.0", "}", ")", "nni", ".", "report_final_result", "(", "test_acc", ")", "logger", ".", "debug", "(", "'Final result is %g'", ",", "test_acc", ")", "logger", ".", "debug", "(", "'Send final result done.'", ")" ]
[ 171, 0 ]
[ 223, 47 ]
python
en
['en', 'error', 'th']
False
generate_defualt_params
()
Generate default parameters for mnist network.
Generate default parameters for mnist network.
def generate_defualt_params(): ''' Generate default parameters for mnist network. ''' params = { 'data_dir': '/tmp/tensorflow/mnist/input_data', 'channel_1_num': 32, 'channel_2_num': 64, 'pool_size': 2} return params
[ "def", "generate_defualt_params", "(", ")", ":", "params", "=", "{", "'data_dir'", ":", "'/tmp/tensorflow/mnist/input_data'", ",", "'channel_1_num'", ":", "32", ",", "'channel_2_num'", ":", "64", ",", "'pool_size'", ":", "2", "}", "return", "params" ]
[ 226, 0 ]
[ 235, 17 ]
python
en
['en', 'error', 'th']
False
MnistNetwork.build_network
(self)
Building network for mnist
Building network for mnist
def build_network(self): ''' Building network for mnist ''' # Reshape to use within a convolutional neural net. # Last dimension is for "features" - there is only one here, since images are # grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc. with tf.name_scope('reshape'): try: input_dim = int(math.sqrt(self.x_dim)) except: print( 'input dim cannot be sqrt and reshape. input dim: ' + str(self.x_dim)) logger.debug( 'input dim cannot be sqrt and reshape. input dim: %s', str(self.x_dim)) raise x_image = tf.reshape(self.images, [-1, input_dim, input_dim, 1]) # First convolutional layer - maps one grayscale image to 32 feature maps. with tf.name_scope('conv1'): w_conv1 = weight_variable( [self.conv_size, self.conv_size, 1, self.channel_1_num]) b_conv1 = bias_variable([self.channel_1_num]) h_conv1 = nni.function_choice( lambda: tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1), lambda: tf.nn.sigmoid(conv2d(x_image, w_conv1) + b_conv1), lambda: tf.nn.tanh(conv2d(x_image, w_conv1) + b_conv1) ) # example: without name # Pooling layer - downsamples by 2X. with tf.name_scope('pool1'): h_pool1 = max_pool(h_conv1, self.pool_size) h_pool1 = nni.function_choice( lambda: max_pool(h_conv1, self.pool_size), lambda: avg_pool(h_conv1, self.pool_size), name='h_pool1') # Second convolutional layer -- maps 32 feature maps to 64. with tf.name_scope('conv2'): w_conv2 = weight_variable([self.conv_size, self.conv_size, self.channel_1_num, self.channel_2_num]) b_conv2 = bias_variable([self.channel_2_num]) h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2) # Second pooling layer. with tf.name_scope('pool2'): # example: another style h_pool2 = max_pool(h_conv2, self.pool_size) # Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image # is down to 7x7x64 feature maps -- maps this to 1024 features. last_dim = int(input_dim / (self.pool_size * self.pool_size)) with tf.name_scope('fc1'): w_fc1 = weight_variable( [last_dim * last_dim * self.channel_2_num, self.hidden_size]) b_fc1 = bias_variable([self.hidden_size]) h_pool2_flat = tf.reshape( h_pool2, [-1, last_dim * last_dim * self.channel_2_num]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, w_fc1) + b_fc1) # Dropout - controls the complexity of the model, prevents co-adaptation of features. with tf.name_scope('dropout'): h_fc1_drop = tf.nn.dropout(h_fc1, self.keep_prob) # Map the 1024 features to 10 classes, one for each digit with tf.name_scope('fc2'): w_fc2 = weight_variable([self.hidden_size, self.y_dim]) b_fc2 = bias_variable([self.y_dim]) y_conv = tf.matmul(h_fc1_drop, w_fc2) + b_fc2 with tf.name_scope('loss'): cross_entropy = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=self.labels, logits=y_conv)) with tf.name_scope('adam_optimizer'): self.train_step = tf.train.AdamOptimizer( self.learning_rate).minimize(cross_entropy) with tf.name_scope('accuracy'): correct_prediction = tf.equal( tf.argmax(y_conv, 1), tf.argmax(self.labels, 1)) self.accuracy = tf.reduce_mean( tf.cast(correct_prediction, tf.float32))
[ "def", "build_network", "(", "self", ")", ":", "# Reshape to use within a convolutional neural net.", "# Last dimension is for \"features\" - there is only one here, since images are", "# grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.", "with", "tf", ".", "name_scope", "(", "'reshape'", ")", ":", "try", ":", "input_dim", "=", "int", "(", "math", ".", "sqrt", "(", "self", ".", "x_dim", ")", ")", "except", ":", "print", "(", "'input dim cannot be sqrt and reshape. input dim: '", "+", "str", "(", "self", ".", "x_dim", ")", ")", "logger", ".", "debug", "(", "'input dim cannot be sqrt and reshape. input dim: %s'", ",", "str", "(", "self", ".", "x_dim", ")", ")", "raise", "x_image", "=", "tf", ".", "reshape", "(", "self", ".", "images", ",", "[", "-", "1", ",", "input_dim", ",", "input_dim", ",", "1", "]", ")", "# First convolutional layer - maps one grayscale image to 32 feature maps.", "with", "tf", ".", "name_scope", "(", "'conv1'", ")", ":", "w_conv1", "=", "weight_variable", "(", "[", "self", ".", "conv_size", ",", "self", ".", "conv_size", ",", "1", ",", "self", ".", "channel_1_num", "]", ")", "b_conv1", "=", "bias_variable", "(", "[", "self", ".", "channel_1_num", "]", ")", "h_conv1", "=", "nni", ".", "function_choice", "(", "lambda", ":", "tf", ".", "nn", ".", "relu", "(", "conv2d", "(", "x_image", ",", "w_conv1", ")", "+", "b_conv1", ")", ",", "lambda", ":", "tf", ".", "nn", ".", "sigmoid", "(", "conv2d", "(", "x_image", ",", "w_conv1", ")", "+", "b_conv1", ")", ",", "lambda", ":", "tf", ".", "nn", ".", "tanh", "(", "conv2d", "(", "x_image", ",", "w_conv1", ")", "+", "b_conv1", ")", ")", "# example: without name", "# Pooling layer - downsamples by 2X.", "with", "tf", ".", "name_scope", "(", "'pool1'", ")", ":", "h_pool1", "=", "max_pool", "(", "h_conv1", ",", "self", ".", "pool_size", ")", "h_pool1", "=", "nni", ".", "function_choice", "(", "lambda", ":", "max_pool", "(", "h_conv1", ",", "self", ".", "pool_size", ")", ",", "lambda", ":", "avg_pool", "(", "h_conv1", ",", "self", ".", "pool_size", ")", ",", "name", "=", "'h_pool1'", ")", "# Second convolutional layer -- maps 32 feature maps to 64.", "with", "tf", ".", "name_scope", "(", "'conv2'", ")", ":", "w_conv2", "=", "weight_variable", "(", "[", "self", ".", "conv_size", ",", "self", ".", "conv_size", ",", "self", ".", "channel_1_num", ",", "self", ".", "channel_2_num", "]", ")", "b_conv2", "=", "bias_variable", "(", "[", "self", ".", "channel_2_num", "]", ")", "h_conv2", "=", "tf", ".", "nn", ".", "relu", "(", "conv2d", "(", "h_pool1", ",", "w_conv2", ")", "+", "b_conv2", ")", "# Second pooling layer.", "with", "tf", ".", "name_scope", "(", "'pool2'", ")", ":", "# example: another style", "h_pool2", "=", "max_pool", "(", "h_conv2", ",", "self", ".", "pool_size", ")", "# Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image", "# is down to 7x7x64 feature maps -- maps this to 1024 features.", "last_dim", "=", "int", "(", "input_dim", "/", "(", "self", ".", "pool_size", "*", "self", ".", "pool_size", ")", ")", "with", "tf", ".", "name_scope", "(", "'fc1'", ")", ":", "w_fc1", "=", "weight_variable", "(", "[", "last_dim", "*", "last_dim", "*", "self", ".", "channel_2_num", ",", "self", ".", "hidden_size", "]", ")", "b_fc1", "=", "bias_variable", "(", "[", "self", ".", "hidden_size", "]", ")", "h_pool2_flat", "=", "tf", ".", "reshape", "(", "h_pool2", ",", "[", "-", "1", ",", "last_dim", "*", "last_dim", "*", "self", ".", "channel_2_num", "]", ")", "h_fc1", "=", "tf", ".", "nn", ".", "relu", "(", "tf", ".", "matmul", "(", "h_pool2_flat", ",", "w_fc1", ")", "+", "b_fc1", ")", "# Dropout - controls the complexity of the model, prevents co-adaptation of features.", "with", "tf", ".", "name_scope", "(", "'dropout'", ")", ":", "h_fc1_drop", "=", "tf", ".", "nn", ".", "dropout", "(", "h_fc1", ",", "self", ".", "keep_prob", ")", "# Map the 1024 features to 10 classes, one for each digit", "with", "tf", ".", "name_scope", "(", "'fc2'", ")", ":", "w_fc2", "=", "weight_variable", "(", "[", "self", ".", "hidden_size", ",", "self", ".", "y_dim", "]", ")", "b_fc2", "=", "bias_variable", "(", "[", "self", ".", "y_dim", "]", ")", "y_conv", "=", "tf", ".", "matmul", "(", "h_fc1_drop", ",", "w_fc2", ")", "+", "b_fc2", "with", "tf", ".", "name_scope", "(", "'loss'", ")", ":", "cross_entropy", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "nn", ".", "softmax_cross_entropy_with_logits", "(", "labels", "=", "self", ".", "labels", ",", "logits", "=", "y_conv", ")", ")", "with", "tf", ".", "name_scope", "(", "'adam_optimizer'", ")", ":", "self", ".", "train_step", "=", "tf", ".", "train", ".", "AdamOptimizer", "(", "self", ".", "learning_rate", ")", ".", "minimize", "(", "cross_entropy", ")", "with", "tf", ".", "name_scope", "(", "'accuracy'", ")", ":", "correct_prediction", "=", "tf", ".", "equal", "(", "tf", ".", "argmax", "(", "y_conv", ",", "1", ")", ",", "tf", ".", "argmax", "(", "self", ".", "labels", ",", "1", ")", ")", "self", ".", "accuracy", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "cast", "(", "correct_prediction", ",", "tf", ".", "float32", ")", ")" ]
[ 49, 4 ]
[ 132, 56 ]
python
en
['en', 'error', 'th']
False
async_setup_entry
(hass, config_entry, async_add_entities)
Set up AirVisual air quality entities based on a config entry.
Set up AirVisual air quality entities based on a config entry.
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up AirVisual air quality entities based on a config entry.""" # Geography-based AirVisual integrations don't utilize this platform: if config_entry.data[CONF_INTEGRATION_TYPE] != INTEGRATION_TYPE_NODE_PRO: return coordinator = hass.data[DOMAIN][DATA_COORDINATOR][config_entry.entry_id] async_add_entities([AirVisualNodeProSensor(coordinator)], True)
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ",", "async_add_entities", ")", ":", "# Geography-based AirVisual integrations don't utilize this platform:", "if", "config_entry", ".", "data", "[", "CONF_INTEGRATION_TYPE", "]", "!=", "INTEGRATION_TYPE_NODE_PRO", ":", "return", "coordinator", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "DATA_COORDINATOR", "]", "[", "config_entry", ".", "entry_id", "]", "async_add_entities", "(", "[", "AirVisualNodeProSensor", "(", "coordinator", ")", "]", ",", "True", ")" ]
[ 18, 0 ]
[ 26, 67 ]
python
en
['en', 'en', 'en']
True
AirVisualNodeProSensor.__init__
(self, airvisual)
Initialize.
Initialize.
def __init__(self, airvisual): """Initialize.""" super().__init__(airvisual) self._icon = "mdi:chemical-weapon" self._unit = CONCENTRATION_MICROGRAMS_PER_CUBIC_METER
[ "def", "__init__", "(", "self", ",", "airvisual", ")", ":", "super", "(", ")", ".", "__init__", "(", "airvisual", ")", "self", ".", "_icon", "=", "\"mdi:chemical-weapon\"", "self", ".", "_unit", "=", "CONCENTRATION_MICROGRAMS_PER_CUBIC_METER" ]
[ 32, 4 ]
[ 37, 61 ]
python
en
['en', 'en', 'it']
False
AirVisualNodeProSensor.air_quality_index
(self)
Return the Air Quality Index (AQI).
Return the Air Quality Index (AQI).
def air_quality_index(self): """Return the Air Quality Index (AQI).""" if self.coordinator.data["settings"]["is_aqi_usa"]: return self.coordinator.data["measurements"]["aqi_us"] return self.coordinator.data["measurements"]["aqi_cn"]
[ "def", "air_quality_index", "(", "self", ")", ":", "if", "self", ".", "coordinator", ".", "data", "[", "\"settings\"", "]", "[", "\"is_aqi_usa\"", "]", ":", "return", "self", ".", "coordinator", ".", "data", "[", "\"measurements\"", "]", "[", "\"aqi_us\"", "]", "return", "self", ".", "coordinator", ".", "data", "[", "\"measurements\"", "]", "[", "\"aqi_cn\"", "]" ]
[ 40, 4 ]
[ 44, 62 ]
python
en
['en', 'cy', 'en']
True
AirVisualNodeProSensor.available
(self)
Return True if entity is available.
Return True if entity is available.
def available(self): """Return True if entity is available.""" return bool(self.coordinator.data)
[ "def", "available", "(", "self", ")", ":", "return", "bool", "(", "self", ".", "coordinator", ".", "data", ")" ]
[ 47, 4 ]
[ 49, 42 ]
python
en
['en', 'en', 'en']
True
AirVisualNodeProSensor.carbon_dioxide
(self)
Return the CO2 (carbon dioxide) level.
Return the CO2 (carbon dioxide) level.
def carbon_dioxide(self): """Return the CO2 (carbon dioxide) level.""" return self.coordinator.data["measurements"].get("co2")
[ "def", "carbon_dioxide", "(", "self", ")", ":", "return", "self", ".", "coordinator", ".", "data", "[", "\"measurements\"", "]", ".", "get", "(", "\"co2\"", ")" ]
[ 52, 4 ]
[ 54, 63 ]
python
en
['en', 'en', 'en']
True
AirVisualNodeProSensor.device_info
(self)
Return device registry information for this entity.
Return device registry information for this entity.
def device_info(self): """Return device registry information for this entity.""" return { "identifiers": {(DOMAIN, self.coordinator.data["serial_number"])}, "name": self.coordinator.data["settings"]["node_name"], "manufacturer": "AirVisual", "model": f'{self.coordinator.data["status"]["model"]}', "sw_version": ( f'Version {self.coordinator.data["status"]["system_version"]}' f'{self.coordinator.data["status"]["app_version"]}' ), }
[ "def", "device_info", "(", "self", ")", ":", "return", "{", "\"identifiers\"", ":", "{", "(", "DOMAIN", ",", "self", ".", "coordinator", ".", "data", "[", "\"serial_number\"", "]", ")", "}", ",", "\"name\"", ":", "self", ".", "coordinator", ".", "data", "[", "\"settings\"", "]", "[", "\"node_name\"", "]", ",", "\"manufacturer\"", ":", "\"AirVisual\"", ",", "\"model\"", ":", "f'{self.coordinator.data[\"status\"][\"model\"]}'", ",", "\"sw_version\"", ":", "(", "f'Version {self.coordinator.data[\"status\"][\"system_version\"]}'", "f'{self.coordinator.data[\"status\"][\"app_version\"]}'", ")", ",", "}" ]
[ 57, 4 ]
[ 68, 9 ]
python
en
['en', 'en', 'en']
True
AirVisualNodeProSensor.name
(self)
Return the name.
Return the name.
def name(self): """Return the name.""" node_name = self.coordinator.data["settings"]["node_name"] return f"{node_name} Node/Pro: Air Quality"
[ "def", "name", "(", "self", ")", ":", "node_name", "=", "self", ".", "coordinator", ".", "data", "[", "\"settings\"", "]", "[", "\"node_name\"", "]", "return", "f\"{node_name} Node/Pro: Air Quality\"" ]
[ 71, 4 ]
[ 74, 51 ]
python
en
['en', 'ig', 'en']
True
AirVisualNodeProSensor.particulate_matter_2_5
(self)
Return the particulate matter 2.5 level.
Return the particulate matter 2.5 level.
def particulate_matter_2_5(self): """Return the particulate matter 2.5 level.""" return self.coordinator.data["measurements"].get("pm2_5")
[ "def", "particulate_matter_2_5", "(", "self", ")", ":", "return", "self", ".", "coordinator", ".", "data", "[", "\"measurements\"", "]", ".", "get", "(", "\"pm2_5\"", ")" ]
[ 77, 4 ]
[ 79, 65 ]
python
en
['en', 'en', 'en']
True
AirVisualNodeProSensor.particulate_matter_10
(self)
Return the particulate matter 10 level.
Return the particulate matter 10 level.
def particulate_matter_10(self): """Return the particulate matter 10 level.""" return self.coordinator.data["measurements"].get("pm1_0")
[ "def", "particulate_matter_10", "(", "self", ")", ":", "return", "self", ".", "coordinator", ".", "data", "[", "\"measurements\"", "]", ".", "get", "(", "\"pm1_0\"", ")" ]
[ 82, 4 ]
[ 84, 65 ]
python
en
['en', 'en', 'en']
True
AirVisualNodeProSensor.particulate_matter_0_1
(self)
Return the particulate matter 0.1 level.
Return the particulate matter 0.1 level.
def particulate_matter_0_1(self): """Return the particulate matter 0.1 level.""" return self.coordinator.data["measurements"].get("pm0_1")
[ "def", "particulate_matter_0_1", "(", "self", ")", ":", "return", "self", ".", "coordinator", ".", "data", "[", "\"measurements\"", "]", ".", "get", "(", "\"pm0_1\"", ")" ]
[ 87, 4 ]
[ 89, 65 ]
python
en
['en', 'en', 'en']
True
AirVisualNodeProSensor.unique_id
(self)
Return a unique, Home Assistant friendly identifier for this entity.
Return a unique, Home Assistant friendly identifier for this entity.
def unique_id(self): """Return a unique, Home Assistant friendly identifier for this entity.""" return self.coordinator.data["serial_number"]
[ "def", "unique_id", "(", "self", ")", ":", "return", "self", ".", "coordinator", ".", "data", "[", "\"serial_number\"", "]" ]
[ 92, 4 ]
[ 94, 53 ]
python
en
['en', 'en', 'en']
True
AirVisualNodeProSensor.update_from_latest_data
(self)
Update the entity from the latest data.
Update the entity from the latest data.
def update_from_latest_data(self): """Update the entity from the latest data.""" self._attrs.update( { ATTR_VOC: self.coordinator.data["measurements"].get("voc"), **{ ATTR_SENSOR_LIFE.format(pollutant): lifespan for pollutant, lifespan in self.coordinator.data["status"][ "sensor_life" ].items() }, } )
[ "def", "update_from_latest_data", "(", "self", ")", ":", "self", ".", "_attrs", ".", "update", "(", "{", "ATTR_VOC", ":", "self", ".", "coordinator", ".", "data", "[", "\"measurements\"", "]", ".", "get", "(", "\"voc\"", ")", ",", "*", "*", "{", "ATTR_SENSOR_LIFE", ".", "format", "(", "pollutant", ")", ":", "lifespan", "for", "pollutant", ",", "lifespan", "in", "self", ".", "coordinator", ".", "data", "[", "\"status\"", "]", "[", "\"sensor_life\"", "]", ".", "items", "(", ")", "}", ",", "}", ")" ]
[ 97, 4 ]
[ 109, 9 ]
python
en
['en', 'en', 'en']
True
test_fire_coroutine_threadsafe_from_inside_event_loop
( mock_ident, _, mock_iscoroutine )
Testing calling fire_coroutine_threadsafe from inside an event loop.
Testing calling fire_coroutine_threadsafe from inside an event loop.
def test_fire_coroutine_threadsafe_from_inside_event_loop( mock_ident, _, mock_iscoroutine ): """Testing calling fire_coroutine_threadsafe from inside an event loop.""" coro = MagicMock() loop = MagicMock() loop._thread_ident = None mock_ident.return_value = 5 mock_iscoroutine.return_value = True hasync.fire_coroutine_threadsafe(coro, loop) assert len(loop.call_soon_threadsafe.mock_calls) == 1 loop._thread_ident = 5 mock_ident.return_value = 5 mock_iscoroutine.return_value = True with pytest.raises(RuntimeError): hasync.fire_coroutine_threadsafe(coro, loop) assert len(loop.call_soon_threadsafe.mock_calls) == 1 loop._thread_ident = 1 mock_ident.return_value = 5 mock_iscoroutine.return_value = False with pytest.raises(TypeError): hasync.fire_coroutine_threadsafe(coro, loop) assert len(loop.call_soon_threadsafe.mock_calls) == 1 loop._thread_ident = 1 mock_ident.return_value = 5 mock_iscoroutine.return_value = True hasync.fire_coroutine_threadsafe(coro, loop) assert len(loop.call_soon_threadsafe.mock_calls) == 2
[ "def", "test_fire_coroutine_threadsafe_from_inside_event_loop", "(", "mock_ident", ",", "_", ",", "mock_iscoroutine", ")", ":", "coro", "=", "MagicMock", "(", ")", "loop", "=", "MagicMock", "(", ")", "loop", ".", "_thread_ident", "=", "None", "mock_ident", ".", "return_value", "=", "5", "mock_iscoroutine", ".", "return_value", "=", "True", "hasync", ".", "fire_coroutine_threadsafe", "(", "coro", ",", "loop", ")", "assert", "len", "(", "loop", ".", "call_soon_threadsafe", ".", "mock_calls", ")", "==", "1", "loop", ".", "_thread_ident", "=", "5", "mock_ident", ".", "return_value", "=", "5", "mock_iscoroutine", ".", "return_value", "=", "True", "with", "pytest", ".", "raises", "(", "RuntimeError", ")", ":", "hasync", ".", "fire_coroutine_threadsafe", "(", "coro", ",", "loop", ")", "assert", "len", "(", "loop", ".", "call_soon_threadsafe", ".", "mock_calls", ")", "==", "1", "loop", ".", "_thread_ident", "=", "1", "mock_ident", ".", "return_value", "=", "5", "mock_iscoroutine", ".", "return_value", "=", "False", "with", "pytest", ".", "raises", "(", "TypeError", ")", ":", "hasync", ".", "fire_coroutine_threadsafe", "(", "coro", ",", "loop", ")", "assert", "len", "(", "loop", ".", "call_soon_threadsafe", ".", "mock_calls", ")", "==", "1", "loop", ".", "_thread_ident", "=", "1", "mock_ident", ".", "return_value", "=", "5", "mock_iscoroutine", ".", "return_value", "=", "True", "hasync", ".", "fire_coroutine_threadsafe", "(", "coro", ",", "loop", ")", "assert", "len", "(", "loop", ".", "call_soon_threadsafe", ".", "mock_calls", ")", "==", "2" ]
[ 14, 0 ]
[ 45, 57 ]
python
en
['en', 'en', 'en']
True
test_run_callback_threadsafe_from_inside_event_loop
(mock_ident, _)
Testing calling run_callback_threadsafe from inside an event loop.
Testing calling run_callback_threadsafe from inside an event loop.
def test_run_callback_threadsafe_from_inside_event_loop(mock_ident, _): """Testing calling run_callback_threadsafe from inside an event loop.""" callback = MagicMock() loop = MagicMock() loop._thread_ident = None mock_ident.return_value = 5 hasync.run_callback_threadsafe(loop, callback) assert len(loop.call_soon_threadsafe.mock_calls) == 1 loop._thread_ident = 5 mock_ident.return_value = 5 with pytest.raises(RuntimeError): hasync.run_callback_threadsafe(loop, callback) assert len(loop.call_soon_threadsafe.mock_calls) == 1 loop._thread_ident = 1 mock_ident.return_value = 5 hasync.run_callback_threadsafe(loop, callback) assert len(loop.call_soon_threadsafe.mock_calls) == 2
[ "def", "test_run_callback_threadsafe_from_inside_event_loop", "(", "mock_ident", ",", "_", ")", ":", "callback", "=", "MagicMock", "(", ")", "loop", "=", "MagicMock", "(", ")", "loop", ".", "_thread_ident", "=", "None", "mock_ident", ".", "return_value", "=", "5", "hasync", ".", "run_callback_threadsafe", "(", "loop", ",", "callback", ")", "assert", "len", "(", "loop", ".", "call_soon_threadsafe", ".", "mock_calls", ")", "==", "1", "loop", ".", "_thread_ident", "=", "5", "mock_ident", ".", "return_value", "=", "5", "with", "pytest", ".", "raises", "(", "RuntimeError", ")", ":", "hasync", ".", "run_callback_threadsafe", "(", "loop", ",", "callback", ")", "assert", "len", "(", "loop", ".", "call_soon_threadsafe", ".", "mock_calls", ")", "==", "1", "loop", ".", "_thread_ident", "=", "1", "mock_ident", ".", "return_value", "=", "5", "hasync", ".", "run_callback_threadsafe", "(", "loop", ",", "callback", ")", "assert", "len", "(", "loop", ".", "call_soon_threadsafe", ".", "mock_calls", ")", "==", "2" ]
[ 50, 0 ]
[ 69, 57 ]
python
en
['en', 'en', 'en']
True
test_check_loop_async
()
Test check_loop detects when called from event loop without integration context.
Test check_loop detects when called from event loop without integration context.
async def test_check_loop_async(): """Test check_loop detects when called from event loop without integration context.""" with pytest.raises(RuntimeError): hasync.check_loop()
[ "async", "def", "test_check_loop_async", "(", ")", ":", "with", "pytest", ".", "raises", "(", "RuntimeError", ")", ":", "hasync", ".", "check_loop", "(", ")" ]
[ 72, 0 ]
[ 75, 27 ]
python
en
['en', 'en', 'en']
True
test_check_loop_async_integration
(caplog)
Test check_loop detects when called from event loop from integration context.
Test check_loop detects when called from event loop from integration context.
async def test_check_loop_async_integration(caplog): """Test check_loop detects when called from event loop from integration context.""" with patch( "homeassistant.util.async_.extract_stack", return_value=[ Mock( filename="/home/paulus/homeassistant/core.py", lineno="23", line="do_something()", ), Mock( filename="/home/paulus/homeassistant/components/hue/light.py", lineno="23", line="self.light.is_on", ), Mock( filename="/home/paulus/aiohue/lights.py", lineno="2", line="something()", ), ], ): hasync.check_loop() assert ( "Detected I/O inside the event loop. This is causing stability issues. Please report issue for hue doing I/O at homeassistant/components/hue/light.py, line 23: self.light.is_on" in caplog.text )
[ "async", "def", "test_check_loop_async_integration", "(", "caplog", ")", ":", "with", "patch", "(", "\"homeassistant.util.async_.extract_stack\"", ",", "return_value", "=", "[", "Mock", "(", "filename", "=", "\"/home/paulus/homeassistant/core.py\"", ",", "lineno", "=", "\"23\"", ",", "line", "=", "\"do_something()\"", ",", ")", ",", "Mock", "(", "filename", "=", "\"/home/paulus/homeassistant/components/hue/light.py\"", ",", "lineno", "=", "\"23\"", ",", "line", "=", "\"self.light.is_on\"", ",", ")", ",", "Mock", "(", "filename", "=", "\"/home/paulus/aiohue/lights.py\"", ",", "lineno", "=", "\"2\"", ",", "line", "=", "\"something()\"", ",", ")", ",", "]", ",", ")", ":", "hasync", ".", "check_loop", "(", ")", "assert", "(", "\"Detected I/O inside the event loop. This is causing stability issues. Please report issue for hue doing I/O at homeassistant/components/hue/light.py, line 23: self.light.is_on\"", "in", "caplog", ".", "text", ")" ]
[ 78, 0 ]
[ 104, 5 ]
python
en
['en', 'en', 'en']
True
test_check_loop_async_custom
(caplog)
Test check_loop detects when called from event loop with custom component context.
Test check_loop detects when called from event loop with custom component context.
async def test_check_loop_async_custom(caplog): """Test check_loop detects when called from event loop with custom component context.""" with patch( "homeassistant.util.async_.extract_stack", return_value=[ Mock( filename="/home/paulus/homeassistant/core.py", lineno="23", line="do_something()", ), Mock( filename="/home/paulus/config/custom_components/hue/light.py", lineno="23", line="self.light.is_on", ), Mock( filename="/home/paulus/aiohue/lights.py", lineno="2", line="something()", ), ], ): hasync.check_loop() assert ( "Detected I/O inside the event loop. This is causing stability issues. Please report issue to the custom component author for hue doing I/O at custom_components/hue/light.py, line 23: self.light.is_on" in caplog.text )
[ "async", "def", "test_check_loop_async_custom", "(", "caplog", ")", ":", "with", "patch", "(", "\"homeassistant.util.async_.extract_stack\"", ",", "return_value", "=", "[", "Mock", "(", "filename", "=", "\"/home/paulus/homeassistant/core.py\"", ",", "lineno", "=", "\"23\"", ",", "line", "=", "\"do_something()\"", ",", ")", ",", "Mock", "(", "filename", "=", "\"/home/paulus/config/custom_components/hue/light.py\"", ",", "lineno", "=", "\"23\"", ",", "line", "=", "\"self.light.is_on\"", ",", ")", ",", "Mock", "(", "filename", "=", "\"/home/paulus/aiohue/lights.py\"", ",", "lineno", "=", "\"2\"", ",", "line", "=", "\"something()\"", ",", ")", ",", "]", ",", ")", ":", "hasync", ".", "check_loop", "(", ")", "assert", "(", "\"Detected I/O inside the event loop. This is causing stability issues. Please report issue to the custom component author for hue doing I/O at custom_components/hue/light.py, line 23: self.light.is_on\"", "in", "caplog", ".", "text", ")" ]
[ 107, 0 ]
[ 133, 5 ]
python
en
['en', 'en', 'en']
True
test_check_loop_sync
(caplog)
Test check_loop does nothing when called from thread.
Test check_loop does nothing when called from thread.
def test_check_loop_sync(caplog): """Test check_loop does nothing when called from thread.""" hasync.check_loop() assert "Detected I/O inside the event loop" not in caplog.text
[ "def", "test_check_loop_sync", "(", "caplog", ")", ":", "hasync", ".", "check_loop", "(", ")", "assert", "\"Detected I/O inside the event loop\"", "not", "in", "caplog", ".", "text" ]
[ 136, 0 ]
[ 139, 66 ]
python
en
['en', 'en', 'en']
True
test_protect_loop_sync
()
Test protect_loop calls check_loop.
Test protect_loop calls check_loop.
def test_protect_loop_sync(): """Test protect_loop calls check_loop.""" calls = [] with patch("homeassistant.util.async_.check_loop") as mock_loop: hasync.protect_loop(calls.append)(1) assert len(mock_loop.mock_calls) == 1 assert calls == [1]
[ "def", "test_protect_loop_sync", "(", ")", ":", "calls", "=", "[", "]", "with", "patch", "(", "\"homeassistant.util.async_.check_loop\"", ")", "as", "mock_loop", ":", "hasync", ".", "protect_loop", "(", "calls", ".", "append", ")", "(", "1", ")", "assert", "len", "(", "mock_loop", ".", "mock_calls", ")", "==", "1", "assert", "calls", "==", "[", "1", "]" ]
[ 142, 0 ]
[ 148, 23 ]
python
en
['it', 'id', 'en']
False
test_gather_with_concurrency
()
Test gather_with_concurrency limits the number of running tasks.
Test gather_with_concurrency limits the number of running tasks.
async def test_gather_with_concurrency(): """Test gather_with_concurrency limits the number of running tasks.""" runs = 0 now_time = time.time() async def _increment_runs_if_in_time(): if time.time() - now_time > 0.1: return -1 nonlocal runs runs += 1 await asyncio.sleep(0.1) return runs results = await hasync.gather_with_concurrency( 2, *[_increment_runs_if_in_time() for i in range(4)] ) assert results == [2, 2, -1, -1]
[ "async", "def", "test_gather_with_concurrency", "(", ")", ":", "runs", "=", "0", "now_time", "=", "time", ".", "time", "(", ")", "async", "def", "_increment_runs_if_in_time", "(", ")", ":", "if", "time", ".", "time", "(", ")", "-", "now_time", ">", "0.1", ":", "return", "-", "1", "nonlocal", "runs", "runs", "+=", "1", "await", "asyncio", ".", "sleep", "(", "0.1", ")", "return", "runs", "results", "=", "await", "hasync", ".", "gather_with_concurrency", "(", "2", ",", "*", "[", "_increment_runs_if_in_time", "(", ")", "for", "i", "in", "range", "(", "4", ")", "]", ")", "assert", "results", "==", "[", "2", ",", "2", ",", "-", "1", ",", "-", "1", "]" ]
[ 151, 0 ]
[ 170, 36 ]
python
en
['en', 'en', 'en']
True
calls
(hass)
Track calls to a mock service.
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
[ "def", "calls", "(", "hass", ")", ":", "return", "async_mock_service", "(", "hass", ",", "\"test\"", ",", "\"automation\"", ")" ]
[ 12, 0 ]
[ 14, 57 ]
python
en
['en', 'en', 'en']
True
setup_comp
(hass)
Initialize components.
Initialize components.
def setup_comp(hass): """Initialize components.""" mock_component(hass, "group") hass.loop.run_until_complete( async_setup_component( hass, zone.DOMAIN, { "zone": { "name": "test", "latitude": 32.880837, "longitude": -117.237561, "radius": 250, } }, ) )
[ "def", "setup_comp", "(", "hass", ")", ":", "mock_component", "(", "hass", ",", "\"group\"", ")", "hass", ".", "loop", ".", "run_until_complete", "(", "async_setup_component", "(", "hass", ",", "zone", ".", "DOMAIN", ",", "{", "\"zone\"", ":", "{", "\"name\"", ":", "\"test\"", ",", "\"latitude\"", ":", "32.880837", ",", "\"longitude\"", ":", "-", "117.237561", ",", "\"radius\"", ":", "250", ",", "}", "}", ",", ")", ")" ]
[ 18, 0 ]
[ 34, 5 ]
python
en
['de', 'en', 'en']
False
test_if_fires_on_zone_enter
(hass, calls)
Test for firing on zone enter.
Test for firing on zone enter.
async def test_if_fires_on_zone_enter(hass, calls): """Test for firing on zone enter.""" context = Context() hass.states.async_set( "test.entity", "hello", {"latitude": 32.881011, "longitude": -117.234758} ) await hass.async_block_till_done() assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: { "trigger": { "platform": "zone", "entity_id": "test.entity", "zone": "zone.test", "event": "enter", }, "action": { "service": "test.automation", "data_template": { "some": "{{ trigger.%s }}" % "}} - {{ trigger.".join( ( "platform", "entity_id", "from_state.state", "to_state.state", "zone.name", ) ) }, }, } }, ) hass.states.async_set( "test.entity", "hello", {"latitude": 32.880586, "longitude": -117.237564}, context=context, ) await hass.async_block_till_done() assert len(calls) == 1 assert calls[0].context.parent_id == context.id assert "zone - test.entity - hello - hello - test" == calls[0].data["some"] # Set out of zone again so we can trigger call hass.states.async_set( "test.entity", "hello", {"latitude": 32.881011, "longitude": -117.234758} ) await hass.async_block_till_done() await hass.services.async_call( automation.DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: ENTITY_MATCH_ALL}, blocking=True, ) hass.states.async_set( "test.entity", "hello", {"latitude": 32.880586, "longitude": -117.237564} ) await hass.async_block_till_done() assert len(calls) == 1
[ "async", "def", "test_if_fires_on_zone_enter", "(", "hass", ",", "calls", ")", ":", "context", "=", "Context", "(", ")", "hass", ".", "states", ".", "async_set", "(", "\"test.entity\"", ",", "\"hello\"", ",", "{", "\"latitude\"", ":", "32.881011", ",", "\"longitude\"", ":", "-", "117.234758", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "automation", ".", "DOMAIN", ",", "{", "automation", ".", "DOMAIN", ":", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"zone\"", ",", "\"entity_id\"", ":", "\"test.entity\"", ",", "\"zone\"", ":", "\"zone.test\"", ",", "\"event\"", ":", "\"enter\"", ",", "}", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", ",", "\"data_template\"", ":", "{", "\"some\"", ":", "\"{{ trigger.%s }}\"", "%", "\"}} - {{ trigger.\"", ".", "join", "(", "(", "\"platform\"", ",", "\"entity_id\"", ",", "\"from_state.state\"", ",", "\"to_state.state\"", ",", "\"zone.name\"", ",", ")", ")", "}", ",", "}", ",", "}", "}", ",", ")", "hass", ".", "states", ".", "async_set", "(", "\"test.entity\"", ",", "\"hello\"", ",", "{", "\"latitude\"", ":", "32.880586", ",", "\"longitude\"", ":", "-", "117.237564", "}", ",", "context", "=", "context", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", ".", "context", ".", "parent_id", "==", "context", ".", "id", "assert", "\"zone - test.entity - hello - hello - test\"", "==", "calls", "[", "0", "]", ".", "data", "[", "\"some\"", "]", "# Set out of zone again so we can trigger call", "hass", ".", "states", ".", "async_set", "(", "\"test.entity\"", ",", "\"hello\"", ",", "{", "\"latitude\"", ":", "32.881011", ",", "\"longitude\"", ":", "-", "117.234758", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "services", ".", "async_call", "(", "automation", ".", "DOMAIN", ",", "SERVICE_TURN_OFF", ",", "{", "ATTR_ENTITY_ID", ":", "ENTITY_MATCH_ALL", "}", ",", "blocking", "=", "True", ",", ")", "hass", ".", "states", ".", "async_set", "(", "\"test.entity\"", ",", "\"hello\"", ",", "{", "\"latitude\"", ":", "32.880586", ",", "\"longitude\"", ":", "-", "117.237564", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1" ]
[ 37, 0 ]
[ 105, 26 ]
python
en
['en', 'no', 'en']
True
test_if_not_fires_for_enter_on_zone_leave
(hass, calls)
Test for not firing on zone leave.
Test for not firing on zone leave.
async def test_if_not_fires_for_enter_on_zone_leave(hass, calls): """Test for not firing on zone leave.""" hass.states.async_set( "test.entity", "hello", {"latitude": 32.880586, "longitude": -117.237564} ) await hass.async_block_till_done() assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: { "trigger": { "platform": "zone", "entity_id": "test.entity", "zone": "zone.test", "event": "enter", }, "action": {"service": "test.automation"}, } }, ) hass.states.async_set( "test.entity", "hello", {"latitude": 32.881011, "longitude": -117.234758} ) await hass.async_block_till_done() assert len(calls) == 0
[ "async", "def", "test_if_not_fires_for_enter_on_zone_leave", "(", "hass", ",", "calls", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"test.entity\"", ",", "\"hello\"", ",", "{", "\"latitude\"", ":", "32.880586", ",", "\"longitude\"", ":", "-", "117.237564", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "automation", ".", "DOMAIN", ",", "{", "automation", ".", "DOMAIN", ":", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"zone\"", ",", "\"entity_id\"", ":", "\"test.entity\"", ",", "\"zone\"", ":", "\"zone.test\"", ",", "\"event\"", ":", "\"enter\"", ",", "}", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", "}", ",", "}", "}", ",", ")", "hass", ".", "states", ".", "async_set", "(", "\"test.entity\"", ",", "\"hello\"", ",", "{", "\"latitude\"", ":", "32.881011", ",", "\"longitude\"", ":", "-", "117.234758", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "0" ]
[ 108, 0 ]
[ 136, 26 ]
python
en
['en', 'en', 'en']
True
test_if_fires_on_zone_leave
(hass, calls)
Test for firing on zone leave.
Test for firing on zone leave.
async def test_if_fires_on_zone_leave(hass, calls): """Test for firing on zone leave.""" hass.states.async_set( "test.entity", "hello", {"latitude": 32.880586, "longitude": -117.237564} ) await hass.async_block_till_done() assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: { "trigger": { "platform": "zone", "entity_id": "test.entity", "zone": "zone.test", "event": "leave", }, "action": {"service": "test.automation"}, } }, ) hass.states.async_set( "test.entity", "hello", {"latitude": 32.881011, "longitude": -117.234758} ) await hass.async_block_till_done() assert len(calls) == 1
[ "async", "def", "test_if_fires_on_zone_leave", "(", "hass", ",", "calls", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"test.entity\"", ",", "\"hello\"", ",", "{", "\"latitude\"", ":", "32.880586", ",", "\"longitude\"", ":", "-", "117.237564", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "automation", ".", "DOMAIN", ",", "{", "automation", ".", "DOMAIN", ":", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"zone\"", ",", "\"entity_id\"", ":", "\"test.entity\"", ",", "\"zone\"", ":", "\"zone.test\"", ",", "\"event\"", ":", "\"leave\"", ",", "}", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", "}", ",", "}", "}", ",", ")", "hass", ".", "states", ".", "async_set", "(", "\"test.entity\"", ",", "\"hello\"", ",", "{", "\"latitude\"", ":", "32.881011", ",", "\"longitude\"", ":", "-", "117.234758", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1" ]
[ 139, 0 ]
[ 167, 26 ]
python
en
['en', 'en', 'en']
True
test_if_not_fires_for_leave_on_zone_enter
(hass, calls)
Test for not firing on zone enter.
Test for not firing on zone enter.
async def test_if_not_fires_for_leave_on_zone_enter(hass, calls): """Test for not firing on zone enter.""" hass.states.async_set( "test.entity", "hello", {"latitude": 32.881011, "longitude": -117.234758} ) await hass.async_block_till_done() assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: { "trigger": { "platform": "zone", "entity_id": "test.entity", "zone": "zone.test", "event": "leave", }, "action": {"service": "test.automation"}, } }, ) hass.states.async_set( "test.entity", "hello", {"latitude": 32.880586, "longitude": -117.237564} ) await hass.async_block_till_done() assert len(calls) == 0
[ "async", "def", "test_if_not_fires_for_leave_on_zone_enter", "(", "hass", ",", "calls", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"test.entity\"", ",", "\"hello\"", ",", "{", "\"latitude\"", ":", "32.881011", ",", "\"longitude\"", ":", "-", "117.234758", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "automation", ".", "DOMAIN", ",", "{", "automation", ".", "DOMAIN", ":", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"zone\"", ",", "\"entity_id\"", ":", "\"test.entity\"", ",", "\"zone\"", ":", "\"zone.test\"", ",", "\"event\"", ":", "\"leave\"", ",", "}", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", "}", ",", "}", "}", ",", ")", "hass", ".", "states", ".", "async_set", "(", "\"test.entity\"", ",", "\"hello\"", ",", "{", "\"latitude\"", ":", "32.880586", ",", "\"longitude\"", ":", "-", "117.237564", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "0" ]
[ 170, 0 ]
[ 198, 26 ]
python
en
['en', 'no', 'en']
True
test_zone_condition
(hass, calls)
Test for zone condition.
Test for zone condition.
async def test_zone_condition(hass, calls): """Test for zone condition.""" hass.states.async_set( "test.entity", "hello", {"latitude": 32.880586, "longitude": -117.237564} ) await hass.async_block_till_done() assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: { "trigger": {"platform": "event", "event_type": "test_event"}, "condition": { "condition": "zone", "entity_id": "test.entity", "zone": "zone.test", }, "action": {"service": "test.automation"}, } }, ) hass.bus.async_fire("test_event") await hass.async_block_till_done() assert len(calls) == 1
[ "async", "def", "test_zone_condition", "(", "hass", ",", "calls", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"test.entity\"", ",", "\"hello\"", ",", "{", "\"latitude\"", ":", "32.880586", ",", "\"longitude\"", ":", "-", "117.237564", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "automation", ".", "DOMAIN", ",", "{", "automation", ".", "DOMAIN", ":", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"event\"", ",", "\"event_type\"", ":", "\"test_event\"", "}", ",", "\"condition\"", ":", "{", "\"condition\"", ":", "\"zone\"", ",", "\"entity_id\"", ":", "\"test.entity\"", ",", "\"zone\"", ":", "\"zone.test\"", ",", "}", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", "}", ",", "}", "}", ",", ")", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1" ]
[ 201, 0 ]
[ 226, 26 ]
python
en
['pl', 'en', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the KIWI lock platform.
Set up the KIWI lock platform.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the KIWI lock platform.""" try: kiwi = KiwiClient(config[CONF_USERNAME], config[CONF_PASSWORD]) except KiwiException as exc: _LOGGER.error(exc) return available_locks = kiwi.get_locks() if not available_locks: # No locks found; abort setup routine. _LOGGER.info("No KIWI locks found in your account") return add_entities([KiwiLock(lock, kiwi) for lock in available_locks], True)
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "try", ":", "kiwi", "=", "KiwiClient", "(", "config", "[", "CONF_USERNAME", "]", ",", "config", "[", "CONF_PASSWORD", "]", ")", "except", "KiwiException", "as", "exc", ":", "_LOGGER", ".", "error", "(", "exc", ")", "return", "available_locks", "=", "kiwi", ".", "get_locks", "(", ")", "if", "not", "available_locks", ":", "# No locks found; abort setup routine.", "_LOGGER", ".", "info", "(", "\"No KIWI locks found in your account\"", ")", "return", "add_entities", "(", "[", "KiwiLock", "(", "lock", ",", "kiwi", ")", "for", "lock", "in", "available_locks", "]", ",", "True", ")" ]
[ 33, 0 ]
[ 46, 74 ]
python
en
['en', 'zu', 'en']
True
KiwiLock.__init__
(self, kiwi_lock, client)
Initialize the lock.
Initialize the lock.
def __init__(self, kiwi_lock, client): """Initialize the lock.""" self._sensor = kiwi_lock self._client = client self.lock_id = kiwi_lock["sensor_id"] self._state = STATE_LOCKED address = kiwi_lock.get("address") address.update( { ATTR_LATITUDE: address.pop("lat", None), ATTR_LONGITUDE: address.pop("lng", None), } ) self._device_attrs = { ATTR_ID: self.lock_id, ATTR_TYPE: kiwi_lock.get("hardware_type"), ATTR_PERMISSION: kiwi_lock.get("highest_permission"), ATTR_CAN_INVITE: kiwi_lock.get("can_invite"), **address, }
[ "def", "__init__", "(", "self", ",", "kiwi_lock", ",", "client", ")", ":", "self", ".", "_sensor", "=", "kiwi_lock", "self", ".", "_client", "=", "client", "self", ".", "lock_id", "=", "kiwi_lock", "[", "\"sensor_id\"", "]", "self", ".", "_state", "=", "STATE_LOCKED", "address", "=", "kiwi_lock", ".", "get", "(", "\"address\"", ")", "address", ".", "update", "(", "{", "ATTR_LATITUDE", ":", "address", ".", "pop", "(", "\"lat\"", ",", "None", ")", ",", "ATTR_LONGITUDE", ":", "address", ".", "pop", "(", "\"lng\"", ",", "None", ")", ",", "}", ")", "self", ".", "_device_attrs", "=", "{", "ATTR_ID", ":", "self", ".", "lock_id", ",", "ATTR_TYPE", ":", "kiwi_lock", ".", "get", "(", "\"hardware_type\"", ")", ",", "ATTR_PERMISSION", ":", "kiwi_lock", ".", "get", "(", "\"highest_permission\"", ")", ",", "ATTR_CAN_INVITE", ":", "kiwi_lock", ".", "get", "(", "\"can_invite\"", ")", ",", "*", "*", "address", ",", "}" ]
[ 52, 4 ]
[ 73, 9 ]
python
en
['en', 'en', 'en']
True
KiwiLock.name
(self)
Return the name of the lock.
Return the name of the lock.
def name(self): """Return the name of the lock.""" name = self._sensor.get("name") specifier = self._sensor["address"].get("specifier") return name or specifier
[ "def", "name", "(", "self", ")", ":", "name", "=", "self", ".", "_sensor", ".", "get", "(", "\"name\"", ")", "specifier", "=", "self", ".", "_sensor", "[", "\"address\"", "]", ".", "get", "(", "\"specifier\"", ")", "return", "name", "or", "specifier" ]
[ 76, 4 ]
[ 80, 32 ]
python
en
['en', 'en', 'en']
True
KiwiLock.is_locked
(self)
Return true if lock is locked.
Return true if lock is locked.
def is_locked(self): """Return true if lock is locked.""" return self._state == STATE_LOCKED
[ "def", "is_locked", "(", "self", ")", ":", "return", "self", ".", "_state", "==", "STATE_LOCKED" ]
[ 83, 4 ]
[ 85, 42 ]
python
en
['en', 'mt', 'en']
True
KiwiLock.device_state_attributes
(self)
Return the device specific state attributes.
Return the device specific state attributes.
def device_state_attributes(self): """Return the device specific state attributes.""" return self._device_attrs
[ "def", "device_state_attributes", "(", "self", ")", ":", "return", "self", ".", "_device_attrs" ]
[ 88, 4 ]
[ 90, 33 ]
python
en
['en', 'en', 'en']
True
KiwiLock.clear_unlock_state
(self, _)
Clear unlock state automatically.
Clear unlock state automatically.
def clear_unlock_state(self, _): """Clear unlock state automatically.""" self._state = STATE_LOCKED self.async_write_ha_state()
[ "def", "clear_unlock_state", "(", "self", ",", "_", ")", ":", "self", ".", "_state", "=", "STATE_LOCKED", "self", ".", "async_write_ha_state", "(", ")" ]
[ 93, 4 ]
[ 96, 35 ]
python
en
['en', 'en', 'en']
True
KiwiLock.unlock
(self, **kwargs)
Unlock the device.
Unlock the device.
def unlock(self, **kwargs): """Unlock the device.""" try: self._client.open_door(self.lock_id) except KiwiException: _LOGGER.error("failed to open door") else: self._state = STATE_UNLOCKED self.hass.add_job( async_call_later, self.hass, UNLOCK_MAINTAIN_TIME, self.clear_unlock_state, )
[ "def", "unlock", "(", "self", ",", "*", "*", "kwargs", ")", ":", "try", ":", "self", ".", "_client", ".", "open_door", "(", "self", ".", "lock_id", ")", "except", "KiwiException", ":", "_LOGGER", ".", "error", "(", "\"failed to open door\"", ")", "else", ":", "self", ".", "_state", "=", "STATE_UNLOCKED", "self", ".", "hass", ".", "add_job", "(", "async_call_later", ",", "self", ".", "hass", ",", "UNLOCK_MAINTAIN_TIME", ",", "self", ".", "clear_unlock_state", ",", ")" ]
[ 98, 4 ]
[ 112, 13 ]
python
en
['en', 'zh', 'en']
True
binary_sensor_unique_id
(risco, zone_id)
Return unique id for the binary sensor.
Return unique id for the binary sensor.
def binary_sensor_unique_id(risco, zone_id): """Return unique id for the binary sensor.""" return f"{risco.site_uuid}_zone_{zone_id}"
[ "def", "binary_sensor_unique_id", "(", "risco", ",", "zone_id", ")", ":", "return", "f\"{risco.site_uuid}_zone_{zone_id}\"" ]
[ 4, 0 ]
[ 6, 46 ]
python
en
['en', 'it', 'en']
True
RiscoEntity.async_added_to_hass
(self)
When entity is added to hass.
When entity is added to hass.
async def async_added_to_hass(self): """When entity is added to hass.""" self.async_on_remove( self.coordinator.async_add_listener(self._refresh_from_coordinator) )
[ "async", "def", "async_added_to_hass", "(", "self", ")", ":", "self", ".", "async_on_remove", "(", "self", ".", "coordinator", ".", "async_add_listener", "(", "self", ".", "_refresh_from_coordinator", ")", ")" ]
[ 19, 4 ]
[ 23, 9 ]
python
en
['en', 'en', 'en']
True
RiscoEntity._risco
(self)
Return the Risco API object.
Return the Risco API object.
def _risco(self): """Return the Risco API object.""" return self.coordinator.risco
[ "def", "_risco", "(", "self", ")", ":", "return", "self", ".", "coordinator", ".", "risco" ]
[ 26, 4 ]
[ 28, 37 ]
python
en
['en', 'sm', 'en']
True
test_async_setup_entry
(hass)
Test a successful setup entry.
Test a successful setup entry.
async def test_async_setup_entry(hass): """Test a successful setup entry.""" await init_integration(hass) state = hass.states.get("sensor.hl_l2340dw_status") assert state is not None assert state.state != STATE_UNAVAILABLE assert state.state == "waiting"
[ "async", "def", "test_async_setup_entry", "(", "hass", ")", ":", "await", "init_integration", "(", "hass", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.hl_l2340dw_status\"", ")", "assert", "state", "is", "not", "None", "assert", "state", ".", "state", "!=", "STATE_UNAVAILABLE", "assert", "state", ".", "state", "==", "\"waiting\"" ]
[ 14, 0 ]
[ 21, 35 ]
python
en
['en', 'en', 'en']
True
test_config_not_ready
(hass)
Test for setup failure if connection to broker is missing.
Test for setup failure if connection to broker is missing.
async def test_config_not_ready(hass): """Test for setup failure if connection to broker is missing.""" entry = MockConfigEntry( domain=DOMAIN, title="HL-L2340DW 0123456789", unique_id="0123456789", data={CONF_HOST: "localhost", CONF_TYPE: "laser"}, ) with patch("brother.Brother._get_data", side_effect=ConnectionError()): entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) assert entry.state == ENTRY_STATE_SETUP_RETRY
[ "async", "def", "test_config_not_ready", "(", "hass", ")", ":", "entry", "=", "MockConfigEntry", "(", "domain", "=", "DOMAIN", ",", "title", "=", "\"HL-L2340DW 0123456789\"", ",", "unique_id", "=", "\"0123456789\"", ",", "data", "=", "{", "CONF_HOST", ":", "\"localhost\"", ",", "CONF_TYPE", ":", "\"laser\"", "}", ",", ")", "with", "patch", "(", "\"brother.Brother._get_data\"", ",", "side_effect", "=", "ConnectionError", "(", ")", ")", ":", "entry", ".", "add_to_hass", "(", "hass", ")", "await", "hass", ".", "config_entries", ".", "async_setup", "(", "entry", ".", "entry_id", ")", "assert", "entry", ".", "state", "==", "ENTRY_STATE_SETUP_RETRY" ]
[ 24, 0 ]
[ 36, 53 ]
python
en
['en', 'en', 'en']
True
test_unload_entry
(hass)
Test successful unload of entry.
Test successful unload of entry.
async def test_unload_entry(hass): """Test successful unload of entry.""" entry = await init_integration(hass) assert len(hass.config_entries.async_entries(DOMAIN)) == 1 assert entry.state == ENTRY_STATE_LOADED assert await hass.config_entries.async_unload(entry.entry_id) await hass.async_block_till_done() assert entry.state == ENTRY_STATE_NOT_LOADED assert not hass.data.get(DOMAIN)
[ "async", "def", "test_unload_entry", "(", "hass", ")", ":", "entry", "=", "await", "init_integration", "(", "hass", ")", "assert", "len", "(", "hass", ".", "config_entries", ".", "async_entries", "(", "DOMAIN", ")", ")", "==", "1", "assert", "entry", ".", "state", "==", "ENTRY_STATE_LOADED", "assert", "await", "hass", ".", "config_entries", ".", "async_unload", "(", "entry", ".", "entry_id", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "entry", ".", "state", "==", "ENTRY_STATE_NOT_LOADED", "assert", "not", "hass", ".", "data", ".", "get", "(", "DOMAIN", ")" ]
[ 39, 0 ]
[ 50, 36 ]
python
en
['en', 'en', 'en']
True
init_config_flow
(hass)
Init a configuration flow.
Init a configuration flow.
async def init_config_flow(hass): """Init a configuration flow.""" await async_setup_component( hass, "http", {"http": {"base_url": "https://hass.com"}} ) config_flow.register_flow_implementation(hass, "id", "secret") flow = config_flow.AmbiclimateFlowHandler() flow.hass = hass return flow
[ "async", "def", "init_config_flow", "(", "hass", ")", ":", "await", "async_setup_component", "(", "hass", ",", "\"http\"", ",", "{", "\"http\"", ":", "{", "\"base_url\"", ":", "\"https://hass.com\"", "}", "}", ")", "config_flow", ".", "register_flow_implementation", "(", "hass", ",", "\"id\"", ",", "\"secret\"", ")", "flow", "=", "config_flow", ".", "AmbiclimateFlowHandler", "(", ")", "flow", ".", "hass", "=", "hass", "return", "flow" ]
[ 12, 0 ]
[ 22, 15 ]
python
en
['es', 'fr', 'en']
False
test_abort_if_no_implementation_registered
(hass)
Test we abort if no implementation is registered.
Test we abort if no implementation is registered.
async def test_abort_if_no_implementation_registered(hass): """Test we abort if no implementation is registered.""" flow = config_flow.AmbiclimateFlowHandler() flow.hass = hass result = await flow.async_step_user() assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "missing_configuration"
[ "async", "def", "test_abort_if_no_implementation_registered", "(", "hass", ")", ":", "flow", "=", "config_flow", ".", "AmbiclimateFlowHandler", "(", ")", "flow", ".", "hass", "=", "hass", "result", "=", "await", "flow", ".", "async_step_user", "(", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_ABORT", "assert", "result", "[", "\"reason\"", "]", "==", "\"missing_configuration\"" ]
[ 25, 0 ]
[ 32, 54 ]
python
en
['en', 'en', 'en']
True
test_abort_if_already_setup
(hass)
Test we abort if Ambiclimate is already setup.
Test we abort if Ambiclimate is already setup.
async def test_abort_if_already_setup(hass): """Test we abort if Ambiclimate is already setup.""" flow = await init_config_flow(hass) with patch.object(hass.config_entries, "async_entries", return_value=[{}]): result = await flow.async_step_user() assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" with patch.object(hass.config_entries, "async_entries", return_value=[{}]): result = await flow.async_step_code() assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
[ "async", "def", "test_abort_if_already_setup", "(", "hass", ")", ":", "flow", "=", "await", "init_config_flow", "(", "hass", ")", "with", "patch", ".", "object", "(", "hass", ".", "config_entries", ",", "\"async_entries\"", ",", "return_value", "=", "[", "{", "}", "]", ")", ":", "result", "=", "await", "flow", ".", "async_step_user", "(", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_ABORT", "assert", "result", "[", "\"reason\"", "]", "==", "\"already_configured\"", "with", "patch", ".", "object", "(", "hass", ".", "config_entries", ",", "\"async_entries\"", ",", "return_value", "=", "[", "{", "}", "]", ")", ":", "result", "=", "await", "flow", ".", "async_step_code", "(", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_ABORT", "assert", "result", "[", "\"reason\"", "]", "==", "\"already_configured\"" ]
[ 35, 0 ]
[ 47, 51 ]
python
en
['en', 'zu', 'en']
True
test_full_flow_implementation
(hass)
Test registering an implementation and finishing flow works.
Test registering an implementation and finishing flow works.
async def test_full_flow_implementation(hass): """Test registering an implementation and finishing flow works.""" config_flow.register_flow_implementation(hass, None, None) flow = await init_config_flow(hass) result = await flow.async_step_user() assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "auth" assert ( result["description_placeholders"]["cb_url"] == "https://hass.com/api/ambiclimate" ) url = result["description_placeholders"]["authorization_url"] assert "https://api.ambiclimate.com/oauth2/authorize" in url assert "client_id=id" in url assert "response_type=code" in url assert "redirect_uri=https%3A%2F%2Fhass.com%2Fapi%2Fambiclimate" in url with patch("ambiclimate.AmbiclimateOAuth.get_access_token", return_value="test"): result = await flow.async_step_code("123ABC") assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == "Ambiclimate" assert result["data"]["callback_url"] == "https://hass.com/api/ambiclimate" assert result["data"][CONF_CLIENT_SECRET] == "secret" assert result["data"][CONF_CLIENT_ID] == "id" with patch("ambiclimate.AmbiclimateOAuth.get_access_token", return_value=None): result = await flow.async_step_code("123ABC") assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT with patch( "ambiclimate.AmbiclimateOAuth.get_access_token", side_effect=ambiclimate.AmbiclimateOauthError(), ): result = await flow.async_step_code("123ABC") assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
[ "async", "def", "test_full_flow_implementation", "(", "hass", ")", ":", "config_flow", ".", "register_flow_implementation", "(", "hass", ",", "None", ",", "None", ")", "flow", "=", "await", "init_config_flow", "(", "hass", ")", "result", "=", "await", "flow", ".", "async_step_user", "(", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_FORM", "assert", "result", "[", "\"step_id\"", "]", "==", "\"auth\"", "assert", "(", "result", "[", "\"description_placeholders\"", "]", "[", "\"cb_url\"", "]", "==", "\"https://hass.com/api/ambiclimate\"", ")", "url", "=", "result", "[", "\"description_placeholders\"", "]", "[", "\"authorization_url\"", "]", "assert", "\"https://api.ambiclimate.com/oauth2/authorize\"", "in", "url", "assert", "\"client_id=id\"", "in", "url", "assert", "\"response_type=code\"", "in", "url", "assert", "\"redirect_uri=https%3A%2F%2Fhass.com%2Fapi%2Fambiclimate\"", "in", "url", "with", "patch", "(", "\"ambiclimate.AmbiclimateOAuth.get_access_token\"", ",", "return_value", "=", "\"test\"", ")", ":", "result", "=", "await", "flow", ".", "async_step_code", "(", "\"123ABC\"", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_CREATE_ENTRY", "assert", "result", "[", "\"title\"", "]", "==", "\"Ambiclimate\"", "assert", "result", "[", "\"data\"", "]", "[", "\"callback_url\"", "]", "==", "\"https://hass.com/api/ambiclimate\"", "assert", "result", "[", "\"data\"", "]", "[", "CONF_CLIENT_SECRET", "]", "==", "\"secret\"", "assert", "result", "[", "\"data\"", "]", "[", "CONF_CLIENT_ID", "]", "==", "\"id\"", "with", "patch", "(", "\"ambiclimate.AmbiclimateOAuth.get_access_token\"", ",", "return_value", "=", "None", ")", ":", "result", "=", "await", "flow", ".", "async_step_code", "(", "\"123ABC\"", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_ABORT", "with", "patch", "(", "\"ambiclimate.AmbiclimateOAuth.get_access_token\"", ",", "side_effect", "=", "ambiclimate", ".", "AmbiclimateOauthError", "(", ")", ",", ")", ":", "result", "=", "await", "flow", ".", "async_step_code", "(", "\"123ABC\"", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_ABORT" ]
[ 50, 0 ]
[ 86, 62 ]
python
en
['en', 'en', 'en']
True
test_abort_invalid_code
(hass)
Test if no code is given to step_code.
Test if no code is given to step_code.
async def test_abort_invalid_code(hass): """Test if no code is given to step_code.""" config_flow.register_flow_implementation(hass, None, None) flow = await init_config_flow(hass) with patch("ambiclimate.AmbiclimateOAuth.get_access_token", return_value=None): result = await flow.async_step_code("invalid") assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "access_token"
[ "async", "def", "test_abort_invalid_code", "(", "hass", ")", ":", "config_flow", ".", "register_flow_implementation", "(", "hass", ",", "None", ",", "None", ")", "flow", "=", "await", "init_config_flow", "(", "hass", ")", "with", "patch", "(", "\"ambiclimate.AmbiclimateOAuth.get_access_token\"", ",", "return_value", "=", "None", ")", ":", "result", "=", "await", "flow", ".", "async_step_code", "(", "\"invalid\"", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_ABORT", "assert", "result", "[", "\"reason\"", "]", "==", "\"access_token\"" ]
[ 89, 0 ]
[ 97, 45 ]
python
en
['en', 'en', 'en']
True
test_already_setup
(hass)
Test when already setup.
Test when already setup.
async def test_already_setup(hass): """Test when already setup.""" config_flow.register_flow_implementation(hass, None, None) flow = await init_config_flow(hass) with patch.object(hass.config_entries, "async_entries", return_value=True): result = await flow.async_step_user() assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
[ "async", "def", "test_already_setup", "(", "hass", ")", ":", "config_flow", ".", "register_flow_implementation", "(", "hass", ",", "None", ",", "None", ")", "flow", "=", "await", "init_config_flow", "(", "hass", ")", "with", "patch", ".", "object", "(", "hass", ".", "config_entries", ",", "\"async_entries\"", ",", "return_value", "=", "True", ")", ":", "result", "=", "await", "flow", ".", "async_step_user", "(", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_ABORT", "assert", "result", "[", "\"reason\"", "]", "==", "\"already_configured\"" ]
[ 100, 0 ]
[ 109, 51 ]
python
en
['en', 'el-Latn', 'en']
True
push_registrations
(hass)
Return a dictionary of push enabled registrations.
Return a dictionary of push enabled registrations.
def push_registrations(hass): """Return a dictionary of push enabled registrations.""" targets = {} for webhook_id, entry in hass.data[DOMAIN][DATA_CONFIG_ENTRIES].items(): data = entry.data app_data = data[ATTR_APP_DATA] if ATTR_PUSH_TOKEN in app_data and ATTR_PUSH_URL in app_data: device_name = data[ATTR_DEVICE_NAME] if device_name in targets: _LOGGER.warning("Found duplicate device name %s", device_name) continue targets[device_name] = webhook_id return targets
[ "def", "push_registrations", "(", "hass", ")", ":", "targets", "=", "{", "}", "for", "webhook_id", ",", "entry", "in", "hass", ".", "data", "[", "DOMAIN", "]", "[", "DATA_CONFIG_ENTRIES", "]", ".", "items", "(", ")", ":", "data", "=", "entry", ".", "data", "app_data", "=", "data", "[", "ATTR_APP_DATA", "]", "if", "ATTR_PUSH_TOKEN", "in", "app_data", "and", "ATTR_PUSH_URL", "in", "app_data", ":", "device_name", "=", "data", "[", "ATTR_DEVICE_NAME", "]", "if", "device_name", "in", "targets", ":", "_LOGGER", ".", "warning", "(", "\"Found duplicate device name %s\"", ",", "device_name", ")", "continue", "targets", "[", "device_name", "]", "=", "webhook_id", "return", "targets" ]
[ 43, 0 ]
[ 55, 18 ]
python
en
['en', 'en', 'en']
True
log_rate_limits
(hass, device_name, resp, level=logging.INFO)
Output rate limit log line at given level.
Output rate limit log line at given level.
def log_rate_limits(hass, device_name, resp, level=logging.INFO): """Output rate limit log line at given level.""" if ATTR_PUSH_RATE_LIMITS not in resp: return rate_limits = resp[ATTR_PUSH_RATE_LIMITS] resetsAt = rate_limits[ATTR_PUSH_RATE_LIMITS_RESETS_AT] resetsAtTime = dt_util.parse_datetime(resetsAt) - dt_util.utcnow() rate_limit_msg = ( "mobile_app push notification rate limits for %s: " "%d sent, %d allowed, %d errors, " "resets in %s" ) _LOGGER.log( level, rate_limit_msg, device_name, rate_limits[ATTR_PUSH_RATE_LIMITS_SUCCESSFUL], rate_limits[ATTR_PUSH_RATE_LIMITS_MAXIMUM], rate_limits[ATTR_PUSH_RATE_LIMITS_ERRORS], str(resetsAtTime).split(".")[0], )
[ "def", "log_rate_limits", "(", "hass", ",", "device_name", ",", "resp", ",", "level", "=", "logging", ".", "INFO", ")", ":", "if", "ATTR_PUSH_RATE_LIMITS", "not", "in", "resp", ":", "return", "rate_limits", "=", "resp", "[", "ATTR_PUSH_RATE_LIMITS", "]", "resetsAt", "=", "rate_limits", "[", "ATTR_PUSH_RATE_LIMITS_RESETS_AT", "]", "resetsAtTime", "=", "dt_util", ".", "parse_datetime", "(", "resetsAt", ")", "-", "dt_util", ".", "utcnow", "(", ")", "rate_limit_msg", "=", "(", "\"mobile_app push notification rate limits for %s: \"", "\"%d sent, %d allowed, %d errors, \"", "\"resets in %s\"", ")", "_LOGGER", ".", "log", "(", "level", ",", "rate_limit_msg", ",", "device_name", ",", "rate_limits", "[", "ATTR_PUSH_RATE_LIMITS_SUCCESSFUL", "]", ",", "rate_limits", "[", "ATTR_PUSH_RATE_LIMITS_MAXIMUM", "]", ",", "rate_limits", "[", "ATTR_PUSH_RATE_LIMITS_ERRORS", "]", ",", "str", "(", "resetsAtTime", ")", ".", "split", "(", "\".\"", ")", "[", "0", "]", ",", ")" ]
[ 59, 0 ]
[ 80, 5 ]
python
en
['da', 'en', 'en']
True
async_get_service
(hass, config, discovery_info=None)
Get the mobile_app notification service.
Get the mobile_app notification service.
async def async_get_service(hass, config, discovery_info=None): """Get the mobile_app notification service.""" session = async_get_clientsession(hass) return MobileAppNotificationService(session)
[ "async", "def", "async_get_service", "(", "hass", ",", "config", ",", "discovery_info", "=", "None", ")", ":", "session", "=", "async_get_clientsession", "(", "hass", ")", "return", "MobileAppNotificationService", "(", "session", ")" ]
[ 83, 0 ]
[ 86, 48 ]
python
en
['en', 'en', 'en']
True
MobileAppNotificationService.__init__
(self, session)
Initialize the service.
Initialize the service.
def __init__(self, session): """Initialize the service.""" self._session = session
[ "def", "__init__", "(", "self", ",", "session", ")", ":", "self", ".", "_session", "=", "session" ]
[ 92, 4 ]
[ 94, 31 ]
python
en
['en', 'en', 'en']
True
MobileAppNotificationService.targets
(self)
Return a dictionary of registered targets.
Return a dictionary of registered targets.
def targets(self): """Return a dictionary of registered targets.""" return push_registrations(self.hass)
[ "def", "targets", "(", "self", ")", ":", "return", "push_registrations", "(", "self", ".", "hass", ")" ]
[ 97, 4 ]
[ 99, 44 ]
python
en
['en', 'en', 'en']
True
MobileAppNotificationService.async_send_message
(self, message="", **kwargs)
Send a message to the Lambda APNS gateway.
Send a message to the Lambda APNS gateway.
async def async_send_message(self, message="", **kwargs): """Send a message to the Lambda APNS gateway.""" data = {ATTR_MESSAGE: message} if kwargs.get(ATTR_TITLE) is not None: # Remove default title from notifications. if kwargs.get(ATTR_TITLE) != ATTR_TITLE_DEFAULT: data[ATTR_TITLE] = kwargs.get(ATTR_TITLE) targets = kwargs.get(ATTR_TARGET) if not targets: targets = push_registrations(self.hass).values() if kwargs.get(ATTR_DATA) is not None: data[ATTR_DATA] = kwargs.get(ATTR_DATA) for target in targets: entry = self.hass.data[DOMAIN][DATA_CONFIG_ENTRIES][target] entry_data = entry.data app_data = entry_data[ATTR_APP_DATA] push_token = app_data[ATTR_PUSH_TOKEN] push_url = app_data[ATTR_PUSH_URL] data[ATTR_PUSH_TOKEN] = push_token reg_info = { ATTR_APP_ID: entry_data[ATTR_APP_ID], ATTR_APP_VERSION: entry_data[ATTR_APP_VERSION], } if ATTR_OS_VERSION in entry_data: reg_info[ATTR_OS_VERSION] = entry_data[ATTR_OS_VERSION] data["registration_info"] = reg_info try: with async_timeout.timeout(10): response = await self._session.post(push_url, json=data) result = await response.json() if response.status in [HTTP_OK, HTTP_CREATED, HTTP_ACCEPTED]: log_rate_limits(self.hass, entry_data[ATTR_DEVICE_NAME], result) continue fallback_error = result.get("errorMessage", "Unknown error") fallback_message = ( f"Internal server error, please try again later: {fallback_error}" ) message = result.get("message", fallback_message) if "message" in result: if message[-1] not in [".", "?", "!"]: message += "." message += ( " This message is generated externally to Home Assistant." ) if response.status == HTTP_TOO_MANY_REQUESTS: _LOGGER.warning(message) log_rate_limits( self.hass, entry_data[ATTR_DEVICE_NAME], result, logging.WARNING ) else: _LOGGER.error(message) except asyncio.TimeoutError: _LOGGER.error("Timeout sending notification to %s", push_url)
[ "async", "def", "async_send_message", "(", "self", ",", "message", "=", "\"\"", ",", "*", "*", "kwargs", ")", ":", "data", "=", "{", "ATTR_MESSAGE", ":", "message", "}", "if", "kwargs", ".", "get", "(", "ATTR_TITLE", ")", "is", "not", "None", ":", "# Remove default title from notifications.", "if", "kwargs", ".", "get", "(", "ATTR_TITLE", ")", "!=", "ATTR_TITLE_DEFAULT", ":", "data", "[", "ATTR_TITLE", "]", "=", "kwargs", ".", "get", "(", "ATTR_TITLE", ")", "targets", "=", "kwargs", ".", "get", "(", "ATTR_TARGET", ")", "if", "not", "targets", ":", "targets", "=", "push_registrations", "(", "self", ".", "hass", ")", ".", "values", "(", ")", "if", "kwargs", ".", "get", "(", "ATTR_DATA", ")", "is", "not", "None", ":", "data", "[", "ATTR_DATA", "]", "=", "kwargs", ".", "get", "(", "ATTR_DATA", ")", "for", "target", "in", "targets", ":", "entry", "=", "self", ".", "hass", ".", "data", "[", "DOMAIN", "]", "[", "DATA_CONFIG_ENTRIES", "]", "[", "target", "]", "entry_data", "=", "entry", ".", "data", "app_data", "=", "entry_data", "[", "ATTR_APP_DATA", "]", "push_token", "=", "app_data", "[", "ATTR_PUSH_TOKEN", "]", "push_url", "=", "app_data", "[", "ATTR_PUSH_URL", "]", "data", "[", "ATTR_PUSH_TOKEN", "]", "=", "push_token", "reg_info", "=", "{", "ATTR_APP_ID", ":", "entry_data", "[", "ATTR_APP_ID", "]", ",", "ATTR_APP_VERSION", ":", "entry_data", "[", "ATTR_APP_VERSION", "]", ",", "}", "if", "ATTR_OS_VERSION", "in", "entry_data", ":", "reg_info", "[", "ATTR_OS_VERSION", "]", "=", "entry_data", "[", "ATTR_OS_VERSION", "]", "data", "[", "\"registration_info\"", "]", "=", "reg_info", "try", ":", "with", "async_timeout", ".", "timeout", "(", "10", ")", ":", "response", "=", "await", "self", ".", "_session", ".", "post", "(", "push_url", ",", "json", "=", "data", ")", "result", "=", "await", "response", ".", "json", "(", ")", "if", "response", ".", "status", "in", "[", "HTTP_OK", ",", "HTTP_CREATED", ",", "HTTP_ACCEPTED", "]", ":", "log_rate_limits", "(", "self", ".", "hass", ",", "entry_data", "[", "ATTR_DEVICE_NAME", "]", ",", "result", ")", "continue", "fallback_error", "=", "result", ".", "get", "(", "\"errorMessage\"", ",", "\"Unknown error\"", ")", "fallback_message", "=", "(", "f\"Internal server error, please try again later: {fallback_error}\"", ")", "message", "=", "result", ".", "get", "(", "\"message\"", ",", "fallback_message", ")", "if", "\"message\"", "in", "result", ":", "if", "message", "[", "-", "1", "]", "not", "in", "[", "\".\"", ",", "\"?\"", ",", "\"!\"", "]", ":", "message", "+=", "\".\"", "message", "+=", "(", "\" This message is generated externally to Home Assistant.\"", ")", "if", "response", ".", "status", "==", "HTTP_TOO_MANY_REQUESTS", ":", "_LOGGER", ".", "warning", "(", "message", ")", "log_rate_limits", "(", "self", ".", "hass", ",", "entry_data", "[", "ATTR_DEVICE_NAME", "]", ",", "result", ",", "logging", ".", "WARNING", ")", "else", ":", "_LOGGER", ".", "error", "(", "message", ")", "except", "asyncio", ".", "TimeoutError", ":", "_LOGGER", ".", "error", "(", "\"Timeout sending notification to %s\"", ",", "push_url", ")" ]
[ 101, 4 ]
[ 168, 77 ]
python
en
['en', 'ht', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the Email sensor platform.
Set up the Email sensor platform.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Email sensor platform.""" reader = EmailReader( config.get(CONF_USERNAME), config.get(CONF_PASSWORD), config.get(CONF_SERVER), config.get(CONF_PORT), config.get(CONF_FOLDER), ) value_template = config.get(CONF_VALUE_TEMPLATE) if value_template is not None: value_template.hass = hass sensor = EmailContentSensor( hass, reader, config.get(CONF_NAME) or config.get(CONF_USERNAME), config.get(CONF_SENDERS), value_template, ) if sensor.connected: add_entities([sensor], True) else: return False
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "reader", "=", "EmailReader", "(", "config", ".", "get", "(", "CONF_USERNAME", ")", ",", "config", ".", "get", "(", "CONF_PASSWORD", ")", ",", "config", ".", "get", "(", "CONF_SERVER", ")", ",", "config", ".", "get", "(", "CONF_PORT", ")", ",", "config", ".", "get", "(", "CONF_FOLDER", ")", ",", ")", "value_template", "=", "config", ".", "get", "(", "CONF_VALUE_TEMPLATE", ")", "if", "value_template", "is", "not", "None", ":", "value_template", ".", "hass", "=", "hass", "sensor", "=", "EmailContentSensor", "(", "hass", ",", "reader", ",", "config", ".", "get", "(", "CONF_NAME", ")", "or", "config", ".", "get", "(", "CONF_USERNAME", ")", ",", "config", ".", "get", "(", "CONF_SENDERS", ")", ",", "value_template", ",", ")", "if", "sensor", ".", "connected", ":", "add_entities", "(", "[", "sensor", "]", ",", "True", ")", "else", ":", "return", "False" ]
[ 48, 0 ]
[ 72, 20 ]
python
en
['en', 'da', 'en']
True
EmailReader.__init__
(self, user, password, server, port, folder)
Initialize the Email Reader.
Initialize the Email Reader.
def __init__(self, user, password, server, port, folder): """Initialize the Email Reader.""" self._user = user self._password = password self._server = server self._port = port self._folder = folder self._last_id = None self._unread_ids = deque([]) self.connection = None
[ "def", "__init__", "(", "self", ",", "user", ",", "password", ",", "server", ",", "port", ",", "folder", ")", ":", "self", ".", "_user", "=", "user", "self", ".", "_password", "=", "password", "self", ".", "_server", "=", "server", "self", ".", "_port", "=", "port", "self", ".", "_folder", "=", "folder", "self", ".", "_last_id", "=", "None", "self", ".", "_unread_ids", "=", "deque", "(", "[", "]", ")", "self", ".", "connection", "=", "None" ]
[ 78, 4 ]
[ 87, 30 ]
python
en
['en', 'en', 'en']
True
EmailReader.connect
(self)
Login and setup the connection.
Login and setup the connection.
def connect(self): """Login and setup the connection.""" try: self.connection = imaplib.IMAP4_SSL(self._server, self._port) self.connection.login(self._user, self._password) return True except imaplib.IMAP4.error: _LOGGER.error("Failed to login to %s", self._server) return False
[ "def", "connect", "(", "self", ")", ":", "try", ":", "self", ".", "connection", "=", "imaplib", ".", "IMAP4_SSL", "(", "self", ".", "_server", ",", "self", ".", "_port", ")", "self", ".", "connection", ".", "login", "(", "self", ".", "_user", ",", "self", ".", "_password", ")", "return", "True", "except", "imaplib", ".", "IMAP4", ".", "error", ":", "_LOGGER", ".", "error", "(", "\"Failed to login to %s\"", ",", "self", ".", "_server", ")", "return", "False" ]
[ 89, 4 ]
[ 97, 24 ]
python
en
['en', 'en', 'en']
True
EmailReader._fetch_message
(self, message_uid)
Get an email message from a message id.
Get an email message from a message id.
def _fetch_message(self, message_uid): """Get an email message from a message id.""" _, message_data = self.connection.uid("fetch", message_uid, "(RFC822)") if message_data is None: return None if message_data[0] is None: return None raw_email = message_data[0][1] email_message = email.message_from_bytes(raw_email) return email_message
[ "def", "_fetch_message", "(", "self", ",", "message_uid", ")", ":", "_", ",", "message_data", "=", "self", ".", "connection", ".", "uid", "(", "\"fetch\"", ",", "message_uid", ",", "\"(RFC822)\"", ")", "if", "message_data", "is", "None", ":", "return", "None", "if", "message_data", "[", "0", "]", "is", "None", ":", "return", "None", "raw_email", "=", "message_data", "[", "0", "]", "[", "1", "]", "email_message", "=", "email", ".", "message_from_bytes", "(", "raw_email", ")", "return", "email_message" ]
[ 99, 4 ]
[ 109, 28 ]
python
en
['en', 'en', 'en']
True
EmailReader.read_next
(self)
Read the next email from the email server.
Read the next email from the email server.
def read_next(self): """Read the next email from the email server.""" try: self.connection.select(self._folder, readonly=True) if not self._unread_ids: search = f"SINCE {datetime.date.today():%d-%b-%Y}" if self._last_id is not None: search = f"UID {self._last_id}:*" _, data = self.connection.uid("search", None, search) self._unread_ids = deque(data[0].split()) while self._unread_ids: message_uid = self._unread_ids.popleft() if self._last_id is None or int(message_uid) > self._last_id: self._last_id = int(message_uid) return self._fetch_message(message_uid) return self._fetch_message(str(self._last_id)) except imaplib.IMAP4.error: _LOGGER.info("Connection to %s lost, attempting to reconnect", self._server) try: self.connect() _LOGGER.info( "Reconnect to %s succeeded, trying last message", self._server ) if self._last_id is not None: return self._fetch_message(str(self._last_id)) except imaplib.IMAP4.error: _LOGGER.error("Failed to reconnect") return None
[ "def", "read_next", "(", "self", ")", ":", "try", ":", "self", ".", "connection", ".", "select", "(", "self", ".", "_folder", ",", "readonly", "=", "True", ")", "if", "not", "self", ".", "_unread_ids", ":", "search", "=", "f\"SINCE {datetime.date.today():%d-%b-%Y}\"", "if", "self", ".", "_last_id", "is", "not", "None", ":", "search", "=", "f\"UID {self._last_id}:*\"", "_", ",", "data", "=", "self", ".", "connection", ".", "uid", "(", "\"search\"", ",", "None", ",", "search", ")", "self", ".", "_unread_ids", "=", "deque", "(", "data", "[", "0", "]", ".", "split", "(", ")", ")", "while", "self", ".", "_unread_ids", ":", "message_uid", "=", "self", ".", "_unread_ids", ".", "popleft", "(", ")", "if", "self", ".", "_last_id", "is", "None", "or", "int", "(", "message_uid", ")", ">", "self", ".", "_last_id", ":", "self", ".", "_last_id", "=", "int", "(", "message_uid", ")", "return", "self", ".", "_fetch_message", "(", "message_uid", ")", "return", "self", ".", "_fetch_message", "(", "str", "(", "self", ".", "_last_id", ")", ")", "except", "imaplib", ".", "IMAP4", ".", "error", ":", "_LOGGER", ".", "info", "(", "\"Connection to %s lost, attempting to reconnect\"", ",", "self", ".", "_server", ")", "try", ":", "self", ".", "connect", "(", ")", "_LOGGER", ".", "info", "(", "\"Reconnect to %s succeeded, trying last message\"", ",", "self", ".", "_server", ")", "if", "self", ".", "_last_id", "is", "not", "None", ":", "return", "self", ".", "_fetch_message", "(", "str", "(", "self", ".", "_last_id", ")", ")", "except", "imaplib", ".", "IMAP4", ".", "error", ":", "_LOGGER", ".", "error", "(", "\"Failed to reconnect\"", ")", "return", "None" ]
[ 111, 4 ]
[ 144, 19 ]
python
en
['en', 'en', 'en']
True
EmailContentSensor.__init__
(self, hass, email_reader, name, allowed_senders, value_template)
Initialize the sensor.
Initialize the sensor.
def __init__(self, hass, email_reader, name, allowed_senders, value_template): """Initialize the sensor.""" self.hass = hass self._email_reader = email_reader self._name = name self._allowed_senders = [sender.upper() for sender in allowed_senders] self._value_template = value_template self._last_id = None self._message = None self._state_attributes = None self.connected = self._email_reader.connect()
[ "def", "__init__", "(", "self", ",", "hass", ",", "email_reader", ",", "name", ",", "allowed_senders", ",", "value_template", ")", ":", "self", ".", "hass", "=", "hass", "self", ".", "_email_reader", "=", "email_reader", "self", ".", "_name", "=", "name", "self", ".", "_allowed_senders", "=", "[", "sender", ".", "upper", "(", ")", "for", "sender", "in", "allowed_senders", "]", "self", ".", "_value_template", "=", "value_template", "self", ".", "_last_id", "=", "None", "self", ".", "_message", "=", "None", "self", ".", "_state_attributes", "=", "None", "self", ".", "connected", "=", "self", ".", "_email_reader", ".", "connect", "(", ")" ]
[ 150, 4 ]
[ 160, 53 ]
python
en
['en', 'en', 'en']
True
EmailContentSensor.name
(self)
Return the name of the sensor.
Return the name of the sensor.
def name(self): """Return the name of the sensor.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 163, 4 ]
[ 165, 25 ]
python
en
['en', 'mi', 'en']
True
EmailContentSensor.state
(self)
Return the current email state.
Return the current email state.
def state(self): """Return the current email state.""" return self._message
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_message" ]
[ 168, 4 ]
[ 170, 28 ]
python
en
['en', 'en', 'en']
True
EmailContentSensor.device_state_attributes
(self)
Return other state attributes for the message.
Return other state attributes for the message.
def device_state_attributes(self): """Return other state attributes for the message.""" return self._state_attributes
[ "def", "device_state_attributes", "(", "self", ")", ":", "return", "self", ".", "_state_attributes" ]
[ 173, 4 ]
[ 175, 37 ]
python
en
['en', 'en', 'en']
True
EmailContentSensor.render_template
(self, email_message)
Render the message template.
Render the message template.
def render_template(self, email_message): """Render the message template.""" variables = { ATTR_FROM: EmailContentSensor.get_msg_sender(email_message), ATTR_SUBJECT: EmailContentSensor.get_msg_subject(email_message), ATTR_DATE: email_message["Date"], ATTR_BODY: EmailContentSensor.get_msg_text(email_message), } return self._value_template.render(variables, parse_result=False)
[ "def", "render_template", "(", "self", ",", "email_message", ")", ":", "variables", "=", "{", "ATTR_FROM", ":", "EmailContentSensor", ".", "get_msg_sender", "(", "email_message", ")", ",", "ATTR_SUBJECT", ":", "EmailContentSensor", ".", "get_msg_subject", "(", "email_message", ")", ",", "ATTR_DATE", ":", "email_message", "[", "\"Date\"", "]", ",", "ATTR_BODY", ":", "EmailContentSensor", ".", "get_msg_text", "(", "email_message", ")", ",", "}", "return", "self", ".", "_value_template", ".", "render", "(", "variables", ",", "parse_result", "=", "False", ")" ]
[ 177, 4 ]
[ 185, 73 ]
python
en
['en', 'en', 'en']
True
EmailContentSensor.sender_allowed
(self, email_message)
Check if the sender is in the allowed senders list.
Check if the sender is in the allowed senders list.
def sender_allowed(self, email_message): """Check if the sender is in the allowed senders list.""" return EmailContentSensor.get_msg_sender(email_message).upper() in ( sender for sender in self._allowed_senders )
[ "def", "sender_allowed", "(", "self", ",", "email_message", ")", ":", "return", "EmailContentSensor", ".", "get_msg_sender", "(", "email_message", ")", ".", "upper", "(", ")", "in", "(", "sender", "for", "sender", "in", "self", ".", "_allowed_senders", ")" ]
[ 187, 4 ]
[ 191, 9 ]
python
en
['en', 'en', 'en']
True
EmailContentSensor.get_msg_sender
(email_message)
Get the parsed message sender from the email.
Get the parsed message sender from the email.
def get_msg_sender(email_message): """Get the parsed message sender from the email.""" return str(email.utils.parseaddr(email_message["From"])[1])
[ "def", "get_msg_sender", "(", "email_message", ")", ":", "return", "str", "(", "email", ".", "utils", ".", "parseaddr", "(", "email_message", "[", "\"From\"", "]", ")", "[", "1", "]", ")" ]
[ 194, 4 ]
[ 196, 67 ]
python
en
['en', 'en', 'en']
True
EmailContentSensor.get_msg_subject
(email_message)
Decode the message subject.
Decode the message subject.
def get_msg_subject(email_message): """Decode the message subject.""" decoded_header = email.header.decode_header(email_message["Subject"]) header = email.header.make_header(decoded_header) return str(header)
[ "def", "get_msg_subject", "(", "email_message", ")", ":", "decoded_header", "=", "email", ".", "header", ".", "decode_header", "(", "email_message", "[", "\"Subject\"", "]", ")", "header", "=", "email", ".", "header", ".", "make_header", "(", "decoded_header", ")", "return", "str", "(", "header", ")" ]
[ 199, 4 ]
[ 203, 26 ]
python
en
['en', 'en', 'en']
True
EmailContentSensor.get_msg_text
(email_message)
Get the message text from the email. Will look for text/plain or use text/html if not found.
Get the message text from the email.
def get_msg_text(email_message): """ Get the message text from the email. Will look for text/plain or use text/html if not found. """ message_text = None message_html = None message_untyped_text = None for part in email_message.walk(): if part.get_content_type() == CONTENT_TYPE_TEXT_PLAIN: if message_text is None: message_text = part.get_payload() elif part.get_content_type() == "text/html": if message_html is None: message_html = part.get_payload() elif part.get_content_type().startswith("text"): if message_untyped_text is None: message_untyped_text = part.get_payload() if message_text is not None: return message_text if message_html is not None: return message_html if message_untyped_text is not None: return message_untyped_text return email_message.get_payload()
[ "def", "get_msg_text", "(", "email_message", ")", ":", "message_text", "=", "None", "message_html", "=", "None", "message_untyped_text", "=", "None", "for", "part", "in", "email_message", ".", "walk", "(", ")", ":", "if", "part", ".", "get_content_type", "(", ")", "==", "CONTENT_TYPE_TEXT_PLAIN", ":", "if", "message_text", "is", "None", ":", "message_text", "=", "part", ".", "get_payload", "(", ")", "elif", "part", ".", "get_content_type", "(", ")", "==", "\"text/html\"", ":", "if", "message_html", "is", "None", ":", "message_html", "=", "part", ".", "get_payload", "(", ")", "elif", "part", ".", "get_content_type", "(", ")", ".", "startswith", "(", "\"text\"", ")", ":", "if", "message_untyped_text", "is", "None", ":", "message_untyped_text", "=", "part", ".", "get_payload", "(", ")", "if", "message_text", "is", "not", "None", ":", "return", "message_text", "if", "message_html", "is", "not", "None", ":", "return", "message_html", "if", "message_untyped_text", "is", "not", "None", ":", "return", "message_untyped_text", "return", "email_message", ".", "get_payload", "(", ")" ]
[ 206, 4 ]
[ 236, 42 ]
python
en
['en', 'error', 'th']
False
EmailContentSensor.update
(self)
Read emails and publish state change.
Read emails and publish state change.
def update(self): """Read emails and publish state change.""" email_message = self._email_reader.read_next() if email_message is None: self._message = None self._state_attributes = {} return if self.sender_allowed(email_message): message = EmailContentSensor.get_msg_subject(email_message) if self._value_template is not None: message = self.render_template(email_message) self._message = message self._state_attributes = { ATTR_FROM: EmailContentSensor.get_msg_sender(email_message), ATTR_SUBJECT: EmailContentSensor.get_msg_subject(email_message), ATTR_DATE: email_message["Date"], ATTR_BODY: EmailContentSensor.get_msg_text(email_message), }
[ "def", "update", "(", "self", ")", ":", "email_message", "=", "self", ".", "_email_reader", ".", "read_next", "(", ")", "if", "email_message", "is", "None", ":", "self", ".", "_message", "=", "None", "self", ".", "_state_attributes", "=", "{", "}", "return", "if", "self", ".", "sender_allowed", "(", "email_message", ")", ":", "message", "=", "EmailContentSensor", ".", "get_msg_subject", "(", "email_message", ")", "if", "self", ".", "_value_template", "is", "not", "None", ":", "message", "=", "self", ".", "render_template", "(", "email_message", ")", "self", ".", "_message", "=", "message", "self", ".", "_state_attributes", "=", "{", "ATTR_FROM", ":", "EmailContentSensor", ".", "get_msg_sender", "(", "email_message", ")", ",", "ATTR_SUBJECT", ":", "EmailContentSensor", ".", "get_msg_subject", "(", "email_message", ")", ",", "ATTR_DATE", ":", "email_message", "[", "\"Date\"", "]", ",", "ATTR_BODY", ":", "EmailContentSensor", ".", "get_msg_text", "(", "email_message", ")", ",", "}" ]
[ 238, 4 ]
[ 259, 13 ]
python
en
['en', 'en', 'en']
True
test_sensitive_data_filter
()
Test the logging sensitive data filter.
Test the logging sensitive data filter.
def test_sensitive_data_filter(): """Test the logging sensitive data filter.""" log_filter = logging_util.HideSensitiveDataFilter("mock_sensitive") clean_record = logging.makeLogRecord({"msg": "clean log data"}) log_filter.filter(clean_record) assert clean_record.msg == "clean log data" sensitive_record = logging.makeLogRecord({"msg": "mock_sensitive log"}) log_filter.filter(sensitive_record) assert sensitive_record.msg == "******* log"
[ "def", "test_sensitive_data_filter", "(", ")", ":", "log_filter", "=", "logging_util", ".", "HideSensitiveDataFilter", "(", "\"mock_sensitive\"", ")", "clean_record", "=", "logging", ".", "makeLogRecord", "(", "{", "\"msg\"", ":", "\"clean log data\"", "}", ")", "log_filter", ".", "filter", "(", "clean_record", ")", "assert", "clean_record", ".", "msg", "==", "\"clean log data\"", "sensitive_record", "=", "logging", ".", "makeLogRecord", "(", "{", "\"msg\"", ":", "\"mock_sensitive log\"", "}", ")", "log_filter", ".", "filter", "(", "sensitive_record", ")", "assert", "sensitive_record", ".", "msg", "==", "\"******* log\"" ]
[ 12, 0 ]
[ 22, 48 ]
python
en
['en', 'da', 'en']
True
test_logging_with_queue_handler
()
Test logging with HomeAssistantQueueHandler.
Test logging with HomeAssistantQueueHandler.
async def test_logging_with_queue_handler(): """Test logging with HomeAssistantQueueHandler.""" simple_queue = queue.SimpleQueue() # type: ignore handler = logging_util.HomeAssistantQueueHandler(simple_queue) log_record = logging.makeLogRecord({"msg": "Test Log Record"}) handler.emit(log_record) with pytest.raises(asyncio.CancelledError), patch.object( handler, "enqueue", side_effect=asyncio.CancelledError ): handler.emit(log_record) with patch.object(handler, "emit") as emit_mock: handler.handle(log_record) emit_mock.assert_called_once() with patch.object(handler, "filter") as filter_mock, patch.object( handler, "emit" ) as emit_mock: filter_mock.return_value = False handler.handle(log_record) emit_mock.assert_not_called() with patch.object(handler, "enqueue", side_effect=OSError), patch.object( handler, "handleError" ) as mock_handle_error: handler.emit(log_record) mock_handle_error.assert_called_once() handler.close() assert simple_queue.get_nowait().msg == "Test Log Record" assert simple_queue.empty()
[ "async", "def", "test_logging_with_queue_handler", "(", ")", ":", "simple_queue", "=", "queue", ".", "SimpleQueue", "(", ")", "# type: ignore", "handler", "=", "logging_util", ".", "HomeAssistantQueueHandler", "(", "simple_queue", ")", "log_record", "=", "logging", ".", "makeLogRecord", "(", "{", "\"msg\"", ":", "\"Test Log Record\"", "}", ")", "handler", ".", "emit", "(", "log_record", ")", "with", "pytest", ".", "raises", "(", "asyncio", ".", "CancelledError", ")", ",", "patch", ".", "object", "(", "handler", ",", "\"enqueue\"", ",", "side_effect", "=", "asyncio", ".", "CancelledError", ")", ":", "handler", ".", "emit", "(", "log_record", ")", "with", "patch", ".", "object", "(", "handler", ",", "\"emit\"", ")", "as", "emit_mock", ":", "handler", ".", "handle", "(", "log_record", ")", "emit_mock", ".", "assert_called_once", "(", ")", "with", "patch", ".", "object", "(", "handler", ",", "\"filter\"", ")", "as", "filter_mock", ",", "patch", ".", "object", "(", "handler", ",", "\"emit\"", ")", "as", "emit_mock", ":", "filter_mock", ".", "return_value", "=", "False", "handler", ".", "handle", "(", "log_record", ")", "emit_mock", ".", "assert_not_called", "(", ")", "with", "patch", ".", "object", "(", "handler", ",", "\"enqueue\"", ",", "side_effect", "=", "OSError", ")", ",", "patch", ".", "object", "(", "handler", ",", "\"handleError\"", ")", "as", "mock_handle_error", ":", "handler", ".", "emit", "(", "log_record", ")", "mock_handle_error", ".", "assert_called_once", "(", ")", "handler", ".", "close", "(", ")", "assert", "simple_queue", ".", "get_nowait", "(", ")", ".", "msg", "==", "\"Test Log Record\"", "assert", "simple_queue", ".", "empty", "(", ")" ]
[ 25, 0 ]
[ 60, 31 ]
python
en
['en', 'de', 'en']
True
test_migrate_log_handler
(hass)
Test migrating log handlers.
Test migrating log handlers.
async def test_migrate_log_handler(hass): """Test migrating log handlers.""" logging_util.async_activate_log_queue_handler(hass) assert len(logging.root.handlers) == 1 assert isinstance(logging.root.handlers[0], logging_util.HomeAssistantQueueHandler)
[ "async", "def", "test_migrate_log_handler", "(", "hass", ")", ":", "logging_util", ".", "async_activate_log_queue_handler", "(", "hass", ")", "assert", "len", "(", "logging", ".", "root", ".", "handlers", ")", "==", "1", "assert", "isinstance", "(", "logging", ".", "root", ".", "handlers", "[", "0", "]", ",", "logging_util", ".", "HomeAssistantQueueHandler", ")" ]
[ 63, 0 ]
[ 69, 87 ]
python
da
['da', 'da', 'en']
True
test_async_create_catching_coro
(hass, caplog)
Test exception logging of wrapped coroutine.
Test exception logging of wrapped coroutine.
async def test_async_create_catching_coro(hass, caplog): """Test exception logging of wrapped coroutine.""" async def job(): raise Exception("This is a bad coroutine") hass.async_create_task(logging_util.async_create_catching_coro(job())) await hass.async_block_till_done() assert "This is a bad coroutine" in caplog.text assert "in test_async_create_catching_coro" in caplog.text
[ "async", "def", "test_async_create_catching_coro", "(", "hass", ",", "caplog", ")", ":", "async", "def", "job", "(", ")", ":", "raise", "Exception", "(", "\"This is a bad coroutine\"", ")", "hass", ".", "async_create_task", "(", "logging_util", ".", "async_create_catching_coro", "(", "job", "(", ")", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "\"This is a bad coroutine\"", "in", "caplog", ".", "text", "assert", "\"in test_async_create_catching_coro\"", "in", "caplog", ".", "text" ]
[ 73, 0 ]
[ 82, 62 ]
python
en
['en', 'en', 'en']
True
test_setup_hass
(hass: HomeAssistant, aioclient_mock)
Test for successfully setting up the smhi platform. This test are deeper integrated with the core. Since only config_flow is used the component are setup with "async_forward_entry_setup". The actual result are tested with the entity state rather than "per function" unity tests
Test for successfully setting up the smhi platform.
async def test_setup_hass(hass: HomeAssistant, aioclient_mock) -> None: """Test for successfully setting up the smhi platform. This test are deeper integrated with the core. Since only config_flow is used the component are setup with "async_forward_entry_setup". The actual result are tested with the entity state rather than "per function" unity tests """ uri = APIURL_TEMPLATE.format(TEST_CONFIG["longitude"], TEST_CONFIG["latitude"]) api_response = load_fixture("smhi.json") aioclient_mock.get(uri, text=api_response) entry = MockConfigEntry(domain="smhi", data=TEST_CONFIG) await hass.config_entries.async_forward_entry_setup(entry, WEATHER_DOMAIN) await hass.async_block_till_done() assert aioclient_mock.call_count == 1 # Testing the actual entity state for # deeper testing than normal unity test state = hass.states.get("weather.smhi_test") assert state.state == "sunny" assert state.attributes[ATTR_SMHI_CLOUDINESS] == 50 assert state.attributes[ATTR_WEATHER_ATTRIBUTION].find("SMHI") >= 0 assert state.attributes[ATTR_WEATHER_HUMIDITY] == 55 assert state.attributes[ATTR_WEATHER_PRESSURE] == 1024 assert state.attributes[ATTR_WEATHER_TEMPERATURE] == 17 assert state.attributes[ATTR_WEATHER_VISIBILITY] == 50 assert state.attributes[ATTR_WEATHER_WIND_SPEED] == 7 assert state.attributes[ATTR_WEATHER_WIND_BEARING] == 134 _LOGGER.error(state.attributes) assert len(state.attributes["forecast"]) == 4 forecast = state.attributes["forecast"][1] assert forecast[ATTR_FORECAST_TIME] == "2018-09-02T12:00:00" assert forecast[ATTR_FORECAST_TEMP] == 21 assert forecast[ATTR_FORECAST_TEMP_LOW] == 6 assert forecast[ATTR_FORECAST_PRECIPITATION] == 0 assert forecast[ATTR_FORECAST_CONDITION] == "partlycloudy"
[ "async", "def", "test_setup_hass", "(", "hass", ":", "HomeAssistant", ",", "aioclient_mock", ")", "->", "None", ":", "uri", "=", "APIURL_TEMPLATE", ".", "format", "(", "TEST_CONFIG", "[", "\"longitude\"", "]", ",", "TEST_CONFIG", "[", "\"latitude\"", "]", ")", "api_response", "=", "load_fixture", "(", "\"smhi.json\"", ")", "aioclient_mock", ".", "get", "(", "uri", ",", "text", "=", "api_response", ")", "entry", "=", "MockConfigEntry", "(", "domain", "=", "\"smhi\"", ",", "data", "=", "TEST_CONFIG", ")", "await", "hass", ".", "config_entries", ".", "async_forward_entry_setup", "(", "entry", ",", "WEATHER_DOMAIN", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "aioclient_mock", ".", "call_count", "==", "1", "# Testing the actual entity state for", "# deeper testing than normal unity test", "state", "=", "hass", ".", "states", ".", "get", "(", "\"weather.smhi_test\"", ")", "assert", "state", ".", "state", "==", "\"sunny\"", "assert", "state", ".", "attributes", "[", "ATTR_SMHI_CLOUDINESS", "]", "==", "50", "assert", "state", ".", "attributes", "[", "ATTR_WEATHER_ATTRIBUTION", "]", ".", "find", "(", "\"SMHI\"", ")", ">=", "0", "assert", "state", ".", "attributes", "[", "ATTR_WEATHER_HUMIDITY", "]", "==", "55", "assert", "state", ".", "attributes", "[", "ATTR_WEATHER_PRESSURE", "]", "==", "1024", "assert", "state", ".", "attributes", "[", "ATTR_WEATHER_TEMPERATURE", "]", "==", "17", "assert", "state", ".", "attributes", "[", "ATTR_WEATHER_VISIBILITY", "]", "==", "50", "assert", "state", ".", "attributes", "[", "ATTR_WEATHER_WIND_SPEED", "]", "==", "7", "assert", "state", ".", "attributes", "[", "ATTR_WEATHER_WIND_BEARING", "]", "==", "134", "_LOGGER", ".", "error", "(", "state", ".", "attributes", ")", "assert", "len", "(", "state", ".", "attributes", "[", "\"forecast\"", "]", ")", "==", "4", "forecast", "=", "state", ".", "attributes", "[", "\"forecast\"", "]", "[", "1", "]", "assert", "forecast", "[", "ATTR_FORECAST_TIME", "]", "==", "\"2018-09-02T12:00:00\"", "assert", "forecast", "[", "ATTR_FORECAST_TEMP", "]", "==", "21", "assert", "forecast", "[", "ATTR_FORECAST_TEMP_LOW", "]", "==", "6", "assert", "forecast", "[", "ATTR_FORECAST_PRECIPITATION", "]", "==", "0", "assert", "forecast", "[", "ATTR_FORECAST_CONDITION", "]", "==", "\"partlycloudy\"" ]
[ 35, 0 ]
[ 74, 62 ]
python
en
['en', 'en', 'en']
True
test_properties_no_data
(hass: HomeAssistant)
Test properties when no API data available.
Test properties when no API data available.
def test_properties_no_data(hass: HomeAssistant) -> None: """Test properties when no API data available.""" weather = weather_smhi.SmhiWeather("name", "10", "10") weather.hass = hass assert weather.name == "name" assert weather.should_poll is True assert weather.temperature is None assert weather.humidity is None assert weather.wind_speed is None assert weather.wind_bearing is None assert weather.visibility is None assert weather.pressure is None assert weather.cloudiness is None assert weather.condition is None assert weather.forecast is None assert weather.temperature_unit == TEMP_CELSIUS
[ "def", "test_properties_no_data", "(", "hass", ":", "HomeAssistant", ")", "->", "None", ":", "weather", "=", "weather_smhi", ".", "SmhiWeather", "(", "\"name\"", ",", "\"10\"", ",", "\"10\"", ")", "weather", ".", "hass", "=", "hass", "assert", "weather", ".", "name", "==", "\"name\"", "assert", "weather", ".", "should_poll", "is", "True", "assert", "weather", ".", "temperature", "is", "None", "assert", "weather", ".", "humidity", "is", "None", "assert", "weather", ".", "wind_speed", "is", "None", "assert", "weather", ".", "wind_bearing", "is", "None", "assert", "weather", ".", "visibility", "is", "None", "assert", "weather", ".", "pressure", "is", "None", "assert", "weather", ".", "cloudiness", "is", "None", "assert", "weather", ".", "condition", "is", "None", "assert", "weather", ".", "forecast", "is", "None", "assert", "weather", ".", "temperature_unit", "==", "TEMP_CELSIUS" ]
[ 77, 0 ]
[ 93, 51 ]
python
en
['en', 'en', 'en']
True
test_properties_unknown_symbol
()
Test behaviour when unknown symbol from API.
Test behaviour when unknown symbol from API.
def test_properties_unknown_symbol() -> None: """Test behaviour when unknown symbol from API.""" hass = Mock() data = Mock() data.temperature = 5 data.mean_precipitation = 0.5 data.total_precipitation = 1 data.humidity = 5 data.wind_speed = 10 data.wind_direction = 180 data.horizontal_visibility = 6 data.pressure = 1008 data.cloudiness = 52 data.symbol = 100 # Faulty symbol data.valid_time = datetime(2018, 1, 1, 0, 1, 2) data2 = Mock() data2.temperature = 5 data2.mean_precipitation = 0.5 data2.total_precipitation = 1 data2.humidity = 5 data2.wind_speed = 10 data2.wind_direction = 180 data2.horizontal_visibility = 6 data2.pressure = 1008 data2.cloudiness = 52 data2.symbol = 100 # Faulty symbol data2.valid_time = datetime(2018, 1, 1, 12, 1, 2) data3 = Mock() data3.temperature = 5 data3.mean_precipitation = 0.5 data3.total_precipitation = 1 data3.humidity = 5 data3.wind_speed = 10 data3.wind_direction = 180 data3.horizontal_visibility = 6 data3.pressure = 1008 data3.cloudiness = 52 data3.symbol = 100 # Faulty symbol data3.valid_time = datetime(2018, 1, 2, 12, 1, 2) testdata = [data, data2, data3] weather = weather_smhi.SmhiWeather("name", "10", "10") weather.hass = hass weather._forecasts = testdata assert weather.condition is None forecast = weather.forecast[0] assert forecast[ATTR_FORECAST_CONDITION] is None
[ "def", "test_properties_unknown_symbol", "(", ")", "->", "None", ":", "hass", "=", "Mock", "(", ")", "data", "=", "Mock", "(", ")", "data", ".", "temperature", "=", "5", "data", ".", "mean_precipitation", "=", "0.5", "data", ".", "total_precipitation", "=", "1", "data", ".", "humidity", "=", "5", "data", ".", "wind_speed", "=", "10", "data", ".", "wind_direction", "=", "180", "data", ".", "horizontal_visibility", "=", "6", "data", ".", "pressure", "=", "1008", "data", ".", "cloudiness", "=", "52", "data", ".", "symbol", "=", "100", "# Faulty symbol", "data", ".", "valid_time", "=", "datetime", "(", "2018", ",", "1", ",", "1", ",", "0", ",", "1", ",", "2", ")", "data2", "=", "Mock", "(", ")", "data2", ".", "temperature", "=", "5", "data2", ".", "mean_precipitation", "=", "0.5", "data2", ".", "total_precipitation", "=", "1", "data2", ".", "humidity", "=", "5", "data2", ".", "wind_speed", "=", "10", "data2", ".", "wind_direction", "=", "180", "data2", ".", "horizontal_visibility", "=", "6", "data2", ".", "pressure", "=", "1008", "data2", ".", "cloudiness", "=", "52", "data2", ".", "symbol", "=", "100", "# Faulty symbol", "data2", ".", "valid_time", "=", "datetime", "(", "2018", ",", "1", ",", "1", ",", "12", ",", "1", ",", "2", ")", "data3", "=", "Mock", "(", ")", "data3", ".", "temperature", "=", "5", "data3", ".", "mean_precipitation", "=", "0.5", "data3", ".", "total_precipitation", "=", "1", "data3", ".", "humidity", "=", "5", "data3", ".", "wind_speed", "=", "10", "data3", ".", "wind_direction", "=", "180", "data3", ".", "horizontal_visibility", "=", "6", "data3", ".", "pressure", "=", "1008", "data3", ".", "cloudiness", "=", "52", "data3", ".", "symbol", "=", "100", "# Faulty symbol", "data3", ".", "valid_time", "=", "datetime", "(", "2018", ",", "1", ",", "2", ",", "12", ",", "1", ",", "2", ")", "testdata", "=", "[", "data", ",", "data2", ",", "data3", "]", "weather", "=", "weather_smhi", ".", "SmhiWeather", "(", "\"name\"", ",", "\"10\"", ",", "\"10\"", ")", "weather", ".", "hass", "=", "hass", "weather", ".", "_forecasts", "=", "testdata", "assert", "weather", ".", "condition", "is", "None", "forecast", "=", "weather", ".", "forecast", "[", "0", "]", "assert", "forecast", "[", "ATTR_FORECAST_CONDITION", "]", "is", "None" ]
[ 97, 0 ]
[ 146, 52 ]
python
en
['en', 'en', 'en']
True
test_refresh_weather_forecast_exceeds_retries
(hass)
Test the refresh weather forecast function.
Test the refresh weather forecast function.
async def test_refresh_weather_forecast_exceeds_retries(hass) -> None: """Test the refresh weather forecast function.""" with patch.object( hass.helpers.event, "async_call_later" ) as call_later, patch.object( weather_smhi.SmhiWeather, "get_weather_forecast", side_effect=SmhiForecastException(), ): weather = weather_smhi.SmhiWeather("name", "17.0022", "62.0022") weather.hass = hass weather._fail_count = 2 await weather.async_update() assert weather._forecasts is None assert not call_later.mock_calls
[ "async", "def", "test_refresh_weather_forecast_exceeds_retries", "(", "hass", ")", "->", "None", ":", "with", "patch", ".", "object", "(", "hass", ".", "helpers", ".", "event", ",", "\"async_call_later\"", ")", "as", "call_later", ",", "patch", ".", "object", "(", "weather_smhi", ".", "SmhiWeather", ",", "\"get_weather_forecast\"", ",", "side_effect", "=", "SmhiForecastException", "(", ")", ",", ")", ":", "weather", "=", "weather_smhi", ".", "SmhiWeather", "(", "\"name\"", ",", "\"17.0022\"", ",", "\"62.0022\"", ")", "weather", ".", "hass", "=", "hass", "weather", ".", "_fail_count", "=", "2", "await", "weather", ".", "async_update", "(", ")", "assert", "weather", ".", "_forecasts", "is", "None", "assert", "not", "call_later", ".", "mock_calls" ]
[ 150, 0 ]
[ 167, 40 ]
python
en
['en', 'en', 'en']
True
test_refresh_weather_forecast_timeout
(hass)
Test timeout exception.
Test timeout exception.
async def test_refresh_weather_forecast_timeout(hass) -> None: """Test timeout exception.""" weather = weather_smhi.SmhiWeather("name", "17.0022", "62.0022") weather.hass = hass with patch.object( hass.helpers.event, "async_call_later" ) as call_later, patch.object( weather_smhi.SmhiWeather, "retry_update" ), patch.object( weather_smhi.SmhiWeather, "get_weather_forecast", side_effect=asyncio.TimeoutError, ): await weather.async_update() assert len(call_later.mock_calls) == 1 # Assert we are going to wait RETRY_TIMEOUT seconds assert call_later.mock_calls[0][1][0] == weather_smhi.RETRY_TIMEOUT
[ "async", "def", "test_refresh_weather_forecast_timeout", "(", "hass", ")", "->", "None", ":", "weather", "=", "weather_smhi", ".", "SmhiWeather", "(", "\"name\"", ",", "\"17.0022\"", ",", "\"62.0022\"", ")", "weather", ".", "hass", "=", "hass", "with", "patch", ".", "object", "(", "hass", ".", "helpers", ".", "event", ",", "\"async_call_later\"", ")", "as", "call_later", ",", "patch", ".", "object", "(", "weather_smhi", ".", "SmhiWeather", ",", "\"retry_update\"", ")", ",", "patch", ".", "object", "(", "weather_smhi", ".", "SmhiWeather", ",", "\"get_weather_forecast\"", ",", "side_effect", "=", "asyncio", ".", "TimeoutError", ",", ")", ":", "await", "weather", ".", "async_update", "(", ")", "assert", "len", "(", "call_later", ".", "mock_calls", ")", "==", "1", "# Assert we are going to wait RETRY_TIMEOUT seconds", "assert", "call_later", ".", "mock_calls", "[", "0", "]", "[", "1", "]", "[", "0", "]", "==", "weather_smhi", ".", "RETRY_TIMEOUT" ]
[ 170, 0 ]
[ 188, 75 ]
python
en
['en', 'en', 'en']
True
test_refresh_weather_forecast_exception
()
Test any exception.
Test any exception.
async def test_refresh_weather_forecast_exception() -> None: """Test any exception.""" hass = Mock() weather = weather_smhi.SmhiWeather("name", "17.0022", "62.0022") weather.hass = hass with patch.object( hass.helpers.event, "async_call_later" ) as call_later, patch.object( weather, "get_weather_forecast", side_effect=SmhiForecastException(), ): await weather.async_update() assert len(call_later.mock_calls) == 1 # Assert we are going to wait RETRY_TIMEOUT seconds assert call_later.mock_calls[0][1][0] == weather_smhi.RETRY_TIMEOUT
[ "async", "def", "test_refresh_weather_forecast_exception", "(", ")", "->", "None", ":", "hass", "=", "Mock", "(", ")", "weather", "=", "weather_smhi", ".", "SmhiWeather", "(", "\"name\"", ",", "\"17.0022\"", ",", "\"62.0022\"", ")", "weather", ".", "hass", "=", "hass", "with", "patch", ".", "object", "(", "hass", ".", "helpers", ".", "event", ",", "\"async_call_later\"", ")", "as", "call_later", ",", "patch", ".", "object", "(", "weather", ",", "\"get_weather_forecast\"", ",", "side_effect", "=", "SmhiForecastException", "(", ")", ",", ")", ":", "await", "weather", ".", "async_update", "(", ")", "assert", "len", "(", "call_later", ".", "mock_calls", ")", "==", "1", "# Assert we are going to wait RETRY_TIMEOUT seconds", "assert", "call_later", ".", "mock_calls", "[", "0", "]", "[", "1", "]", "[", "0", "]", "==", "weather_smhi", ".", "RETRY_TIMEOUT" ]
[ 191, 0 ]
[ 208, 75 ]
python
en
['en', 'en', 'en']
True
test_retry_update
()
Test retry function of refresh forecast.
Test retry function of refresh forecast.
async def test_retry_update(): """Test retry function of refresh forecast.""" hass = Mock() weather = weather_smhi.SmhiWeather("name", "17.0022", "62.0022") weather.hass = hass with patch.object(weather, "async_update", AsyncMock()) as update: await weather.retry_update(None) assert len(update.mock_calls) == 1
[ "async", "def", "test_retry_update", "(", ")", ":", "hass", "=", "Mock", "(", ")", "weather", "=", "weather_smhi", ".", "SmhiWeather", "(", "\"name\"", ",", "\"17.0022\"", ",", "\"62.0022\"", ")", "weather", ".", "hass", "=", "hass", "with", "patch", ".", "object", "(", "weather", ",", "\"async_update\"", ",", "AsyncMock", "(", ")", ")", "as", "update", ":", "await", "weather", ".", "retry_update", "(", "None", ")", "assert", "len", "(", "update", ".", "mock_calls", ")", "==", "1" ]
[ 211, 0 ]
[ 219, 42 ]
python
en
['en', 'en', 'en']
True
test_condition_class
()
Test condition class.
Test condition class.
def test_condition_class(): """Test condition class.""" def get_condition(index: int) -> str: """Return condition given index.""" return [k for k, v in weather_smhi.CONDITION_CLASSES.items() if index in v][0] # SMHI definitions as follows, see # http://opendata.smhi.se/apidocs/metfcst/parameters.html # 1. Clear sky assert get_condition(1) == "sunny" # 2. Nearly clear sky assert get_condition(2) == "sunny" # 3. Variable cloudiness assert get_condition(3) == "partlycloudy" # 4. Halfclear sky assert get_condition(4) == "partlycloudy" # 5. Cloudy sky assert get_condition(5) == "cloudy" # 6. Overcast assert get_condition(6) == "cloudy" # 7. Fog assert get_condition(7) == "fog" # 8. Light rain showers assert get_condition(8) == "rainy" # 9. Moderate rain showers assert get_condition(9) == "rainy" # 18. Light rain assert get_condition(18) == "rainy" # 19. Moderate rain assert get_condition(19) == "rainy" # 10. Heavy rain showers assert get_condition(10) == "pouring" # 20. Heavy rain assert get_condition(20) == "pouring" # 21. Thunder assert get_condition(21) == "lightning" # 11. Thunderstorm assert get_condition(11) == "lightning-rainy" # 15. Light snow showers assert get_condition(15) == "snowy" # 16. Moderate snow showers assert get_condition(16) == "snowy" # 17. Heavy snow showers assert get_condition(17) == "snowy" # 25. Light snowfall assert get_condition(25) == "snowy" # 26. Moderate snowfall assert get_condition(26) == "snowy" # 27. Heavy snowfall assert get_condition(27) == "snowy" # 12. Light sleet showers assert get_condition(12) == "snowy-rainy" # 13. Moderate sleet showers assert get_condition(13) == "snowy-rainy" # 14. Heavy sleet showers assert get_condition(14) == "snowy-rainy" # 22. Light sleet assert get_condition(22) == "snowy-rainy" # 23. Moderate sleet assert get_condition(23) == "snowy-rainy" # 24. Heavy sleet assert get_condition(24) == "snowy-rainy"
[ "def", "test_condition_class", "(", ")", ":", "def", "get_condition", "(", "index", ":", "int", ")", "->", "str", ":", "\"\"\"Return condition given index.\"\"\"", "return", "[", "k", "for", "k", ",", "v", "in", "weather_smhi", ".", "CONDITION_CLASSES", ".", "items", "(", ")", "if", "index", "in", "v", "]", "[", "0", "]", "# SMHI definitions as follows, see", "# http://opendata.smhi.se/apidocs/metfcst/parameters.html", "# 1. Clear sky", "assert", "get_condition", "(", "1", ")", "==", "\"sunny\"", "# 2. Nearly clear sky", "assert", "get_condition", "(", "2", ")", "==", "\"sunny\"", "# 3. Variable cloudiness", "assert", "get_condition", "(", "3", ")", "==", "\"partlycloudy\"", "# 4. Halfclear sky", "assert", "get_condition", "(", "4", ")", "==", "\"partlycloudy\"", "# 5. Cloudy sky", "assert", "get_condition", "(", "5", ")", "==", "\"cloudy\"", "# 6. Overcast", "assert", "get_condition", "(", "6", ")", "==", "\"cloudy\"", "# 7. Fog", "assert", "get_condition", "(", "7", ")", "==", "\"fog\"", "# 8. Light rain showers", "assert", "get_condition", "(", "8", ")", "==", "\"rainy\"", "# 9. Moderate rain showers", "assert", "get_condition", "(", "9", ")", "==", "\"rainy\"", "# 18. Light rain", "assert", "get_condition", "(", "18", ")", "==", "\"rainy\"", "# 19. Moderate rain", "assert", "get_condition", "(", "19", ")", "==", "\"rainy\"", "# 10. Heavy rain showers", "assert", "get_condition", "(", "10", ")", "==", "\"pouring\"", "# 20. Heavy rain", "assert", "get_condition", "(", "20", ")", "==", "\"pouring\"", "# 21. Thunder", "assert", "get_condition", "(", "21", ")", "==", "\"lightning\"", "# 11. Thunderstorm", "assert", "get_condition", "(", "11", ")", "==", "\"lightning-rainy\"", "# 15. Light snow showers", "assert", "get_condition", "(", "15", ")", "==", "\"snowy\"", "# 16. Moderate snow showers", "assert", "get_condition", "(", "16", ")", "==", "\"snowy\"", "# 17. Heavy snow showers", "assert", "get_condition", "(", "17", ")", "==", "\"snowy\"", "# 25. Light snowfall", "assert", "get_condition", "(", "25", ")", "==", "\"snowy\"", "# 26. Moderate snowfall", "assert", "get_condition", "(", "26", ")", "==", "\"snowy\"", "# 27. Heavy snowfall", "assert", "get_condition", "(", "27", ")", "==", "\"snowy\"", "# 12. Light sleet showers", "assert", "get_condition", "(", "12", ")", "==", "\"snowy-rainy\"", "# 13. Moderate sleet showers", "assert", "get_condition", "(", "13", ")", "==", "\"snowy-rainy\"", "# 14. Heavy sleet showers", "assert", "get_condition", "(", "14", ")", "==", "\"snowy-rainy\"", "# 22. Light sleet", "assert", "get_condition", "(", "22", ")", "==", "\"snowy-rainy\"", "# 23. Moderate sleet", "assert", "get_condition", "(", "23", ")", "==", "\"snowy-rainy\"", "# 24. Heavy sleet", "assert", "get_condition", "(", "24", ")", "==", "\"snowy-rainy\"" ]
[ 222, 0 ]
[ 285, 45 ]
python
en
['en', 'en', 'en']
True
validate_input
(hass: core.HomeAssistant, data)
Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user.
Validate the user input allows us to connect.
async def validate_input(hass: core.HomeAssistant, data): """Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user. """ try: await get_async_monoprice(data[CONF_PORT], hass.loop) except SerialException as err: _LOGGER.error("Error connecting to Monoprice controller") raise CannotConnect from err sources = _sources_from_config(data) # Return info that you want to store in the config entry. return {CONF_PORT: data[CONF_PORT], CONF_SOURCES: sources}
[ "async", "def", "validate_input", "(", "hass", ":", "core", ".", "HomeAssistant", ",", "data", ")", ":", "try", ":", "await", "get_async_monoprice", "(", "data", "[", "CONF_PORT", "]", ",", "hass", ".", "loop", ")", "except", "SerialException", "as", "err", ":", "_LOGGER", ".", "error", "(", "\"Error connecting to Monoprice controller\"", ")", "raise", "CannotConnect", "from", "err", "sources", "=", "_sources_from_config", "(", "data", ")", "# Return info that you want to store in the config entry.", "return", "{", "CONF_PORT", ":", "data", "[", "CONF_PORT", "]", ",", "CONF_SOURCES", ":", "sources", "}" ]
[ 50, 0 ]
[ 64, 62 ]
python
en
['en', 'en', 'en']
True
ConfigFlow.async_step_user
(self, user_input=None)
Handle the initial step.
Handle the initial step.
async def async_step_user(self, user_input=None): """Handle the initial step.""" errors = {} if user_input is not None: try: info = await validate_input(self.hass, user_input) return self.async_create_entry(title=user_input[CONF_PORT], data=info) except CannotConnect: errors["base"] = "cannot_connect" except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" return self.async_show_form( step_id="user", data_schema=DATA_SCHEMA, errors=errors )
[ "async", "def", "async_step_user", "(", "self", ",", "user_input", "=", "None", ")", ":", "errors", "=", "{", "}", "if", "user_input", "is", "not", "None", ":", "try", ":", "info", "=", "await", "validate_input", "(", "self", ".", "hass", ",", "user_input", ")", "return", "self", ".", "async_create_entry", "(", "title", "=", "user_input", "[", "CONF_PORT", "]", ",", "data", "=", "info", ")", "except", "CannotConnect", ":", "errors", "[", "\"base\"", "]", "=", "\"cannot_connect\"", "except", "Exception", ":", "# pylint: disable=broad-except", "_LOGGER", ".", "exception", "(", "\"Unexpected exception\"", ")", "errors", "[", "\"base\"", "]", "=", "\"unknown\"", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"user\"", ",", "data_schema", "=", "DATA_SCHEMA", ",", "errors", "=", "errors", ")" ]
[ 73, 4 ]
[ 89, 9 ]
python
en
['en', 'en', 'en']
True
ConfigFlow.async_get_options_flow
(config_entry)
Define the config flow to handle options.
Define the config flow to handle options.
def async_get_options_flow(config_entry): """Define the config flow to handle options.""" return MonopriceOptionsFlowHandler(config_entry)
[ "def", "async_get_options_flow", "(", "config_entry", ")", ":", "return", "MonopriceOptionsFlowHandler", "(", "config_entry", ")" ]
[ 93, 4 ]
[ 95, 56 ]
python
en
['en', 'en', 'en']
True