django cms plugin instance related_set returns empty list - plugins

I have the following models
class NewSlide(models.Model):
slider = models.ForeignKey('NewSliderPlugin')
title = models.CharField(max_length=255)
content = models.TextField(max_length=80, null=True)
link = models.CharField(max_length=255)
image = models.ImageField(upload_to='slides', null=True)
visible = models.BooleanField(default=False)
def __unicode__(self): # Python 3: def __str__(self):
return self.title
class NewSliderPlugin(CMSPlugin):
title = models.CharField(max_length=255)
template = models.CharField(max_length=255, choices=(('slider.html','Top Level Slider'), ('slider2.html','Featured Slider')))
The plugin code as below:
class NewSlideInline(admin.StackedInline):
model = NewSlide
extra = 1
class NewCMSSliderPlugin(CMSPluginBase):
model = NewSliderPlugin
name = "NewSlider"
render_template = "slider.html"
inlines = [NewSlideInline]
def render(self, context, instance, placeholder):
self.render_template = instance.template
print instance.title
print instance.newslide_set.all(), 1111111111111111
context.update({
'slider': instance,
'object': instance,
'placeholder': placeholder
})
return context
I have added slides to the plugin and published changes, however 1instance.newslide_set.all()1 returns empty list: [] 1111111111111111
Update:
it creates 2 records, somehow the admin references 49, but render code gives 63
mysql> select * from cmsplugin_newsliderplugin;
+------------------+-----------+-------------+
| cmsplugin_ptr_id | title | template |
+------------------+-----------+-------------+
| 49 | slide | slider.html |
| 63 | slide | slider.html |
+------------------+-----------+-------------+
mysql> select * from slider_newslide;
+----+-----------+-------+---------+------+----------------+---------+
| id | slider_id | title | content | link | image | visible |
+----+-----------+-------+---------+------+----------------+---------+
| 6 | 49 | ttttt | testt | test | slides/287.jpg | 0 |
+----+-----------+-------+---------+------+----------------+---------+
By the way, I have django-reversion installed, not sure if it's because of this app.

OK according to the documentation I need to copy the related items:
class NewSliderPlugin(CMSPlugin):
title = models.CharField(max_length=255)
template = models.CharField(max_length=255, choices=(('slider.html','Top Level Slider'), ('slider2.html','Featured Slider')))
def copy_relations(self, oldinstance):
for slide in oldinstance.newslide_set.all():
# instance.pk = None; instance.pk.save() is the slightly odd but
# standard Django way of copying a saved model instance
slide.pk = None
slide.slider = self
slide.save()

Related

How to check for level in react-testing-library?

I have a heading <h4>Big offer!</h4> on the page, when I first ran my tests I got:
Expected: "Big offer!"
Received: <h4>Big offer!</h4>
35 | const switchToggle = screen.getByRole('checkbox');
36 | expect(switchToggle.checked).toEqual(true);
> 37 | expect(titleEl).toEqual(title);
Ok, it get's correct file, so I changed my code to actually check heading level and text, but it failed:
Expected: "Big offer!"
Received: undefined
35 | const switchToggle = screen.getByRole('checkbox');
36 | expect(switchToggle.checked).toEqual(true);
> 37 | expect(titleEl.name).toEqual(title);
| ^
38 | expect(titleEl.level).toEqual(4);
I always thought that .name is equal to getByText(). I commented out a line and tried checking for level, and it failed again:
Expected: 4
Received: undefined
36 | expect(switchToggle.checked).toEqual(true);
37 | //expect(titleEl.name).toEqual(title);
> 38 | expect(titleEl.level).toEqual(4);
I don't understand why my test cases failed. Code for test was:
const title = 'Big offer!';
render(<Component title={title}/>);
const titleEl = screen.getByRole('heading');
expect(titleEl).toEqual(title);
expect(titleEl.level).toEqual(4);
It wont work because screen.getByRole (or others querys) returns an HTMLElement (in your case returns a HTMLHeadingElement that inherits HTMLElement). And it doesnt have name or level properties. You can check more here.
To check the text rendered you should use:
expect(titleEl).toHaveTextContent(title);
And for h4 type check you just need to filter it on query:
const titleEl = screen.getByRole('heading', { level: 4 });
The full test:
it('test search input', async () => {
const title = 'Big offer!';
render(<SearchBox title={title} />);
const titleEl = screen.getByRole('heading', { level: 4 });
expect(titleEl).toBeInTheDocument();
expect(titleEl).toHaveTextContent(title);
});

How to get the status of each line of a Datatable rows that is executed

