Unit test for date conversion

main
Bob Mottram 2021-07-28 10:35:21 +01:00
parent 95129e2e58
commit 64f63aa0b6
3 changed files with 43 additions and 16 deletions

View File

@ -20,6 +20,8 @@ from posts import getPersonBox
from session import postJson from session import postJson
from session import postImage from session import postImage
from session import createSession from session import createSession
from utils import dateStringToSeconds
from utils import dateSecondsToString
from utils import getConfigParam from utils import getConfigParam
from utils import getFullDomain from utils import getFullDomain
from utils import validNickname from utils import validNickname
@ -924,10 +926,8 @@ def sharesCatalogEndpoint(baseDir: str, httpPrefix: str,
if not re.match(matchPattern, description): if not re.match(matchPattern, description):
continue continue
expireDate = \ startDateStr = dateSecondsToString(item['published'])
datetime.datetime.fromtimestamp(item['expire']) expireDateStr = dateSecondsToString(item['expire'])
expireDateStr = expireDate.strftime("%Y-%m-%dT%H:%M:%SZ")
shareId = getValidSharedItemID(owner, item['displayName']) shareId = getValidSharedItemID(owner, item['displayName'])
if item['dfcId'].startswith('epicyon#'): if item['dfcId'].startswith('epicyon#'):
dfcId = "epicyon:" + item['dfcId'].split('#')[1] dfcId = "epicyon:" + item['dfcId'].split('#')[1]
@ -938,7 +938,7 @@ def sharesCatalogEndpoint(baseDir: str, httpPrefix: str,
"@id": shareId, "@id": shareId,
"@type": "DFC:SuppliedProduct", "@type": "DFC:SuppliedProduct",
"DFC:hasType": dfcId, "DFC:hasType": dfcId,
"DFC:startDate": item['published'], "DFC:startDate": startDateStr,
"DFC:expiryDate": expireDateStr, "DFC:expiryDate": expireDateStr,
"DFC:quantity": item['itemQty'], "DFC:quantity": item['itemQty'],
"DFC:price": priceStr, "DFC:price": priceStr,
@ -1280,15 +1280,13 @@ def _dfcToSharesFormat(catalogJson: {},
if ':' not in item['DFC:hasType']: if ':' not in item['DFC:hasType']:
continue continue
try: startTimeSec = dateStringToSeconds(item['DFC:startDate'])
expiryTime = \ if not startTimeSec:
datetime.datetime.strptime(item['DFC:expiryDate'],
'%Y-%m-%dT%H:%M:%SZ')
except BaseException:
continue continue
durationSec = \ expiryTimeSec = dateStringToSeconds(item['DFC:expiryDate'])
int((expiryTime - datetime.datetime(1970, 1, 1)).total_seconds()) if not expiryTimeSec:
if durationSec < currTime: continue
if expiryTimeSec < currTime:
# has expired # has expired
continue continue
@ -1314,8 +1312,8 @@ def _dfcToSharesFormat(catalogJson: {},
"itemType": itemType, "itemType": itemType,
"category": itemCategory, "category": itemCategory,
"location": "", "location": "",
"published": item['DFC:startDate'], "published": startTimeSec,
"expire": durationSec, "expire": expiryTimeSec,
"itemPrice": item['DFC:price'].split(' ')[0], "itemPrice": item['DFC:price'].split(' ')[0],
"itemCurrency": item['DFC:price'].split(' ')[1] "itemCurrency": item['DFC:price'].split(' ')[1]
} }

View File

@ -39,6 +39,8 @@ from follow import clearFollowers
from follow import sendFollowRequestViaServer from follow import sendFollowRequestViaServer
from follow import sendUnfollowRequestViaServer from follow import sendUnfollowRequestViaServer
from siteactive import siteIsActive from siteactive import siteIsActive
from utils import dateStringToSeconds
from utils import dateSecondsToString
from utils import validPassword from utils import validPassword
from utils import userAgentDomain from utils import userAgentDomain
from utils import camelCaseSplit from utils import camelCaseSplit
@ -4318,9 +4320,19 @@ def _testAuthorizeSharedItems():
assert len(tokensJson['possum.domain']) == 0 assert len(tokensJson['possum.domain']) == 0
def _testDateConversions() -> None:
print('testDateConversions')
dateStr = "2021-05-16T14:37:41Z"
dateSec = dateStringToSeconds(dateStr)
dateStr2 = dateSecondsToString(dateSec)
assert dateStr == dateStr2
def runAllTests(): def runAllTests():
print('Running tests...') print('Running tests...')
updateDefaultThemesList(os.getcwd()) updateDefaultThemesList(os.getcwd())
_testFunctions()
_testDateConversions()
_testAuthorizeSharedItems() _testAuthorizeSharedItems()
_testValidPassword() _testValidPassword()
_testGetLinksFromContent() _testGetLinksFromContent()
@ -4328,7 +4340,6 @@ def runAllTests():
_testLimitRepetedWords() _testLimitRepetedWords()
_testLimitWordLengths() _testLimitWordLengths()
_testSwitchWords() _testSwitchWords()
_testFunctions()
_testUserAgentDomain() _testUserAgentDomain()
_testRoles() _testRoles()
_testSkills() _testSkills()

View File

@ -2634,3 +2634,21 @@ def isfloat(value):
return True return True
except ValueError: except ValueError:
return False return False
def dateStringToSeconds(dateStr: str) -> int:
"""Converts a date string (eg "published") into seconds since epoch
"""
try:
expiryTime = \
datetime.datetime.strptime(dateStr, '%Y-%m-%dT%H:%M:%SZ')
except BaseException:
return None
return int(datetime.datetime.timestamp(expiryTime))
def dateSecondsToString(dateSec: int) -> str:
"""Converts a date in seconds since epoch to a string
"""
thisDate = datetime.datetime.fromtimestamp(dateSec)
return thisDate.strftime("%Y-%m-%dT%H:%M:%SZ")