prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>inhibit.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2011 Christoph Reiter <reiter.christoph@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
import os
import sys
if os.name == "nt" or sys.platform == "darwin":
from quodlibet.plugins import PluginNotSupportedError
raise PluginNotSupportedError
import dbus
from quodlibet import _
from quodlibet import app
from quodlibet.qltk import Icons
from quodlibet.plugins.events import EventPlugin
def get_toplevel_xid():
if app.window.get_window():
try:
return app.window.get_window().get_xid()
except AttributeError: # non x11
pass
return 0
class InhibitFlags(object):
LOGOUT = 1
USERSWITCH = 1 << 1
SUSPEND = 1 << 2
IDLE = 1 << 3
class SessionInhibit(EventPlugin):
PLUGIN_ID = "screensaver_inhibit"
PLUGIN_NAME = _("Inhibit Screensaver")
PLUGIN_DESC = _("Prevents the GNOME screensaver from activating while"
" a song is playing.")
PLUGIN_ICON = Icons.PREFERENCES_DESKTOP_SCREENSAVER
DBUS_NAME = "org.gnome.SessionManager"
DBUS_INTERFACE = "org.gnome.SessionManager"
DBUS_PATH = "/org/gnome/SessionManager"
APPLICATION_ID = "quodlibet"
INHIBIT_REASON = _("Music is playing")
__cookie = None
def enabled(self):
if not app.player.paused:
<|fim_middle|>
def disabled(self):
if not app.player.paused:
self.plugin_on_paused()
def plugin_on_unpaused(self):
xid = dbus.UInt32(get_toplevel_xid())
flags = dbus.UInt32(InhibitFlags.IDLE)
try:
bus = dbus.SessionBus()
obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH)
iface = dbus.Interface(obj, self.DBUS_INTERFACE)
self.__cookie = iface.Inhibit(
self.APPLICATION_ID, xid, self.INHIBIT_REASON, flags)
except dbus.DBusException:
pass
def plugin_on_paused(self):
if self.__cookie is None:
return
try:
bus = dbus.SessionBus()
obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH)
iface = dbus.Interface(obj, self.DBUS_INTERFACE)
iface.Uninhibit(self.__cookie)
self.__cookie = None
except dbus.DBusException:
pass
<|fim▁end|>
|
self.plugin_on_unpaused()
|
<|file_name|>inhibit.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2011 Christoph Reiter <reiter.christoph@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
import os
import sys
if os.name == "nt" or sys.platform == "darwin":
from quodlibet.plugins import PluginNotSupportedError
raise PluginNotSupportedError
import dbus
from quodlibet import _
from quodlibet import app
from quodlibet.qltk import Icons
from quodlibet.plugins.events import EventPlugin
def get_toplevel_xid():
if app.window.get_window():
try:
return app.window.get_window().get_xid()
except AttributeError: # non x11
pass
return 0
class InhibitFlags(object):
LOGOUT = 1
USERSWITCH = 1 << 1
SUSPEND = 1 << 2
IDLE = 1 << 3
class SessionInhibit(EventPlugin):
PLUGIN_ID = "screensaver_inhibit"
PLUGIN_NAME = _("Inhibit Screensaver")
PLUGIN_DESC = _("Prevents the GNOME screensaver from activating while"
" a song is playing.")
PLUGIN_ICON = Icons.PREFERENCES_DESKTOP_SCREENSAVER
DBUS_NAME = "org.gnome.SessionManager"
DBUS_INTERFACE = "org.gnome.SessionManager"
DBUS_PATH = "/org/gnome/SessionManager"
APPLICATION_ID = "quodlibet"
INHIBIT_REASON = _("Music is playing")
__cookie = None
def enabled(self):
if not app.player.paused:
self.plugin_on_unpaused()
def disabled(self):
if not app.player.paused:
<|fim_middle|>
def plugin_on_unpaused(self):
xid = dbus.UInt32(get_toplevel_xid())
flags = dbus.UInt32(InhibitFlags.IDLE)
try:
bus = dbus.SessionBus()
obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH)
iface = dbus.Interface(obj, self.DBUS_INTERFACE)
self.__cookie = iface.Inhibit(
self.APPLICATION_ID, xid, self.INHIBIT_REASON, flags)
except dbus.DBusException:
pass
def plugin_on_paused(self):
if self.__cookie is None:
return
try:
bus = dbus.SessionBus()
obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH)
iface = dbus.Interface(obj, self.DBUS_INTERFACE)
iface.Uninhibit(self.__cookie)
self.__cookie = None
except dbus.DBusException:
pass
<|fim▁end|>
|
self.plugin_on_paused()
|
<|file_name|>inhibit.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2011 Christoph Reiter <reiter.christoph@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
import os
import sys
if os.name == "nt" or sys.platform == "darwin":
from quodlibet.plugins import PluginNotSupportedError
raise PluginNotSupportedError
import dbus
from quodlibet import _
from quodlibet import app
from quodlibet.qltk import Icons
from quodlibet.plugins.events import EventPlugin
def get_toplevel_xid():
if app.window.get_window():
try:
return app.window.get_window().get_xid()
except AttributeError: # non x11
pass
return 0
class InhibitFlags(object):
LOGOUT = 1
USERSWITCH = 1 << 1
SUSPEND = 1 << 2
IDLE = 1 << 3
class SessionInhibit(EventPlugin):
PLUGIN_ID = "screensaver_inhibit"
PLUGIN_NAME = _("Inhibit Screensaver")
PLUGIN_DESC = _("Prevents the GNOME screensaver from activating while"
" a song is playing.")
PLUGIN_ICON = Icons.PREFERENCES_DESKTOP_SCREENSAVER
DBUS_NAME = "org.gnome.SessionManager"
DBUS_INTERFACE = "org.gnome.SessionManager"
DBUS_PATH = "/org/gnome/SessionManager"
APPLICATION_ID = "quodlibet"
INHIBIT_REASON = _("Music is playing")
__cookie = None
def enabled(self):
if not app.player.paused:
self.plugin_on_unpaused()
def disabled(self):
if not app.player.paused:
self.plugin_on_paused()
def plugin_on_unpaused(self):
xid = dbus.UInt32(get_toplevel_xid())
flags = dbus.UInt32(InhibitFlags.IDLE)
try:
bus = dbus.SessionBus()
obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH)
iface = dbus.Interface(obj, self.DBUS_INTERFACE)
self.__cookie = iface.Inhibit(
self.APPLICATION_ID, xid, self.INHIBIT_REASON, flags)
except dbus.DBusException:
pass
def plugin_on_paused(self):
if self.__cookie is None:
<|fim_middle|>
try:
bus = dbus.SessionBus()
obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH)
iface = dbus.Interface(obj, self.DBUS_INTERFACE)
iface.Uninhibit(self.__cookie)
self.__cookie = None
except dbus.DBusException:
pass
<|fim▁end|>
|
return
|
<|file_name|>inhibit.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2011 Christoph Reiter <reiter.christoph@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
import os
import sys
if os.name == "nt" or sys.platform == "darwin":
from quodlibet.plugins import PluginNotSupportedError
raise PluginNotSupportedError
import dbus
from quodlibet import _
from quodlibet import app
from quodlibet.qltk import Icons
from quodlibet.plugins.events import EventPlugin
def <|fim_middle|>():
if app.window.get_window():
try:
return app.window.get_window().get_xid()
except AttributeError: # non x11
pass
return 0
class InhibitFlags(object):
LOGOUT = 1
USERSWITCH = 1 << 1
SUSPEND = 1 << 2
IDLE = 1 << 3
class SessionInhibit(EventPlugin):
PLUGIN_ID = "screensaver_inhibit"
PLUGIN_NAME = _("Inhibit Screensaver")
PLUGIN_DESC = _("Prevents the GNOME screensaver from activating while"
" a song is playing.")
PLUGIN_ICON = Icons.PREFERENCES_DESKTOP_SCREENSAVER
DBUS_NAME = "org.gnome.SessionManager"
DBUS_INTERFACE = "org.gnome.SessionManager"
DBUS_PATH = "/org/gnome/SessionManager"
APPLICATION_ID = "quodlibet"
INHIBIT_REASON = _("Music is playing")
__cookie = None
def enabled(self):
if not app.player.paused:
self.plugin_on_unpaused()
def disabled(self):
if not app.player.paused:
self.plugin_on_paused()
def plugin_on_unpaused(self):
xid = dbus.UInt32(get_toplevel_xid())
flags = dbus.UInt32(InhibitFlags.IDLE)
try:
bus = dbus.SessionBus()
obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH)
iface = dbus.Interface(obj, self.DBUS_INTERFACE)
self.__cookie = iface.Inhibit(
self.APPLICATION_ID, xid, self.INHIBIT_REASON, flags)
except dbus.DBusException:
pass
def plugin_on_paused(self):
if self.__cookie is None:
return
try:
bus = dbus.SessionBus()
obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH)
iface = dbus.Interface(obj, self.DBUS_INTERFACE)
iface.Uninhibit(self.__cookie)
self.__cookie = None
except dbus.DBusException:
pass
<|fim▁end|>
|
get_toplevel_xid
|
<|file_name|>inhibit.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2011 Christoph Reiter <reiter.christoph@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
import os
import sys
if os.name == "nt" or sys.platform == "darwin":
from quodlibet.plugins import PluginNotSupportedError
raise PluginNotSupportedError
import dbus
from quodlibet import _
from quodlibet import app
from quodlibet.qltk import Icons
from quodlibet.plugins.events import EventPlugin
def get_toplevel_xid():
if app.window.get_window():
try:
return app.window.get_window().get_xid()
except AttributeError: # non x11
pass
return 0
class InhibitFlags(object):
LOGOUT = 1
USERSWITCH = 1 << 1
SUSPEND = 1 << 2
IDLE = 1 << 3
class SessionInhibit(EventPlugin):
PLUGIN_ID = "screensaver_inhibit"
PLUGIN_NAME = _("Inhibit Screensaver")
PLUGIN_DESC = _("Prevents the GNOME screensaver from activating while"
" a song is playing.")
PLUGIN_ICON = Icons.PREFERENCES_DESKTOP_SCREENSAVER
DBUS_NAME = "org.gnome.SessionManager"
DBUS_INTERFACE = "org.gnome.SessionManager"
DBUS_PATH = "/org/gnome/SessionManager"
APPLICATION_ID = "quodlibet"
INHIBIT_REASON = _("Music is playing")
__cookie = None
def <|fim_middle|>(self):
if not app.player.paused:
self.plugin_on_unpaused()
def disabled(self):
if not app.player.paused:
self.plugin_on_paused()
def plugin_on_unpaused(self):
xid = dbus.UInt32(get_toplevel_xid())
flags = dbus.UInt32(InhibitFlags.IDLE)
try:
bus = dbus.SessionBus()
obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH)
iface = dbus.Interface(obj, self.DBUS_INTERFACE)
self.__cookie = iface.Inhibit(
self.APPLICATION_ID, xid, self.INHIBIT_REASON, flags)
except dbus.DBusException:
pass
def plugin_on_paused(self):
if self.__cookie is None:
return
try:
bus = dbus.SessionBus()
obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH)
iface = dbus.Interface(obj, self.DBUS_INTERFACE)
iface.Uninhibit(self.__cookie)
self.__cookie = None
except dbus.DBusException:
pass
<|fim▁end|>
|
enabled
|
<|file_name|>inhibit.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2011 Christoph Reiter <reiter.christoph@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
import os
import sys
if os.name == "nt" or sys.platform == "darwin":
from quodlibet.plugins import PluginNotSupportedError
raise PluginNotSupportedError
import dbus
from quodlibet import _
from quodlibet import app
from quodlibet.qltk import Icons
from quodlibet.plugins.events import EventPlugin
def get_toplevel_xid():
if app.window.get_window():
try:
return app.window.get_window().get_xid()
except AttributeError: # non x11
pass
return 0
class InhibitFlags(object):
LOGOUT = 1
USERSWITCH = 1 << 1
SUSPEND = 1 << 2
IDLE = 1 << 3
class SessionInhibit(EventPlugin):
PLUGIN_ID = "screensaver_inhibit"
PLUGIN_NAME = _("Inhibit Screensaver")
PLUGIN_DESC = _("Prevents the GNOME screensaver from activating while"
" a song is playing.")
PLUGIN_ICON = Icons.PREFERENCES_DESKTOP_SCREENSAVER
DBUS_NAME = "org.gnome.SessionManager"
DBUS_INTERFACE = "org.gnome.SessionManager"
DBUS_PATH = "/org/gnome/SessionManager"
APPLICATION_ID = "quodlibet"
INHIBIT_REASON = _("Music is playing")
__cookie = None
def enabled(self):
if not app.player.paused:
self.plugin_on_unpaused()
def <|fim_middle|>(self):
if not app.player.paused:
self.plugin_on_paused()
def plugin_on_unpaused(self):
xid = dbus.UInt32(get_toplevel_xid())
flags = dbus.UInt32(InhibitFlags.IDLE)
try:
bus = dbus.SessionBus()
obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH)
iface = dbus.Interface(obj, self.DBUS_INTERFACE)
self.__cookie = iface.Inhibit(
self.APPLICATION_ID, xid, self.INHIBIT_REASON, flags)
except dbus.DBusException:
pass
def plugin_on_paused(self):
if self.__cookie is None:
return
try:
bus = dbus.SessionBus()
obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH)
iface = dbus.Interface(obj, self.DBUS_INTERFACE)
iface.Uninhibit(self.__cookie)
self.__cookie = None
except dbus.DBusException:
pass
<|fim▁end|>
|
disabled
|
<|file_name|>inhibit.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2011 Christoph Reiter <reiter.christoph@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
import os
import sys
if os.name == "nt" or sys.platform == "darwin":
from quodlibet.plugins import PluginNotSupportedError
raise PluginNotSupportedError
import dbus
from quodlibet import _
from quodlibet import app
from quodlibet.qltk import Icons
from quodlibet.plugins.events import EventPlugin
def get_toplevel_xid():
if app.window.get_window():
try:
return app.window.get_window().get_xid()
except AttributeError: # non x11
pass
return 0
class InhibitFlags(object):
LOGOUT = 1
USERSWITCH = 1 << 1
SUSPEND = 1 << 2
IDLE = 1 << 3
class SessionInhibit(EventPlugin):
PLUGIN_ID = "screensaver_inhibit"
PLUGIN_NAME = _("Inhibit Screensaver")
PLUGIN_DESC = _("Prevents the GNOME screensaver from activating while"
" a song is playing.")
PLUGIN_ICON = Icons.PREFERENCES_DESKTOP_SCREENSAVER
DBUS_NAME = "org.gnome.SessionManager"
DBUS_INTERFACE = "org.gnome.SessionManager"
DBUS_PATH = "/org/gnome/SessionManager"
APPLICATION_ID = "quodlibet"
INHIBIT_REASON = _("Music is playing")
__cookie = None
def enabled(self):
if not app.player.paused:
self.plugin_on_unpaused()
def disabled(self):
if not app.player.paused:
self.plugin_on_paused()
def <|fim_middle|>(self):
xid = dbus.UInt32(get_toplevel_xid())
flags = dbus.UInt32(InhibitFlags.IDLE)
try:
bus = dbus.SessionBus()
obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH)
iface = dbus.Interface(obj, self.DBUS_INTERFACE)
self.__cookie = iface.Inhibit(
self.APPLICATION_ID, xid, self.INHIBIT_REASON, flags)
except dbus.DBusException:
pass
def plugin_on_paused(self):
if self.__cookie is None:
return
try:
bus = dbus.SessionBus()
obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH)
iface = dbus.Interface(obj, self.DBUS_INTERFACE)
iface.Uninhibit(self.__cookie)
self.__cookie = None
except dbus.DBusException:
pass
<|fim▁end|>
|
plugin_on_unpaused
|
<|file_name|>inhibit.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2011 Christoph Reiter <reiter.christoph@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
import os
import sys
if os.name == "nt" or sys.platform == "darwin":
from quodlibet.plugins import PluginNotSupportedError
raise PluginNotSupportedError
import dbus
from quodlibet import _
from quodlibet import app
from quodlibet.qltk import Icons
from quodlibet.plugins.events import EventPlugin
def get_toplevel_xid():
if app.window.get_window():
try:
return app.window.get_window().get_xid()
except AttributeError: # non x11
pass
return 0
class InhibitFlags(object):
LOGOUT = 1
USERSWITCH = 1 << 1
SUSPEND = 1 << 2
IDLE = 1 << 3
class SessionInhibit(EventPlugin):
PLUGIN_ID = "screensaver_inhibit"
PLUGIN_NAME = _("Inhibit Screensaver")
PLUGIN_DESC = _("Prevents the GNOME screensaver from activating while"
" a song is playing.")
PLUGIN_ICON = Icons.PREFERENCES_DESKTOP_SCREENSAVER
DBUS_NAME = "org.gnome.SessionManager"
DBUS_INTERFACE = "org.gnome.SessionManager"
DBUS_PATH = "/org/gnome/SessionManager"
APPLICATION_ID = "quodlibet"
INHIBIT_REASON = _("Music is playing")
__cookie = None
def enabled(self):
if not app.player.paused:
self.plugin_on_unpaused()
def disabled(self):
if not app.player.paused:
self.plugin_on_paused()
def plugin_on_unpaused(self):
xid = dbus.UInt32(get_toplevel_xid())
flags = dbus.UInt32(InhibitFlags.IDLE)
try:
bus = dbus.SessionBus()
obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH)
iface = dbus.Interface(obj, self.DBUS_INTERFACE)
self.__cookie = iface.Inhibit(
self.APPLICATION_ID, xid, self.INHIBIT_REASON, flags)
except dbus.DBusException:
pass
def <|fim_middle|>(self):
if self.__cookie is None:
return
try:
bus = dbus.SessionBus()
obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH)
iface = dbus.Interface(obj, self.DBUS_INTERFACE)
iface.Uninhibit(self.__cookie)
self.__cookie = None
except dbus.DBusException:
pass
<|fim▁end|>
|
plugin_on_paused
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.<|fim▁hole|> """
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self<|fim▁end|>
|
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
<|fim_middle|>
<|fim▁end|>
|
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
<|fim_middle|>
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
<|fim_middle|>
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
"""Performs all stored actions."""
for action in self._actions:
action()
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
<|fim_middle|>
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
<|fim_middle|>
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
<|fim_middle|>
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
<|fim_middle|>
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
<|fim_middle|>
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
<|fim_middle|>
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
<|fim_middle|>
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
<|fim_middle|>
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
<|fim_middle|>
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
<|fim_middle|>
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
<|fim_middle|>
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
<|fim_middle|>
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
<|fim_middle|>
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
<|fim_middle|>
<|fim▁end|>
|
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: <|fim_middle|>
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
self.move_to_element(on_element)
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: <|fim_middle|>
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
self.move_to_element(on_element)
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: <|fim_middle|>
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
self.move_to_element(on_element)
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: <|fim_middle|>
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
self.move_to_element(on_element)
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: <|fim_middle|>
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
self.click(element)
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: <|fim_middle|>
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
self.click(element)
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: <|fim_middle|>
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
self.move_to_element(on_element)
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def <|fim_middle|>(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
__init__
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def <|fim_middle|>(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
perform
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def <|fim_middle|>(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
click
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def <|fim_middle|>(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
click_and_hold
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def <|fim_middle|>(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
context_click
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def <|fim_middle|>(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
double_click
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def <|fim_middle|>(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
drag_and_drop
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def <|fim_middle|>(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
drag_and_drop_by_offset
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def <|fim_middle|>(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
key_down
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def <|fim_middle|>(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
key_up
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def <|fim_middle|>(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
move_by_offset
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def <|fim_middle|>(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
move_to_element
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def <|fim_middle|>(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
move_to_element_with_offset
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def <|fim_middle|>(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
release
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def <|fim_middle|>(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
send_keys
|
<|file_name|>action_chains.py<|end_file_name|><|fim▁begin|># Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def <|fim_middle|>(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
<|fim▁end|>
|
send_keys_to_element
|
<|file_name|>test_range.py<|end_file_name|><|fim▁begin|># Authors:
# Petr Vobornik <pvoborni@redhat.com>
#
# Copyright (C) 2013 Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Range tests
"""
import ipatests.test_webui.test_trust as trust_mod
from ipatests.test_webui.ui_driver import screenshot
from ipatests.test_webui.task_range import range_tasks<|fim▁hole|>PKEY = 'itest-range'
class test_range(range_tasks):
@screenshot
def test_crud(self):
"""
Basic CRUD: range
"""
self.init_app()
self.get_shifts()
self.basic_crud(ENTITY, self.get_data(PKEY))
@screenshot
def test_types(self):
"""
Test range types
Only 'local' and 'ipa-ad-trust' types are tested since range validation
made quite hard to test the other types:
- 'ipa-ad-trust-posix' can be tested only with subdomains.
- 'ipa-ad-winsync' and 'ipa-ipa-trust' and are not supported yet
https://fedorahosted.org/freeipa/ticket/4323
"""
self.init_app()
self.get_shifts()
pkey_local = 'itest-local'
pkey_ad = 'itest-ad'
pkey_posix = 'itest-ad-posix'
pkey_winsync = 'itest-ad-winsync'
pkey_trust = 'itest-ipa-trust'
column = 'iparangetype'
add = self.get_add_data(pkey_local)
data = self.get_data(pkey_local, add_data=add)
self.add_record(ENTITY, data)
self.assert_record_value('local domain range', pkey_local, column)
if self.has_trusts():
trust_tasks = trust_mod.trust_tasks()
trust_data = trust_tasks.get_data()
self.add_record(trust_mod.ENTITY, trust_data)
domain = self.get_domain()
self.navigate_to_entity(ENTITY)
add = self.get_add_data(pkey_ad, range_type='ipa-ad-trust', domain=domain)
data = self.get_data(pkey_ad, add_data=add)
self.add_record(ENTITY, data, navigate=False)
self.assert_record_value('Active Directory domain range', pkey_ad, column)
self.delete(trust_mod.ENTITY, [trust_data])
self.navigate_to_entity(ENTITY)
self.delete_record(pkey_ad)
self.delete_record(pkey_local)<|fim▁end|>
|
ENTITY = 'idrange'
|
<|file_name|>test_range.py<|end_file_name|><|fim▁begin|># Authors:
# Petr Vobornik <pvoborni@redhat.com>
#
# Copyright (C) 2013 Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Range tests
"""
import ipatests.test_webui.test_trust as trust_mod
from ipatests.test_webui.ui_driver import screenshot
from ipatests.test_webui.task_range import range_tasks
ENTITY = 'idrange'
PKEY = 'itest-range'
class test_range(range_tasks):
<|fim_middle|>
<|fim▁end|>
|
@screenshot
def test_crud(self):
"""
Basic CRUD: range
"""
self.init_app()
self.get_shifts()
self.basic_crud(ENTITY, self.get_data(PKEY))
@screenshot
def test_types(self):
"""
Test range types
Only 'local' and 'ipa-ad-trust' types are tested since range validation
made quite hard to test the other types:
- 'ipa-ad-trust-posix' can be tested only with subdomains.
- 'ipa-ad-winsync' and 'ipa-ipa-trust' and are not supported yet
https://fedorahosted.org/freeipa/ticket/4323
"""
self.init_app()
self.get_shifts()
pkey_local = 'itest-local'
pkey_ad = 'itest-ad'
pkey_posix = 'itest-ad-posix'
pkey_winsync = 'itest-ad-winsync'
pkey_trust = 'itest-ipa-trust'
column = 'iparangetype'
add = self.get_add_data(pkey_local)
data = self.get_data(pkey_local, add_data=add)
self.add_record(ENTITY, data)
self.assert_record_value('local domain range', pkey_local, column)
if self.has_trusts():
trust_tasks = trust_mod.trust_tasks()
trust_data = trust_tasks.get_data()
self.add_record(trust_mod.ENTITY, trust_data)
domain = self.get_domain()
self.navigate_to_entity(ENTITY)
add = self.get_add_data(pkey_ad, range_type='ipa-ad-trust', domain=domain)
data = self.get_data(pkey_ad, add_data=add)
self.add_record(ENTITY, data, navigate=False)
self.assert_record_value('Active Directory domain range', pkey_ad, column)
self.delete(trust_mod.ENTITY, [trust_data])
self.navigate_to_entity(ENTITY)
self.delete_record(pkey_ad)
self.delete_record(pkey_local)
|
<|file_name|>test_range.py<|end_file_name|><|fim▁begin|># Authors:
# Petr Vobornik <pvoborni@redhat.com>
#
# Copyright (C) 2013 Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Range tests
"""
import ipatests.test_webui.test_trust as trust_mod
from ipatests.test_webui.ui_driver import screenshot
from ipatests.test_webui.task_range import range_tasks
ENTITY = 'idrange'
PKEY = 'itest-range'
class test_range(range_tasks):
@screenshot
def test_crud(self):
<|fim_middle|>
@screenshot
def test_types(self):
"""
Test range types
Only 'local' and 'ipa-ad-trust' types are tested since range validation
made quite hard to test the other types:
- 'ipa-ad-trust-posix' can be tested only with subdomains.
- 'ipa-ad-winsync' and 'ipa-ipa-trust' and are not supported yet
https://fedorahosted.org/freeipa/ticket/4323
"""
self.init_app()
self.get_shifts()
pkey_local = 'itest-local'
pkey_ad = 'itest-ad'
pkey_posix = 'itest-ad-posix'
pkey_winsync = 'itest-ad-winsync'
pkey_trust = 'itest-ipa-trust'
column = 'iparangetype'
add = self.get_add_data(pkey_local)
data = self.get_data(pkey_local, add_data=add)
self.add_record(ENTITY, data)
self.assert_record_value('local domain range', pkey_local, column)
if self.has_trusts():
trust_tasks = trust_mod.trust_tasks()
trust_data = trust_tasks.get_data()
self.add_record(trust_mod.ENTITY, trust_data)
domain = self.get_domain()
self.navigate_to_entity(ENTITY)
add = self.get_add_data(pkey_ad, range_type='ipa-ad-trust', domain=domain)
data = self.get_data(pkey_ad, add_data=add)
self.add_record(ENTITY, data, navigate=False)
self.assert_record_value('Active Directory domain range', pkey_ad, column)
self.delete(trust_mod.ENTITY, [trust_data])
self.navigate_to_entity(ENTITY)
self.delete_record(pkey_ad)
self.delete_record(pkey_local)
<|fim▁end|>
|
"""
Basic CRUD: range
"""
self.init_app()
self.get_shifts()
self.basic_crud(ENTITY, self.get_data(PKEY))
|
<|file_name|>test_range.py<|end_file_name|><|fim▁begin|># Authors:
# Petr Vobornik <pvoborni@redhat.com>
#
# Copyright (C) 2013 Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Range tests
"""
import ipatests.test_webui.test_trust as trust_mod
from ipatests.test_webui.ui_driver import screenshot
from ipatests.test_webui.task_range import range_tasks
ENTITY = 'idrange'
PKEY = 'itest-range'
class test_range(range_tasks):
@screenshot
def test_crud(self):
"""
Basic CRUD: range
"""
self.init_app()
self.get_shifts()
self.basic_crud(ENTITY, self.get_data(PKEY))
@screenshot
def test_types(self):
<|fim_middle|>
<|fim▁end|>
|
"""
Test range types
Only 'local' and 'ipa-ad-trust' types are tested since range validation
made quite hard to test the other types:
- 'ipa-ad-trust-posix' can be tested only with subdomains.
- 'ipa-ad-winsync' and 'ipa-ipa-trust' and are not supported yet
https://fedorahosted.org/freeipa/ticket/4323
"""
self.init_app()
self.get_shifts()
pkey_local = 'itest-local'
pkey_ad = 'itest-ad'
pkey_posix = 'itest-ad-posix'
pkey_winsync = 'itest-ad-winsync'
pkey_trust = 'itest-ipa-trust'
column = 'iparangetype'
add = self.get_add_data(pkey_local)
data = self.get_data(pkey_local, add_data=add)
self.add_record(ENTITY, data)
self.assert_record_value('local domain range', pkey_local, column)
if self.has_trusts():
trust_tasks = trust_mod.trust_tasks()
trust_data = trust_tasks.get_data()
self.add_record(trust_mod.ENTITY, trust_data)
domain = self.get_domain()
self.navigate_to_entity(ENTITY)
add = self.get_add_data(pkey_ad, range_type='ipa-ad-trust', domain=domain)
data = self.get_data(pkey_ad, add_data=add)
self.add_record(ENTITY, data, navigate=False)
self.assert_record_value('Active Directory domain range', pkey_ad, column)
self.delete(trust_mod.ENTITY, [trust_data])
self.navigate_to_entity(ENTITY)
self.delete_record(pkey_ad)
self.delete_record(pkey_local)
|
<|file_name|>test_range.py<|end_file_name|><|fim▁begin|># Authors:
# Petr Vobornik <pvoborni@redhat.com>
#
# Copyright (C) 2013 Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Range tests
"""
import ipatests.test_webui.test_trust as trust_mod
from ipatests.test_webui.ui_driver import screenshot
from ipatests.test_webui.task_range import range_tasks
ENTITY = 'idrange'
PKEY = 'itest-range'
class test_range(range_tasks):
@screenshot
def test_crud(self):
"""
Basic CRUD: range
"""
self.init_app()
self.get_shifts()
self.basic_crud(ENTITY, self.get_data(PKEY))
@screenshot
def test_types(self):
"""
Test range types
Only 'local' and 'ipa-ad-trust' types are tested since range validation
made quite hard to test the other types:
- 'ipa-ad-trust-posix' can be tested only with subdomains.
- 'ipa-ad-winsync' and 'ipa-ipa-trust' and are not supported yet
https://fedorahosted.org/freeipa/ticket/4323
"""
self.init_app()
self.get_shifts()
pkey_local = 'itest-local'
pkey_ad = 'itest-ad'
pkey_posix = 'itest-ad-posix'
pkey_winsync = 'itest-ad-winsync'
pkey_trust = 'itest-ipa-trust'
column = 'iparangetype'
add = self.get_add_data(pkey_local)
data = self.get_data(pkey_local, add_data=add)
self.add_record(ENTITY, data)
self.assert_record_value('local domain range', pkey_local, column)
if self.has_trusts():
<|fim_middle|>
self.delete_record(pkey_local)
<|fim▁end|>
|
trust_tasks = trust_mod.trust_tasks()
trust_data = trust_tasks.get_data()
self.add_record(trust_mod.ENTITY, trust_data)
domain = self.get_domain()
self.navigate_to_entity(ENTITY)
add = self.get_add_data(pkey_ad, range_type='ipa-ad-trust', domain=domain)
data = self.get_data(pkey_ad, add_data=add)
self.add_record(ENTITY, data, navigate=False)
self.assert_record_value('Active Directory domain range', pkey_ad, column)
self.delete(trust_mod.ENTITY, [trust_data])
self.navigate_to_entity(ENTITY)
self.delete_record(pkey_ad)
|
<|file_name|>test_range.py<|end_file_name|><|fim▁begin|># Authors:
# Petr Vobornik <pvoborni@redhat.com>
#
# Copyright (C) 2013 Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Range tests
"""
import ipatests.test_webui.test_trust as trust_mod
from ipatests.test_webui.ui_driver import screenshot
from ipatests.test_webui.task_range import range_tasks
ENTITY = 'idrange'
PKEY = 'itest-range'
class test_range(range_tasks):
@screenshot
def <|fim_middle|>(self):
"""
Basic CRUD: range
"""
self.init_app()
self.get_shifts()
self.basic_crud(ENTITY, self.get_data(PKEY))
@screenshot
def test_types(self):
"""
Test range types
Only 'local' and 'ipa-ad-trust' types are tested since range validation
made quite hard to test the other types:
- 'ipa-ad-trust-posix' can be tested only with subdomains.
- 'ipa-ad-winsync' and 'ipa-ipa-trust' and are not supported yet
https://fedorahosted.org/freeipa/ticket/4323
"""
self.init_app()
self.get_shifts()
pkey_local = 'itest-local'
pkey_ad = 'itest-ad'
pkey_posix = 'itest-ad-posix'
pkey_winsync = 'itest-ad-winsync'
pkey_trust = 'itest-ipa-trust'
column = 'iparangetype'
add = self.get_add_data(pkey_local)
data = self.get_data(pkey_local, add_data=add)
self.add_record(ENTITY, data)
self.assert_record_value('local domain range', pkey_local, column)
if self.has_trusts():
trust_tasks = trust_mod.trust_tasks()
trust_data = trust_tasks.get_data()
self.add_record(trust_mod.ENTITY, trust_data)
domain = self.get_domain()
self.navigate_to_entity(ENTITY)
add = self.get_add_data(pkey_ad, range_type='ipa-ad-trust', domain=domain)
data = self.get_data(pkey_ad, add_data=add)
self.add_record(ENTITY, data, navigate=False)
self.assert_record_value('Active Directory domain range', pkey_ad, column)
self.delete(trust_mod.ENTITY, [trust_data])
self.navigate_to_entity(ENTITY)
self.delete_record(pkey_ad)
self.delete_record(pkey_local)
<|fim▁end|>
|
test_crud
|
<|file_name|>test_range.py<|end_file_name|><|fim▁begin|># Authors:
# Petr Vobornik <pvoborni@redhat.com>
#
# Copyright (C) 2013 Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Range tests
"""
import ipatests.test_webui.test_trust as trust_mod
from ipatests.test_webui.ui_driver import screenshot
from ipatests.test_webui.task_range import range_tasks
ENTITY = 'idrange'
PKEY = 'itest-range'
class test_range(range_tasks):
@screenshot
def test_crud(self):
"""
Basic CRUD: range
"""
self.init_app()
self.get_shifts()
self.basic_crud(ENTITY, self.get_data(PKEY))
@screenshot
def <|fim_middle|>(self):
"""
Test range types
Only 'local' and 'ipa-ad-trust' types are tested since range validation
made quite hard to test the other types:
- 'ipa-ad-trust-posix' can be tested only with subdomains.
- 'ipa-ad-winsync' and 'ipa-ipa-trust' and are not supported yet
https://fedorahosted.org/freeipa/ticket/4323
"""
self.init_app()
self.get_shifts()
pkey_local = 'itest-local'
pkey_ad = 'itest-ad'
pkey_posix = 'itest-ad-posix'
pkey_winsync = 'itest-ad-winsync'
pkey_trust = 'itest-ipa-trust'
column = 'iparangetype'
add = self.get_add_data(pkey_local)
data = self.get_data(pkey_local, add_data=add)
self.add_record(ENTITY, data)
self.assert_record_value('local domain range', pkey_local, column)
if self.has_trusts():
trust_tasks = trust_mod.trust_tasks()
trust_data = trust_tasks.get_data()
self.add_record(trust_mod.ENTITY, trust_data)
domain = self.get_domain()
self.navigate_to_entity(ENTITY)
add = self.get_add_data(pkey_ad, range_type='ipa-ad-trust', domain=domain)
data = self.get_data(pkey_ad, add_data=add)
self.add_record(ENTITY, data, navigate=False)
self.assert_record_value('Active Directory domain range', pkey_ad, column)
self.delete(trust_mod.ENTITY, [trust_data])
self.navigate_to_entity(ENTITY)
self.delete_record(pkey_ad)
self.delete_record(pkey_local)
<|fim▁end|>
|
test_types
|
<|file_name|>test_server.py<|end_file_name|><|fim▁begin|># Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from common_openstack import OpenStackTest
class ServerTest(OpenStackTest):
def test_server_query(self):
factory = self.replay_flight_data()
p = self.load_policy({
'name': 'all-servers',
'resource': 'openstack.server'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 2)
def test_server_filter_name(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "value",
"key": "name",
"value": "c7n-test-1",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-1")
def test_server_filter_flavor(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "flavor",
"flavor_name": "m1.tiny",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-1")
def test_server_filter_tags(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "tags",
"tags": [
{
"key": "a",
"value": "a",
},
{
"key": "b",
"value": "b",
},
],
"op": "all",
},
],
}<|fim▁hole|> resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-2")<|fim▁end|>
|
p = self.load_policy(policy, session_factory=factory)
|
<|file_name|>test_server.py<|end_file_name|><|fim▁begin|># Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from common_openstack import OpenStackTest
class ServerTest(OpenStackTest):
<|fim_middle|>
<|fim▁end|>
|
def test_server_query(self):
factory = self.replay_flight_data()
p = self.load_policy({
'name': 'all-servers',
'resource': 'openstack.server'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 2)
def test_server_filter_name(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "value",
"key": "name",
"value": "c7n-test-1",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-1")
def test_server_filter_flavor(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "flavor",
"flavor_name": "m1.tiny",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-1")
def test_server_filter_tags(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "tags",
"tags": [
{
"key": "a",
"value": "a",
},
{
"key": "b",
"value": "b",
},
],
"op": "all",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-2")
|
<|file_name|>test_server.py<|end_file_name|><|fim▁begin|># Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from common_openstack import OpenStackTest
class ServerTest(OpenStackTest):
def test_server_query(self):
<|fim_middle|>
def test_server_filter_name(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "value",
"key": "name",
"value": "c7n-test-1",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-1")
def test_server_filter_flavor(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "flavor",
"flavor_name": "m1.tiny",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-1")
def test_server_filter_tags(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "tags",
"tags": [
{
"key": "a",
"value": "a",
},
{
"key": "b",
"value": "b",
},
],
"op": "all",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-2")
<|fim▁end|>
|
factory = self.replay_flight_data()
p = self.load_policy({
'name': 'all-servers',
'resource': 'openstack.server'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 2)
|
<|file_name|>test_server.py<|end_file_name|><|fim▁begin|># Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from common_openstack import OpenStackTest
class ServerTest(OpenStackTest):
def test_server_query(self):
factory = self.replay_flight_data()
p = self.load_policy({
'name': 'all-servers',
'resource': 'openstack.server'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 2)
def test_server_filter_name(self):
<|fim_middle|>
def test_server_filter_flavor(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "flavor",
"flavor_name": "m1.tiny",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-1")
def test_server_filter_tags(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "tags",
"tags": [
{
"key": "a",
"value": "a",
},
{
"key": "b",
"value": "b",
},
],
"op": "all",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-2")
<|fim▁end|>
|
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "value",
"key": "name",
"value": "c7n-test-1",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-1")
|
<|file_name|>test_server.py<|end_file_name|><|fim▁begin|># Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from common_openstack import OpenStackTest
class ServerTest(OpenStackTest):
def test_server_query(self):
factory = self.replay_flight_data()
p = self.load_policy({
'name': 'all-servers',
'resource': 'openstack.server'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 2)
def test_server_filter_name(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "value",
"key": "name",
"value": "c7n-test-1",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-1")
def test_server_filter_flavor(self):
<|fim_middle|>
def test_server_filter_tags(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "tags",
"tags": [
{
"key": "a",
"value": "a",
},
{
"key": "b",
"value": "b",
},
],
"op": "all",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-2")
<|fim▁end|>
|
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "flavor",
"flavor_name": "m1.tiny",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-1")
|
<|file_name|>test_server.py<|end_file_name|><|fim▁begin|># Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from common_openstack import OpenStackTest
class ServerTest(OpenStackTest):
def test_server_query(self):
factory = self.replay_flight_data()
p = self.load_policy({
'name': 'all-servers',
'resource': 'openstack.server'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 2)
def test_server_filter_name(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "value",
"key": "name",
"value": "c7n-test-1",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-1")
def test_server_filter_flavor(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "flavor",
"flavor_name": "m1.tiny",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-1")
def test_server_filter_tags(self):
<|fim_middle|>
<|fim▁end|>
|
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "tags",
"tags": [
{
"key": "a",
"value": "a",
},
{
"key": "b",
"value": "b",
},
],
"op": "all",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-2")
|
<|file_name|>test_server.py<|end_file_name|><|fim▁begin|># Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from common_openstack import OpenStackTest
class ServerTest(OpenStackTest):
def <|fim_middle|>(self):
factory = self.replay_flight_data()
p = self.load_policy({
'name': 'all-servers',
'resource': 'openstack.server'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 2)
def test_server_filter_name(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "value",
"key": "name",
"value": "c7n-test-1",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-1")
def test_server_filter_flavor(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "flavor",
"flavor_name": "m1.tiny",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-1")
def test_server_filter_tags(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "tags",
"tags": [
{
"key": "a",
"value": "a",
},
{
"key": "b",
"value": "b",
},
],
"op": "all",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-2")
<|fim▁end|>
|
test_server_query
|
<|file_name|>test_server.py<|end_file_name|><|fim▁begin|># Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from common_openstack import OpenStackTest
class ServerTest(OpenStackTest):
def test_server_query(self):
factory = self.replay_flight_data()
p = self.load_policy({
'name': 'all-servers',
'resource': 'openstack.server'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 2)
def <|fim_middle|>(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "value",
"key": "name",
"value": "c7n-test-1",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-1")
def test_server_filter_flavor(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "flavor",
"flavor_name": "m1.tiny",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-1")
def test_server_filter_tags(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "tags",
"tags": [
{
"key": "a",
"value": "a",
},
{
"key": "b",
"value": "b",
},
],
"op": "all",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-2")
<|fim▁end|>
|
test_server_filter_name
|
<|file_name|>test_server.py<|end_file_name|><|fim▁begin|># Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from common_openstack import OpenStackTest
class ServerTest(OpenStackTest):
def test_server_query(self):
factory = self.replay_flight_data()
p = self.load_policy({
'name': 'all-servers',
'resource': 'openstack.server'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 2)
def test_server_filter_name(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "value",
"key": "name",
"value": "c7n-test-1",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-1")
def <|fim_middle|>(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "flavor",
"flavor_name": "m1.tiny",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-1")
def test_server_filter_tags(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "tags",
"tags": [
{
"key": "a",
"value": "a",
},
{
"key": "b",
"value": "b",
},
],
"op": "all",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-2")
<|fim▁end|>
|
test_server_filter_flavor
|
<|file_name|>test_server.py<|end_file_name|><|fim▁begin|># Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from common_openstack import OpenStackTest
class ServerTest(OpenStackTest):
def test_server_query(self):
factory = self.replay_flight_data()
p = self.load_policy({
'name': 'all-servers',
'resource': 'openstack.server'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 2)
def test_server_filter_name(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "value",
"key": "name",
"value": "c7n-test-1",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-1")
def test_server_filter_flavor(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "flavor",
"flavor_name": "m1.tiny",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-1")
def <|fim_middle|>(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
{
"type": "tags",
"tags": [
{
"key": "a",
"value": "a",
},
{
"key": "b",
"value": "b",
},
],
"op": "all",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-2")
<|fim▁end|>
|
test_server_filter_tags
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop<|fim▁hole|> # TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data<|fim▁end|>
| |
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
<|fim_middle|>
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
<|fim_middle|>
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
<|fim_middle|>
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
<|fim_middle|>
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
<|fim_middle|>
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
<|fim_middle|>
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
<|fim_middle|>
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
<|fim_middle|>
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
<|fim_middle|>
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
<|fim_middle|>
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
<|fim_middle|>
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
<|fim_middle|>
<|fim▁end|>
|
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
<|fim_middle|>
<|fim▁end|>
|
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
<|fim_middle|>
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
<|fim_middle|>
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
<|fim_middle|>
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
<|fim_middle|>
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
<|fim_middle|>
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
return validation_helper(self, content)
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
<|fim_middle|>
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
return content
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
<|fim_middle|>
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
raise forms.ValidationError(_("You can't start a day before itself"))
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
<|fim_middle|>
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
raise forms.ValidationError(_("You can't start a day after itself"))
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
<|fim_middle|>
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
<|fim_middle|>
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
raise forms.ValidationError(_("Stop time can't be more than the next day"))
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
<|fim_middle|>
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
raise forms.ValidationError(_("Worked days require a content text"))
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
<|fim_middle|>
return cleaned_data
<|fim▁end|>
|
raise forms.ValidationError(_("This day entry has allready been created"))
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def <|fim_middle|>(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
fill_initial_data
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def <|fim_middle|>(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
init_fields
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def <|fim_middle|>(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
clean_content
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def <|fim_middle|>(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
clean_start_datetime
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def <|fim_middle|>(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
clean_stop_datetime
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def <|fim_middle|>(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
__init__
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def <|fim_middle|>(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def save(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
clean
|
<|file_name|>day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module
DATETIME_FORMATS = {
'input_date_formats': ['%d/%m/%Y'],
'input_time_formats': ['%H:%M'],
'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'),
}
class DayBaseFormMixin(object):
"""
DayBase form mixin
"""
crispy_form_helper_path = 'datebook.forms.crispies.day_helper'
crispy_form_helper_kwargs = {}
def fill_initial_data(self, *args, **kwargs):
# Pass initial data for start and stop to their SplitDateTimeField clones
if 'start' in kwargs['initial']:
kwargs['initial']['start_datetime'] = kwargs['initial']['start']
if 'stop' in kwargs['initial']:
kwargs['initial']['stop_datetime'] = kwargs['initial']['stop']
# For existing instance (in edit mode) pass the start and stop values to their
# clone with SplitDateTimeField via initial datas
if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS)
self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS)
# Set the form field for DayEntry.content
field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH)
if field_helper is not None:
self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False})
def clean_content(self):
"""
Text content validation
"""
content = self.cleaned_data.get("content")
validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, content)
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before itself"))
# Day entry can't start after the targeted day date
if start and start.date() > self.daydate:
raise forms.ValidationError(_("You can't start a day after itself"))
return start
def clean_stop_datetime(self):
start = self.cleaned_data.get('start_datetime')
stop = self.cleaned_data['stop_datetime']
# Day entry can't stop before the start
if start and stop and stop <= start:
raise forms.ValidationError(_("Stop time can't be less or equal to start time"))
# Day entry can't stop in more than one futur day from the targeted day date
if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date():
raise forms.ValidationError(_("Stop time can't be more than the next day"))
return stop
# TODO: overtime must not be more than effective worked time
#def clean_overtime(self):
#overtime = self.cleaned_data.get('overtime')
#return overtime
# TODO
#def clean_pause(self):
#start = self.cleaned_data.get('start_datetime')
#stop = self.cleaned_data.get('stop_datetime')
#pause = self.cleaned_data['pause']
## Pause time can't be more than elapsed time between start and stop
#if start and stop and pause and False:
#raise forms.ValidationError("Pause time is more than the elapsed time")
#return pause
class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm):
"""
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url': kwargs.pop('day_to_model_url', None),
'form_action': kwargs.pop('form_action'),
'remove_url': kwargs.pop('remove_url', None),
})
# Fill initial datas
kwargs = self.fill_initial_data(*args, **kwargs)
super(DayEntryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs)
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when vacation is not checked
if not vacation and not content:
raise forms.ValidationError(_("Worked days require a content text"))
return cleaned_data
def <|fim_middle|>(self, *args, **kwargs):
instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs)
instance.start = self.cleaned_data['start_datetime']
instance.stop = self.cleaned_data['stop_datetime']
instance.datebook = self.datebook
instance.activity_date = self.daydate
instance.save()
return instance
class Meta:
model = DayEntry
exclude = ('datebook', 'activity_date', 'start', 'stop')
widgets = {
'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]),
}
class DayEntryCreateForm(DayEntryForm):
def clean(self):
cleaned_data = super(DayEntryCreateForm, self).clean()
# Validate that there is not allready a day entry for the same day
try:
obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate)
except DayEntry.DoesNotExist:
pass
else:
raise forms.ValidationError(_("This day entry has allready been created"))
return cleaned_data
<|fim▁end|>
|
save
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.