File sensor#7569
Conversation
| return self._state | ||
|
|
||
| @asyncio.coroutine | ||
| def async_update(self): |
There was a problem hiding this comment.
We should not do I/O inside an async context. Since you're dealing with a file, best to just keep the method update
| with open(self._file_path, 'r', encoding='utf-8') as file_data: | ||
| data = file_data.readlines()[-1].strip() | ||
| except (IndexError, FileNotFoundError, IsADirectoryError): | ||
| data = STATE_UNKNOWN |
There was a problem hiding this comment.
Please return None instead of STATE_UNKNOWN, the Entity helper class will set it to unknown
There was a problem hiding this comment.
Also return when an error occurs. Templates don't need to run on None
| m_open = MockOpen() | ||
| with patch('homeassistant.components.sensor.file.open', m_open, | ||
| create=True): | ||
| content = open('mock.file1') |
There was a problem hiding this comment.
Wait, why would you open the file? Shouldn't you instead trigger an update to the component here ?
| } | ||
| } | ||
|
|
||
| assert setup_component(self.hass, 'sensor', config) |
There was a problem hiding this comment.
You should run this inside the patch context and block till done. The sensor updates on load, so it will hit your mock.
|
|
||
| def create_file(path, data): | ||
| """Create a sensor file.""" | ||
| with open(path, 'w') as test_file: |
There was a problem hiding this comment.
We should never do any actual I/O in tests. That's why we use mock_open.
balloob
left a comment
There was a problem hiding this comment.
Ok to merge when tests pass 🐬
(if tests don't pass feel free to revert my optimization)
|
Thanks |
|
Is it possible to write to the file using HA to be read by this sensor? |
|
@arsaboo https://home-assistant.io/components/notify.command_line/ could be used in combination with |
Description:
The
filesensor reads the last entry of a plain text file. The entries can be simple values or JSON with is handled by our templating featureRelated issue (if applicable): fixes File sensors
Pull request in home-assistant.github.io with documentation (if applicable): home-assistant/home-assistant.io#2625
Example entry for
configuration.yaml(if applicable):Checklist:
If user exposed functionality or configuration variables are added/changed:
If the code does not interact with devices:
toxrun successfully. Your PR cannot be merged unless tests pass