Im testing a scenario where there are about 100s of username and password. I should use each username-password pair one by one and then try login to application. Then logout. Login again in the same browser without closing it. Here if any of the credentials are invalid then only that particular row should be marked fail and rest should continue execution
I tried to search for the solution but couldnot get any proper resolution
Scenario: To test if the given list of users credentials are valid
Given user is already at Login page
And user enters credentails
| Username | Password |
| user1 | password1 |
| user2 | invalid |
| user3 | password3 |
| user4 | password4 |
| user5 | password5 |
| user6 | password6 |
| user7 | password7 |
Here the status of 2nd row of datatable should be marked failed in the report and rest of the data should be executed except the failed ones. Passed data should be marked PASS in the report. How to achieve this.
First you would need to modify scenario as per below outline.
Scenario Outline: To test if the given list of users credentials are valid
Given user is already at Login page
And In credentails, user enters name as <Username> and Pwd as <Password>
Examples: Checking Login Scenarios
| Username | Password |
| user1 | password1 |
| user2 | invalid |
Second lets consider below is your step implementation
package my.package.name
import cucumber.api.PendingException;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.And;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;
#RunWith(Cucumber.class)
public class MyStepDefinitions {
#Given("^user is already at Login page$")
public void user_is_already_at_login_page() throws Throwable {
throw new PendingException();
}
#And("^In credentails, user enters name as (.+) and Pwd as (.+)$")
public void in_credentails_user_enters_name_as_and_pwd_as(String username, String password) throws Throwable {
throw new PendingException();
}
}
Third lets say under above step implementation, you write action to log into site and Action gets failed as Password was invalid. Now depending on which report you are using, you would need to write one method as per API of report, like i am sharing for extent.
public static synchronized void logFail(String message) {
try {
testReport.get().fail("<details>" + "<summary>" + "<b>" + "<font color=" + "red>" + "</font>" + "</b >" + "</summary>" + "<br>" + "<h6>" + "<b>" + BasePage.returnLocator(message) + "</b>"+ "</h6>" + "</br>" + message +"</details>"+" \n");
}
catch(Exception e) {
}
}
At last, following above hierarchy you would be able to print Passed/Failed in report.

How to remove SOAP Optional elements in the request

Using Karate, I would like to build a soap request.
There are Optional elements in the SOAP Request, how to remove them based on the Scenario Outline: Example?
Shared an example, for the purpose of discussion. If there is already a sample code, please share, thank you.
Feature: SOAP request to get Customer Details
Background:
Given url 'http://localhost:8080/CustomerService_V2_Ws'
Scenario Outline:
* def removeElement =
"""
function(parameters, inputXml) {
if (parameters.city = null)
karate.remove(inputXml, '/Envelope/Header/AutHeader/ClientContext/city');
if (parameters.zipcode = null)
karate.remove(inputXml, '/Envelope/Header/AutHeader/ClientContext/zipcode');
return inputXml;
}
"""
* def inputXml = read('soap-request.xml')
* def updatedXml = removeElement(parameters,inputXml)
Given request updatedXml
When soap action ''
Then status <http_code>
Examples:
| CustomerId | ZipCode | City |
| 001 | null | null |
| 002 | 41235 | null |
| 003 | null | New York |
**Contents of "soap-request.xml"**
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header>
<wsc1:AutHeader xmlns:wsc1="http://example.com/ws/WSCommon_v22">
<wsc1:SourceApplication>ABC</wsc1:SourceApplication>
<wsc1:DestinationApplication>SoapUI</wsc1:DestinationApplication>
<wsc1:Function>CustomerService.readDetails</wsc1:Function>
<wsc1:Version>2</wsc1:Version>
<wsc1:ClientContext>
<wsc1:customerid>10000</wsc1:customerid>
<!--Optional:-->
<wsc1:zipcode>11111</wsc1:zipcode>
<!--Optional:-->
<wsc1:city>xyz</wsc1:city>
</wsc1:ClientContext>
</wsc1:AutHeader>
</soapenv:Header>
<soapenv:Body />
</soapenv:Envelope>
Yes my suggestion is use embedded expressions. When the expression is prefixed with 2 hash signs, this will "delete if null" which was designed for your exact use case. Here is an example:
Scenario: set / remove xml chunks using embedded expressions
* def phone = '123456'
# this will remove the <acc:phoneNumberSearchOption> element
* def searchOption = null
* def search =
"""
<acc:getAccountByPhoneNumber>
<acc:phoneNumber>#(phone)</acc:phoneNumber>
<acc:phoneNumberSearchOption>##(searchOption)</acc:phoneNumberSearchOption>
</acc:getAccountByPhoneNumber>
"""
* match search ==
"""
<acc:getAccountByPhoneNumber>
<acc:phoneNumber>123456</acc:phoneNumber>
</acc:getAccountByPhoneNumber>
"""
Do note that there are many more examples here: xml.feature

spark dataframe handle option some none

