Automatically install default content types in tests on Plone 5 - testing

I've been trying to add compatibility with Plone 5 in some of our add-ons and I found a pattern that I want to avoid: seem that I have to manually install default content types on test fixture like this:
...
PLONE_VERSION = api.env.plone_version()
class Fixture(PloneSandboxLayer):
defaultBases = (PLONE_FIXTURE,)
def setUpZope(self, app, configurationContext):
if PLONE_VERSION >= '5.0':
import plone.app.contenttypes
self.loadZCML(package=plone.app.contenttypes)
...
def setUpPloneSite(self, portal):
if PLONE_VERSION >= '5.0':
self.applyProfile(portal, 'plone.app.contenttypes:default')
...
FIXTURE = Fixture()
...
Is there any way to avoid this?

As far as I remember it is enough to depend on PLONE_APP_CONTENTTYPES_FIXTURE.
Something like this (untested):
try:
from plone.app.contenttypes.testing import PLONE_APP_CONTENTTYPES_FIXTURE
except ImportError:
PLONE_APP_CONTENTTYPES_FIXTURE = None
class Fixture(PloneSandboxLayer):
if PLONE_VERSION >= '5.0':
defaultBases = (PLONE_APP_CONTENTTYPES_FIXTURE,)
else:
defaultBases = (PLONE_FIXTURE,)

Related

ValueError: <module 'random' from 'C:...anaconda3\\lib\\random.py'> cannot be used to seed a numpy.random.RandomState instance

I am trying to perform the automatic clustering with the UMAP.
I am using the r wrapper function of UMAP, with all the requirements satisfied but unfortunately I cannot set the seed into the umapr function. i tried to run the code:
`hspace = {
"n_neighbors": hp.choice('n_neighbors', range(3,32)),
"n_components": hp.choice('n_components', range(3,32)),
"min_cluster_size": hp.choice('min_cluster_size', range(2,32)),
"random_state": 42
}
label_lower = 10
label_upper = 100
max_evals = 25 # change it to 50 or 100 for extra steps as wished.
import importlib
importlib.reload(utils)
%%time
from utils import *
best_params_use, best_clusters_use, trials_use = utils.bayesian_search(embeddings_st1,
space=hspace,
label_lower=label_lower,
label_upper=label_upper,
max_evals=max_evals)`
and the error I get is:
enter image description here
ValueError: <module 'random' from 'C:...anaconda3\lib\random.py'> cannot be used to seed a numpy.random.RandomState instance
Can someone please help me solve this problem, I tried to open the 'random" file and couldn't fix the problem.

How to extract the [Documentation] text from Robot framework test case

I am trying to extract the content of the [Documentation] section as a string for comparision with other part in a Python script.
I was told to use Robot framework API https://robot-framework.readthedocs.io/en/stable/
to extract but I have no idea how.
However, I am required to work with version 3.1.2
Example:
*** Test Cases ***
ATC Verify that Sensor Battery can enable and disable manufacturing mode
[Documentation] E1: This is the description of the test 1
... E2: This is the description of the test 2
[Tags] E1 TRACE{Trace_of_E1}
... E2 TRACE{Trace_of_E2}
Extract the string as
E1: This is the description of the test 1
E2: This is the description of the test 2
Have a look at these examples. I did something similar to generate testplans descritio. I tried to adapt my code to your requirements and this could maybe work for you.
import os
import re
from robot.api.parsing import (
get_model, get_tokens, Documentation, EmptyLine, KeywordCall,
ModelVisitor, Token
)
class RobotParser(ModelVisitor):
def __init__(self):
# Create object with remarkup_text to store formated documentation
self.text = ''
def get_text(self):
return self.text
def visit_TestCase(self, node):
# The matched `TestCase` node is a block with `header` and
# `body` attributes. `header` is a statement with familiar
# `get_token` and `get_value` methods for getting certain
# tokens or their value.
for keyword in node.body:
# skip empty lines
if keyword.get_value(Token.DOCUMENTATION) == None:
continue
self.text += keyword.get_value(Token.ARGUMENT)
def visit_Documentation(self,node):
# The matched "Documentation" node with value
self.remarkup_text += node.value + self.new_line
def visit_File(self, node):
# Call `generic_visit` to visit also child nodes.
return self.generic_visit(node)
if __name__ == "__main__":
path = "../tests"
for filename in os.listdir(path):
if re.match(".*\.robot", filename):
model = get_model(os.path.join(path, filename))
robot_parser = RobotParser()
robot_parser.visit(model)
text=robot_parser._text()
The code marked as best answer didn't quite work for me and has a lot of redundancy but it inspired me enough to get into the parsing and write it in a much readable and efficient way that actually works as is. You just have to have your own way of generating & iterating through filesystem where you call the get_robot_metadata(filepath) function.
from robot.api.parsing import (get_model, ModelVisitor, Token)
class RobotParser(ModelVisitor):
def __init__(self):
self.testcases = {}
def visit_TestCase(self, node):
testcasename = (node.header.name)
self.testcases[testcasename] = {}
for section in node.body:
if section.get_value(Token.DOCUMENTATION) != None:
documentation = section.value
self.testcases[testcasename]['Documentation'] = documentation
elif section.get_value(Token.TAGS) != None:
tags = section.values
self.testcases[testcasename]['Tags'] = tags
def get_testcases(self):
return self.testcases
def get_robot_metadata(filepath):
if filepath.endswith('.robot'):
robot_parser = RobotParser()
model = get_model(filepath)
robot_parser.visit(model)
metadata = robot_parser.get_testcases()
return metadata
This function will be able to extract the [Documentation] section from the testcase:
def documentation_extractor(testcase):
documentation = []
for setting in testcase.settings:
if len(setting) > 2 and setting[1].lower() == "[documentation]":
for doc in setting[2:]:
if doc.startswith("#"):
# the start of a comment, so skip rest of the line
break
documentation.append(doc)
break
return "\n".join(documentation)

