mrw02.gms : Test MessageReceiverWindow.exe from Python

Description


Small Model of Type : GAMS


Category : GAMS Test library


Main file : mrw02.gms

$title Test MessageReceiverWindow.exe from Python (mrw02,SEQ=823)

$if %system.filesys% == UNIX $abort.noError WinMsg works on Windows only

$onEmbeddedCode Python:
    from subprocess import Popen
    import time
    import ctypes
    import os
        
    class _CopyDataStruct(ctypes.Structure):
        _fields_ = [('dwData', ctypes.c_char_p),
                    ('cbData', ctypes.c_ulong),
                    ('lpData', ctypes.c_char_p)]
                  
    def sendMessage(windowName, message):
        cs = _CopyDataStruct()
        receiver = ctypes.windll.user32.FindWindowA(None, bytes(windowName, 'utf-8'))
        cmd = bytes(message, 'utf-8')
        cs.dwData = 1
        cs.cbData = len(cmd)+1
        cs.lpData = cmd
        WM_COPYDATA = 0x4A
        ctypes.windll.user32.SendMessageA(receiver, WM_COPYDATA, 0, ctypes.byref(cs))
    
    windowName = 'MRW Python'
    p = Popen([os.path.join(r"%gams.sysdir%.", 'MessageReceiverWindow.exe'), windowName])
        
    # wait for the window to be ready
    waitTime = 120
    readyFile = 'msg_ready.txt'
    while not os.path.exists(readyFile):
        time.sleep(1)
        waitTime -= 1
        sendMessage(windowName, '@SaveAs '+readyFile)
        if waitTime==0:
            raise Exception('Error: Time limit reached')
    os.remove(readyFile)
    
    sendMessage(windowName, "This is some Windows Message from Python")
    time.sleep(1)
    
    sendMessage(windowName, "Another Windows Message from Python")
    time.sleep(1)
    
    sendMessage(windowName, "@CopyToClipboard")
    saveAsFile = 'mrw02.txt'
    sendMessage(windowName, "@SaveAs "+saveAsFile)   
    sendMessage(windowName, "@Terminate")
    
    if not os.path.exists(saveAsFile):
        raise Exception("File '" + saveAsFile + "' does not exist")
        
    with open(saveAsFile) as f:
        lines = f.readlines()
        if 'This is some Windows Message from Python' not in lines[0] or 'Another Windows Message from Python' not in lines[1]:
            raise Exception("Content of '" + saveAsFile + "' is different than expected")
    os.remove(saveAsFile)
$offEmbeddedCode