created temp path function

pull/2892/head
dzekem christa 2020-11-10 20:22:51 +01:00 committed by Kris Gesling
parent 304439ed4b
commit 3f745c52ad
11 changed files with 46 additions and 48 deletions

View File

@ -15,8 +15,6 @@
import subprocess
import time
import sys
import os
import tempfile
from alsaaudio import Mixer
from threading import Thread, Timer
@ -37,6 +35,7 @@ from mycroft.util import play_wav, create_signal, connected, check_for_signal
from mycroft.util.audio_test import record
from mycroft.util.log import LOG
from queue import Queue
from mycroft.util import create_temp_path
# The Mark 1 hardware consists of a Raspberry Pi main CPU which is connected
# to an Arduino over the serial port. A custom serial protocol sends
@ -132,9 +131,9 @@ class EnclosureReader(Thread):
'utterance': "I am testing one two three"}))
time.sleep(0.5) # Prevents recording the loud button press
record(os.path.join(tempfile.gettempdir(), 'test.wav'), 3.0)
record(create_temp_path('test.wav', 3.0)
mixer.setvolume(prev_vol)
play_wav(os.path.join(tempfile.gettempdir(), 'test.wav').communicate())
play_wav(creat_temp_path('test.wav')).communicate()
# Test audio muting on arduino
subprocess.call('speaker-test -P 10 -l 0 -s 1', shell=True)

View File

@ -16,13 +16,13 @@ from signal import getsignal, signal, SIGKILL, SIGINT, SIGTERM, \
SIG_DFL, default_int_handler, SIG_IGN # signals
import os # Operating System functions
import tempfile
#
# Wrapper around chain of handler functions for a specific system level signal.
# Often used to trap Ctrl-C for specific application purposes.
from mycroft.util import LOG
from mycroft.util import create_temp_path
class Signal: # python 3+ class Signal
@ -99,8 +99,7 @@ class Lock: # python 3+ 'class Lock'
#
# Class constants
DIRECTORY = os.path.join(tempfile.gettempdir(),
'mycroft')
DIRECTORY = create_temp_path('mycroft')
FILE = '/{}.pid'
#

View File

@ -19,9 +19,6 @@ more skills that are installed on a device, the longer these interactions
take. This is especially true at boot time when MSM is instantiated
frequently. To improve performance, the MSM instance is cached.
"""
import os
import tempfile
from collections import namedtuple
from functools import lru_cache
from os import path, makedirs
@ -30,6 +27,7 @@ from msm import MycroftSkillsManager, SkillRepo
from mycroft.util.combo_lock import ComboLock
from mycroft.util.log import LOG
from mycroft.util import create_temp_path
MsmConfig = namedtuple(
'MsmConfig',
@ -47,8 +45,7 @@ MsmConfig = namedtuple(
def _init_msm_lock():
msm_lock = None
try:
msm_lock = ComboLock(os.path.join(
tempfile.gettempdir(), 'mycroft-msm.lck'))
msm_lock = ComboLock(create_temp_path('mycroft-msm.lck'))
LOG.debug('mycroft-msm combo lock instantiated')
except Exception:
LOG.exception('Failed to create msm lock!')

View File

@ -14,7 +14,6 @@
#
"""Periodically run by skill manager to update skills and post the manifest."""
import os
import tempfile
import sys
from datetime import datetime
from time import time
@ -27,6 +26,7 @@ from mycroft.util import connected
from mycroft.util.combo_lock import ComboLock
from mycroft.util.log import LOG
from .msm_wrapper import build_msm_config, create_msm
from mycroft.util import create_temp_path
ONE_HOUR = 3600
FIVE_MINUTES = 300 # number of seconds in a minute
@ -49,7 +49,7 @@ class SkillUpdater:
_msm = None
def __init__(self, bus=None):
self.msm_lock = ComboLock(os.path.join(tempfile.gettempdir(), 'mycroft-msm.lck'))
self.msm_lock = ComboLock(create_temp_path('mycroft-msm.lck'))
self.install_retries = 0
self.config = Configuration.get()
update_interval = self.config['skills']['update_interval']

View File

@ -14,7 +14,6 @@
#
from copy import deepcopy
import os
import tempfile
import random
import re
from abc import ABCMeta, abstractmethod
@ -32,6 +31,7 @@ from mycroft.metrics import report_timing, Stopwatch
from mycroft.util import (
play_wav, play_mp3, check_for_signal, create_signal, resolve_resource_file
)
from mycroft.util import create_temp_path
from mycroft.util.log import LOG
from mycroft.util.plugins import load_plugin
from queue import Queue, Empty
@ -178,7 +178,7 @@ class TTS(metaclass=ABCMeta):
self.ssml_tags = ssml_tags or []
self.voice = config.get("voice")
self.filename = os.path.join(tempfile.gettempdir(), 'tts.wav')
self.filename = create_temp_path('tts.wav')
self.enclosure = None
random.seed()
self.queue = Queue()

View File

@ -14,7 +14,6 @@
#
import argparse
import os
import tempfile
import pyaudio
from contextlib import contextmanager
@ -25,6 +24,7 @@ from mycroft.configuration import Configuration
from mycroft.util.audio_utils import play_wav
from mycroft.util.log import LOG
import logging
from mycroft.util import create_temp_path
"""
Audio Test
@ -73,8 +73,8 @@ def record(filename, duration):
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'-f', '--filename', dest='filename', default = os.path.join(tempfile.gettempdir(), 'test.wav'),
help="Filename for saved audio (Default:{}".format(os.path.join(tempfile.gettempdir(), 'test.wav')))
'-f', '--filename', dest='filename', default = create_temp_path('test.wav'),
help="Filename for saved audio (Default:{}".format(create_temp_path('test.wav')))
parser.add_argument(
'-d', '--duration', dest='duration', type=int, default=10,
help="Duration of recording in seconds (Default: 10)")