django rest framework test code self.client.delete problem

from rest_framework import status, response
from rest_framework.test import APITestCase
from lots.models import Lot
class LotsTestCase(APITestCase):
def setUp(self) -> None:
self.lot = Lot.objects.create(name="1",
address="Dont Know",
phone_num="010-4451-2211",
latitude=127.12,
longitude=352.123,
basic_rate=20000,
additional_rate=2000,
partnership=False,
section_count=3,)
def test_delete(self):
response = self.client.delete(f'api/lots/{self.lot["name"]}')
# response = self.client.delete(f'/api/users/{self.users[0].pk}')
# url = reverse(f'/api/lots/{self.lot}', kwargs={'pk': self.lot.pk})
# self.client.delete(url)
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
self.assertEqual(self.lot.objects.filter(pk=self.lot.pk.count()))
I have problems with the test code above. Why doesn't it work? I know it has to do with calling dictionary values but I just can't figure it out. Thanks for your help.
Lot.objects.create(...) returns a Lot type so you access name by self.lot.name.

How to set developer Mode as default in ODOO

i use a lot developer Mode in odoo so i always have to go to config and set dev mode every time i need it
is there any way to make this developper mode as default
thank you so much
you can enable odoo dev mode very easy !
You can use a chrome extension called Odoo Debug:
Odoo Debug
Or a Firefox extension called Odoo Easy Debug:
Odoo Easy Debug
Regards,
You don't need a chrome or firefox extension to activate and set the debug mode by default in Odoo. You can do something like the following code withing the Odoo framework. This is taken from this Odoo module and works at least in Odoo v8
Create a class with the settings values
class DevelopmentToolsConfigSettings(models.TransientModel):
_name = 'development_tools.config.settings'
development_mode = fields.Boolean(
string='Development mode as default',
required=False,
readonly=False,
index=False,
default=True,
help='Set development mode by default'
)
#api.model
def get_default_values(self, values):
return dict(
development_mode=self.get_debug_mode(),
)
def get_debug_mode(self):
param = self._get_parameter('development_mode')
if param:
value = self._safe_eval(param.value, bool)
else:
value = self._defaults['development_mode']
return value
def _set_debug_mode(self):
param = self._get_parameter('development_mode', force=True)
param.value = unicode(self.development_mode)
Override web.Home controller and add auto-debug mode behavior:
from openerp.http import route, request, Controller, redirect_with_hash
import openerp.addons.web.controllers.main as webmain
from openerp.tools.translate import _
from logging import getLogger
import werkzeug
_logger = getLogger(__name__)
class Home(webmain.Home):
#route()
def web_client(self, s_action=None, **kw):
result = None
if not request.debug and request.db and self._get_debug_mode():
_logger.info(self._debug_message)
result = self._build_debug_response()
return result or super(Home, self).web_client(s_action, **kw)
def _get_debug_mode(self):
config = request.env['development_tools.config.settings']
debug = config.get_debug_mode()
return debug == True
def _build_debug_response(self):
result = None
try:
query = request.params
query.update({'debug': u''})
url = '/web?' + werkzeug.url_encode(query)
result = redirect_with_hash(url)
except Exception as ex:
_logger.error(self._error_response.format(ex))
return result
_debug_message = _(u'Auto-redirect to enter in debug mode')
_error_response = _(
u'The debug response could not be built.\n'
u'System has said: {}'
)

Test fails in tests.py but succeeds in python shell

I'm a newbee to python and django and I can't figure out what I'm doing wrong here.
I have a Site object:
class Site (models.Model):
domain = models.CharField(max_length=30)
support_status = models.CharField(max_length=20, choices= SITE_SUPPORTED_STATUS, blank=False)
requests = models.IntegerField()
objects = SiteManager()
def __unicode__(self):
return u'%s %s' % (self.domain, self.support_status)
And a SiteManager object
class SiteManager(models.Manager):
def supported_site_counts(self):
i = self.filter(support_status__iexact="SUPPORTED").count()
return i
From the console, the method "supported_site_counts()" works just fine
>>(InteractiveConsole)
>>> from bookmark.models import Site, SiteManager
>>> Site.objects.supported_site_counts()
>>>>2012-05-18 18:09:20,027 DEBUG (0.001) SELECT COUNT(*) FROM "bookmark_site" WHERE
>>>>"bookmark_site"."support_status" LIKE SUPPORTED ESCAPE '\' ; args=(u'SUPPORTED',)
>>>>2012-05-18 18:09:20,028 DEBUG Got 1 supported site
>>>>1
But when it's called from a testcase, the count returns as 0
class SiteManagerTest(unittest.TestCase):
def test_supported_site_counts(self):
self.x = False
self.count = Site.objects.supported_site_counts()
logging.debug(self.count)
This is probably because the tests will set up a database separate from your development database to run the tests in. You will need to put testing data in to the testing database, either programmatically or using fixtures.