format: Add a function for formatting search strings
This takes the input string, casefolds it, and then adds some extra glob operators to it so we can do a case insensitive substring search by default. Signed-off-by: Anna Schumaker <Anna@NoWheyCreamery.com>
This commit is contained in:
parent
6ede296ba6
commit
3cf730a5cc
|
@ -0,0 +1,21 @@
|
|||
# Copyright 2022 (c) Anna Schumaker
|
||||
"""Helper functions for formatting strings."""
|
||||
|
||||
|
||||
def search(input: str) -> str | None:
|
||||
"""Translate the input string into a sqlite3 GLOB statement."""
|
||||
input = input.strip().casefold()
|
||||
if len(input) == 0:
|
||||
return None
|
||||
|
||||
if input[0] == "^":
|
||||
input = input[1:] if len(input) > 1 else "*"
|
||||
elif input[0] != "*":
|
||||
input = "*" + input
|
||||
|
||||
if input[-1] == "$":
|
||||
input = input[:-1]
|
||||
elif input[-1] != "*":
|
||||
input += "*"
|
||||
|
||||
return input
|
|
@ -0,0 +1,20 @@
|
|||
# Copyright 2022 (c) Anna Schumaker
|
||||
"""Tests our string formatting functions."""
|
||||
import unittest
|
||||
from emmental import format
|
||||
|
||||
|
||||
class TestFormatter(unittest.TestCase):
|
||||
"""Tests our formatting functions."""
|
||||
|
||||
def test_search(self):
|
||||
"""Test formatting a case-insensitive search query."""
|
||||
self.assertIsNone(format.search(""))
|
||||
self.assertIsNone(format.search(" "))
|
||||
self.assertEqual(format.search(" TeSt "), "*test*")
|
||||
self.assertEqual(format.search("*Test*"), "*test*")
|
||||
self.assertEqual(format.search("^Test*"), "test*")
|
||||
self.assertEqual(format.search("^*Test*"), "*test*")
|
||||
self.assertEqual(format.search("*Test$"), "*test")
|
||||
self.assertEqual(format.search("^"), "*")
|
||||
self.assertEqual(format.search("$"), "*")
|
Loading…
Reference in New Issue