Similar to Apache Spark: dealing with Option/Some/None in RDDs I have a function which is applied via df.mapPartitions
def mapToTopics(iterator: Iterator[RawRecords]): Iterator[TopicContent] = {
iterator.map(k => {
browser.parseString(k.content) >> elementList("doc").map(d => {
TopicContent((d >> text("docno")).head, (d >> text("text")).head, k.path)
})
})
}
The following is also defined:
#transient lazy val browser = JsoupBrowser()
case class TopicContent(topic: String, content: String, filepath: String)
case class RawRecords(path: String, content: String)
Above will throw an error (NoSuchElementException) if no xml tags with text exist (which happens for some malformed documents)
How can I correct and simplify this code to properly handle the options?
When trying to use a util.Try as outlined by the link above and applying a flatMap my code would fail, as instead of Element it was using Char
edit
try {
Some(TopicContent((d >> text("docno")).head, (d >> text("text")).head, k.path))
} catch {
case noelem: NoSuchElementException => {
println(d.head)
None
}
}
})
val flattended = results.flatten
Will unfortunately only return a Option[Nothing]
edit4
https://gist.github.com/geoHeil/bfb01427b88cf58ea755f912ce539712 a minimal sample without spark (and full code below as well)
import net.ruippeixotog.scalascraper.browser.JsoupBrowser
import net.ruippeixotog.scalascraper.dsl.DSL.Extract._
import net.ruippeixotog.scalascraper.dsl.DSL._
import net.ruippeixotog.scalascraper.scraper.ContentExtractors.elementList
#transient lazy val browser = JsoupBrowser()
val broken =
"""
|<docno>
| LA051089-0001
| </docno>
| <docid>
| 54901
| </docid>
| <date>
| <p> May 10, 1989, Wednesday, Home Edition </p>
| </date>
| <section>
| <p> Metro; Part 2; Page 2; Column 2 </p>
| </section>
| <graphic>
| <p> Photo, Cloudy and Clear A stormy afternoon provides a clear view of Los Angeles' skyline, with the still-emerging Library Tower rising above its companion buildings. KEN LUBAS / Los Angeles Times </p>
| </graphic>
| <type>
| <p> Wild Art </p>
| </type>
""".stripMargin
val correct =
"""
|<DOC>
|<DOCNO> FR940104-0-00001 </DOCNO>
|<PARENT> FR940104-0-00001 </PARENT>
|<TEXT>
|
|<!-- PJG FTAG 4700 -->
|
|<!-- PJG STAG 4700 -->
|
|<!-- PJG ITAG l=90 g=1 f=1 -->
|
|<!-- PJG /ITAG -->
|
|<!-- PJG ITAG l=90 g=1 f=4 -->
|Federal Register
|<!-- PJG /ITAG -->
|
|<!-- PJG ITAG l=90 g=1 f=1 -->
|&blank;/&blank;Vol. 59, No. 2&blank;/&blank;Tuesday, January 4, 1994&blank;/&blank;Rules and Regulations
|
|<!-- PJG 0012 frnewline -->
|
|<!-- PJG /ITAG -->
|
|<!-- PJG ITAG l=01 g=1 f=1 -->
|Vol. 59, No. 2
|<!-- PJG 0012 frnewline -->
|
|<!-- PJG /ITAG -->
|
|<!-- PJG ITAG l=02 g=1 f=1 -->
|Tuesday, January 4, 1994
|<!-- PJG 0012 frnewline -->
|
|<!-- PJG 0012 frnewline -->
|
|<!-- PJG /ITAG -->
|
|<!-- PJG /STAG -->
|
|<!-- PJG /FTAG -->
|</TEXT>
|</DOC>
""".stripMargin
case class RawRecords(path: String, content: String)
case class TopicContent(topic: String, content: String, filepath: String)
val raw = Seq(RawRecords("first", correct), RawRecords("second", broken))
val result = mapToTopics(raw.iterator)
// Variant 1
def mapToTopics(iterator: Iterator[RawRecords]): Iterator[TopicContent] = {
iterator.flatMap(k => {
val documents = browser.parseString(k.content) >> elementList("doc")
documents.map(d => {
val docno = d >> text("docno")
// try {
val textContent = d >> text("text")
TopicContent(docno, textContent, k.path)
// } catch {
// case _:NoSuchElementException => TopicContent(docno, None, k.path)
// }
}) //.filter(_.content !=None)
})
}
// When broken down even further you see the following will produce Options of strings
browser.parseString(raw(0).content) >> elementList("doc").map(d => {
val docno = d >> text("docno")
val textContent = d >> text("text")
(docno.headOption, textContent.headOption)
})
// while below will now map to characters. What is wrong here?
val documents = browser.parseString(raw(0).content) >> elementList("doc")
documents.map(d => {
val docno = d >> text("docno")
val textContent = d >> text("text")
(docno.headOption, textContent.headOption)
})
The difference between the two examples lies in the precedence of the operators. When you're doing browser.parseString(raw(0).content) >> elementList("doc").map(...), you're calling map on elementList("doc"), and not on the whole expression. In order for the first example to behave the same as the second one, you need to write either (browser.parseString(raw(0).content) >> elementList("doc")).map(...) (recommended) or browser.parseString(raw(0).content) >> elementList("doc") map(...).
In the context of scala-scraper, the library you're using, the two expressions mean very different things. With browser.parseString(raw(0).content) >> elementList("doc") you're extracting a List[Element] from a document, and calling map on that does just what you'd expect from a collection. On the other hand, elementList("doc") is an HtmlExtractor[List[Element]] and calling map on an extractor creates a new HtmlExtractor with the results of the original extractor transformed. That's the reason why you end up with two very different results.
I am unfamiliar with the API you are using, but using headOpton in a for comprehension might help you:
import net.ruippeixotog.scalascraper.dsl.DSL._
import net.ruippeixotog.scalascraper.dsl.DSL.Extract._
import net.ruippeixotog.scalascraper.dsl.DSL.Parse._
iterator.map(k => {
browser.parseString(k.content) >> elementList("doc").flatMap(d => {
for {
docno <- text("docno")).headOption
text <- (d >> text("text")).headOption
} yield TopicContent(docno, text, k.path)
})
})
This way you only construct TopicContent, really a Some(TopicContent), when both docno and text are present--and None otherwise. Then the flatMap removes all the Nones and extracts the content in Somes leaving you with a collection of TopicContent instances created for all valid XML.

