feat: migrate config to YAML, add dual-caching and 0ms fzf wrapper

- Migrated configuration backend from JSON to YAML for better readability.
- Added automatic dual-caching (.config.cache.json) to preserve fast load times with YAML.
- Implemented a new 0ms latency fzf wrapper for bash and zsh (--fzf-wrapper).
- Updated sync plugin to support the new YAML config format and clear caches on extraction.
- Refactored 'completion.py' to gracefully handle fallback config formats.
- Added new test modules (test_capture, test_context, test_sync) covering core plugins.
- Updated existing unit tests to handle YAML config creation and parsing.
- Bumped version to 5.0b3 and regenerated HTML documentation.
This commit is contained in:
2026-04-03 18:47:03 -03:00
parent 5d8c372f23
commit d8f7d4db87
16 changed files with 1681 additions and 109 deletions
+3
View File
@@ -142,3 +142,6 @@ GEMINI.md
node_modules/ node_modules/
package-lock.json package-lock.json
package.json package.json
# Development docs
connpy_roadmap.md
+1 -1
View File
@@ -1,2 +1,2 @@
__version__ = "5.0b2" __version__ = "5.0b3"
+14 -2
View File
@@ -97,9 +97,21 @@ def main():
configdir = f.read().strip() configdir = f.read().strip()
except (FileNotFoundError, IOError): except (FileNotFoundError, IOError):
configdir = defaultdir configdir = defaultdir
defaultfile = configdir + '/config.json' cachefile = configdir + '/.config.cache.json'
jsonconf = open(defaultfile) try:
with open(cachefile, "r") as jsonconf:
config = json.load(jsonconf) config = json.load(jsonconf)
except FileNotFoundError:
try:
import yaml
with open(configdir + '/config.yaml', "r") as yamlconf:
config = yaml.safe_load(yamlconf)
except Exception:
try:
with open(configdir + '/config.json', "r") as jsonconf:
config = json.load(jsonconf)
except Exception:
exit()
nodes = _getallnodes(config) nodes = _getallnodes(config)
folders = _getallfolders(config) folders = _getallfolders(config)
profiles = list(config["profiles"].keys()) profiles = list(config["profiles"].keys())
+82 -31
View File
@@ -3,6 +3,8 @@
import json import json
import os import os
import re import re
import yaml
import shutil
from Crypto.PublicKey import RSA from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP from Crypto.Cipher import PKCS1_OAEP
from pathlib import Path from pathlib import Path
@@ -65,16 +67,40 @@ class configfile:
with open(pathfile, "w") as f: with open(pathfile, "w") as f:
f.write(str(defaultdir)) f.write(str(defaultdir))
configdir = defaultdir configdir = defaultdir
defaultfile = configdir + '/config.json' defaultfile = configdir + '/config.yaml'
self.cachefile = configdir + '/.config.cache.json'
self.fzf_cachefile = configdir + '/.fzf_nodes_cache.txt'
defaultkey = configdir + '/.osk' defaultkey = configdir + '/.osk'
if conf == None: if conf == None:
self.file = defaultfile self.file = defaultfile
# Backwards compatibility: Migrate from JSON to YAML
legacy_json = configdir + '/config.json'
legacy_noext = configdir + '/config'
legacy_file = None
if os.path.exists(legacy_json): legacy_file = legacy_json
elif os.path.exists(legacy_noext): legacy_file = legacy_noext
if not os.path.exists(self.file) and legacy_file:
try:
with open(legacy_file, 'r') as f:
old_data = json.load(f)
with open(self.file, 'w') as f:
yaml.dump(old_data, f, default_flow_style=False, sort_keys=False)
with open(self.cachefile, 'w') as f:
json.dump(old_data, f)
shutil.move(legacy_file, legacy_file + ".backup")
printer.success(f"Migrated legacy config ({len(old_data.get('connections',{}))} folders/nodes) into YAML and Cache successfully!")
except Exception as e:
printer.warning(f"Failed to migrate legacy config: {e}")
else: else:
self.file = conf self.file = conf
if key == None: if key == None:
self.key = defaultkey self.key = defaultkey
else: else:
self.key = key self.key = key
if os.path.exists(self.file): if os.path.exists(self.file):
config = self._loadconfig(self.file) config = self._loadconfig(self.file)
else: else:
@@ -91,23 +117,38 @@ class configfile:
def _loadconfig(self, conf): def _loadconfig(self, conf):
#Loads config file #Loads config file using dual cache
jsonconf = open(conf) cache_exists = os.path.exists(self.cachefile)
jsondata = json.load(jsonconf) yaml_time = os.path.getmtime(conf) if os.path.exists(conf) else 0
jsonconf.close() cache_time = os.path.getmtime(self.cachefile) if cache_exists else 0
return jsondata
if not cache_exists or yaml_time > cache_time:
with open(conf, 'r') as f:
data = yaml.safe_load(f)
try:
with open(self.cachefile, 'w') as f:
json.dump(data, f)
except Exception:
pass
return data
else:
with open(self.cachefile, 'r') as f:
return json.load(f)
def _createconfig(self, conf): def _createconfig(self, conf):
#Create config file #Create config file
defaultconfig = {'config': {'case': False, 'idletime': 30, 'fzf': False}, 'connections': {}, 'profiles': { "default": { "host":"", "protocol":"ssh", "port":"", "user":"", "password":"", "options":"", "logs":"", "tags": "", "jumphost":""}}} defaultconfig = {'config': {'case': False, 'idletime': 30, 'fzf': False}, 'connections': {}, 'profiles': { "default": { "host":"", "protocol":"ssh", "port":"", "user":"", "password":"", "options":"", "logs":"", "tags": "", "jumphost":""}}}
if not os.path.exists(conf): if not os.path.exists(conf):
with open(conf, "w") as f: with open(conf, "w") as f:
json.dump(defaultconfig, f, indent = 4) yaml.dump(defaultconfig, f, default_flow_style=False, sort_keys=False)
f.close()
os.chmod(conf, 0o600) os.chmod(conf, 0o600)
jsonconf = open(conf) try:
jsondata = json.load(jsonconf) with open(self.cachefile, 'w') as f:
jsonconf.close() json.dump(defaultconfig, f)
except Exception:
pass
with open(conf, 'r') as f:
jsondata = yaml.safe_load(f)
return jsondata return jsondata
@MethodHook @MethodHook
@@ -119,13 +160,23 @@ class configfile:
newconfig["profiles"] = self.profiles newconfig["profiles"] = self.profiles
try: try:
with open(conf, "w") as f: with open(conf, "w") as f:
json.dump(newconfig, f, indent = 4) yaml.dump(newconfig, f, default_flow_style=False, sort_keys=False)
f.close() with open(self.cachefile, "w") as f:
json.dump(newconfig, f)
self._generate_nodes_cache()
except (IOError, OSError) as e: except (IOError, OSError) as e:
printer.error(f"Failed to save config: {e}") printer.error(f"Failed to save config: {e}")
return 1 return 1
return 0 return 0
def _generate_nodes_cache(self):
try:
nodes = self._getallnodes()
with open(self.fzf_cachefile, "w") as f:
f.write("\n".join(nodes))
except Exception:
pass
def _createkey(self, keyfile): def _createkey(self, keyfile):
#Create key file #Create key file
key = RSA.generate(2048) key = RSA.generate(2048)
@@ -344,15 +395,15 @@ class configfile:
def _getallnodes(self, filter = None): def _getallnodes(self, filter = None):
#get all nodes on configfile #get all nodes on configfile
nodes = [] nodes = []
layer1 = [k for k,v in self.connections.items() if isinstance(v, dict) and v["type"] == "connection"] layer1 = [k for k,v in self.connections.items() if isinstance(v, dict) and v.get("type") == "connection"]
folders = [k for k,v in self.connections.items() if isinstance(v, dict) and v["type"] == "folder"] folders = [k for k,v in self.connections.items() if isinstance(v, dict) and v.get("type") == "folder"]
nodes.extend(layer1) nodes.extend(layer1)
for f in folders: for f in folders:
layer2 = [k + "@" + f for k,v in self.connections[f].items() if isinstance(v, dict) and v["type"] == "connection"] layer2 = [k + "@" + f for k,v in self.connections[f].items() if isinstance(v, dict) and v.get("type") == "connection"]
nodes.extend(layer2) nodes.extend(layer2)
subfolders = [k for k,v in self.connections[f].items() if isinstance(v, dict) and v["type"] == "subfolder"] subfolders = [k for k,v in self.connections[f].items() if isinstance(v, dict) and v.get("type") == "subfolder"]
for s in subfolders: for s in subfolders:
layer3 = [k + "@" + s + "@" + f for k,v in self.connections[f][s].items() if isinstance(v, dict) and v["type"] == "connection"] layer3 = [k + "@" + s + "@" + f for k,v in self.connections[f][s].items() if isinstance(v, dict) and v.get("type") == "connection"]
nodes.extend(layer3) nodes.extend(layer3)
if filter: if filter:
if isinstance(filter, str): if isinstance(filter, str):
@@ -367,15 +418,15 @@ class configfile:
def _getallnodesfull(self, filter = None, extract = True): def _getallnodesfull(self, filter = None, extract = True):
#get all nodes on configfile with all their attributes. #get all nodes on configfile with all their attributes.
nodes = {} nodes = {}
layer1 = {k:v for k,v in self.connections.items() if isinstance(v, dict) and v["type"] == "connection"} layer1 = {k:v for k,v in self.connections.items() if isinstance(v, dict) and v.get("type") == "connection"}
folders = [k for k,v in self.connections.items() if isinstance(v, dict) and v["type"] == "folder"] folders = [k for k,v in self.connections.items() if isinstance(v, dict) and v.get("type") == "folder"]
nodes.update(layer1) nodes.update(layer1)
for f in folders: for f in folders:
layer2 = {k + "@" + f:v for k,v in self.connections[f].items() if isinstance(v, dict) and v["type"] == "connection"} layer2 = {k + "@" + f:v for k,v in self.connections[f].items() if isinstance(v, dict) and v.get("type") == "connection"}
nodes.update(layer2) nodes.update(layer2)
subfolders = [k for k,v in self.connections[f].items() if isinstance(v, dict) and v["type"] == "subfolder"] subfolders = [k for k,v in self.connections[f].items() if isinstance(v, dict) and v.get("type") == "subfolder"]
for s in subfolders: for s in subfolders:
layer3 = {k + "@" + s + "@" + f:v for k,v in self.connections[f][s].items() if isinstance(v, dict) and v["type"] == "connection"} layer3 = {k + "@" + s + "@" + f:v for k,v in self.connections[f][s].items() if isinstance(v, dict) and v.get("type") == "connection"}
nodes.update(layer3) nodes.update(layer3)
if filter: if filter:
if isinstance(filter, str): if isinstance(filter, str):
@@ -406,27 +457,27 @@ class configfile:
@MethodHook @MethodHook
def _getallfolders(self): def _getallfolders(self):
#get all folders on configfile #get all folders on configfile
folders = ["@" + k for k,v in self.connections.items() if isinstance(v, dict) and v["type"] == "folder"] folders = ["@" + k for k,v in self.connections.items() if isinstance(v, dict) and v.get("type") == "folder"]
subfolders = [] subfolders = []
for f in folders: for f in folders:
s = ["@" + k + f for k,v in self.connections[f[1:]].items() if isinstance(v, dict) and v["type"] == "subfolder"] s = ["@" + k + f for k,v in self.connections[f[1:]].items() if isinstance(v, dict) and v.get("type") == "subfolder"]
subfolders.extend(s) subfolders.extend(s)
folders.extend(subfolders) folders.extend(subfolders)
return folders return folders
@MethodHook @MethodHook
def _profileused(self, profile): def _profileused(self, profile):
#Check if profile is used before deleting it #Return all the nodes that uses this profile.
nodes = [] nodes = []
layer1 = [k for k,v in self.connections.items() if isinstance(v, dict) and v["type"] == "connection" and ("@" + profile in v.values() or ( isinstance(v["password"],list) and "@" + profile in v["password"]))] layer1 = [k for k,v in self.connections.items() if isinstance(v, dict) and v.get("type") == "connection" and ("@" + profile in v.values() or ( isinstance(v.get("password"),list) and "@" + profile in v.get("password")))]
folders = [k for k,v in self.connections.items() if isinstance(v, dict) and v["type"] == "folder"] folders = [k for k,v in self.connections.items() if isinstance(v, dict) and v.get("type") == "folder"]
nodes.extend(layer1) nodes.extend(layer1)
for f in folders: for f in folders:
layer2 = [k + "@" + f for k,v in self.connections[f].items() if isinstance(v, dict) and v["type"] == "connection" and ("@" + profile in v.values() or ( isinstance(v["password"],list) and "@" + profile in v["password"]))] layer2 = [k + "@" + f for k,v in self.connections[f].items() if isinstance(v, dict) and v.get("type") == "connection" and ("@" + profile in v.values() or ( isinstance(v.get("password"),list) and "@" + profile in v.get("password")))]
nodes.extend(layer2) nodes.extend(layer2)
subfolders = [k for k,v in self.connections[f].items() if isinstance(v, dict) and v["type"] == "subfolder"] subfolders = [k for k,v in self.connections[f].items() if isinstance(v, dict) and v.get("type") == "subfolder"]
for s in subfolders: for s in subfolders:
layer3 = [k + "@" + s + "@" + f for k,v in self.connections[f][s].items() if isinstance(v, dict) and v["type"] == "connection" and ("@" + profile in v.values() or ( isinstance(v["password"],list) and "@" + profile in v["password"]))] layer3 = [k + "@" + s + "@" + f for k,v in self.connections[f][s].items() if isinstance(v, dict) and v.get("type") == "connection" and ("@" + profile in v.values() or ( isinstance(v.get("password"),list) and "@" + profile in v.get("password")))]
nodes.extend(layer3) nodes.extend(layer3)
return nodes return nodes
+58 -6
View File
@@ -166,6 +166,7 @@ class connapp:
configcrud.add_argument("--fzf", dest="fzf", nargs=1, action=self._store_type, help="Use fzf for lists", choices=["true","false"]) configcrud.add_argument("--fzf", dest="fzf", nargs=1, action=self._store_type, help="Use fzf for lists", choices=["true","false"])
configcrud.add_argument("--keepalive", dest="idletime", nargs=1, action=self._store_type, help="Set keepalive time in seconds, 0 to disable", type=int, metavar="INT") configcrud.add_argument("--keepalive", dest="idletime", nargs=1, action=self._store_type, help="Set keepalive time in seconds, 0 to disable", type=int, metavar="INT")
configcrud.add_argument("--completion", dest="completion", nargs=1, choices=["bash","zsh"], action=self._store_type, help="Get terminal completion configuration for conn") configcrud.add_argument("--completion", dest="completion", nargs=1, choices=["bash","zsh"], action=self._store_type, help="Get terminal completion configuration for conn")
configcrud.add_argument("--fzf-wrapper", dest="fzf_wrapper", nargs=1, choices=["bash","zsh"], action=self._store_type, help="Get 0ms latency fzf bash/zsh wrapper")
configcrud.add_argument("--configfolder", dest="configfolder", nargs=1, action=self._store_type, help="Set the default location for config file", metavar="FOLDER") configcrud.add_argument("--configfolder", dest="configfolder", nargs=1, action=self._store_type, help="Set the default location for config file", metavar="FOLDER")
configcrud.add_argument("--engineer-model", dest="engineer_model", nargs=1, action=self._store_type, help="Set engineer model", metavar="MODEL") configcrud.add_argument("--engineer-model", dest="engineer_model", nargs=1, action=self._store_type, help="Set engineer model", metavar="MODEL")
configcrud.add_argument("--engineer-api-key", dest="engineer_api_key", nargs=1, action=self._store_type, help="Set engineer api_key", metavar="API_KEY") configcrud.add_argument("--engineer-api-key", dest="engineer_api_key", nargs=1, action=self._store_type, help="Set engineer api_key", metavar="API_KEY")
@@ -186,6 +187,10 @@ class connapp:
printer.warning(e) printer.warning(e)
for preload in self.plugins.preloads.values(): for preload in self.plugins.preloads.values():
preload.Preload(self) preload.Preload(self)
if not os.path.exists(self.config.fzf_cachefile):
self.config._generate_nodes_cache()
#Generate helps #Generate helps
nodeparser.usage = self._help("usage", subparsers) nodeparser.usage = self._help("usage", subparsers)
nodeparser.epilog = self._help("end", subparsers) nodeparser.epilog = self._help("end", subparsers)
@@ -482,7 +487,7 @@ class connapp:
def _func_others(self, args): def _func_others(self, args):
#Function called when using other commands #Function called when using other commands
actions = {"ls": self._ls, "move": self._mvcp, "cp": self._mvcp, "bulk": self._bulk, "completion": self._completion, "case": self._case, "fzf": self._fzf, "idletime": self._idletime, "configfolder": self._configfolder, "engineer_model": self._ai_config, "engineer_api_key": self._ai_config, "architect_model": self._ai_config, "architect_api_key": self._ai_config} actions = {"ls": self._ls, "move": self._mvcp, "cp": self._mvcp, "bulk": self._bulk, "completion": self._completion, "fzf_wrapper": self._fzf_wrapper, "case": self._case, "fzf": self._fzf, "idletime": self._idletime, "configfolder": self._configfolder, "engineer_model": self._ai_config, "engineer_api_key": self._ai_config, "architect_model": self._ai_config, "architect_api_key": self._ai_config}
return actions.get(args.command)(args) return actions.get(args.command)(args)
def _ai_config(self, args): def _ai_config(self, args):
@@ -622,6 +627,12 @@ class connapp:
elif args.data[0] == "zsh": elif args.data[0] == "zsh":
print(self._help("zshcompletion")) print(self._help("zshcompletion"))
def _fzf_wrapper(self, args):
if args.data[0] == "bash":
print(self._help("fzf_wrapper_bash"))
elif args.data[0] == "zsh":
print(self._help("fzf_wrapper_zsh"))
def _case(self, args): def _case(self, args):
if args.data[0] == "true": if args.data[0] == "true":
args.data[0] = True args.data[0] = True
@@ -1520,10 +1531,10 @@ _conn()
mapfile -t strings < <(connpy-completion-helper "bash" "${#COMP_WORDS[@]}" "${COMP_WORDS[@]}") mapfile -t strings < <(connpy-completion-helper "bash" "${#COMP_WORDS[@]}" "${COMP_WORDS[@]}")
local IFS=$'\t\n' local IFS=$'\t\n'
local home_dir=$(eval echo ~) local home_dir=$(eval echo ~)
local last_word=${COMP_WORDS[-1]/\~/$home_dir} local last_word=${COMP_WORDS[-1]/\\~/$home_dir}
COMPREPLY=($(compgen -W "$(printf '%s' "${strings[@]}")" -- "$last_word")) COMPREPLY=($(compgen -W "$(printf '%s' "${strings[@]}")" -- "$last_word"))
if [ "$last_word" != "${COMP_WORDS[-1]}" ]; then if [ "$last_word" != "${COMP_WORDS[-1]}" ]; then
COMPREPLY=(${COMPREPLY[@]/$home_dir/\~}) COMPREPLY=(${COMPREPLY[@]/$home_dir/\\~})
fi fi
} }
@@ -1538,12 +1549,12 @@ autoload -U compinit && compinit
_conn() _conn()
{ {
local home_dir=$(eval echo ~) local home_dir=$(eval echo ~)
last_word=${words[-1]/\~/$home_dir} last_word=${words[-1]/\\~/$home_dir}
strings=($(connpy-completion-helper "zsh" ${#words} $words[1,-2] $last_word)) strings=($(connpy-completion-helper "zsh" ${#words} $words[1,-2] $last_word))
for string in "${strings[@]}"; do for string in "${strings[@]}"; do
#Replace the expanded home directory with ~ #Replace the expanded home directory with ~
if [ "$last_word" != "$words[-1]" ]; then if [ "$last_word" != "$words[-1]" ]; then
string=${string/$home_dir/\~} string=${string/$home_dir/\\~}
fi fi
if [[ "${string}" =~ .*/$ ]]; then if [[ "${string}" =~ .*/$ ]]; then
# If the string ends with a '/', do not append a space # If the string ends with a '/', do not append a space
@@ -1558,10 +1569,51 @@ compdef _conn conn
compdef _conn connpy compdef _conn connpy
#Here ends zsh completion for conn #Here ends zsh completion for conn
''' '''
if type == "fzf_wrapper_bash":
return '''\n#Here starts bash 0ms fzf wrapper for connpy
connpy() {
if [ $# -eq 0 ]; then
local selected
if [ -f ~/.config/conn/.fzf_nodes_cache.txt ]; then
selected=$(cat ~/.config/conn/.fzf_nodes_cache.txt | fzf-tmux -d 25% --reverse)
else
command connpy
return
fi
if [ -n "$selected" ]; then
command connpy "$selected"
fi
else
command connpy "$@"
fi
}
alias c="connpy"
#Here ends bash 0ms fzf wrapper\n'''
if type == "fzf_wrapper_zsh":
return '''\n#Here starts zsh 0ms fzf wrapper for connpy
connpy() {
if [ $# -eq 0 ]; then
local selected
if [ -f ~/.config/conn/.fzf_nodes_cache.txt ]; then
selected=$(cat ~/.config/conn/.fzf_nodes_cache.txt | fzf-tmux -d 25% --reverse)
else
command connpy
return
fi
if [ -n "$selected" ]; then
command connpy "$selected"
fi
else
command connpy "$@"
fi
}
alias c="connpy"
#Here ends zsh 0ms fzf wrapper\n'''
if type == "run": if type == "run":
return "node[@subfolder][@folder] commmand to run\nRun the specific command on the node and print output\n/path/to/file.yaml\nUse a yaml file to run an automation script" return "node[@subfolder][@folder] commmand to run\nRun the specific command on the node and print output\n/path/to/file.yaml\nUse a yaml file to run an automation script"
if type == "generate": if type == "generate":
return '''--- return r'''---
tasks: tasks:
- name: "Config" - name: "Config"
+16 -1
View File
@@ -213,7 +213,7 @@ class sync:
def compress_specific_files(self, zip_path): def compress_specific_files(self, zip_path):
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf: with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
zipf.write(self.file, "config.json") zipf.write(self.file, os.path.basename(self.file))
zipf.write(self.key, ".osk") zipf.write(self.key, ".osk")
def compress_and_upload(self): def compress_and_upload(self):
@@ -251,8 +251,23 @@ class sync:
try: try:
with zipfile.ZipFile(zip_path, 'r') as zipf: with zipfile.ZipFile(zip_path, 'r') as zipf:
# Extract the specific file to the specified destination # Extract the specific file to the specified destination
names = zipf.namelist()
if "config.yaml" in names:
zipf.extract("config.yaml", os.path.dirname(self.file))
elif "config.json" in names:
zipf.extract("config.json", os.path.dirname(self.file)) zipf.extract("config.json", os.path.dirname(self.file))
if ".osk" in names:
zipf.extract(".osk", os.path.dirname(self.key)) zipf.extract(".osk", os.path.dirname(self.key))
# Delete caches to force auto-regeneration on next run
try:
if os.path.exists(self.connapp.config.cachefile):
os.remove(self.connapp.config.cachefile)
if os.path.exists(self.connapp.config.fzf_cachefile):
os.remove(self.connapp.config.fzf_cachefile)
except Exception:
pass
return 0 return 0
except Exception as e: except Exception as e:
printer.error(f"An error occurred: {e}") printer.error(f"An error occurred: {e}")
+51
View File
@@ -0,0 +1,51 @@
"""Tests for connpy.core_plugins.capture"""
import pytest
from unittest.mock import MagicMock, patch
from connpy.core_plugins.capture import RemoteCapture
@pytest.fixture
def mock_connapp():
app = MagicMock()
app.nodes_list = ["test_node"]
app.config.getitem.return_value = {"host": "127.0.0.1", "protocol": "ssh"}
mock_node = MagicMock()
mock_node.protocol = "ssh"
mock_node.unique = "test_node"
app.node.return_value = mock_node
app.config.config = {"wireshark_path": "/fake/ws"}
return app
class TestRemoteCapture:
def test_init_node_not_found(self, mock_connapp):
# Attempt to capture a node not in nodes_list
mock_connapp.nodes_list = ["other_node"]
with pytest.raises(SystemExit) as exc:
RemoteCapture(mock_connapp, "test_node", "eth0")
assert exc.value.code == 2
def test_init_success(self, mock_connapp):
rc = RemoteCapture(mock_connapp, "test_node", "eth0")
assert rc.node_name == "test_node"
assert rc.interface == "eth0"
assert rc.wireshark_path == "/fake/ws"
@patch("connpy.core_plugins.capture.socket")
def test_is_port_in_use(self, mock_socket, mock_connapp):
rc = RemoteCapture(mock_connapp, "test_node", "eth0")
mock_sock_instance = MagicMock()
mock_socket.socket.return_value.__enter__.return_value = mock_sock_instance
mock_sock_instance.connect_ex.return_value = 0
assert rc._is_port_in_use(8080) is True
mock_sock_instance.connect_ex.return_value = 1
assert rc._is_port_in_use(8080) is False
@patch.object(RemoteCapture, "_is_port_in_use")
def test_find_free_port(self, mock_is_in_use, mock_connapp):
rc = RemoteCapture(mock_connapp, "test_node", "eth0")
# First 2 ports in use, 3rd is free
mock_is_in_use.side_effect = [True, True, False]
port = rc._find_free_port(20000, 30000)
assert 20000 <= port <= 30000
assert mock_is_in_use.call_count == 3
+12 -11
View File
@@ -3,14 +3,15 @@ import json
import os import os
import re import re
import pytest import pytest
import yaml
from copy import deepcopy from copy import deepcopy
class TestConfigfileInit: class TestConfigfileInit:
def test_creates_default_config(self, tmp_config_dir): def test_creates_default_config(self, tmp_config_dir):
"""Creates config.json with defaults when it doesn't exist.""" """Creates config.yaml with defaults when it doesn't exist."""
config_file = tmp_config_dir / "config.json" config_file = tmp_config_dir / "config.yaml"
config_file.unlink() # Remove existing config_file.unlink(missing_ok=True) # Remove existing
key_file = tmp_config_dir / ".osk" key_file = tmp_config_dir / ".osk"
from connpy.configfile import configfile from connpy.configfile import configfile
@@ -27,7 +28,7 @@ class TestConfigfileInit:
key_file.unlink() # Remove existing key_file.unlink() # Remove existing
from connpy.configfile import configfile from connpy.configfile import configfile
conf = configfile(conf=str(tmp_config_dir / "config.json"), key=str(key_file)) conf = configfile(conf=str(tmp_config_dir / "config.yaml"), key=str(key_file))
assert key_file.exists() assert key_file.exists()
assert conf.privatekey is not None assert conf.privatekey is not None
@@ -41,8 +42,8 @@ class TestConfigfileInit:
def test_config_file_permissions(self, tmp_config_dir): def test_config_file_permissions(self, tmp_config_dir):
"""Config is created with 0o600 permissions.""" """Config is created with 0o600 permissions."""
config_file = tmp_config_dir / "config.json" config_file = tmp_config_dir / "config.yaml"
config_file.unlink() config_file.unlink(missing_ok=True)
from connpy.configfile import configfile from connpy.configfile import configfile
configfile(conf=str(config_file), key=str(tmp_config_dir / ".osk")) configfile(conf=str(config_file), key=str(tmp_config_dir / ".osk"))
@@ -62,7 +63,7 @@ class TestConfigfileInit:
(dot_folder / ".folder").write_text(str(config_dir)) (dot_folder / ".folder").write_text(str(config_dir))
(dot_folder / "plugins").mkdir(exist_ok=True) (dot_folder / "plugins").mkdir(exist_ok=True)
conf_path = str(config_dir / "my_config.json") conf_path = str(config_dir / "my_config.yaml")
key_path = str(config_dir / "my_key") key_path = str(config_dir / "my_key")
from connpy.configfile import configfile from connpy.configfile import configfile
@@ -248,7 +249,7 @@ class TestGetItem:
def test_getitem_with_profile_extraction(self, tmp_config_dir): def test_getitem_with_profile_extraction(self, tmp_config_dir):
"""extract=True resolves @profile references.""" """extract=True resolves @profile references."""
config_file = tmp_config_dir / "config.json" config_file = tmp_config_dir / "config.yaml"
data = { data = {
"config": {"case": False, "idletime": 30, "fzf": False}, "config": {"case": False, "idletime": 30, "fzf": False},
"connections": { "connections": {
@@ -268,7 +269,7 @@ class TestGetItem:
"options": "", "logs": "", "tags": "", "jumphost": ""} "options": "", "logs": "", "tags": "", "jumphost": ""}
} }
} }
config_file.write_text(json.dumps(data, indent=4)) config_file.write_text(yaml.dump(data, default_flow_style=False, sort_keys=False))
from connpy.configfile import configfile from connpy.configfile import configfile
conf = configfile(conf=str(config_file), key=str(tmp_config_dir / ".osk")) conf = configfile(conf=str(config_file), key=str(tmp_config_dir / ".osk"))
@@ -326,7 +327,7 @@ class TestGetAll:
def test_profileused(self, tmp_config_dir): def test_profileused(self, tmp_config_dir):
"""Detects nodes using a specific profile.""" """Detects nodes using a specific profile."""
config_file = tmp_config_dir / "config.json" config_file = tmp_config_dir / "config.yaml"
data = { data = {
"config": {"case": False, "idletime": 30, "fzf": False}, "config": {"case": False, "idletime": 30, "fzf": False},
"connections": { "connections": {
@@ -352,7 +353,7 @@ class TestGetAll:
"options": "", "logs": "", "tags": "", "jumphost": ""} "options": "", "logs": "", "tags": "", "jumphost": ""}
} }
} }
config_file.write_text(json.dumps(data, indent=4)) config_file.write_text(yaml.dump(data, default_flow_style=False, sort_keys=False))
from connpy.configfile import configfile from connpy.configfile import configfile
conf = configfile(conf=str(config_file), key=str(tmp_config_dir / ".osk")) conf = configfile(conf=str(config_file), key=str(tmp_config_dir / ".osk"))
+109
View File
@@ -0,0 +1,109 @@
"""Tests for connpy.core_plugins.context"""
import pytest
from unittest.mock import MagicMock, patch
from connpy.core_plugins.context import context_manager, Preload, Entrypoint
@pytest.fixture
def mock_connapp():
connapp = MagicMock()
connapp.config.config = {
"contexts": {"all": [".*"]},
"current_context": "all"
}
return connapp
class TestContextManager:
def test_init(self, mock_connapp):
cm = context_manager(mock_connapp)
assert cm.contexts == {"all": [".*"]}
assert cm.current_context == "all"
assert len(cm.regex) == 1
def test_add_context_success(self, mock_connapp):
cm = context_manager(mock_connapp)
cm.add_context("prod", ["^prod_.*"])
assert "prod" in cm.contexts
mock_connapp._change_settings.assert_called_with("contexts", cm.contexts)
def test_add_context_invalid_name(self, mock_connapp):
cm = context_manager(mock_connapp)
with pytest.raises(SystemExit) as exc:
cm.add_context("prod-env", ["Regex"])
assert exc.value.code == 1
def test_add_context_already_exists(self, mock_connapp):
cm = context_manager(mock_connapp)
with pytest.raises(SystemExit) as exc:
cm.add_context("all", ["Regex"])
assert exc.value.code == 2
def test_modify_context_success(self, mock_connapp):
cm = context_manager(mock_connapp)
cm.add_context("prod", ["old"])
cm.modify_context("prod", ["new"])
assert cm.contexts["prod"] == ["new"]
def test_modify_context_all(self, mock_connapp):
cm = context_manager(mock_connapp)
with pytest.raises(SystemExit) as exc:
cm.modify_context("all", ["new"])
assert exc.value.code == 3
def test_modify_context_not_exists(self, mock_connapp):
cm = context_manager(mock_connapp)
with pytest.raises(SystemExit) as exc:
cm.modify_context("fake", ["new"])
assert exc.value.code == 4
def test_delete_context_success(self, mock_connapp):
cm = context_manager(mock_connapp)
cm.add_context("prod", ["old"])
cm.delete_context("prod")
assert "prod" not in cm.contexts
def test_delete_context_all(self, mock_connapp):
cm = context_manager(mock_connapp)
with pytest.raises(SystemExit) as exc:
cm.delete_context("all")
assert exc.value.code == 3
def test_delete_context_current(self, mock_connapp):
mock_connapp.config.config["current_context"] = "prod"
mock_connapp.config.config["contexts"]["prod"] = [".*"]
cm = context_manager(mock_connapp)
with pytest.raises(SystemExit) as exc:
cm.delete_context("prod")
assert exc.value.code == 5
def test_set_context_success(self, mock_connapp):
cm = context_manager(mock_connapp)
cm.contexts["prod"] = [".*"]
cm.set_context("prod")
mock_connapp._change_settings.assert_called_with("current_context", "prod")
def test_set_context_already_set(self, mock_connapp):
cm = context_manager(mock_connapp)
with pytest.raises(SystemExit) as exc:
cm.set_context("all")
assert exc.value.code == 0
def test_match_regexp(self, mock_connapp):
mock_connapp.config.config["contexts"]["all"] = ["^prod", "^test"]
cm = context_manager(mock_connapp)
assert cm.match_any_regex("prod_node", cm.regex) is True
assert cm.match_any_regex("test_node", cm.regex) is True
assert cm.match_any_regex("dev_node", cm.regex) is False
def test_modify_node_list(self, mock_connapp):
mock_connapp.config.config["contexts"]["all"] = ["^prod"]
cm = context_manager(mock_connapp)
nodes = ["prod_1", "dev_1", "prod_2"]
result = cm.modify_node_list(result=nodes)
assert result == ["prod_1", "prod_2"]
def test_modify_node_dict(self, mock_connapp):
mock_connapp.config.config["contexts"]["all"] = ["^prod"]
cm = context_manager(mock_connapp)
nodes = {"prod_1": {}, "dev_1": {}, "prod_2": {}}
result = cm.modify_node_dict(result=nodes)
assert set(result.keys()) == {"prod_1", "prod_2"}
+108
View File
@@ -0,0 +1,108 @@
"""Tests for connpy.core_plugins.sync"""
import pytest
from unittest.mock import MagicMock, patch, mock_open
from connpy.core_plugins.sync import sync
@pytest.fixture
def mock_connapp():
app = MagicMock()
app.config.defaultdir = "/fake/dir"
app.config.file = "/fake/dir/config.yaml"
app.config.key = "/fake/dir/.osk"
app.config.config = {"sync": True}
return app
class TestSyncPlugin:
def test_init(self, mock_connapp):
s = sync(mock_connapp)
assert s.sync is True
assert s.file == "/fake/dir/config.yaml"
assert s.token_file == "/fake/dir/gtoken.json"
@patch("connpy.core_plugins.sync.os.path.exists")
@patch("connpy.core_plugins.sync.Credentials")
def test_get_credentials_success(self, MockCreds, mock_exists, mock_connapp):
mock_exists.return_value = True
mock_cred_instance = MagicMock()
mock_cred_instance.valid = True
MockCreds.from_authorized_user_file.return_value = mock_cred_instance
s = sync(mock_connapp)
creds = s.get_credentials()
assert creds == mock_cred_instance
@patch("connpy.core_plugins.sync.os.path.exists")
def test_get_credentials_not_found(self, mock_exists, mock_connapp):
mock_exists.return_value = False
s = sync(mock_connapp)
assert s.get_credentials() == 0
@patch("connpy.core_plugins.sync.zipfile.ZipFile")
@patch("connpy.core_plugins.sync.os.path.basename")
def test_compress_specific_files(self, mock_basename, MockZipFile, mock_connapp):
mock_basename.return_value = "config.yaml"
s = sync(mock_connapp)
zip_mock = MagicMock()
MockZipFile.return_value.__enter__.return_value = zip_mock
s.compress_specific_files("/fake/zip.zip")
zip_mock.write.assert_any_call(s.file, "config.yaml")
zip_mock.write.assert_any_call(s.key, ".osk")
@patch("connpy.core_plugins.sync.zipfile.ZipFile")
@patch("connpy.core_plugins.sync.os.path.dirname")
def test_decompress_zip_yaml(self, mock_dirname, MockZipFile, mock_connapp):
mock_dirname.return_value = "/fake/dir"
s = sync(mock_connapp)
zip_mock = MagicMock()
zip_mock.namelist.return_value = ["config.yaml", ".osk"]
MockZipFile.return_value.__enter__.return_value = zip_mock
assert s.decompress_zip("/fake/zip.zip") == 0
zip_mock.extract.assert_any_call("config.yaml", "/fake/dir")
zip_mock.extract.assert_any_call(".osk", "/fake/dir")
@patch("connpy.core_plugins.sync.zipfile.ZipFile")
@patch("connpy.core_plugins.sync.os.path.dirname")
def test_decompress_zip_json_fallback(self, mock_dirname, MockZipFile, mock_connapp):
mock_dirname.return_value = "/fake/dir"
s = sync(mock_connapp)
zip_mock = MagicMock()
zip_mock.namelist.return_value = ["config.json", ".osk"]
MockZipFile.return_value.__enter__.return_value = zip_mock
assert s.decompress_zip("/fake/old_zip.zip") == 0
zip_mock.extract.assert_any_call("config.json", "/fake/dir")
@patch.object(sync, "get_credentials")
@patch("connpy.core_plugins.sync.build")
def test_get_appdata_files(self, mock_build, mock_get_credentials, mock_connapp):
mock_get_credentials.return_value = MagicMock()
mock_service = MagicMock()
mock_build.return_value = mock_service
mock_service.files().list().execute.return_value = {
"files": [
{"id": "1", "name": "backup1.zip", "appProperties": {"timestamp": "1000", "date": "2024"}}
]
}
s = sync(mock_connapp)
files = s.get_appdata_files()
assert len(files) == 1
assert files[0]["id"] == "1"
assert files[0]["timestamp"] == "1000"
@patch.object(sync, "get_credentials")
@patch("connpy.core_plugins.sync.build")
@patch("connpy.core_plugins.sync.MediaFileUpload")
@patch("connpy.core_plugins.sync.os.path.basename")
def test_backup_file_to_drive(self, mock_basename, mock_media, mock_build, mock_get_credentials, mock_connapp):
mock_get_credentials.return_value = MagicMock()
mock_basename.return_value = "backup.zip"
mock_service = MagicMock()
mock_build.return_value = mock_service
s = sync(mock_connapp)
assert s.backup_file_to_drive("/fake/backup.zip", 1234567890000) == 0
mock_service.files().create.assert_called_once()
+80 -31
View File
@@ -2259,16 +2259,40 @@ class configfile:
with open(pathfile, &#34;w&#34;) as f: with open(pathfile, &#34;w&#34;) as f:
f.write(str(defaultdir)) f.write(str(defaultdir))
configdir = defaultdir configdir = defaultdir
defaultfile = configdir + &#39;/config.json&#39; defaultfile = configdir + &#39;/config.yaml&#39;
self.cachefile = configdir + &#39;/.config.cache.json&#39;
self.fzf_cachefile = configdir + &#39;/.fzf_nodes_cache.txt&#39;
defaultkey = configdir + &#39;/.osk&#39; defaultkey = configdir + &#39;/.osk&#39;
if conf == None: if conf == None:
self.file = defaultfile self.file = defaultfile
# Backwards compatibility: Migrate from JSON to YAML
legacy_json = configdir + &#39;/config.json&#39;
legacy_noext = configdir + &#39;/config&#39;
legacy_file = None
if os.path.exists(legacy_json): legacy_file = legacy_json
elif os.path.exists(legacy_noext): legacy_file = legacy_noext
if not os.path.exists(self.file) and legacy_file:
try:
with open(legacy_file, &#39;r&#39;) as f:
old_data = json.load(f)
with open(self.file, &#39;w&#39;) as f:
yaml.dump(old_data, f, default_flow_style=False, sort_keys=False)
with open(self.cachefile, &#39;w&#39;) as f:
json.dump(old_data, f)
shutil.move(legacy_file, legacy_file + &#34;.backup&#34;)
printer.success(f&#34;Migrated legacy config ({len(old_data.get(&#39;connections&#39;,{}))} folders/nodes) into YAML and Cache successfully!&#34;)
except Exception as e:
printer.warning(f&#34;Failed to migrate legacy config: {e}&#34;)
else: else:
self.file = conf self.file = conf
if key == None: if key == None:
self.key = defaultkey self.key = defaultkey
else: else:
self.key = key self.key = key
if os.path.exists(self.file): if os.path.exists(self.file):
config = self._loadconfig(self.file) config = self._loadconfig(self.file)
else: else:
@@ -2285,23 +2309,38 @@ class configfile:
def _loadconfig(self, conf): def _loadconfig(self, conf):
#Loads config file #Loads config file using dual cache
jsonconf = open(conf) cache_exists = os.path.exists(self.cachefile)
jsondata = json.load(jsonconf) yaml_time = os.path.getmtime(conf) if os.path.exists(conf) else 0
jsonconf.close() cache_time = os.path.getmtime(self.cachefile) if cache_exists else 0
return jsondata
if not cache_exists or yaml_time &gt; cache_time:
with open(conf, &#39;r&#39;) as f:
data = yaml.safe_load(f)
try:
with open(self.cachefile, &#39;w&#39;) as f:
json.dump(data, f)
except Exception:
pass
return data
else:
with open(self.cachefile, &#39;r&#39;) as f:
return json.load(f)
def _createconfig(self, conf): def _createconfig(self, conf):
#Create config file #Create config file
defaultconfig = {&#39;config&#39;: {&#39;case&#39;: False, &#39;idletime&#39;: 30, &#39;fzf&#39;: False}, &#39;connections&#39;: {}, &#39;profiles&#39;: { &#34;default&#34;: { &#34;host&#34;:&#34;&#34;, &#34;protocol&#34;:&#34;ssh&#34;, &#34;port&#34;:&#34;&#34;, &#34;user&#34;:&#34;&#34;, &#34;password&#34;:&#34;&#34;, &#34;options&#34;:&#34;&#34;, &#34;logs&#34;:&#34;&#34;, &#34;tags&#34;: &#34;&#34;, &#34;jumphost&#34;:&#34;&#34;}}} defaultconfig = {&#39;config&#39;: {&#39;case&#39;: False, &#39;idletime&#39;: 30, &#39;fzf&#39;: False}, &#39;connections&#39;: {}, &#39;profiles&#39;: { &#34;default&#34;: { &#34;host&#34;:&#34;&#34;, &#34;protocol&#34;:&#34;ssh&#34;, &#34;port&#34;:&#34;&#34;, &#34;user&#34;:&#34;&#34;, &#34;password&#34;:&#34;&#34;, &#34;options&#34;:&#34;&#34;, &#34;logs&#34;:&#34;&#34;, &#34;tags&#34;: &#34;&#34;, &#34;jumphost&#34;:&#34;&#34;}}}
if not os.path.exists(conf): if not os.path.exists(conf):
with open(conf, &#34;w&#34;) as f: with open(conf, &#34;w&#34;) as f:
json.dump(defaultconfig, f, indent = 4) yaml.dump(defaultconfig, f, default_flow_style=False, sort_keys=False)
f.close()
os.chmod(conf, 0o600) os.chmod(conf, 0o600)
jsonconf = open(conf) try:
jsondata = json.load(jsonconf) with open(self.cachefile, &#39;w&#39;) as f:
jsonconf.close() json.dump(defaultconfig, f)
except Exception:
pass
with open(conf, &#39;r&#39;) as f:
jsondata = yaml.safe_load(f)
return jsondata return jsondata
@MethodHook @MethodHook
@@ -2313,13 +2352,23 @@ class configfile:
newconfig[&#34;profiles&#34;] = self.profiles newconfig[&#34;profiles&#34;] = self.profiles
try: try:
with open(conf, &#34;w&#34;) as f: with open(conf, &#34;w&#34;) as f:
json.dump(newconfig, f, indent = 4) yaml.dump(newconfig, f, default_flow_style=False, sort_keys=False)
f.close() with open(self.cachefile, &#34;w&#34;) as f:
json.dump(newconfig, f)
self._generate_nodes_cache()
except (IOError, OSError) as e: except (IOError, OSError) as e:
printer.error(f&#34;Failed to save config: {e}&#34;) printer.error(f&#34;Failed to save config: {e}&#34;)
return 1 return 1
return 0 return 0
def _generate_nodes_cache(self):
try:
nodes = self._getallnodes()
with open(self.fzf_cachefile, &#34;w&#34;) as f:
f.write(&#34;\n&#34;.join(nodes))
except Exception:
pass
def _createkey(self, keyfile): def _createkey(self, keyfile):
#Create key file #Create key file
key = RSA.generate(2048) key = RSA.generate(2048)
@@ -2538,15 +2587,15 @@ class configfile:
def _getallnodes(self, filter = None): def _getallnodes(self, filter = None):
#get all nodes on configfile #get all nodes on configfile
nodes = [] nodes = []
layer1 = [k for k,v in self.connections.items() if isinstance(v, dict) and v[&#34;type&#34;] == &#34;connection&#34;] layer1 = [k for k,v in self.connections.items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;connection&#34;]
folders = [k for k,v in self.connections.items() if isinstance(v, dict) and v[&#34;type&#34;] == &#34;folder&#34;] folders = [k for k,v in self.connections.items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;folder&#34;]
nodes.extend(layer1) nodes.extend(layer1)
for f in folders: for f in folders:
layer2 = [k + &#34;@&#34; + f for k,v in self.connections[f].items() if isinstance(v, dict) and v[&#34;type&#34;] == &#34;connection&#34;] layer2 = [k + &#34;@&#34; + f for k,v in self.connections[f].items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;connection&#34;]
nodes.extend(layer2) nodes.extend(layer2)
subfolders = [k for k,v in self.connections[f].items() if isinstance(v, dict) and v[&#34;type&#34;] == &#34;subfolder&#34;] subfolders = [k for k,v in self.connections[f].items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;subfolder&#34;]
for s in subfolders: for s in subfolders:
layer3 = [k + &#34;@&#34; + s + &#34;@&#34; + f for k,v in self.connections[f][s].items() if isinstance(v, dict) and v[&#34;type&#34;] == &#34;connection&#34;] layer3 = [k + &#34;@&#34; + s + &#34;@&#34; + f for k,v in self.connections[f][s].items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;connection&#34;]
nodes.extend(layer3) nodes.extend(layer3)
if filter: if filter:
if isinstance(filter, str): if isinstance(filter, str):
@@ -2561,15 +2610,15 @@ class configfile:
def _getallnodesfull(self, filter = None, extract = True): def _getallnodesfull(self, filter = None, extract = True):
#get all nodes on configfile with all their attributes. #get all nodes on configfile with all their attributes.
nodes = {} nodes = {}
layer1 = {k:v for k,v in self.connections.items() if isinstance(v, dict) and v[&#34;type&#34;] == &#34;connection&#34;} layer1 = {k:v for k,v in self.connections.items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;connection&#34;}
folders = [k for k,v in self.connections.items() if isinstance(v, dict) and v[&#34;type&#34;] == &#34;folder&#34;] folders = [k for k,v in self.connections.items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;folder&#34;]
nodes.update(layer1) nodes.update(layer1)
for f in folders: for f in folders:
layer2 = {k + &#34;@&#34; + f:v for k,v in self.connections[f].items() if isinstance(v, dict) and v[&#34;type&#34;] == &#34;connection&#34;} layer2 = {k + &#34;@&#34; + f:v for k,v in self.connections[f].items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;connection&#34;}
nodes.update(layer2) nodes.update(layer2)
subfolders = [k for k,v in self.connections[f].items() if isinstance(v, dict) and v[&#34;type&#34;] == &#34;subfolder&#34;] subfolders = [k for k,v in self.connections[f].items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;subfolder&#34;]
for s in subfolders: for s in subfolders:
layer3 = {k + &#34;@&#34; + s + &#34;@&#34; + f:v for k,v in self.connections[f][s].items() if isinstance(v, dict) and v[&#34;type&#34;] == &#34;connection&#34;} layer3 = {k + &#34;@&#34; + s + &#34;@&#34; + f:v for k,v in self.connections[f][s].items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;connection&#34;}
nodes.update(layer3) nodes.update(layer3)
if filter: if filter:
if isinstance(filter, str): if isinstance(filter, str):
@@ -2600,27 +2649,27 @@ class configfile:
@MethodHook @MethodHook
def _getallfolders(self): def _getallfolders(self):
#get all folders on configfile #get all folders on configfile
folders = [&#34;@&#34; + k for k,v in self.connections.items() if isinstance(v, dict) and v[&#34;type&#34;] == &#34;folder&#34;] folders = [&#34;@&#34; + k for k,v in self.connections.items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;folder&#34;]
subfolders = [] subfolders = []
for f in folders: for f in folders:
s = [&#34;@&#34; + k + f for k,v in self.connections[f[1:]].items() if isinstance(v, dict) and v[&#34;type&#34;] == &#34;subfolder&#34;] s = [&#34;@&#34; + k + f for k,v in self.connections[f[1:]].items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;subfolder&#34;]
subfolders.extend(s) subfolders.extend(s)
folders.extend(subfolders) folders.extend(subfolders)
return folders return folders
@MethodHook @MethodHook
def _profileused(self, profile): def _profileused(self, profile):
#Check if profile is used before deleting it #Return all the nodes that uses this profile.
nodes = [] nodes = []
layer1 = [k for k,v in self.connections.items() if isinstance(v, dict) and v[&#34;type&#34;] == &#34;connection&#34; and (&#34;@&#34; + profile in v.values() or ( isinstance(v[&#34;password&#34;],list) and &#34;@&#34; + profile in v[&#34;password&#34;]))] layer1 = [k for k,v in self.connections.items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;connection&#34; and (&#34;@&#34; + profile in v.values() or ( isinstance(v.get(&#34;password&#34;),list) and &#34;@&#34; + profile in v.get(&#34;password&#34;)))]
folders = [k for k,v in self.connections.items() if isinstance(v, dict) and v[&#34;type&#34;] == &#34;folder&#34;] folders = [k for k,v in self.connections.items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;folder&#34;]
nodes.extend(layer1) nodes.extend(layer1)
for f in folders: for f in folders:
layer2 = [k + &#34;@&#34; + f for k,v in self.connections[f].items() if isinstance(v, dict) and v[&#34;type&#34;] == &#34;connection&#34; and (&#34;@&#34; + profile in v.values() or ( isinstance(v[&#34;password&#34;],list) and &#34;@&#34; + profile in v[&#34;password&#34;]))] layer2 = [k + &#34;@&#34; + f for k,v in self.connections[f].items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;connection&#34; and (&#34;@&#34; + profile in v.values() or ( isinstance(v.get(&#34;password&#34;),list) and &#34;@&#34; + profile in v.get(&#34;password&#34;)))]
nodes.extend(layer2) nodes.extend(layer2)
subfolders = [k for k,v in self.connections[f].items() if isinstance(v, dict) and v[&#34;type&#34;] == &#34;subfolder&#34;] subfolders = [k for k,v in self.connections[f].items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;subfolder&#34;]
for s in subfolders: for s in subfolders:
layer3 = [k + &#34;@&#34; + s + &#34;@&#34; + f for k,v in self.connections[f][s].items() if isinstance(v, dict) and v[&#34;type&#34;] == &#34;connection&#34; and (&#34;@&#34; + profile in v.values() or ( isinstance(v[&#34;password&#34;],list) and &#34;@&#34; + profile in v[&#34;password&#34;]))] layer3 = [k + &#34;@&#34; + s + &#34;@&#34; + f for k,v in self.connections[f][s].items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;connection&#34; and (&#34;@&#34; + profile in v.values() or ( isinstance(v.get(&#34;password&#34;),list) and &#34;@&#34; + profile in v.get(&#34;password&#34;)))]
nodes.extend(layer3) nodes.extend(layer3)
return nodes return nodes
+15
View File
@@ -52,6 +52,10 @@ el.replaceWith(d);
<dd> <dd>
<div class="desc"><p>Tests for connpy.api module — Flask routes.</p></div> <div class="desc"><p>Tests for connpy.api module — Flask routes.</p></div>
</dd> </dd>
<dt><code class="name"><a title="connpy.tests.test_capture" href="test_capture.html">connpy.tests.test_capture</a></code></dt>
<dd>
<div class="desc"><p>Tests for connpy.core_plugins.capture</p></div>
</dd>
<dt><code class="name"><a title="connpy.tests.test_completion" href="test_completion.html">connpy.tests.test_completion</a></code></dt> <dt><code class="name"><a title="connpy.tests.test_completion" href="test_completion.html">connpy.tests.test_completion</a></code></dt>
<dd> <dd>
<div class="desc"><p>Tests for connpy.completion module.</p></div> <div class="desc"><p>Tests for connpy.completion module.</p></div>
@@ -60,6 +64,10 @@ el.replaceWith(d);
<dd> <dd>
<div class="desc"><p>Tests for connpy.configfile module.</p></div> <div class="desc"><p>Tests for connpy.configfile module.</p></div>
</dd> </dd>
<dt><code class="name"><a title="connpy.tests.test_context" href="test_context.html">connpy.tests.test_context</a></code></dt>
<dd>
<div class="desc"><p>Tests for connpy.core_plugins.context</p></div>
</dd>
<dt><code class="name"><a title="connpy.tests.test_core" href="test_core.html">connpy.tests.test_core</a></code></dt> <dt><code class="name"><a title="connpy.tests.test_core" href="test_core.html">connpy.tests.test_core</a></code></dt>
<dd> <dd>
<div class="desc"><p>Tests for connpy.core module — node and nodes classes.</p></div> <div class="desc"><p>Tests for connpy.core module — node and nodes classes.</p></div>
@@ -76,6 +84,10 @@ el.replaceWith(d);
<dd> <dd>
<div class="desc"><p>Tests for connpy.printer module.</p></div> <div class="desc"><p>Tests for connpy.printer module.</p></div>
</dd> </dd>
<dt><code class="name"><a title="connpy.tests.test_sync" href="test_sync.html">connpy.tests.test_sync</a></code></dt>
<dd>
<div class="desc"><p>Tests for connpy.core_plugins.sync</p></div>
</dd>
</dl> </dl>
</section> </section>
<section> <section>
@@ -100,12 +112,15 @@ el.replaceWith(d);
<li><code><a title="connpy.tests.conftest" href="conftest.html">connpy.tests.conftest</a></code></li> <li><code><a title="connpy.tests.conftest" href="conftest.html">connpy.tests.conftest</a></code></li>
<li><code><a title="connpy.tests.test_ai" href="test_ai.html">connpy.tests.test_ai</a></code></li> <li><code><a title="connpy.tests.test_ai" href="test_ai.html">connpy.tests.test_ai</a></code></li>
<li><code><a title="connpy.tests.test_api" href="test_api.html">connpy.tests.test_api</a></code></li> <li><code><a title="connpy.tests.test_api" href="test_api.html">connpy.tests.test_api</a></code></li>
<li><code><a title="connpy.tests.test_capture" href="test_capture.html">connpy.tests.test_capture</a></code></li>
<li><code><a title="connpy.tests.test_completion" href="test_completion.html">connpy.tests.test_completion</a></code></li> <li><code><a title="connpy.tests.test_completion" href="test_completion.html">connpy.tests.test_completion</a></code></li>
<li><code><a title="connpy.tests.test_configfile" href="test_configfile.html">connpy.tests.test_configfile</a></code></li> <li><code><a title="connpy.tests.test_configfile" href="test_configfile.html">connpy.tests.test_configfile</a></code></li>
<li><code><a title="connpy.tests.test_context" href="test_context.html">connpy.tests.test_context</a></code></li>
<li><code><a title="connpy.tests.test_core" href="test_core.html">connpy.tests.test_core</a></code></li> <li><code><a title="connpy.tests.test_core" href="test_core.html">connpy.tests.test_core</a></code></li>
<li><code><a title="connpy.tests.test_hooks" href="test_hooks.html">connpy.tests.test_hooks</a></code></li> <li><code><a title="connpy.tests.test_hooks" href="test_hooks.html">connpy.tests.test_hooks</a></code></li>
<li><code><a title="connpy.tests.test_plugins" href="test_plugins.html">connpy.tests.test_plugins</a></code></li> <li><code><a title="connpy.tests.test_plugins" href="test_plugins.html">connpy.tests.test_plugins</a></code></li>
<li><code><a title="connpy.tests.test_printer" href="test_printer.html">connpy.tests.test_printer</a></code></li> <li><code><a title="connpy.tests.test_printer" href="test_printer.html">connpy.tests.test_printer</a></code></li>
<li><code><a title="connpy.tests.test_sync" href="test_sync.html">connpy.tests.test_sync</a></code></li>
</ul> </ul>
</li> </li>
</ul> </ul>
+235
View File
@@ -0,0 +1,235 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.6">
<title>connpy.tests.test_capture API documentation</title>
<meta name="description" content="Tests for connpy.core_plugins.capture">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source > summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible;min-width:max-content}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin:1em 0}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
/* Collapse source docstrings */
setTimeout(() => {
[...document.querySelectorAll('.hljs.language-python > .hljs-string')]
.filter(el => el.innerHTML.length > 200 && ['"""', "'''"].includes(el.innerHTML.substring(0, 3)))
.forEach(el => {
let d = document.createElement('details');
d.classList.add('hljs-string');
d.innerHTML = '<summary>"""</summary>' + el.innerHTML.substring(3);
el.replaceWith(d);
});
}, 100);
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>connpy.tests.test_capture</code></h1>
</header>
<section id="section-intro">
<p>Tests for connpy.core_plugins.capture</p>
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="connpy.tests.test_capture.mock_connapp"><code class="name flex">
<span>def <span class="ident">mock_connapp</span></span>(<span>)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@pytest.fixture
def mock_connapp():
app = MagicMock()
app.nodes_list = [&#34;test_node&#34;]
app.config.getitem.return_value = {&#34;host&#34;: &#34;127.0.0.1&#34;, &#34;protocol&#34;: &#34;ssh&#34;}
mock_node = MagicMock()
mock_node.protocol = &#34;ssh&#34;
mock_node.unique = &#34;test_node&#34;
app.node.return_value = mock_node
app.config.config = {&#34;wireshark_path&#34;: &#34;/fake/ws&#34;}
return app</code></pre>
</details>
<div class="desc"></div>
</dd>
</dl>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="connpy.tests.test_capture.TestRemoteCapture"><code class="flex name class">
<span>class <span class="ident">TestRemoteCapture</span></span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class TestRemoteCapture:
def test_init_node_not_found(self, mock_connapp):
# Attempt to capture a node not in nodes_list
mock_connapp.nodes_list = [&#34;other_node&#34;]
with pytest.raises(SystemExit) as exc:
RemoteCapture(mock_connapp, &#34;test_node&#34;, &#34;eth0&#34;)
assert exc.value.code == 2
def test_init_success(self, mock_connapp):
rc = RemoteCapture(mock_connapp, &#34;test_node&#34;, &#34;eth0&#34;)
assert rc.node_name == &#34;test_node&#34;
assert rc.interface == &#34;eth0&#34;
assert rc.wireshark_path == &#34;/fake/ws&#34;
@patch(&#34;connpy.core_plugins.capture.socket&#34;)
def test_is_port_in_use(self, mock_socket, mock_connapp):
rc = RemoteCapture(mock_connapp, &#34;test_node&#34;, &#34;eth0&#34;)
mock_sock_instance = MagicMock()
mock_socket.socket.return_value.__enter__.return_value = mock_sock_instance
mock_sock_instance.connect_ex.return_value = 0
assert rc._is_port_in_use(8080) is True
mock_sock_instance.connect_ex.return_value = 1
assert rc._is_port_in_use(8080) is False
@patch.object(RemoteCapture, &#34;_is_port_in_use&#34;)
def test_find_free_port(self, mock_is_in_use, mock_connapp):
rc = RemoteCapture(mock_connapp, &#34;test_node&#34;, &#34;eth0&#34;)
# First 2 ports in use, 3rd is free
mock_is_in_use.side_effect = [True, True, False]
port = rc._find_free_port(20000, 30000)
assert 20000 &lt;= port &lt;= 30000
assert mock_is_in_use.call_count == 3</code></pre>
</details>
<div class="desc"></div>
<h3>Methods</h3>
<dl>
<dt id="connpy.tests.test_capture.TestRemoteCapture.test_find_free_port"><code class="name flex">
<span>def <span class="ident">test_find_free_port</span></span>(<span>self, mock_is_in_use, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@patch.object(RemoteCapture, &#34;_is_port_in_use&#34;)
def test_find_free_port(self, mock_is_in_use, mock_connapp):
rc = RemoteCapture(mock_connapp, &#34;test_node&#34;, &#34;eth0&#34;)
# First 2 ports in use, 3rd is free
mock_is_in_use.side_effect = [True, True, False]
port = rc._find_free_port(20000, 30000)
assert 20000 &lt;= port &lt;= 30000
assert mock_is_in_use.call_count == 3</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_capture.TestRemoteCapture.test_init_node_not_found"><code class="name flex">
<span>def <span class="ident">test_init_node_not_found</span></span>(<span>self, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def test_init_node_not_found(self, mock_connapp):
# Attempt to capture a node not in nodes_list
mock_connapp.nodes_list = [&#34;other_node&#34;]
with pytest.raises(SystemExit) as exc:
RemoteCapture(mock_connapp, &#34;test_node&#34;, &#34;eth0&#34;)
assert exc.value.code == 2</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_capture.TestRemoteCapture.test_init_success"><code class="name flex">
<span>def <span class="ident">test_init_success</span></span>(<span>self, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def test_init_success(self, mock_connapp):
rc = RemoteCapture(mock_connapp, &#34;test_node&#34;, &#34;eth0&#34;)
assert rc.node_name == &#34;test_node&#34;
assert rc.interface == &#34;eth0&#34;
assert rc.wireshark_path == &#34;/fake/ws&#34;</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_capture.TestRemoteCapture.test_is_port_in_use"><code class="name flex">
<span>def <span class="ident">test_is_port_in_use</span></span>(<span>self, mock_socket, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@patch(&#34;connpy.core_plugins.capture.socket&#34;)
def test_is_port_in_use(self, mock_socket, mock_connapp):
rc = RemoteCapture(mock_connapp, &#34;test_node&#34;, &#34;eth0&#34;)
mock_sock_instance = MagicMock()
mock_socket.socket.return_value.__enter__.return_value = mock_sock_instance
mock_sock_instance.connect_ex.return_value = 0
assert rc._is_port_in_use(8080) is True
mock_sock_instance.connect_ex.return_value = 1
assert rc._is_port_in_use(8080) is False</code></pre>
</details>
<div class="desc"></div>
</dd>
</dl>
</dd>
</dl>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="connpy.tests" href="index.html">connpy.tests</a></code></li>
</ul>
</li>
<li><h3><a href="#header-functions">Functions</a></h3>
<ul class="">
<li><code><a title="connpy.tests.test_capture.mock_connapp" href="#connpy.tests.test_capture.mock_connapp">mock_connapp</a></code></li>
</ul>
</li>
<li><h3><a href="#header-classes">Classes</a></h3>
<ul>
<li>
<h4><code><a title="connpy.tests.test_capture.TestRemoteCapture" href="#connpy.tests.test_capture.TestRemoteCapture">TestRemoteCapture</a></code></h4>
<ul class="">
<li><code><a title="connpy.tests.test_capture.TestRemoteCapture.test_find_free_port" href="#connpy.tests.test_capture.TestRemoteCapture.test_find_free_port">test_find_free_port</a></code></li>
<li><code><a title="connpy.tests.test_capture.TestRemoteCapture.test_init_node_not_found" href="#connpy.tests.test_capture.TestRemoteCapture.test_init_node_not_found">test_init_node_not_found</a></code></li>
<li><code><a title="connpy.tests.test_capture.TestRemoteCapture.test_init_success" href="#connpy.tests.test_capture.TestRemoteCapture.test_init_success">test_init_success</a></code></li>
<li><code><a title="connpy.tests.test_capture.TestRemoteCapture.test_is_port_in_use" href="#connpy.tests.test_capture.TestRemoteCapture.test_is_port_in_use">test_is_port_in_use</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
</footer>
</body>
</html>
+23 -23
View File
@@ -383,9 +383,9 @@ el.replaceWith(d);
</summary> </summary>
<pre><code class="python">class TestConfigfileInit: <pre><code class="python">class TestConfigfileInit:
def test_creates_default_config(self, tmp_config_dir): def test_creates_default_config(self, tmp_config_dir):
&#34;&#34;&#34;Creates config.json with defaults when it doesn&#39;t exist.&#34;&#34;&#34; &#34;&#34;&#34;Creates config.yaml with defaults when it doesn&#39;t exist.&#34;&#34;&#34;
config_file = tmp_config_dir / &#34;config.json&#34; config_file = tmp_config_dir / &#34;config.yaml&#34;
config_file.unlink() # Remove existing config_file.unlink(missing_ok=True) # Remove existing
key_file = tmp_config_dir / &#34;.osk&#34; key_file = tmp_config_dir / &#34;.osk&#34;
from connpy.configfile import configfile from connpy.configfile import configfile
@@ -402,7 +402,7 @@ el.replaceWith(d);
key_file.unlink() # Remove existing key_file.unlink() # Remove existing
from connpy.configfile import configfile from connpy.configfile import configfile
conf = configfile(conf=str(tmp_config_dir / &#34;config.json&#34;), key=str(key_file)) conf = configfile(conf=str(tmp_config_dir / &#34;config.yaml&#34;), key=str(key_file))
assert key_file.exists() assert key_file.exists()
assert conf.privatekey is not None assert conf.privatekey is not None
@@ -416,8 +416,8 @@ el.replaceWith(d);
def test_config_file_permissions(self, tmp_config_dir): def test_config_file_permissions(self, tmp_config_dir):
&#34;&#34;&#34;Config is created with 0o600 permissions.&#34;&#34;&#34; &#34;&#34;&#34;Config is created with 0o600 permissions.&#34;&#34;&#34;
config_file = tmp_config_dir / &#34;config.json&#34; config_file = tmp_config_dir / &#34;config.yaml&#34;
config_file.unlink() config_file.unlink(missing_ok=True)
from connpy.configfile import configfile from connpy.configfile import configfile
configfile(conf=str(config_file), key=str(tmp_config_dir / &#34;.osk&#34;)) configfile(conf=str(config_file), key=str(tmp_config_dir / &#34;.osk&#34;))
@@ -437,7 +437,7 @@ el.replaceWith(d);
(dot_folder / &#34;.folder&#34;).write_text(str(config_dir)) (dot_folder / &#34;.folder&#34;).write_text(str(config_dir))
(dot_folder / &#34;plugins&#34;).mkdir(exist_ok=True) (dot_folder / &#34;plugins&#34;).mkdir(exist_ok=True)
conf_path = str(config_dir / &#34;my_config.json&#34;) conf_path = str(config_dir / &#34;my_config.yaml&#34;)
key_path = str(config_dir / &#34;my_key&#34;) key_path = str(config_dir / &#34;my_key&#34;)
from connpy.configfile import configfile from connpy.configfile import configfile
@@ -459,8 +459,8 @@ el.replaceWith(d);
</summary> </summary>
<pre><code class="python">def test_config_file_permissions(self, tmp_config_dir): <pre><code class="python">def test_config_file_permissions(self, tmp_config_dir):
&#34;&#34;&#34;Config is created with 0o600 permissions.&#34;&#34;&#34; &#34;&#34;&#34;Config is created with 0o600 permissions.&#34;&#34;&#34;
config_file = tmp_config_dir / &#34;config.json&#34; config_file = tmp_config_dir / &#34;config.yaml&#34;
config_file.unlink() config_file.unlink(missing_ok=True)
from connpy.configfile import configfile from connpy.configfile import configfile
configfile(conf=str(config_file), key=str(tmp_config_dir / &#34;.osk&#34;)) configfile(conf=str(config_file), key=str(tmp_config_dir / &#34;.osk&#34;))
@@ -479,9 +479,9 @@ el.replaceWith(d);
<span>Expand source code</span> <span>Expand source code</span>
</summary> </summary>
<pre><code class="python">def test_creates_default_config(self, tmp_config_dir): <pre><code class="python">def test_creates_default_config(self, tmp_config_dir):
&#34;&#34;&#34;Creates config.json with defaults when it doesn&#39;t exist.&#34;&#34;&#34; &#34;&#34;&#34;Creates config.yaml with defaults when it doesn&#39;t exist.&#34;&#34;&#34;
config_file = tmp_config_dir / &#34;config.json&#34; config_file = tmp_config_dir / &#34;config.yaml&#34;
config_file.unlink() # Remove existing config_file.unlink(missing_ok=True) # Remove existing
key_file = tmp_config_dir / &#34;.osk&#34; key_file = tmp_config_dir / &#34;.osk&#34;
from connpy.configfile import configfile from connpy.configfile import configfile
@@ -492,7 +492,7 @@ el.replaceWith(d);
assert conf.config[&#34;idletime&#34;] == 30 assert conf.config[&#34;idletime&#34;] == 30
assert &#34;default&#34; in conf.profiles</code></pre> assert &#34;default&#34; in conf.profiles</code></pre>
</details> </details>
<div class="desc"><p>Creates config.json with defaults when it doesn't exist.</p></div> <div class="desc"><p>Creates config.yaml with defaults when it doesn't exist.</p></div>
</dd> </dd>
<dt id="connpy.tests.test_configfile.TestConfigfileInit.test_creates_rsa_key"><code class="name flex"> <dt id="connpy.tests.test_configfile.TestConfigfileInit.test_creates_rsa_key"><code class="name flex">
<span>def <span class="ident">test_creates_rsa_key</span></span>(<span>self, tmp_config_dir)</span> <span>def <span class="ident">test_creates_rsa_key</span></span>(<span>self, tmp_config_dir)</span>
@@ -508,7 +508,7 @@ el.replaceWith(d);
key_file.unlink() # Remove existing key_file.unlink() # Remove existing
from connpy.configfile import configfile from connpy.configfile import configfile
conf = configfile(conf=str(tmp_config_dir / &#34;config.json&#34;), key=str(key_file)) conf = configfile(conf=str(tmp_config_dir / &#34;config.yaml&#34;), key=str(key_file))
assert key_file.exists() assert key_file.exists()
assert conf.privatekey is not None assert conf.privatekey is not None
@@ -536,7 +536,7 @@ el.replaceWith(d);
(dot_folder / &#34;.folder&#34;).write_text(str(config_dir)) (dot_folder / &#34;.folder&#34;).write_text(str(config_dir))
(dot_folder / &#34;plugins&#34;).mkdir(exist_ok=True) (dot_folder / &#34;plugins&#34;).mkdir(exist_ok=True)
conf_path = str(config_dir / &#34;my_config.json&#34;) conf_path = str(config_dir / &#34;my_config.yaml&#34;)
key_path = str(config_dir / &#34;my_key&#34;) key_path = str(config_dir / &#34;my_key&#34;)
from connpy.configfile import configfile from connpy.configfile import configfile
@@ -846,7 +846,7 @@ el.replaceWith(d);
def test_profileused(self, tmp_config_dir): def test_profileused(self, tmp_config_dir):
&#34;&#34;&#34;Detects nodes using a specific profile.&#34;&#34;&#34; &#34;&#34;&#34;Detects nodes using a specific profile.&#34;&#34;&#34;
config_file = tmp_config_dir / &#34;config.json&#34; config_file = tmp_config_dir / &#34;config.yaml&#34;
data = { data = {
&#34;config&#34;: {&#34;case&#34;: False, &#34;idletime&#34;: 30, &#34;fzf&#34;: False}, &#34;config&#34;: {&#34;case&#34;: False, &#34;idletime&#34;: 30, &#34;fzf&#34;: False},
&#34;connections&#34;: { &#34;connections&#34;: {
@@ -872,7 +872,7 @@ el.replaceWith(d);
&#34;options&#34;: &#34;&#34;, &#34;logs&#34;: &#34;&#34;, &#34;tags&#34;: &#34;&#34;, &#34;jumphost&#34;: &#34;&#34;} &#34;options&#34;: &#34;&#34;, &#34;logs&#34;: &#34;&#34;, &#34;tags&#34;: &#34;&#34;, &#34;jumphost&#34;: &#34;&#34;}
} }
} }
config_file.write_text(json.dumps(data, indent=4)) config_file.write_text(yaml.dump(data, default_flow_style=False, sort_keys=False))
from connpy.configfile import configfile from connpy.configfile import configfile
conf = configfile(conf=str(config_file), key=str(tmp_config_dir / &#34;.osk&#34;)) conf = configfile(conf=str(config_file), key=str(tmp_config_dir / &#34;.osk&#34;))
@@ -1014,7 +1014,7 @@ el.replaceWith(d);
</summary> </summary>
<pre><code class="python">def test_profileused(self, tmp_config_dir): <pre><code class="python">def test_profileused(self, tmp_config_dir):
&#34;&#34;&#34;Detects nodes using a specific profile.&#34;&#34;&#34; &#34;&#34;&#34;Detects nodes using a specific profile.&#34;&#34;&#34;
config_file = tmp_config_dir / &#34;config.json&#34; config_file = tmp_config_dir / &#34;config.yaml&#34;
data = { data = {
&#34;config&#34;: {&#34;case&#34;: False, &#34;idletime&#34;: 30, &#34;fzf&#34;: False}, &#34;config&#34;: {&#34;case&#34;: False, &#34;idletime&#34;: 30, &#34;fzf&#34;: False},
&#34;connections&#34;: { &#34;connections&#34;: {
@@ -1040,7 +1040,7 @@ el.replaceWith(d);
&#34;options&#34;: &#34;&#34;, &#34;logs&#34;: &#34;&#34;, &#34;tags&#34;: &#34;&#34;, &#34;jumphost&#34;: &#34;&#34;} &#34;options&#34;: &#34;&#34;, &#34;logs&#34;: &#34;&#34;, &#34;tags&#34;: &#34;&#34;, &#34;jumphost&#34;: &#34;&#34;}
} }
} }
config_file.write_text(json.dumps(data, indent=4)) config_file.write_text(yaml.dump(data, default_flow_style=False, sort_keys=False))
from connpy.configfile import configfile from connpy.configfile import configfile
conf = configfile(conf=str(config_file), key=str(tmp_config_dir / &#34;.osk&#34;)) conf = configfile(conf=str(config_file), key=str(tmp_config_dir / &#34;.osk&#34;))
@@ -1111,7 +1111,7 @@ el.replaceWith(d);
def test_getitem_with_profile_extraction(self, tmp_config_dir): def test_getitem_with_profile_extraction(self, tmp_config_dir):
&#34;&#34;&#34;extract=True resolves @profile references.&#34;&#34;&#34; &#34;&#34;&#34;extract=True resolves @profile references.&#34;&#34;&#34;
config_file = tmp_config_dir / &#34;config.json&#34; config_file = tmp_config_dir / &#34;config.yaml&#34;
data = { data = {
&#34;config&#34;: {&#34;case&#34;: False, &#34;idletime&#34;: 30, &#34;fzf&#34;: False}, &#34;config&#34;: {&#34;case&#34;: False, &#34;idletime&#34;: 30, &#34;fzf&#34;: False},
&#34;connections&#34;: { &#34;connections&#34;: {
@@ -1131,7 +1131,7 @@ el.replaceWith(d);
&#34;options&#34;: &#34;&#34;, &#34;logs&#34;: &#34;&#34;, &#34;tags&#34;: &#34;&#34;, &#34;jumphost&#34;: &#34;&#34;} &#34;options&#34;: &#34;&#34;, &#34;logs&#34;: &#34;&#34;, &#34;tags&#34;: &#34;&#34;, &#34;jumphost&#34;: &#34;&#34;}
} }
} }
config_file.write_text(json.dumps(data, indent=4)) config_file.write_text(yaml.dump(data, default_flow_style=False, sort_keys=False))
from connpy.configfile import configfile from connpy.configfile import configfile
conf = configfile(conf=str(config_file), key=str(tmp_config_dir / &#34;.osk&#34;)) conf = configfile(conf=str(config_file), key=str(tmp_config_dir / &#34;.osk&#34;))
@@ -1235,7 +1235,7 @@ el.replaceWith(d);
</summary> </summary>
<pre><code class="python">def test_getitem_with_profile_extraction(self, tmp_config_dir): <pre><code class="python">def test_getitem_with_profile_extraction(self, tmp_config_dir):
&#34;&#34;&#34;extract=True resolves @profile references.&#34;&#34;&#34; &#34;&#34;&#34;extract=True resolves @profile references.&#34;&#34;&#34;
config_file = tmp_config_dir / &#34;config.json&#34; config_file = tmp_config_dir / &#34;config.yaml&#34;
data = { data = {
&#34;config&#34;: {&#34;case&#34;: False, &#34;idletime&#34;: 30, &#34;fzf&#34;: False}, &#34;config&#34;: {&#34;case&#34;: False, &#34;idletime&#34;: 30, &#34;fzf&#34;: False},
&#34;connections&#34;: { &#34;connections&#34;: {
@@ -1255,7 +1255,7 @@ el.replaceWith(d);
&#34;options&#34;: &#34;&#34;, &#34;logs&#34;: &#34;&#34;, &#34;tags&#34;: &#34;&#34;, &#34;jumphost&#34;: &#34;&#34;} &#34;options&#34;: &#34;&#34;, &#34;logs&#34;: &#34;&#34;, &#34;tags&#34;: &#34;&#34;, &#34;jumphost&#34;: &#34;&#34;}
} }
} }
config_file.write_text(json.dumps(data, indent=4)) config_file.write_text(yaml.dump(data, default_flow_style=False, sort_keys=False))
from connpy.configfile import configfile from connpy.configfile import configfile
conf = configfile(conf=str(config_file), key=str(tmp_config_dir / &#34;.osk&#34;)) conf = configfile(conf=str(config_file), key=str(tmp_config_dir / &#34;.osk&#34;))
+475
View File
@@ -0,0 +1,475 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.6">
<title>connpy.tests.test_context API documentation</title>
<meta name="description" content="Tests for connpy.core_plugins.context">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source > summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible;min-width:max-content}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin:1em 0}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
/* Collapse source docstrings */
setTimeout(() => {
[...document.querySelectorAll('.hljs.language-python > .hljs-string')]
.filter(el => el.innerHTML.length > 200 && ['"""', "'''"].includes(el.innerHTML.substring(0, 3)))
.forEach(el => {
let d = document.createElement('details');
d.classList.add('hljs-string');
d.innerHTML = '<summary>"""</summary>' + el.innerHTML.substring(3);
el.replaceWith(d);
});
}, 100);
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>connpy.tests.test_context</code></h1>
</header>
<section id="section-intro">
<p>Tests for connpy.core_plugins.context</p>
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="connpy.tests.test_context.mock_connapp"><code class="name flex">
<span>def <span class="ident">mock_connapp</span></span>(<span>)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@pytest.fixture
def mock_connapp():
connapp = MagicMock()
connapp.config.config = {
&#34;contexts&#34;: {&#34;all&#34;: [&#34;.*&#34;]},
&#34;current_context&#34;: &#34;all&#34;
}
return connapp</code></pre>
</details>
<div class="desc"></div>
</dd>
</dl>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="connpy.tests.test_context.TestContextManager"><code class="flex name class">
<span>class <span class="ident">TestContextManager</span></span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class TestContextManager:
def test_init(self, mock_connapp):
cm = context_manager(mock_connapp)
assert cm.contexts == {&#34;all&#34;: [&#34;.*&#34;]}
assert cm.current_context == &#34;all&#34;
assert len(cm.regex) == 1
def test_add_context_success(self, mock_connapp):
cm = context_manager(mock_connapp)
cm.add_context(&#34;prod&#34;, [&#34;^prod_.*&#34;])
assert &#34;prod&#34; in cm.contexts
mock_connapp._change_settings.assert_called_with(&#34;contexts&#34;, cm.contexts)
def test_add_context_invalid_name(self, mock_connapp):
cm = context_manager(mock_connapp)
with pytest.raises(SystemExit) as exc:
cm.add_context(&#34;prod-env&#34;, [&#34;Regex&#34;])
assert exc.value.code == 1
def test_add_context_already_exists(self, mock_connapp):
cm = context_manager(mock_connapp)
with pytest.raises(SystemExit) as exc:
cm.add_context(&#34;all&#34;, [&#34;Regex&#34;])
assert exc.value.code == 2
def test_modify_context_success(self, mock_connapp):
cm = context_manager(mock_connapp)
cm.add_context(&#34;prod&#34;, [&#34;old&#34;])
cm.modify_context(&#34;prod&#34;, [&#34;new&#34;])
assert cm.contexts[&#34;prod&#34;] == [&#34;new&#34;]
def test_modify_context_all(self, mock_connapp):
cm = context_manager(mock_connapp)
with pytest.raises(SystemExit) as exc:
cm.modify_context(&#34;all&#34;, [&#34;new&#34;])
assert exc.value.code == 3
def test_modify_context_not_exists(self, mock_connapp):
cm = context_manager(mock_connapp)
with pytest.raises(SystemExit) as exc:
cm.modify_context(&#34;fake&#34;, [&#34;new&#34;])
assert exc.value.code == 4
def test_delete_context_success(self, mock_connapp):
cm = context_manager(mock_connapp)
cm.add_context(&#34;prod&#34;, [&#34;old&#34;])
cm.delete_context(&#34;prod&#34;)
assert &#34;prod&#34; not in cm.contexts
def test_delete_context_all(self, mock_connapp):
cm = context_manager(mock_connapp)
with pytest.raises(SystemExit) as exc:
cm.delete_context(&#34;all&#34;)
assert exc.value.code == 3
def test_delete_context_current(self, mock_connapp):
mock_connapp.config.config[&#34;current_context&#34;] = &#34;prod&#34;
mock_connapp.config.config[&#34;contexts&#34;][&#34;prod&#34;] = [&#34;.*&#34;]
cm = context_manager(mock_connapp)
with pytest.raises(SystemExit) as exc:
cm.delete_context(&#34;prod&#34;)
assert exc.value.code == 5
def test_set_context_success(self, mock_connapp):
cm = context_manager(mock_connapp)
cm.contexts[&#34;prod&#34;] = [&#34;.*&#34;]
cm.set_context(&#34;prod&#34;)
mock_connapp._change_settings.assert_called_with(&#34;current_context&#34;, &#34;prod&#34;)
def test_set_context_already_set(self, mock_connapp):
cm = context_manager(mock_connapp)
with pytest.raises(SystemExit) as exc:
cm.set_context(&#34;all&#34;)
assert exc.value.code == 0
def test_match_regexp(self, mock_connapp):
mock_connapp.config.config[&#34;contexts&#34;][&#34;all&#34;] = [&#34;^prod&#34;, &#34;^test&#34;]
cm = context_manager(mock_connapp)
assert cm.match_any_regex(&#34;prod_node&#34;, cm.regex) is True
assert cm.match_any_regex(&#34;test_node&#34;, cm.regex) is True
assert cm.match_any_regex(&#34;dev_node&#34;, cm.regex) is False
def test_modify_node_list(self, mock_connapp):
mock_connapp.config.config[&#34;contexts&#34;][&#34;all&#34;] = [&#34;^prod&#34;]
cm = context_manager(mock_connapp)
nodes = [&#34;prod_1&#34;, &#34;dev_1&#34;, &#34;prod_2&#34;]
result = cm.modify_node_list(result=nodes)
assert result == [&#34;prod_1&#34;, &#34;prod_2&#34;]
def test_modify_node_dict(self, mock_connapp):
mock_connapp.config.config[&#34;contexts&#34;][&#34;all&#34;] = [&#34;^prod&#34;]
cm = context_manager(mock_connapp)
nodes = {&#34;prod_1&#34;: {}, &#34;dev_1&#34;: {}, &#34;prod_2&#34;: {}}
result = cm.modify_node_dict(result=nodes)
assert set(result.keys()) == {&#34;prod_1&#34;, &#34;prod_2&#34;}</code></pre>
</details>
<div class="desc"></div>
<h3>Methods</h3>
<dl>
<dt id="connpy.tests.test_context.TestContextManager.test_add_context_already_exists"><code class="name flex">
<span>def <span class="ident">test_add_context_already_exists</span></span>(<span>self, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def test_add_context_already_exists(self, mock_connapp):
cm = context_manager(mock_connapp)
with pytest.raises(SystemExit) as exc:
cm.add_context(&#34;all&#34;, [&#34;Regex&#34;])
assert exc.value.code == 2</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_context.TestContextManager.test_add_context_invalid_name"><code class="name flex">
<span>def <span class="ident">test_add_context_invalid_name</span></span>(<span>self, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def test_add_context_invalid_name(self, mock_connapp):
cm = context_manager(mock_connapp)
with pytest.raises(SystemExit) as exc:
cm.add_context(&#34;prod-env&#34;, [&#34;Regex&#34;])
assert exc.value.code == 1</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_context.TestContextManager.test_add_context_success"><code class="name flex">
<span>def <span class="ident">test_add_context_success</span></span>(<span>self, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def test_add_context_success(self, mock_connapp):
cm = context_manager(mock_connapp)
cm.add_context(&#34;prod&#34;, [&#34;^prod_.*&#34;])
assert &#34;prod&#34; in cm.contexts
mock_connapp._change_settings.assert_called_with(&#34;contexts&#34;, cm.contexts)</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_context.TestContextManager.test_delete_context_all"><code class="name flex">
<span>def <span class="ident">test_delete_context_all</span></span>(<span>self, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def test_delete_context_all(self, mock_connapp):
cm = context_manager(mock_connapp)
with pytest.raises(SystemExit) as exc:
cm.delete_context(&#34;all&#34;)
assert exc.value.code == 3</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_context.TestContextManager.test_delete_context_current"><code class="name flex">
<span>def <span class="ident">test_delete_context_current</span></span>(<span>self, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def test_delete_context_current(self, mock_connapp):
mock_connapp.config.config[&#34;current_context&#34;] = &#34;prod&#34;
mock_connapp.config.config[&#34;contexts&#34;][&#34;prod&#34;] = [&#34;.*&#34;]
cm = context_manager(mock_connapp)
with pytest.raises(SystemExit) as exc:
cm.delete_context(&#34;prod&#34;)
assert exc.value.code == 5</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_context.TestContextManager.test_delete_context_success"><code class="name flex">
<span>def <span class="ident">test_delete_context_success</span></span>(<span>self, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def test_delete_context_success(self, mock_connapp):
cm = context_manager(mock_connapp)
cm.add_context(&#34;prod&#34;, [&#34;old&#34;])
cm.delete_context(&#34;prod&#34;)
assert &#34;prod&#34; not in cm.contexts</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_context.TestContextManager.test_init"><code class="name flex">
<span>def <span class="ident">test_init</span></span>(<span>self, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def test_init(self, mock_connapp):
cm = context_manager(mock_connapp)
assert cm.contexts == {&#34;all&#34;: [&#34;.*&#34;]}
assert cm.current_context == &#34;all&#34;
assert len(cm.regex) == 1</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_context.TestContextManager.test_match_regexp"><code class="name flex">
<span>def <span class="ident">test_match_regexp</span></span>(<span>self, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def test_match_regexp(self, mock_connapp):
mock_connapp.config.config[&#34;contexts&#34;][&#34;all&#34;] = [&#34;^prod&#34;, &#34;^test&#34;]
cm = context_manager(mock_connapp)
assert cm.match_any_regex(&#34;prod_node&#34;, cm.regex) is True
assert cm.match_any_regex(&#34;test_node&#34;, cm.regex) is True
assert cm.match_any_regex(&#34;dev_node&#34;, cm.regex) is False</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_context.TestContextManager.test_modify_context_all"><code class="name flex">
<span>def <span class="ident">test_modify_context_all</span></span>(<span>self, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def test_modify_context_all(self, mock_connapp):
cm = context_manager(mock_connapp)
with pytest.raises(SystemExit) as exc:
cm.modify_context(&#34;all&#34;, [&#34;new&#34;])
assert exc.value.code == 3</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_context.TestContextManager.test_modify_context_not_exists"><code class="name flex">
<span>def <span class="ident">test_modify_context_not_exists</span></span>(<span>self, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def test_modify_context_not_exists(self, mock_connapp):
cm = context_manager(mock_connapp)
with pytest.raises(SystemExit) as exc:
cm.modify_context(&#34;fake&#34;, [&#34;new&#34;])
assert exc.value.code == 4</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_context.TestContextManager.test_modify_context_success"><code class="name flex">
<span>def <span class="ident">test_modify_context_success</span></span>(<span>self, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def test_modify_context_success(self, mock_connapp):
cm = context_manager(mock_connapp)
cm.add_context(&#34;prod&#34;, [&#34;old&#34;])
cm.modify_context(&#34;prod&#34;, [&#34;new&#34;])
assert cm.contexts[&#34;prod&#34;] == [&#34;new&#34;]</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_context.TestContextManager.test_modify_node_dict"><code class="name flex">
<span>def <span class="ident">test_modify_node_dict</span></span>(<span>self, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def test_modify_node_dict(self, mock_connapp):
mock_connapp.config.config[&#34;contexts&#34;][&#34;all&#34;] = [&#34;^prod&#34;]
cm = context_manager(mock_connapp)
nodes = {&#34;prod_1&#34;: {}, &#34;dev_1&#34;: {}, &#34;prod_2&#34;: {}}
result = cm.modify_node_dict(result=nodes)
assert set(result.keys()) == {&#34;prod_1&#34;, &#34;prod_2&#34;}</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_context.TestContextManager.test_modify_node_list"><code class="name flex">
<span>def <span class="ident">test_modify_node_list</span></span>(<span>self, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def test_modify_node_list(self, mock_connapp):
mock_connapp.config.config[&#34;contexts&#34;][&#34;all&#34;] = [&#34;^prod&#34;]
cm = context_manager(mock_connapp)
nodes = [&#34;prod_1&#34;, &#34;dev_1&#34;, &#34;prod_2&#34;]
result = cm.modify_node_list(result=nodes)
assert result == [&#34;prod_1&#34;, &#34;prod_2&#34;]</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_context.TestContextManager.test_set_context_already_set"><code class="name flex">
<span>def <span class="ident">test_set_context_already_set</span></span>(<span>self, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def test_set_context_already_set(self, mock_connapp):
cm = context_manager(mock_connapp)
with pytest.raises(SystemExit) as exc:
cm.set_context(&#34;all&#34;)
assert exc.value.code == 0</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_context.TestContextManager.test_set_context_success"><code class="name flex">
<span>def <span class="ident">test_set_context_success</span></span>(<span>self, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def test_set_context_success(self, mock_connapp):
cm = context_manager(mock_connapp)
cm.contexts[&#34;prod&#34;] = [&#34;.*&#34;]
cm.set_context(&#34;prod&#34;)
mock_connapp._change_settings.assert_called_with(&#34;current_context&#34;, &#34;prod&#34;)</code></pre>
</details>
<div class="desc"></div>
</dd>
</dl>
</dd>
</dl>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="connpy.tests" href="index.html">connpy.tests</a></code></li>
</ul>
</li>
<li><h3><a href="#header-functions">Functions</a></h3>
<ul class="">
<li><code><a title="connpy.tests.test_context.mock_connapp" href="#connpy.tests.test_context.mock_connapp">mock_connapp</a></code></li>
</ul>
</li>
<li><h3><a href="#header-classes">Classes</a></h3>
<ul>
<li>
<h4><code><a title="connpy.tests.test_context.TestContextManager" href="#connpy.tests.test_context.TestContextManager">TestContextManager</a></code></h4>
<ul class="">
<li><code><a title="connpy.tests.test_context.TestContextManager.test_add_context_already_exists" href="#connpy.tests.test_context.TestContextManager.test_add_context_already_exists">test_add_context_already_exists</a></code></li>
<li><code><a title="connpy.tests.test_context.TestContextManager.test_add_context_invalid_name" href="#connpy.tests.test_context.TestContextManager.test_add_context_invalid_name">test_add_context_invalid_name</a></code></li>
<li><code><a title="connpy.tests.test_context.TestContextManager.test_add_context_success" href="#connpy.tests.test_context.TestContextManager.test_add_context_success">test_add_context_success</a></code></li>
<li><code><a title="connpy.tests.test_context.TestContextManager.test_delete_context_all" href="#connpy.tests.test_context.TestContextManager.test_delete_context_all">test_delete_context_all</a></code></li>
<li><code><a title="connpy.tests.test_context.TestContextManager.test_delete_context_current" href="#connpy.tests.test_context.TestContextManager.test_delete_context_current">test_delete_context_current</a></code></li>
<li><code><a title="connpy.tests.test_context.TestContextManager.test_delete_context_success" href="#connpy.tests.test_context.TestContextManager.test_delete_context_success">test_delete_context_success</a></code></li>
<li><code><a title="connpy.tests.test_context.TestContextManager.test_init" href="#connpy.tests.test_context.TestContextManager.test_init">test_init</a></code></li>
<li><code><a title="connpy.tests.test_context.TestContextManager.test_match_regexp" href="#connpy.tests.test_context.TestContextManager.test_match_regexp">test_match_regexp</a></code></li>
<li><code><a title="connpy.tests.test_context.TestContextManager.test_modify_context_all" href="#connpy.tests.test_context.TestContextManager.test_modify_context_all">test_modify_context_all</a></code></li>
<li><code><a title="connpy.tests.test_context.TestContextManager.test_modify_context_not_exists" href="#connpy.tests.test_context.TestContextManager.test_modify_context_not_exists">test_modify_context_not_exists</a></code></li>
<li><code><a title="connpy.tests.test_context.TestContextManager.test_modify_context_success" href="#connpy.tests.test_context.TestContextManager.test_modify_context_success">test_modify_context_success</a></code></li>
<li><code><a title="connpy.tests.test_context.TestContextManager.test_modify_node_dict" href="#connpy.tests.test_context.TestContextManager.test_modify_node_dict">test_modify_node_dict</a></code></li>
<li><code><a title="connpy.tests.test_context.TestContextManager.test_modify_node_list" href="#connpy.tests.test_context.TestContextManager.test_modify_node_list">test_modify_node_list</a></code></li>
<li><code><a title="connpy.tests.test_context.TestContextManager.test_set_context_already_set" href="#connpy.tests.test_context.TestContextManager.test_set_context_already_set">test_set_context_already_set</a></code></li>
<li><code><a title="connpy.tests.test_context.TestContextManager.test_set_context_success" href="#connpy.tests.test_context.TestContextManager.test_set_context_success">test_set_context_success</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
</footer>
</body>
</html>
+396
View File
@@ -0,0 +1,396 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.6">
<title>connpy.tests.test_sync API documentation</title>
<meta name="description" content="Tests for connpy.core_plugins.sync">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source > summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible;min-width:max-content}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin:1em 0}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
/* Collapse source docstrings */
setTimeout(() => {
[...document.querySelectorAll('.hljs.language-python > .hljs-string')]
.filter(el => el.innerHTML.length > 200 && ['"""', "'''"].includes(el.innerHTML.substring(0, 3)))
.forEach(el => {
let d = document.createElement('details');
d.classList.add('hljs-string');
d.innerHTML = '<summary>"""</summary>' + el.innerHTML.substring(3);
el.replaceWith(d);
});
}, 100);
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>connpy.tests.test_sync</code></h1>
</header>
<section id="section-intro">
<p>Tests for connpy.core_plugins.sync</p>
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="connpy.tests.test_sync.mock_connapp"><code class="name flex">
<span>def <span class="ident">mock_connapp</span></span>(<span>)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@pytest.fixture
def mock_connapp():
app = MagicMock()
app.config.defaultdir = &#34;/fake/dir&#34;
app.config.file = &#34;/fake/dir/config.yaml&#34;
app.config.key = &#34;/fake/dir/.osk&#34;
app.config.config = {&#34;sync&#34;: True}
return app</code></pre>
</details>
<div class="desc"></div>
</dd>
</dl>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="connpy.tests.test_sync.TestSyncPlugin"><code class="flex name class">
<span>class <span class="ident">TestSyncPlugin</span></span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class TestSyncPlugin:
def test_init(self, mock_connapp):
s = sync(mock_connapp)
assert s.sync is True
assert s.file == &#34;/fake/dir/config.yaml&#34;
assert s.token_file == &#34;/fake/dir/gtoken.json&#34;
@patch(&#34;connpy.core_plugins.sync.os.path.exists&#34;)
@patch(&#34;connpy.core_plugins.sync.Credentials&#34;)
def test_get_credentials_success(self, MockCreds, mock_exists, mock_connapp):
mock_exists.return_value = True
mock_cred_instance = MagicMock()
mock_cred_instance.valid = True
MockCreds.from_authorized_user_file.return_value = mock_cred_instance
s = sync(mock_connapp)
creds = s.get_credentials()
assert creds == mock_cred_instance
@patch(&#34;connpy.core_plugins.sync.os.path.exists&#34;)
def test_get_credentials_not_found(self, mock_exists, mock_connapp):
mock_exists.return_value = False
s = sync(mock_connapp)
assert s.get_credentials() == 0
@patch(&#34;connpy.core_plugins.sync.zipfile.ZipFile&#34;)
@patch(&#34;connpy.core_plugins.sync.os.path.basename&#34;)
def test_compress_specific_files(self, mock_basename, MockZipFile, mock_connapp):
mock_basename.return_value = &#34;config.yaml&#34;
s = sync(mock_connapp)
zip_mock = MagicMock()
MockZipFile.return_value.__enter__.return_value = zip_mock
s.compress_specific_files(&#34;/fake/zip.zip&#34;)
zip_mock.write.assert_any_call(s.file, &#34;config.yaml&#34;)
zip_mock.write.assert_any_call(s.key, &#34;.osk&#34;)
@patch(&#34;connpy.core_plugins.sync.zipfile.ZipFile&#34;)
@patch(&#34;connpy.core_plugins.sync.os.path.dirname&#34;)
def test_decompress_zip_yaml(self, mock_dirname, MockZipFile, mock_connapp):
mock_dirname.return_value = &#34;/fake/dir&#34;
s = sync(mock_connapp)
zip_mock = MagicMock()
zip_mock.namelist.return_value = [&#34;config.yaml&#34;, &#34;.osk&#34;]
MockZipFile.return_value.__enter__.return_value = zip_mock
assert s.decompress_zip(&#34;/fake/zip.zip&#34;) == 0
zip_mock.extract.assert_any_call(&#34;config.yaml&#34;, &#34;/fake/dir&#34;)
zip_mock.extract.assert_any_call(&#34;.osk&#34;, &#34;/fake/dir&#34;)
@patch(&#34;connpy.core_plugins.sync.zipfile.ZipFile&#34;)
@patch(&#34;connpy.core_plugins.sync.os.path.dirname&#34;)
def test_decompress_zip_json_fallback(self, mock_dirname, MockZipFile, mock_connapp):
mock_dirname.return_value = &#34;/fake/dir&#34;
s = sync(mock_connapp)
zip_mock = MagicMock()
zip_mock.namelist.return_value = [&#34;config.json&#34;, &#34;.osk&#34;]
MockZipFile.return_value.__enter__.return_value = zip_mock
assert s.decompress_zip(&#34;/fake/old_zip.zip&#34;) == 0
zip_mock.extract.assert_any_call(&#34;config.json&#34;, &#34;/fake/dir&#34;)
@patch.object(sync, &#34;get_credentials&#34;)
@patch(&#34;connpy.core_plugins.sync.build&#34;)
def test_get_appdata_files(self, mock_build, mock_get_credentials, mock_connapp):
mock_get_credentials.return_value = MagicMock()
mock_service = MagicMock()
mock_build.return_value = mock_service
mock_service.files().list().execute.return_value = {
&#34;files&#34;: [
{&#34;id&#34;: &#34;1&#34;, &#34;name&#34;: &#34;backup1.zip&#34;, &#34;appProperties&#34;: {&#34;timestamp&#34;: &#34;1000&#34;, &#34;date&#34;: &#34;2024&#34;}}
]
}
s = sync(mock_connapp)
files = s.get_appdata_files()
assert len(files) == 1
assert files[0][&#34;id&#34;] == &#34;1&#34;
assert files[0][&#34;timestamp&#34;] == &#34;1000&#34;
@patch.object(sync, &#34;get_credentials&#34;)
@patch(&#34;connpy.core_plugins.sync.build&#34;)
@patch(&#34;connpy.core_plugins.sync.MediaFileUpload&#34;)
@patch(&#34;connpy.core_plugins.sync.os.path.basename&#34;)
def test_backup_file_to_drive(self, mock_basename, mock_media, mock_build, mock_get_credentials, mock_connapp):
mock_get_credentials.return_value = MagicMock()
mock_basename.return_value = &#34;backup.zip&#34;
mock_service = MagicMock()
mock_build.return_value = mock_service
s = sync(mock_connapp)
assert s.backup_file_to_drive(&#34;/fake/backup.zip&#34;, 1234567890000) == 0
mock_service.files().create.assert_called_once()</code></pre>
</details>
<div class="desc"></div>
<h3>Methods</h3>
<dl>
<dt id="connpy.tests.test_sync.TestSyncPlugin.test_backup_file_to_drive"><code class="name flex">
<span>def <span class="ident">test_backup_file_to_drive</span></span>(<span>self, mock_basename, mock_media, mock_build, mock_get_credentials, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@patch.object(sync, &#34;get_credentials&#34;)
@patch(&#34;connpy.core_plugins.sync.build&#34;)
@patch(&#34;connpy.core_plugins.sync.MediaFileUpload&#34;)
@patch(&#34;connpy.core_plugins.sync.os.path.basename&#34;)
def test_backup_file_to_drive(self, mock_basename, mock_media, mock_build, mock_get_credentials, mock_connapp):
mock_get_credentials.return_value = MagicMock()
mock_basename.return_value = &#34;backup.zip&#34;
mock_service = MagicMock()
mock_build.return_value = mock_service
s = sync(mock_connapp)
assert s.backup_file_to_drive(&#34;/fake/backup.zip&#34;, 1234567890000) == 0
mock_service.files().create.assert_called_once()</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_sync.TestSyncPlugin.test_compress_specific_files"><code class="name flex">
<span>def <span class="ident">test_compress_specific_files</span></span>(<span>self, mock_basename, MockZipFile, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@patch(&#34;connpy.core_plugins.sync.zipfile.ZipFile&#34;)
@patch(&#34;connpy.core_plugins.sync.os.path.basename&#34;)
def test_compress_specific_files(self, mock_basename, MockZipFile, mock_connapp):
mock_basename.return_value = &#34;config.yaml&#34;
s = sync(mock_connapp)
zip_mock = MagicMock()
MockZipFile.return_value.__enter__.return_value = zip_mock
s.compress_specific_files(&#34;/fake/zip.zip&#34;)
zip_mock.write.assert_any_call(s.file, &#34;config.yaml&#34;)
zip_mock.write.assert_any_call(s.key, &#34;.osk&#34;)</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_sync.TestSyncPlugin.test_decompress_zip_json_fallback"><code class="name flex">
<span>def <span class="ident">test_decompress_zip_json_fallback</span></span>(<span>self, mock_dirname, MockZipFile, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@patch(&#34;connpy.core_plugins.sync.zipfile.ZipFile&#34;)
@patch(&#34;connpy.core_plugins.sync.os.path.dirname&#34;)
def test_decompress_zip_json_fallback(self, mock_dirname, MockZipFile, mock_connapp):
mock_dirname.return_value = &#34;/fake/dir&#34;
s = sync(mock_connapp)
zip_mock = MagicMock()
zip_mock.namelist.return_value = [&#34;config.json&#34;, &#34;.osk&#34;]
MockZipFile.return_value.__enter__.return_value = zip_mock
assert s.decompress_zip(&#34;/fake/old_zip.zip&#34;) == 0
zip_mock.extract.assert_any_call(&#34;config.json&#34;, &#34;/fake/dir&#34;)</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_sync.TestSyncPlugin.test_decompress_zip_yaml"><code class="name flex">
<span>def <span class="ident">test_decompress_zip_yaml</span></span>(<span>self, mock_dirname, MockZipFile, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@patch(&#34;connpy.core_plugins.sync.zipfile.ZipFile&#34;)
@patch(&#34;connpy.core_plugins.sync.os.path.dirname&#34;)
def test_decompress_zip_yaml(self, mock_dirname, MockZipFile, mock_connapp):
mock_dirname.return_value = &#34;/fake/dir&#34;
s = sync(mock_connapp)
zip_mock = MagicMock()
zip_mock.namelist.return_value = [&#34;config.yaml&#34;, &#34;.osk&#34;]
MockZipFile.return_value.__enter__.return_value = zip_mock
assert s.decompress_zip(&#34;/fake/zip.zip&#34;) == 0
zip_mock.extract.assert_any_call(&#34;config.yaml&#34;, &#34;/fake/dir&#34;)
zip_mock.extract.assert_any_call(&#34;.osk&#34;, &#34;/fake/dir&#34;)</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_sync.TestSyncPlugin.test_get_appdata_files"><code class="name flex">
<span>def <span class="ident">test_get_appdata_files</span></span>(<span>self, mock_build, mock_get_credentials, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@patch.object(sync, &#34;get_credentials&#34;)
@patch(&#34;connpy.core_plugins.sync.build&#34;)
def test_get_appdata_files(self, mock_build, mock_get_credentials, mock_connapp):
mock_get_credentials.return_value = MagicMock()
mock_service = MagicMock()
mock_build.return_value = mock_service
mock_service.files().list().execute.return_value = {
&#34;files&#34;: [
{&#34;id&#34;: &#34;1&#34;, &#34;name&#34;: &#34;backup1.zip&#34;, &#34;appProperties&#34;: {&#34;timestamp&#34;: &#34;1000&#34;, &#34;date&#34;: &#34;2024&#34;}}
]
}
s = sync(mock_connapp)
files = s.get_appdata_files()
assert len(files) == 1
assert files[0][&#34;id&#34;] == &#34;1&#34;
assert files[0][&#34;timestamp&#34;] == &#34;1000&#34;</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_sync.TestSyncPlugin.test_get_credentials_not_found"><code class="name flex">
<span>def <span class="ident">test_get_credentials_not_found</span></span>(<span>self, mock_exists, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@patch(&#34;connpy.core_plugins.sync.os.path.exists&#34;)
def test_get_credentials_not_found(self, mock_exists, mock_connapp):
mock_exists.return_value = False
s = sync(mock_connapp)
assert s.get_credentials() == 0</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_sync.TestSyncPlugin.test_get_credentials_success"><code class="name flex">
<span>def <span class="ident">test_get_credentials_success</span></span>(<span>self, MockCreds, mock_exists, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@patch(&#34;connpy.core_plugins.sync.os.path.exists&#34;)
@patch(&#34;connpy.core_plugins.sync.Credentials&#34;)
def test_get_credentials_success(self, MockCreds, mock_exists, mock_connapp):
mock_exists.return_value = True
mock_cred_instance = MagicMock()
mock_cred_instance.valid = True
MockCreds.from_authorized_user_file.return_value = mock_cred_instance
s = sync(mock_connapp)
creds = s.get_credentials()
assert creds == mock_cred_instance</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.tests.test_sync.TestSyncPlugin.test_init"><code class="name flex">
<span>def <span class="ident">test_init</span></span>(<span>self, mock_connapp)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def test_init(self, mock_connapp):
s = sync(mock_connapp)
assert s.sync is True
assert s.file == &#34;/fake/dir/config.yaml&#34;
assert s.token_file == &#34;/fake/dir/gtoken.json&#34;</code></pre>
</details>
<div class="desc"></div>
</dd>
</dl>
</dd>
</dl>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="connpy.tests" href="index.html">connpy.tests</a></code></li>
</ul>
</li>
<li><h3><a href="#header-functions">Functions</a></h3>
<ul class="">
<li><code><a title="connpy.tests.test_sync.mock_connapp" href="#connpy.tests.test_sync.mock_connapp">mock_connapp</a></code></li>
</ul>
</li>
<li><h3><a href="#header-classes">Classes</a></h3>
<ul>
<li>
<h4><code><a title="connpy.tests.test_sync.TestSyncPlugin" href="#connpy.tests.test_sync.TestSyncPlugin">TestSyncPlugin</a></code></h4>
<ul class="">
<li><code><a title="connpy.tests.test_sync.TestSyncPlugin.test_backup_file_to_drive" href="#connpy.tests.test_sync.TestSyncPlugin.test_backup_file_to_drive">test_backup_file_to_drive</a></code></li>
<li><code><a title="connpy.tests.test_sync.TestSyncPlugin.test_compress_specific_files" href="#connpy.tests.test_sync.TestSyncPlugin.test_compress_specific_files">test_compress_specific_files</a></code></li>
<li><code><a title="connpy.tests.test_sync.TestSyncPlugin.test_decompress_zip_json_fallback" href="#connpy.tests.test_sync.TestSyncPlugin.test_decompress_zip_json_fallback">test_decompress_zip_json_fallback</a></code></li>
<li><code><a title="connpy.tests.test_sync.TestSyncPlugin.test_decompress_zip_yaml" href="#connpy.tests.test_sync.TestSyncPlugin.test_decompress_zip_yaml">test_decompress_zip_yaml</a></code></li>
<li><code><a title="connpy.tests.test_sync.TestSyncPlugin.test_get_appdata_files" href="#connpy.tests.test_sync.TestSyncPlugin.test_get_appdata_files">test_get_appdata_files</a></code></li>
<li><code><a title="connpy.tests.test_sync.TestSyncPlugin.test_get_credentials_not_found" href="#connpy.tests.test_sync.TestSyncPlugin.test_get_credentials_not_found">test_get_credentials_not_found</a></code></li>
<li><code><a title="connpy.tests.test_sync.TestSyncPlugin.test_get_credentials_success" href="#connpy.tests.test_sync.TestSyncPlugin.test_get_credentials_success">test_get_credentials_success</a></code></li>
<li><code><a title="connpy.tests.test_sync.TestSyncPlugin.test_init" href="#connpy.tests.test_sync.TestSyncPlugin.test_init">test_init</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
</footer>
</body>
</html>