While using Spock i can do something like this:
when:
12.times {mailSender.send("blabla", "subject", "content")}
then:
12 * javaMailSender.send(_)
When i tried to do same in Mockito:
verify(javaMailSender,times(12)).send(any(SimpleMailMessage.class))
I got an error that SimpleMailMessage has null values, so i had to initialize it in test:
SimpleMailMessage simpleMailMessage = new SimpleMailMessage()
simpleMailMessage.setTo("blablabla")
simpleMailMessage.subject = "subject"
simpleMailMessage.text = "content"
verify(javaMailSender,times(12)).send(simpleMailMessage))
Now it works but it's a large workload and i really don't care about equality. What if SimpleMailMessage will have much more arguments or another objects with another arguments, meh. Is there any way to check that send method was just called X times?
EDIT: added implementation of send method.
private fun sendEmail(recipient: String, subject: String, content: String)
{
val mailMessage = SimpleMailMessage()
mailMessage.setTo(recipient)
mailMessage.subject = subject
mailMessage.text = content
javaMailSender.send(mailMessage)
}
There are 2 senders, mailSender is my custom object and javaMailSender is from another libary
Stacktrace:
Mockito.verify(javaMailSender,
Mockito.times(2)).send(Mockito.any(SimpleMailMessage.class))
| | | | |
| | | | null
| | | Wanted but not invoked:
| | | javaMailSender.send(
| | | <any org.springframework.mail.SimpleMailMessage>
| | | );
| | | -> at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
| | |
| | | However, there were exactly 2 interactions with this mock:
| | | javaMailSender.send(
| | | SimpleMailMessage: from=null; replyTo=null; to=blabla; cc=; bcc=; sentDate=null; subject=subject; text=content
| | | );
| | | -> at MailSenderServiceImpl.sendEmail(MailSenderServiceImpl.kt:42)
| | |
| | | javaMailSender.send(
| | | SimpleMailMessage: from=null; replyTo=null; to=blabla; cc=; bcc=; sentDate=null; subject=subject; text=content
| | | );
If you don't care for the parameter of send, leave any() empty:
verify(javaMailSender,times(12)).send(any())
Related
hellow my models see the blow
class IP(models.Model):
subnet = models.ForeignKey(Subnet,verbose_name="SUBNET",on_delete=models.CASCADE,related_name="ip_set")
ip = models.GenericIPAddressField(verbose_name="IP",protocol="both",unpack_ipv4=True,unique=True)
asset = models.ManyToManyField(Asset,verbose_name="HOSTNAME",through="AssetIP",related_name="ip_set",blank=True,)
description = models.CharField(verbose_name="DESCRIPTION",max_length=50,default="",null=True,blank=True)
class AssetIP(models.Model):
TYPE_CHOICES = [
("GATEWAY-IP", "GATEWAY-IP"),
("MGT-IP", "MGT-IP"),
("PRIMARY-IP", "PRIMARY-IP"),
("OTHER-IP", "OTHER-IP"),
]
ip_type = models.CharField(verbose_name="IP TYPE",max_length=30,choices=TYPE_CHOICES)
ip = models.ForeignKey(IP,verbose_name="IP",on_delete=models.CASCADE,related_name="asset_ip_set")
asset = models.ForeignKey(Asset,verbose_name="HOSTNAME",on_delete=models.CASCADE,related_name="asset_ip_set")
class Asset(models.Model):
barcode = models.CharField(verbose_name="Barcode",max_length=60,blank=True,null=True,unique=True)
hostname= models.CharField(verbose_name="Hostname",max_length=30)
so in this model data is blow
IP Model
| IP | Asset | Description |
|:---- |:------:| -----:|
| 10.10.10.2 | A_HOST,B_HOST,C_HOST | - |
| 10.10.10.3 | A_HOST,B_HOST | - |
| 10.10.10.4 | A_HOST | - |
| 10.10.10.5 | A_HOST | - |
AssetIP through Model
| IP | Asset | IP_TYPE |
|:---- |:------:| -----:|
| 10.10.10.2 | A_HOST | OTHER-IP |
| 10.10.10.2 | B_HOST | OTHER-IP |
| 10.10.10.2 | C_HOST | OTHER-IP |
| 10.10.10.3 | A_HOST | OTHER-IP |
| 10.10.10.4 | A_HOST | OTHER-IP |
| 10.10.10.5 | A_HOST | PRIMARY-IP |
So Asset Query Result in this
Result = Asset.objects.all()
in this result Field
Asset = {
barcode: "ddd",
hostname: "A_HOST",
}
I Want Field and Result
Asset = {
barcode: "ddd",
hostname: "A_HOST",
primary_ip : "10.10.10.5",
other_ip : "10.10.10.2, 10.10.10.3, 10.10.10.4"
}
I Try the this query in this queryset is not filtering "OHTER-IP"
assets = Asset.objects.annotate(other_ips=GroupConcat('asset_ip_set__ip__ip'))
assets[0].other_ips
result : '10.10.10.2,10.10.10.3,10.10.10.4,10.10.10.5'
and try to this queryset
filtered_ips = AssetIP.objects.filter(asset=OuterRef('pk'), ip_type="OTHER-IP").values_list('ip__ip', flat=True)
Asset.objects.filter(asset_ip_set__ip_type="OTHER-IP").annotate(
other_ips=GroupConcat(
Subquery(filtered_ips),
delimiter=', '
)
)
result : django.db.utils.OperationalError: (1242, 'Subquery returns more than 1 row')
Help me....
I've been adding std::string_views to some old code for representing string like config params, as it provides a read only view, which is faster due to no need for copying.
However, one cannot concatenate two string_view together as the operator+ isn't defined. I see this question has a couple answers stating its an oversight and there is a proposal in for adding that in. However, that is for adding a string and a string_view, presumably if that gets implemented, the resulting concatenation would be a std::string
Would adding two string_view also fall in the same category? And if not, why shouldn't adding two string_view be supported?
Sample
std::string_view s1{"concate"};
std::string_view s2{"nate"};
std::string_view s3{s1 + s2};
And here's the error
error: no match for 'operator+' (operand types are 'std::string_view' {aka 'std::basic_string_view<char>'} and 'std::string_view' {aka 'std::basic_string_view<char>'})
A view is similar to a span in that it does not own the data, as the name implies it is just a view of the data. To concatenate the string views you'd first need to construct a std::string then you can concatenate.
std::string s3 = std::string(s1) + std::string(s2);
Note that s3 will be a std::string not a std::string_view since it would own this data.
A std::string_view is an alias for std::basic_string_view<char>, which is a std::basic_string_view templated on a specific type of character, i.e. char.
But what does it look like?
Beside the fairly large number of useful member functions such as find, substr, and others (maybe it's an ordinary number, if compared to other container/string-like things offered by the STL), std::basic_string_view<_CharT>, with _CharT being the generic char-like type, has just 2 data members,
// directly from my /usr/include/c++/12.2.0/string_view
size_t _M_len;
const _CharT* _M_str;
i.e. a constant pointer to _CharT to indicate where the view starts, and a size_t (an appropriate type of number) to indicate how long the view is starting from _M_str's pointee.
In other words, a string view just knows where it starts and how long it is, so it represents a sequence of char-like entities which are consecutive in memory. With just two such memebrs, you can't represent a string which is made up of non-contiguous substrings.
Yet in other words, if you want to create a std::string_view, you need to be able to tell how many chars it is long and from which position. Can you tell where s1 + s2 would have to start and how many characters it should be long? Think about it: you can't, becase s1 and s2 are not adjacent.
Maybe a diagram can help.
Assume these lines of code
std::string s1{"hello"};
std::string s2{"world"};
s1 and s2 are totally unrelated objects, as far as their memory location is concerned; here is what they looks like:
&s2[0]
|
| &s2[1]
| |
&s1[0] | | &s2[2]
| | | |
| &s1[1] | | | &s2[3]
| | | | | |
| | &s1[2] | | | | &s2[4]
| | | | | | | |
| | | &s1[3] v v v v v
| | | | +---+---+---+---+---+
| | | | &s1[4] | w | o | r | l | d |
| | | | | +---+---+---+---+---+
v v v v v
+---+---+---+---+---+
| h | e | l | l | o |
+---+---+---+---+---+
I've intentionally drawn them misaligned to mean that &s1[0], the memory location where s1 starts, and &s2[0], the memory location where s2 starts, have nothing to do with each other.
Now, imagine you create two string views like this:
std::string_view sv1{s1};
std::string_view sv2(s2.begin() + 1, s2.begin() + 4);
Here's what they will look like, in terms of the two implementation-defined members _M_str and _M_len:
&s2[0]
|
| &s2[1]
| |
&s1[0] | | &s2[2]
| | | |
| &s1[1] | | | &s2[3]
| | | | | |
| | &s1[2] | | | | &s2[4]
| | | | | | | |
| | | &s1[3] v v v v v
| | | | +---+---+---+---+---+
| | | | &s1[4] | w | o | r | l | d |
| | | | | +---+---+---+---+---+
v v v v v · ^ ·
+---+---+---+---+---+ · | ·
| h | e | l | l | o | +---+ ·
+---+---+---+---+---+ | · ·
· ^ · | · s2._M_len ·
· | · | <----------->
+---+ · |
| · · +-- s2._M_str
| · s1._M_len ·
| <------------------->
|
+-------- s1._M_str
Given the above, can you see what's wrong with expecting that
std::string_view s3{s1 + s2};
works?
How can you possible define s3._M_str and s3._M_len (based on s1._M_str, s1._M_len, s2._M_str, and s2._M_len), such that they represent a view on "helloworld"?
You can't because "hello" and "world" are located in two unrelated areas of memory.
std::string_view does not own any data, it is only a view. If you want to join two views to get a joined view, you can use boost::join() from the Boost library. But result type will be not a std::string_view.
#include <iostream>
#include <string_view>
#include <boost/range.hpp>
#include <boost/range/join.hpp>
void test()
{
std::string_view s1{"hello, "}, s2{"world"};
auto joined = boost::join(s1, s2);
// print joined string
std::copy(joined.begin(), joined.end(), std::ostream_iterator(std::cout, ""));
std::cout << std::endl;
// other method to print
for (auto c : joined) std::cout << c;
std::cout << std::endl;
}
C++23 has joined ranges in the standard library with the name of std::ranges::views::join_with_view
#include <iostream>
#include <ranges>
#include <string_view>
void test()
{
std::string_view s1{"hello, "}, s2{"world"};
auto joined = std::ranges::views::join_with_view(s1, s2);
for (auto c : joined) std::cout << c;
std::cout << std::endl;
}
I just wanted to know how deque is implemented and how are the basic operations like push_front and random access operator are provided in that implementation.
I just wanted to know how deque is implemented
It's always a good to have an excuse for doing ASCII art:
+-------------------------------------------------------------+
| std::deque<int> |
| |
| subarrays: |
| +---------------------------------------------------------+ |
| | | | | | | |
| | int(*)[8] | int(*)[8] | int(*)[8] |int(*)[8]|int(*)[8] | |
| | | | | | | |
| +---------------------------------------------------------+ |
| / \ |
| / \ |
| / \ |
| / \ |
| / \ |
| / \ |
| / \ |
| / \ |
| - - |
| +------------------------------+ |
| | ?, ?, 42, 43, 50, ?, ?, ?, ? | |
| +------------------------------+ |
| |
| additional state: |
| |
| - pointer to begin of the subarrays |
| - current capacity and size |
| - pointer to current begin and end |
+-------------------------------------------------------------+
how are the basic operations like push_front and random access operator are provided in that implementation?
First, std::deque::push_front, from libcxx:
template <class _Tp, class _Allocator>
void
deque<_Tp, _Allocator>::push_front(const value_type& __v)
{
allocator_type& __a = __base::__alloc();
if (__front_spare() == 0)
__add_front_capacity();
__alloc_traits::construct(__a, _VSTD::addressof(*--__base::begin()), __v);
--__base::__start_;
++__base::size();
}
This obviously checks whether the memory already allocated at the front can hold an additional element. If not, it allocates. Then, the main work is shifted to the iterator: _VSTD::addressof(*--__base::begin()) goes one location before the current front element of the container, and this address is passed to the allocator to construct a new element in place by copying v (the default allocator will definitely do a placement-new).
Now random access. Again from libcxx, std::deque::operator[] (the non-const version) is
template <class _Tp, class _Allocator>
inline
typename deque<_Tp, _Allocator>::reference
deque<_Tp, _Allocator>::operator[](size_type __i) _NOEXCEPT
{
size_type __p = __base::__start_ + __i;
return *(*(__base::__map_.begin() + __p / __base::__block_size) + __p % __base::__block_size);
}
This pretty much computes an index relative to some start index, and then determines the subarray and the index relative to the start of the subarray. __base::__block_size should be the size of one subarray here.
I have a symfony app with doctrine. There is a table like:
+--------+---------------------+-------+
| user | log_date | foo |
+---------+---------------------+-------+
| john | 2018-03-20 22:59:18 | 58 |
| kyle | 2018-04-11 13:45:02 | 22 |
| paul | 2018-11-08 22:19:16 | 41 |
| kyle | 2018-08-14 09:39:26 | 19 |
| fred | 2018-03-28 06:08:31 | 24 |
| john | 2018-01-21 11:52:17 | 81 |
| ... | ... | ... |
+---------+---------------------+-------+
A cron should execute a symfony command to delete all records but keep the latest 10 of every user. Can this be done using DQL or do I have to use an SQL (sub-)query?
I think something like this in entity repository can get all the entries for the user except the last 10
public function getAllExceptLatest($user)
{
return $this
->createQueryBuilder('t')
->andWhere('t.logDate <= :logDate')
->orderBy('t.logDate', 'DESC')
->setParameter(':logDate', $this->getLatestDate($user))
->setFirstResult(10)
->getQuery()
->execute();
}
public function getLatestDate($user)
{
return $this->createQueryBuilder('e')
->select('MAX(e.logDate)')
->andWhere('e.user = :user')
->setParameter(':user', $user)
->getQuery()
->getSingleScalarResult();
}
And in controller you can use
public function keepLatest(){
$em = $this->getDoctrine()->getManager();
$userRepo = $em->getRepository(User::class);
$users = $userRepo->findAll();
foreach ($users as $u) {
$records = $userRepo->getAllExceptLatest($u);
foreach ($records as $r)
$em->remove($r);
}
$em->flush();
}
I didn't test this, but in mine apps similar methods works fine
I'm using the building tool of dojo to generate a single file dojo.js, but I don't know why I'm getting multiple files.
This is my example profile:
var profile = (function(){
return {
basePath: "../../../",
releaseDir: "./app",
releaseName: "lib",
action: "release",
layerOptimize: "closure",
optimize: "closure",
mini: true,
stripConsole: "warn",
selectorEngine: "lite",
defaultConfig: {
hasCache:{
"dojo-built": 1,
"dojo-loader": 1,
"dom": 1,
"host-browser": 1,
"config-selectorEngine": "lite"
},
async: 1
},
staticHasFeatures: {
'dojo-trace-api': 0,
'dojo-log-api': 0,
'dojo-publish-privates': 0,
'dojo-sync-loader': 0,
'dojo-test-sniff': 0
},
packages:['dojo'],
layers: {
"dojo/dojo": {
include: ["dojo/domReady"],
customBase: true,
boot: true
}
}
};
})();
This is my .bat:
./util/buildscripts/build profile=cgl-dojo
After execute it, this is the release folder:
app
\---lib
\---dojo
+---cldr
| \---nls
| +---ar
| +---ca
| +---cs
| +---da
| +---de
| +---el
| +---en
| +---en-au
| +---en-ca
| +---en-gb
| +---es
| +---fi
| +---fr
| +---fr-ch
| +---he
| +---hu
| +---it
| +---ja
| +---ko
| +---nb
| +---nl
| +---pl
| +---pt
| +---pt-pt
| +---ro
| +---ru
| +---sk
| +---sl
| +---sv
| +---th
| +---tr
| +---zh
| +---zh-hant
| +---zh-hk
| \---zh-tw
+---data
| +---api
| \---util
+---date
+---dnd
+---errors
+---fx
+---io
+---nls
| +---ar
| +---az
| +---bg
| +---ca
| +---cs
| +---da
| +---de
| +---el
| +---es
| +---fi
| +---fr
| +---he
| +---hr
| +---hu
| +---it
| +---ja
| +---kk
| +---ko
| +---nb
| +---nl
| +---pl
| +---pt
| +---pt-pt
| +---ro
| +---ru
| +---sk
| +---sl
| +---sv
| +---th
| +---tr
| +---uk
| +---zh
| \---zh-tw
+---promise
+---request
+---resources
| \---images
+---router
+---rpc
+---selector
+---store
| +---api
| \---util
+---_base
\---_firebug
I need a release folder with only one file, please help me.
The entire tree of registered packages is always built because the build tool has no way of knowing whether or not you are conditionally requiring other modules within your application. There is no way to make the build system only output one file, and in fact a single file is a bad idea because each locale has its own set of localisation rules. If you want to reduce the number of files after a build, you can just delete all the ones you don’t want.