Using TNT4J, activity statistics are not coming properly

I want to log a activity which starts in the scope of a different class and ends in the scope of another class. Using TrackingLogger.getCurrentActivity() throws an exception as there is no activity in memory.Now if I try to store the activity in static HashMap in singleton Class and retrieve it in the other class, the snapshot of activity is showing confusing values. Here is what I am trying to do :
In first Class :
TrackingLogger tracker = TrackingLogger.getInstance(this.getClass()) ;
TrackingActivity activity = tracker.newActivity(); //
activity.start();
CacheUtil.addTrackingActivity("logger",activity); // Store it in static Hashmap in singleton class
In Second Class :
TrackingLogger tracker = TrackingLogger.getInstance(this.getClass());
TrackingActivity activity = CacheUtil.getTrackingActivity("logger");
activity.stop();
tracker.tnt(activity);
this is the snapshot generated :
18:37:39,780 INFO [Nastel TNT4J] {status: 'END' | time: '2014-07-30 13:07:39.778000 UTC' | sev: 'INFO' | type: 'ACTIVITY' | name: 'NOOP' | usec: '72827000' | wait.usec: '21000' | start.time: '2014-07-30 18:36:26.196000 IST' | end.time: '2014-07-30 18:37:39.023000 IST' | pid: '8092' | tid: '90' | id-count: '0' | snap-count: '6' | source: 'APPL=Nastel TNT4J#JVM=8092#FACH13140035#SERVER=FACH13140035#NETADDR=172.25.19.28#DATACENTER=default#GEOADDR=unknown' | track-id: '09d708c4-a6a9-4200-a70f-25c1da838c11'
Snapshot(CPU#Java) {
Count: 4
TotalCpuUsec: 46800.3
TotalCpuUserUsec: 46800.3
}
Snapshot(Thread#Java) {
Count: 69
DaemonCount: 46
StartedCount: 85
PeakCount: 69
BlockedCount: 7
WaitedCount: 0
BlockedUsec: 21000
WaitUsec: 0
}
Snapshot(Memory#Java) {
MaxBytes: 532742144
TotalBytes: 512499712
FreeBytes: 216341712
UsedBytes: 296158000
Usage: 57
}
Snapshot(Copy#GarbageCollector) {
Count: 477
Time: 1940
isValid: true
}
Snapshot(MarkSweepCompact#GarbageCollector) {
Count: 13
Time: 4652
isValid: true
}
Snapshot(Activity#Java) {
TotalCpuUsec: -1778411.4
SlackUsec: 74584411
WallUsec: -1757411.4
BlockedCount: -24
WaitedCount: -1
BlockedUsec: 21000
WaitUsec: 0
OverheadUsec: 24290.215
}}
Am I missing something?? Pls help ..
TrackingLogger.getCurrentActivity() will only return a valid activity if executed within the same thread. The activity handle is stored in thread local. so you most likely calling TrackingLogger.getCurrentActivity() from a different thread and therefore get an exception.
I am not exactly clear where the confusing values are. Can you elaborate?