View File

@ -77,6 +77,14 @@ def resolve_resource_file(res_name):
return None # Resource cannot be resolved
def create_temp_path(*args):
try:
path = os.path.join(tempfile.gettempdir(), *args)
except TypeError:
path = None
LOG.error('Could not create a temp path, create_temp_path() only accepts Strings')
return path
def read_stripped_lines(filename):
"""Read a file and return a list of stripped lines.
@ -231,7 +239,7 @@ def get_cache_directory(domain=None):
directory = config.get("cache_path")
if not directory:
# If not defined, use /tmp/mycroft/cache
directory = os.path.join(tempfile.gettempdir(), "mycroft", "cache")
directory = create_temp_path('mycroft', 'cache')
return ensure_directory_exists(directory, domain)

View File

@ -14,8 +14,6 @@
#
import unittest
import unittest.mock as mock
import os
import tempfile
from shutil import rmtree
from threading import Thread
@ -25,6 +23,7 @@ from os.path import exists
import mycroft.audio
from mycroft.util import create_signal, check_for_signal
from mycroft.util import create_temp_path
"""Tests for public audio service utils."""
@ -40,8 +39,8 @@ def wait_while_speaking_thread():
class TestInterface(unittest.TestCase):
def setUp(self):
if exists(os.path.join(tempfile.gettempdir(), 'mycroft')):
rmtree(os.path.join(tempfile.gettempdir(), 'mycroft'))
if exists(create_temp_path('mycroft')):
rmtree(create_temp_path('mycroft'))
def test_is_speaking(self):
create_signal('isSpeaking')

View File

@ -13,7 +13,6 @@
# limitations under the License.
#
import signal
import tempfile
import unittest
from shutil import rmtree
@ -22,32 +21,33 @@ import os
from os.path import exists, isfile
from mycroft.lock import Lock
from mycroft.util import create_temp_path
class TestLock(unittest.TestCase):
def setUp(self):
if exists(os.path.join(tempfile.gettempdir(), 'mycroft')):
rmtree(os.path.join(tempfile.gettempdir(), 'mycroft'))
if exists(create_temp_path('mycroft')):
rmtree(create_temp_path('mycroft'))
def test_create_lock(self):
l1 = Lock('test')
self.assertTrue(
isfile(os.path.join(tempfile.gettempdir(), 'mycroft', 'test.pid')))
isfile(create_temp_path('mycroft', 'test.pid')))
def test_delete_lock(self):
l1 = Lock('test')
self.assertTrue(
isfile(os.path.join(tempfile.gettempdir(), 'mycroft', 'test.pid')))
isfile(create_temp_path('mycroft', 'test.pid')))
l1.delete()
self.assertFalse(
isfile(os.path.join(tempfile.gettempdir(), 'mycroft', 'test.pid')))
isfile(create_temp_path('mycroft', 'test.pid')))
@patch('os.kill')
def test_existing_lock(self, mock_kill):
""" Test that an existing lock will kill the old pid. """
l1 = Lock('test')
self.assertTrue(
isfile(os.path.join(tempfile.gettempdir(), 'mycroft', 'test.pid')))
isfile(create_temp_path('mycroft', 'test.pid')))
l2 = Lock('test2')
self.assertFalse(mock_kill.called)
l2 = Lock('test')
@ -56,13 +56,13 @@ class TestLock(unittest.TestCase):
def test_keyboard_interrupt(self):
l1 = Lock('test')
self.assertTrue(
isfile(os.path.join(tempfile.gettempdir(), 'mycroft', 'test.pid')))
isfile(create_temp_path('mycroft', 'test.pid')))
try:
os.kill(os.getpid(), signal.SIGINT)
except KeyboardInterrupt:
pass
self.assertFalse(
isfile(os.path.join(tempfile.gettempdir(), 'mycroft', 'test.pid')))
isfile(create_temp_path('mycroft', 'test.pid')))
if __name__ == '__main__':

View File

@ -1,12 +1,10 @@
import os
import tempfile
from unittest import TestCase, mock
from test.util import Anything
from mycroft.util import (play_ogg, play_mp3, play_wav, play_audio_file,
record)
from mycroft.util import create_temp_path
test_config = {
'play_wav_cmdline': 'mock_wav %1',
@ -141,7 +139,7 @@ class TestRecordSounds(TestCase):
mock_subprocess.Popen.return_value = mock_proc
rate = 16000
channels = 1
filename = os.path.join(tempfile.gettempdir(), 'test.wav')
filename = create_temp_path('test.wav')
duration = 42
res = record(filename, duration, rate, channels)
mock_subprocess.Popen.assert_called_once_with(['arecord',
@ -156,7 +154,7 @@ class TestRecordSounds(TestCase):
mock_subprocess.Popen.return_value = mock_proc
rate = 16000
channels = 1
filename = os.path.join(tempfile.gettempdir(), 'test.wav')
filename = create_temp_path('test.wav')
duration = 0
res = record(filename, duration, rate, channels)
mock_subprocess.Popen.assert_called_once_with(['arecord',

View File

@ -1,14 +1,13 @@
import os
import tempfile
from threading import Event
from unittest import TestCase, mock
from mycroft.util.download import (download, _running_downloads,
_get_download_tmp)
from mycroft.util import create_temp_path
TEST_URL = 'http://example.com/mycroft-test.tar.gz'
TEST_DEST = os.path.join(tempfile.gettempdir(), 'file.tar.gz')
TEST_DEST = create_temp_path('file.tar.gz')
@mock.patch('mycroft.util.download.subprocess')
@ -93,18 +92,17 @@ class TestDownload(TestCase):
class TestGetTemp(TestCase):
def test_no_existing(self, mock_glob):
mock_glob.return_value = []
dest = os.path.join(tempfile.gettempdir(), 'test')
dest = create_temp_path('test')
self.assertEqual(_get_download_tmp(dest), dest + '.part')
def test_existing(self, mock_glob):
mock_glob.return_value = [os.path.join(
tempfile.gettempdir(), 'test.part')]
dest = os.path.join(tempfile.gettempdir(), 'test')
mock_glob.return_value = [create_temp_path('test.part')]
dest = create_temp_path('test')
self.assertEqual(_get_download_tmp(dest), dest + '.part.1')
def test_multiple_existing(self, mock_glob):
mock_glob.return_value = [os.path.join(tempfile.gettempdir(), 'test.part'), os.path.join(tempfile.gettempdir(), 'test.part.1'),
os.path.join(tempfile.gettempdir(), 'test.part.2')]
mock_glob.return_value = [create_temp_path('test.part'), create_temp_path('test.part.1'),
create_temp_path('test.part.2')]
dest = os.path.join(tempfile.gettempdir(), 'test')
dest = create_temp_path('test')
self.assertEqual(_get_download_tmp(dest), dest + '.part.3')